failproofai 1.0.13 → 1.0.14

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 (370) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +44 -44
  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 +6 -6
  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 -3
  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 +6 -6
  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 +3 -4
  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 +6 -6
  22. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +6 -6
  23. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +5 -5
  24. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  25. package/.next/standalone/.next/server/app/api/audit/invite/route.js +3 -4
  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 +22 -23
  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 +2 -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 +4 -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 +4 -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 +4 -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 +3 -4
  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 +2 -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 +6 -6
  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 +5 -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 +6 -6
  48. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +5 -5
  49. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +6 -6
  50. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  51. package/.next/standalone/.next/server/app/page/build-manifest.json +6 -6
  52. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  53. package/.next/standalone/.next/server/app/page.js +4 -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 +6 -6
  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 +4 -5
  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 +6 -6
  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 +20 -21
  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 +6 -6
  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 +8 -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 +6 -6
  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 +6 -7
  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 +6 -6
  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 +3 -4
  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/{[root-of-the-server]__1a2d0ewycsp6k._.js → [externals]__0h0p9dmv_e7r7._.js} +2 -2
  83. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__1am_1tz0o0aqz._.js → [externals]__1_407huhlmj1m._.js} +2 -2
  84. package/.next/standalone/.next/server/chunks/{[root-of-the-server]__031qp1lkow_kc._.js → [externals]__1rlxpymm37wel._.js} +2 -2
  85. package/.next/standalone/.next/server/chunks/[root-of-the-server]__03s1za0hn71yp._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/[root-of-the-server]__048f1wnr8pysf._.js +63 -0
  87. package/.next/standalone/.next/server/chunks/[root-of-the-server]__07a0sa6fuw5_b._.js +1 -1
  88. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0l-oi4gdtmlo5._.js +3 -0
  89. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0spt0kv8azrpl._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0yvyp5b7jmlc4._.js +1 -1
  91. package/.next/standalone/.next/server/chunks/[root-of-the-server]__145vo_drnuvas._.js +1 -1
  92. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1lh8c0mmhdrbj._.js +1 -1
  93. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1oclamblhzhrf._.js +7 -7
  94. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1qjnp3fa0e5g3._.js +3 -0
  95. package/.next/standalone/.next/server/chunks/[turbopack]_runtime.js +7 -9
  96. package/.next/standalone/.next/server/chunks/_02sa8fcu9_9xo._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/_09dz7xva4ce_2._.js +18 -18
  98. package/.next/standalone/.next/server/chunks/_0hf5q4xzyg40j._.js +1 -1
  99. package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
  100. package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
  101. package/.next/standalone/.next/server/chunks/_1-2owkp-1_987._.js +1 -1
  102. package/.next/standalone/.next/server/chunks/_13ltj8a9z92o8._.js +1 -1
  103. package/.next/standalone/.next/server/chunks/_15k37au70vjvg._.js +1 -1
  104. package/.next/standalone/.next/server/chunks/_18rfu4__wjhwb._.js +1 -1
  105. package/.next/standalone/.next/server/chunks/_19011-u44143j._.js +1 -1
  106. package/.next/standalone/.next/server/chunks/_1ek68lnh2daur._.js +2 -2
  107. package/.next/standalone/.next/server/chunks/_1fz8m31sndkcu._.js +1 -1
  108. package/.next/standalone/.next/server/chunks/_1ogwigfb0163w._.js +1 -1
  109. package/.next/standalone/.next/server/chunks/_1vslkoe35wok6._.js +1 -1
  110. package/.next/standalone/.next/server/chunks/lib_11qmqmccehybz._.js +1 -1
  111. package/.next/standalone/.next/server/chunks/lib_1sezqnatvr8j-._.js +1 -1
  112. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oigsgz07._.js +1 -2
  113. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p77cu37y._.js +1 -2
  114. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
  115. package/.next/standalone/.next/server/chunks/src_hooks_0_em82s16zfym._.js +2 -2
  116. package/.next/standalone/.next/server/chunks/ssr/[externals]__0ilfh9mfnzsth._.js +3 -0
  117. package/.next/standalone/.next/server/chunks/ssr/[externals]__0ohnuzsaozaca._.js +3 -0
  118. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__097i34ct1o88x._.js → [externals]__12qr51qgrrt6o._.js} +2 -2
  119. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__021vebe-4il8s._.js +1 -1
  120. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
  121. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
  122. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0evgy902m9h5e._.js +1 -1
  123. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ezoipo-r7_5k._.js +14 -0
  124. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h1jw32uvrhh0._.js +1 -1
  125. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
  126. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
  127. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__10v5cyxvj64j4._.js → [root-of-the-server]__0tfnj3v_mp6rv._.js} +1 -1
  128. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-9s1nsw-5q8o._.js +1 -1
  129. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
  130. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15bi9em2xe0x2._.js +1 -1
  131. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
  132. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
  133. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
  134. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__20dt376-socef._.js → [root-of-the-server]__1e00l_e_8r_-g._.js} +1 -1
  135. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1mc9-zlnh656_._.js +1 -1
  136. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1ob2uzmms1adf._.js +1 -1
  137. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
  138. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0ed1zh4scn7-k._.js → [root-of-the-server]__1tq3x9i_3_860._.js} +1 -1
  139. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1utel1l1-u64v._.js +3 -0
  140. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vofkb2oq7p7e._.js +1 -1
  141. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1vxwetblyf8vp._.js +1 -1
  142. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1xwr4hi-on27i._.js +3 -0
  143. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__2158020r_amn9._.js +1 -1
  144. package/.next/standalone/.next/server/chunks/ssr/[turbopack]_runtime.js +7 -9
  145. package/.next/standalone/.next/server/chunks/ssr/_0-f9uotv7v2n9._.js +1 -1
  146. package/.next/standalone/.next/server/chunks/ssr/_00e4_rvim31u_._.js +1 -1
  147. package/.next/standalone/.next/server/chunks/ssr/_0bseae9u7g98r._.js +1 -1
  148. package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +2 -2
  149. package/.next/standalone/.next/server/chunks/ssr/_0kqw2_f1ywmpo._.js +1 -1
  150. package/.next/standalone/.next/server/chunks/ssr/_0mouhaflye1ro._.js +1 -1
  151. package/.next/standalone/.next/server/chunks/ssr/_0ouu886szh6yj._.js +10 -10
  152. package/.next/standalone/.next/server/chunks/ssr/_0p1cb69sml__f._.js +3 -0
  153. package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
  154. package/.next/standalone/.next/server/chunks/ssr/_0tfqha481f033._.js +2 -2
  155. package/.next/standalone/.next/server/chunks/ssr/_1_ozgifqv1ssi._.js +1 -1
  156. package/.next/standalone/.next/server/chunks/ssr/_1a516zcgtqius._.js +1 -1
  157. package/.next/standalone/.next/server/chunks/ssr/_1ddpc5gj57uuf._.js +1 -1
  158. package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
  159. package/.next/standalone/.next/server/chunks/ssr/_1ew6ra24vt-ij._.js +1 -1
  160. package/.next/standalone/.next/server/chunks/ssr/_1or8gixmrpv5i._.js +1 -1
  161. package/.next/standalone/.next/server/chunks/ssr/_1s8zk-upxzp00._.js +1 -1
  162. package/.next/standalone/.next/server/chunks/ssr/_1u9tpla2o6utw._.js +1 -1
  163. package/.next/standalone/.next/server/chunks/ssr/_1v4_ul3sj2lq_._.js +1 -1
  164. package/.next/standalone/.next/server/chunks/ssr/_1y3xzro8ca8t6._.js +1 -1
  165. package/.next/standalone/.next/server/chunks/ssr/_20hn4gn87nsjc._.js +1 -1
  166. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +2 -2
  167. package/.next/standalone/.next/server/chunks/ssr/app_087bt9wus25zs._.js +1 -1
  168. package/.next/standalone/.next/server/chunks/ssr/app_0trz6ik19xz5_._.js +1 -1
  169. package/.next/standalone/.next/server/chunks/ssr/app_1fvisnppn1unv._.js +1 -1
  170. package/.next/standalone/.next/server/chunks/ssr/app_209u41o446my6._.js +1 -1
  171. package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
  172. package/.next/standalone/.next/server/chunks/ssr/app_audit_0hku_y73ischw._.js +1 -1
  173. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
  174. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
  175. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
  176. package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
  177. package/.next/standalone/.next/server/chunks/ssr/lib_16jvhmthj_k3a._.js +1 -1
  178. package/.next/standalone/.next/server/chunks/ssr/node_modules_05vgn62--7c5e._.js +1 -1
  179. package/.next/standalone/.next/server/chunks/ssr/node_modules_0dad4au22rq0p._.js +1 -1
  180. package/.next/standalone/.next/server/chunks/ssr/node_modules_0gxlxpuufujz9._.js +2 -2
  181. package/.next/standalone/.next/server/chunks/ssr/node_modules_0ptcnmeaxvd_a._.js +2 -2
  182. package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_1cmkmhnty0-x7.js → node_modules_html-to-image_es_index_0r9i9nq3-ei-l.js} +1 -1
  183. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_0bz67659f5z-3._.js +4 -4
  184. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0-amwqbrge23p._.js +6 -0
  185. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0ocrceo0c9psx._.js +4 -4
  186. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1alv566ojmz5j._.js +4 -4
  187. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1et9oq9q9-y3v._.js +1 -1
  188. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_1khq67j4vo9y4._.js +1 -1
  189. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_client_components_0wpq8j32_ibz4._.js +1 -1
  190. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_shared_lib_0ftnv26hg1lry._.js +1 -1
  191. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_0dagmbznysrc2._.js +1 -1
  192. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js +1 -2
  193. package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
  194. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0-q0ummbuhlg5._.js +1 -1
  195. package/.next/standalone/.next/server/chunks/ssr/src_hooks_06kzv9ddabn3_._.js +2 -2
  196. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0agdmptetetdt._.js +2 -2
  197. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0g194syq7r7ql._.js +1 -1
  198. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0mdwgjisv4fub._.js +2 -2
  199. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1cv9_c4l1tzrm._.js +2 -2
  200. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1kx9e0dx_1-8o._.js +1 -1
  201. package/.next/standalone/.next/server/middleware-build-manifest.js +44 -44
  202. package/.next/standalone/.next/server/pages/404.html +1 -1
  203. package/.next/standalone/.next/server/pages/500.html +1 -1
  204. package/.next/standalone/.next/server/preview-props.json +3 -3
  205. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  206. package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
  207. package/.next/standalone/.next/static/chunks/0tiuj32d-qcy3.js +1 -0
  208. package/.next/standalone/.next/static/chunks/0ztuix-ip2oiv.js +1 -0
  209. package/.next/standalone/.next/static/chunks/{40g_e46c1-j4k.js → 107jrtkeylnrv.js} +1 -1
  210. package/.next/standalone/.next/static/chunks/110hwwc6agsr8.js +1 -0
  211. package/.next/standalone/.next/static/chunks/19e9khxgv8fb8.js +1 -0
  212. package/.next/standalone/.next/static/chunks/1dudxmlwx2n3q.js +1 -0
  213. package/.next/standalone/.next/static/chunks/1i9zuw01f0ogt.js +22 -0
  214. package/.next/standalone/.next/static/chunks/2codb6nb412m9.js +1 -0
  215. package/.next/standalone/.next/static/chunks/2hqfk_jgesiw2.js +1 -0
  216. package/.next/standalone/.next/static/chunks/2k6xp6kdy7lmd.js +1 -0
  217. package/.next/standalone/.next/static/chunks/2maurwweshrsj.js +1 -0
  218. package/.next/standalone/.next/static/chunks/2wh64znsc_mo2.js +1 -0
  219. package/.next/standalone/.next/static/chunks/2wye36b3mbzpa.js +31 -0
  220. package/.next/standalone/.next/static/chunks/{0mm-e5t9denbu.js → 2zlfhyqvlvf7o.js} +1 -1
  221. package/.next/standalone/.next/static/chunks/3hk5y4kny2ktd.js +1 -0
  222. package/.next/standalone/.next/static/chunks/3i_9ugyh1q1o1.js +1 -0
  223. package/.next/standalone/.next/static/chunks/3o30fiw7llng3.js +1 -0
  224. package/.next/standalone/.next/static/chunks/3v49ogp389dun.js +1 -0
  225. package/.next/standalone/.next/static/chunks/41ujrab732qi3.css +2 -0
  226. package/.next/standalone/.next/static/chunks/435eshlryosz1.js +1 -0
  227. package/.next/standalone/.next/static/chunks/436g_rqa42mr7.js +1 -0
  228. package/.next/standalone/.next/static/chunks/436nql0jk__xy.js +1 -0
  229. package/.next/standalone/.next/static/chunks/{turbopack-3-ry682tkyiqk.js → turbopack-2u1d16houkiyo.js} +1 -1
  230. package/.next/standalone/SECURITY.md +19 -4
  231. package/.next/standalone/fp-cloud-cli/CHANGELOG.md +13 -3
  232. package/.next/standalone/fp-cloud-cli/README.md +14 -7
  233. package/.next/standalone/fp-cloud-cli/fp_cli/_version.py +1 -1
  234. package/.next/standalone/fp-cloud-cli/fp_cli/app.py +2 -8
  235. package/.next/standalone/fp-cloud-cli/fp_cli/auth.py +325 -3
  236. package/.next/standalone/fp-cloud-cli/fp_cli/cloud_output.py +3 -3
  237. package/.next/standalone/fp-cloud-cli/fp_cli/commands/account_cmds.py +1 -11
  238. package/.next/standalone/fp-cloud-cli/fp_cli/commands/auth_cmds.py +218 -51
  239. package/.next/standalone/fp-cloud-cli/fp_cli/commands/orgs_cmds.py +1 -1
  240. package/.next/standalone/fp-cloud-cli/fp_cli/output.py +112 -135
  241. package/.next/standalone/fp-cloud-cli/fp_cli/permissions.py +10 -1
  242. package/.next/standalone/fp-cloud-cli/fp_cli/select.py +85 -6
  243. package/.next/standalone/fp-cloud-cli/fp_cli/theme.py +21 -21
  244. package/.next/standalone/fp-cloud-cli/pyproject.toml +1 -1
  245. package/.next/standalone/fp-cloud-cli/skill/SKILL.md +4 -4
  246. package/.next/standalone/fp-cloud-cli/skill/references/commands.md +4 -4
  247. package/.next/standalone/fp-cloud-cli/tests/fake_cloud_smoke.py +2 -2
  248. package/.next/standalone/fp-cloud-cli/tests/test_browser_login.py +943 -0
  249. package/.next/standalone/fp-cloud-cli/tests/test_cloud_account.py +0 -2
  250. package/.next/standalone/fp-cloud-cli/tests/test_cloud_agent.py +4 -8
  251. package/.next/standalone/fp-cloud-cli/tests/test_cloud_human_views.py +0 -4
  252. package/.next/standalone/fp-cloud-cli/tests/test_commands.py +3 -3
  253. package/.next/standalone/fp-cloud-cli/tests/test_dashboards_agent.py +3 -3
  254. package/.next/standalone/fp-cloud-cli/tests/test_facets.py +1 -1
  255. package/.next/standalone/fp-cloud-cli/tests/test_keys_queries.py +19 -2
  256. package/.next/standalone/fp-cloud-cli/tests/test_operator.py +1 -1
  257. package/.next/standalone/fp-cloud-cli/tests/test_orgs.py +1 -1
  258. package/.next/standalone/fp-cloud-cli/tests/test_output.py +19 -19
  259. package/.next/standalone/fp-cloud-cli/tests/test_round4_behaviour.py +3 -2
  260. package/.next/standalone/fp-cloud-cli/tests/test_screen_language.py +86 -25
  261. package/.next/standalone/fp-cloud-cli/tests/test_whoami.py +1 -1
  262. package/.next/standalone/fp-cloud-cli/uv.lock +200 -13
  263. package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
  264. package/.next/standalone/node_modules/@next/env/package.json +1 -1
  265. package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
  266. package/.next/standalone/node_modules/next/dist/compiled/fast-jwt/index.js +3 -0
  267. package/.next/standalone/node_modules/next/dist/compiled/fast-jwt/package.json +1 -0
  268. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +23 -23
  269. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +23 -23
  270. package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +1 -1
  271. package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +7 -7
  272. package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
  273. package/.next/standalone/node_modules/next/dist/server/api-utils/node/api-resolver.js +8 -5
  274. package/.next/standalone/node_modules/next/dist/server/api-utils/node/try-get-preview-data.js +8 -2
  275. package/.next/standalone/node_modules/next/dist/server/app-render/app-render.js +52 -14
  276. package/.next/standalone/node_modules/next/dist/server/app-render/async-local-storage.js +1 -1
  277. package/.next/standalone/node_modules/next/dist/server/app-render/get-script-nonce-from-header.js +19 -3
  278. package/.next/standalone/node_modules/next/dist/server/app-render/turbopack-bootstrap-script.js +50 -0
  279. package/.next/standalone/node_modules/next/dist/server/base-server.js +8 -0
  280. package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
  281. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +59 -10
  282. package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
  283. package/.next/standalone/node_modules/next/dist/server/dev/turbopack-utils.js +15 -0
  284. package/.next/standalone/node_modules/next/dist/server/image-optimizer/detect-content-type.js +24 -20
  285. package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
  286. package/.next/standalone/node_modules/next/dist/server/lib/dev-bundler-service.js +3 -0
  287. package/.next/standalone/node_modules/next/dist/server/lib/router-server.js +1 -1
  288. package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
  289. package/.next/standalone/node_modules/next/dist/server/lib/trace/tracer.js +1 -1
  290. package/.next/standalone/node_modules/next/dist/server/next-server.js +10 -2
  291. package/.next/standalone/node_modules/next/dist/server/render.js +2 -2
  292. package/.next/standalone/node_modules/next/dist/server/route-modules/app-page/parse-request-headers.js +1 -2
  293. package/.next/standalone/node_modules/next/dist/server/send-response.js +12 -0
  294. package/.next/standalone/node_modules/next/dist/server/use-cache/use-cache-wrapper.js +69 -6
  295. package/.next/standalone/node_modules/next/dist/server/web/adapter.js +5 -1
  296. package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
  297. package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
  298. package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
  299. package/.next/standalone/node_modules/next/package.json +10 -10
  300. package/.next/standalone/package.json +11 -11
  301. package/.next/standalone/sdk/python/skill/SKILL.md +5 -0
  302. package/.next/standalone/sdk/python/uv.lock +79 -47
  303. package/.next/standalone/sdk/typescript/CHANGELOG.md +48 -5
  304. package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package-lock.json +0 -9
  305. package/.next/standalone/sdk/typescript/integration/fixtures/langchain-dup-core/package.json +2 -1
  306. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package-lock.json +72 -44
  307. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.11/package.json +2 -1
  308. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package-lock.json +72 -44
  309. package/.next/standalone/sdk/typescript/integration/fixtures/llamaindex-0.12/package.json +3 -0
  310. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package-lock.json +18 -332
  311. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-0/package.json +4 -2
  312. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package-lock.json +925 -296
  313. package/.next/standalone/sdk/typescript/integration/fixtures/mastra-1/package.json +3 -8
  314. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package-lock.json +279 -277
  315. package/.next/standalone/sdk/typescript/integration/fixtures/nextjs/package.json +2 -2
  316. package/.next/standalone/server.js +1 -1
  317. package/dist/cli.mjs +22 -12
  318. package/dist/worker.mjs +1 -1
  319. package/hermes-plugin/plugin.yaml +1 -1
  320. package/package.json +11 -11
  321. package/src/hooks/delivery-health.ts +11 -1
  322. package/.next/standalone/.next/server/chunks/[root-of-the-server]__038kwryp970nh._.js +0 -3
  323. package/.next/standalone/.next/server/chunks/[root-of-the-server]__08atcie7jzswm._.js +0 -3
  324. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0car70pylmvor._.js +0 -3
  325. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1j6kfp0vzu5rw._.js +0 -3
  326. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1l0ayum_hqqsw._.js +0 -3
  327. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1o9rznwc0w7og._.js +0 -3
  328. package/.next/standalone/.next/server/chunks/[root-of-the-server]__1v1-l-83czzsr._.js +0 -63
  329. package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_0oo58a7rymoxh.js +0 -3
  330. package/.next/standalone/.next/server/chunks/node_modules_@opentelemetry_api_build_esm_index_1jp9ij0_ddtgk.js +0 -3
  331. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__075uro8t92s0_._.js +0 -14
  332. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0alpzjn3450sr._.js +0 -3
  333. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0aup10z2o8zc1._.js +0 -3
  334. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bioghlkjf7s7._.js +0 -3
  335. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0nhm28v58ty9z._.js +0 -3
  336. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0vse4qi496ol-._.js +0 -3
  337. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__190xwrr5zrfi3._.js +0 -3
  338. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1guwlpkyurdn9._.js +0 -3
  339. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1jq2bh84rafc7._.js +0 -3
  340. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1k96jctukf65_._.js +0 -3
  341. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1sj-wn2jp6va5._.js +0 -3
  342. package/.next/standalone/.next/server/chunks/ssr/_100nvr7rei3us._.js +0 -3
  343. package/.next/standalone/.next/server/chunks/ssr/node_modules_@opentelemetry_api_build_esm_index_0ntwr8lzj6p2i.js +0 -3
  344. package/.next/standalone/.next/server/chunks/ssr/node_modules_next_dist_0janj0i6dqko7._.js +0 -6
  345. package/.next/standalone/.next/static/chunks/0rucj5pu307i4.js +0 -1
  346. package/.next/standalone/.next/static/chunks/1-0se0uwja_ny.js +0 -1
  347. package/.next/standalone/.next/static/chunks/1024g0jaymm46.js +0 -1
  348. package/.next/standalone/.next/static/chunks/165ezyyx0j1ft.js +0 -22
  349. package/.next/standalone/.next/static/chunks/173vw1xs-5m5g.js +0 -1
  350. package/.next/standalone/.next/static/chunks/20cme7d6wv6md.js +0 -1
  351. package/.next/standalone/.next/static/chunks/26c4gmdpsthv6.css +0 -2
  352. package/.next/standalone/.next/static/chunks/2_sj5ssr_m_wm.js +0 -1
  353. package/.next/standalone/.next/static/chunks/2mz-k_jt_76xt.js +0 -1
  354. package/.next/standalone/.next/static/chunks/2ojf3r8g4tn7s.js +0 -1
  355. package/.next/standalone/.next/static/chunks/2tjfp9dirxnku.js +0 -1
  356. package/.next/standalone/.next/static/chunks/2u1m0f-wnhz44.js +0 -1
  357. package/.next/standalone/.next/static/chunks/2ytnb83xmjn3u.js +0 -1
  358. package/.next/standalone/.next/static/chunks/2zyrjasvbmwpq.js +0 -1
  359. package/.next/standalone/.next/static/chunks/31fan-ze541d1.js +0 -1
  360. package/.next/standalone/.next/static/chunks/32s3y34p0t2pe.js +0 -1
  361. package/.next/standalone/.next/static/chunks/36re0fegaocq-.js +0 -1
  362. package/.next/standalone/.next/static/chunks/3fhk60ouw_ae6.js +0 -1
  363. package/.next/standalone/.next/static/chunks/3xgxl1s_in776.js +0 -31
  364. package/.next/standalone/.next/static/chunks/44yz8zx53euy1.js +0 -1
  365. package/.next/standalone/node_modules/next/dist/compiled/jsonwebtoken/index.js +0 -11
  366. package/.next/standalone/node_modules/next/dist/compiled/jsonwebtoken/package.json +0 -1
  367. package/.next/standalone/node_modules/next/dist/lib/semver-noop.js +0 -18
  368. /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -iBiSmrLiylRKLAg77zlQ}/_buildManifest.js +0 -0
  369. /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -iBiSmrLiylRKLAg77zlQ}/_clientMiddlewareManifest.js +0 -0
  370. /package/.next/standalone/.next/static/{4MgI0mZP1iVhhocpUivMm → -iBiSmrLiylRKLAg77zlQ}/_ssgManifest.js +0 -0
@@ -1,4 +1,3 @@
1
- module.exports=[74493,a=>{"use strict";let b,c,d,e,f,g,h;var i,j=a.i(14747);function k(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var l=((i={}).AnonymousId="anonymous_id",i.DistinctId="distinct_id",i.Props="props",i.EnablePersonProcessing="enable_person_processing",i.PersonMode="person_mode",i.FeatureFlagDetails="feature_flag_details",i.FeatureFlags="feature_flags",i.FeatureFlagPayloads="feature_flag_payloads",i.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",i.BootstrapFeatureFlags="bootstrap_feature_flags",i.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",i.OverrideFeatureFlags="override_feature_flags",i.Queue="queue",i.AiQueue="ai_queue",i.AiCaptureQueue="ai_capture_queue",i.LogsQueue="logs_queue",i.OptedOut="opted_out",i.SessionId="session_id",i.SessionStartTimestamp="session_start_timestamp",i.SessionLastTimestamp="session_timestamp",i.PersonProperties="person_properties",i.GroupProperties="group_properties",i.InstalledAppBuild="installed_app_build",i.InstalledAppVersion="installed_app_version",i.SessionReplay="session_replay",i.PushRegistered="push_registered",i.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",i.SurveyLastSeenDate="survey_last_seen_date",i.SurveysInProgress="surveys_in_progress",i.SurveysSeen="surveys_seen",i.Surveys="surveys",i.RemoteConfig="remote_config",i.FlagsEndpointWasHit="flags_endpoint_was_hit",i.DeviceId="device_id",i);let m={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:a=>`api_error_${a}`};function n(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let o=Array.isArray,p=Object.prototype;p.hasOwnProperty;let q=p.toString,r=o||function(a){return"[object Array]"===q.call(a)},s=a=>a===Object(a)&&!r(a),t=a=>void 0===a,u=a=>"[object String]"==q.call(a),v=a=>u(a)&&0===a.trim().length,w=a=>null===a,x=a=>t(a)||w(a),y=a=>"[object Number]"==q.call(a)&&a==a;function z(a){return null===a||"object"!=typeof a}function A(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function B(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return D(a,Error)}}function C(a){return"u">typeof Event&&D(a,Event)}function D(a,b){try{return a instanceof b}catch{return!1}}let E="Android",F="BlackBerry",G="Nintendo",H="PlayStation",I="Xbox",J="Windows",K="(\\d+(\\.\\d+)?)";RegExp("Version/"+K),RegExp("(Claude|Codex|ChatGPT)\\/"+K),RegExp(I,"i"),RegExp(H+" \\w+","i"),RegExp(G+" \\w+","i"),RegExp(F+"|PlayBook|BB10","i");RegExp("rv:"+K),RegExp("Edge?\\/"+K),RegExp("(Chrome|CrMo)\\/"+K),RegExp("CriOS\\/"+K),RegExp("(UCBrowser|UCWEB)\\/"+K),RegExp("(Opera|OPR)\\/"+K),RegExp("Firefox\\/"+K),RegExp("FxiOS\\/"+K),RegExp("Konqueror[:/]?"+K,"i"),RegExp(F+" "+K),RegExp("android\\s"+K,"i"),RegExp("SamsungBrowser\\/"+K),RegExp("OculusBrowser\\/"+K),RegExp("Vivaldi\\/"+K),RegExp("YaBrowser\\/"+K),RegExp("Whale\\/"+K),RegExp("Brave\\/"+K),RegExp("(DuckDuckGo|Ddg)\\/"+K),RegExp("PaleMoon\\/"+K),RegExp("Waterfox\\/"+K),RegExp("GSA\\/"+K),RegExp("(rv:|MSIE )"+K),RegExp("rv:"+K),RegExp(I+"; "+I+" (.*?)[);]","i"),RegExp(G,"i"),RegExp(H,"i"),RegExp(J,"i"),RegExp("("+E+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+E+")","i");let L=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function M(a,b){return"string"==typeof a&&L.test(a)?a:b()}function N(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function O(a){return a?a.split("#")[0]:a}async function P(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function Q(){return new Date().toISOString()}function R(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function S(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=R(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function T(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}function U(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class V{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&r(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let f=globalThis._posthogChunkIds,g=globalThis._debugIds;if(!f&&!g)return;let h=f?Object.keys(f):[],i=g?Object.keys(g):[];if(e&&U(f,h,c)&&U(g,i,d))return e;c=f?{...f}:void 0,d=g?{...g}:void 0,e={},b??={};let j=(c,d)=>{for(let f of c){let c=d[f];if(!c)continue;let g=b?.[f];if(g){e[g]=c;continue}let h=a(f);for(let a=h.length-1;a>=0;a--){let d=h[a]?.filename;if(d){e[d]=c,b[f]=d;break}}}};return g&&j(i,g),f&&j(h,f),e}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(B(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return r(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,V],39564);let W=/^([a-z][a-z0-9.+-]+):/i,X=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function Y(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=W.exec(a);return!b||X.includes(b[1].toLowerCase())}(b)};return t(d)||(f.lineno=d),t(e)||(f.colno=e),f}let Z=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},$=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,_=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,aa=/\((\S*)(?::(\d+))(?::(\d+))\)/,ab=(a,b)=>{let c=$.exec(a);if(c){let[,a,d,e]=c;return Y(b,a,"?",+d,+e)}let d=_.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=aa.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=Z(d[1]||"?",d[2]);return Y(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},ac=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ad=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ae=(a,b)=>{let c=ac.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=ad.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=Z(d,a),Y(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},af=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ag=(a,b)=>{let c=af.exec(a);return c?Y(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ah=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,ai=(a,b)=>{let c=ah.exec(a);return c?Y(b,c[2],c[3]||"?",+c[1]):void 0},aj=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ak=(a,b)=>{let c=aj.exec(a);return c?Y(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},al=/^\s*[-]{4,}$/,am=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,an=/^Promise\.(?:all|any)$/,ao=/^index \d+$/,ap=(a,b)=>{let c=a.match(am);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),an.test(e)&&ao.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:aq(c[3]),colno:aq(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(al))return{filename:a,platform:b}};function aq(a){return parseInt(a||"",10)||void 0}let ar=/\(error: (.*)\)/;function as(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function at(a,b){let c=b.start;for(;c>0&&as(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function au(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&as(a[d],a[d-b.length]);)d++;return d-c}function av(a){if(!a.length)return[];let b=Array.from(a);return b.reverse(),b.slice(0,50).map(a=>{var c;return{...a,filename:a.filename||((c=b)[c.length-1]||{}).filename,function:a.function||"?"}})}function aw(){return ax("web:javascript",ab,ae)}function ax(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=ar.test(d)?d.replace(ar,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!as(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?at(a,c):0);for(let c of b)d-=au(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=at(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=au(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);return h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e),av(e)}}class ay{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=u(a.stack);return{type:this.getType(a),value:this.getValue(a),stack:c?a.stack:void 0,cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}getType(a){return this.isDOMError(a)?"DOMError":"DOMException"}getValue(a){let b=a.name||(this.isDOMError(a)?"DOMError":"DOMException");return a.message?`${b}: ${a.message}`:b}isDOMException(a){return A(a,"DOMException")}isDOMError(a){return A(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,ay],51671);class az{match(a){return!!A(a,"ErrorEvent")&&(void 0!=a.error||this._hasUsableMessage(a))}coerce(a,b){if(void 0!=a.error)return b.apply(a.error);let c=b.apply(a.message);return{...c,stack:this._buildLocationStack(a)??c.stack,synthetic:!0}}_hasUsableMessage(a){return u(a.message)&&a.message.length>0}_buildLocationStack(a){let b=a.lineno??0,c=a.colno??0;if(u(a.filename)&&0!==a.filename.length&&0!==b)return`Error
2
- at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,az],75368);let aA=["fatal","error","warning","log","info","debug"];function aB(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";for(let a=c.length;a>0;a--){let d=c.slice(0,a).join(", ");if(!(d.length>b)){if(a===c.length)return d;return d.length<=b?d:`${d.slice(0,b)}...`}}return""}class aC{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(C(a))return a.constructor.name;let b="name"in a?a.name:void 0;return u(b)&&!v(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=aB(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return u(a)&&!v(a)&&aA.indexOf(a)>=0}getStack(a){try{if(u(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return u(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(B(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,aC],93874);class aD{match(a){return C(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${aB(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aD],46980);class aE{match(a){return z(a)}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,aE],28150);class aF{match(a){return A(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!C(a))return!1;try{let b=a.detail;return null!=b&&"object"==typeof b&&"reason"in b}catch{return!1}}coerce(a,b){let c=this.getUnhandledRejectionReason(a);return z(c)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(c)}`,stack:b.syntheticException?.stack,synthetic:!0}:b.apply(c)}getUnhandledRejectionReason(a){try{if("reason"in a)return a.reason;if("detail"in a&&null!=a.detail&&"object"==typeof a.detail&&"reason"in a.detail)return a.detail.reason}catch{}return a}}a.s(["PromiseRejectionEventCoercer",0,aF],98140);let aG={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aH=new Set([aG.MESSAGE,aG.TIMESTAMP]),aI={enabled:!0,max_bytes:32768};function aJ(a){return a?{enabled:a.enabled??aI.enabled,max_bytes:function(a,b){if(!y(a)||1/0===a||-1/0===a)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aI.max_bytes)}:{...aI}}function aK(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aH.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aL{constructor(a){this._entries=[],this._totalBytes=0,this._config=aJ(a)}setConfig(a){this._config=aJ(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=n(a)}catch{return}try{let a=JSON.parse(b);if(!s(a))return;let c=a[aG.MESSAGE],d=a[aG.TIMESTAMP];if(!u(c)||0===c.trim().length||!u(d)&&!y(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aM(b.json);c>this._config.max_bytes||(this._entries.push({step:b.step,bytes:c}),this._totalBytes+=c,this._trimToMaxBytes())}getAttachable(){return this._entries.map(a=>a.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 a=this._entries.shift();a&&(this._totalBytes-=a.bytes)}}}function aM(a){if("u">typeof TextEncoder)return new TextEncoder().encode(a).length;let b=encodeURIComponent(a),c=0;for(let a=0;a<b.length;a++)"%"===b[a]?(c+=1,a+=2):c+=1;return c}a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aI,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aG,"ExceptionStepsBuffer",0,aL,"getUtf8ByteLength",0,aM,"resolveExceptionStepsConfig",0,aJ,"stripReservedExceptionStepFields",0,aK],97383),a.i(39564),a.s(["chromeStackLineParser",0,ab,"createDefaultStackParser",0,aw,"createStackParser",0,ax,"geckoStackLineParser",0,ae,"nodeStackLineParser",0,ap,"opera10StackLineParser",0,ai,"opera11StackLineParser",0,ak,"reverseAndStripFrames",0,av,"winjsStackLineParser",0,ag],64583),a.i(64583),a.i(51671);class aN{match(a){return B(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,aN],10692),a.i(10692),a.i(75368);let aO=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aP{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(aO);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aP],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,ay,"ErrorCoercer",0,aN,"ErrorEventCoercer",0,az,"EventCoercer",0,aD,"ObjectCoercer",0,aC,"PrimitiveCoercer",0,aE,"PromiseRejectionEventCoercer",0,aF,"StringCoercer",0,aP],54253),a.i(54253);class aQ{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}function aR(){if("u">typeof process){let a=process.env.POSTHOG_RELEASE_ID?.trim();if(a)return a}let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s(["ReduceableCache",0,aQ],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,aR],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aI,"DOMExceptionCoercer",0,ay,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aG,"ErrorCoercer",0,aN,"ErrorEventCoercer",0,az,"ErrorPropertiesBuilder",0,V,"EventCoercer",0,aD,"ExceptionStepsBuffer",0,aL,"ObjectCoercer",0,aC,"PrimitiveCoercer",0,aE,"PromiseRejectionEventCoercer",0,aF,"ReduceableCache",0,aQ,"StringCoercer",0,aP,"chromeStackLineParser",0,ab,"createDefaultStackParser",0,aw,"createStackParser",0,ax,"geckoStackLineParser",0,ae,"getInjectedReleaseId",0,aR,"getUtf8ByteLength",0,aM,"nodeStackLineParser",0,ap,"opera10StackLineParser",0,ai,"opera11StackLineParser",0,ak,"resolveExceptionStepsConfig",0,aJ,"reverseAndStripFrames",0,av,"stripReservedExceptionStepFields",0,aK,"winjsStackLineParser",0,ag],60485);var aS=a.i(60485);let aT="0123456789abcdef";class aU{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aU(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aU(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aU(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aT.charAt(this.bytes[b]>>>4),a+=aT.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aT.charAt(this.bytes[b]>>>4),a+=aT.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aU(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aV{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aW()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aU.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 a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aU.ofInner(a)}}let aW=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aX=()=>aY().toString(),aY=()=>(f||(f=new aV)).generate();function aZ(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function a$(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function a_(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aX(),b]})}function a0(a,b){let c=a$(b),d=a.get(c);return d?a2(d.value):null}function a1(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function a2(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=r(b.$sesid)?b.$sesid[1]:void 0;return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof c?c:void 0,deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}let a3=a=>void 0===a?void 0:a.variant??a.enabled,a4=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},a5=["$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"],a6=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return a5.forEach(d),b.forEach(d),c};class a7{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let a8=a=>{throw N("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},a9=async(a,b)=>{a.size<18&&a8("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||a8("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(g)return g;g=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;g[a]=b>>>0}return g})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&a8("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&a8("invalid-size")};async function ba(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await a9(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}class bb{add(a){let b=aX(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let bc=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>bc(`${a} ${d}`,b,c)}};class bd{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class be extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(a,b=Date.now()){if("string"!=typeof a||!a)return;let c=a.trim(),d=/^\d+\s*,/.test(c)?c.slice(0,c.indexOf(",")).trim():c;if(/^\d+$/.test(d)){let a=1e3*Math.min(Number(d),300);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(d))return;let e=Date.parse(/^\w{3} \w{3} /.test(d)?d+" GMT":d)-b;if(Number.isFinite(e)&&!(e<=0))return Math.min(e,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 a=N("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=R(()=>{this._bodyReadTimedOut=!0;let a=N("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class bf extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bg(a){if(a instanceof be){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function bh(a){return a instanceof bf}function bi(a){if(a instanceof be)return 502===a.status||504===a.status;if(!(a instanceof bf))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bj(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function bk(a){return"object"==typeof a&&a instanceof be&&413===a.status}function bl(a){return a instanceof be?408===a.status||429===a.status||a.status>=500:bh(a)}function bm(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bn="default";class bo{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new V([new aN,new aC,new aP,new aE],aw())}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(a,b={}){var c;this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new bb,this._events=new a7,this._isInitialized=!1;let d="string"==typeof a?a.trim():"",e="string"==typeof b.host?b.host.trim():"",f=!d;this._logger=function(a,b=a=>a()){return bc(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),f&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=d,this.host=(c=e||"https://us.i.posthog.com",c?.replace(/\/+$/,"")),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:bl},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||f,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.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)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(l.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(l.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(l.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c=this.mergeCommonEventProperties(b);var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=a6(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}mergeCommonEventProperties(a){return{...a,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.projectToken}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=`${this.host}/flags/?v=2${f?"&config=true":""}`,h={token:this.projectToken,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(h.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(h.evaluation_contexts=this.evaluationContexts);let i=this.getEvaluationRuntime();i&&(h.evaluation_runtime=i);let j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,j,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:bi},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,a3(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?a4(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,a4(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof be)return{type:"api_error",statusCode:a.status};if(a instanceof bf){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=a3(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.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"),i.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:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.projectToken}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(l.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(l.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(l.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return bn}persistedQueueKeyForRoute(a){return l.Queue}getActiveQueueRoutes(){return[bn]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=R(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){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(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=bm(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=M(e.uuid,aX),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:Q(),uuid:M(b?.uuid,aX)};return(b?.disableGeoip??this.disableGeoip)&&(bm(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await bg(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>T([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),T([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return ba(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bn){let d={api_key:this.projectToken,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:Q()};this.historicalMigration&&(d.historical_migration=!0);let e=n(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!bk(a)&&bl(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bk(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof bf||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=bj(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.projectToken)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.projectToken}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!bk(a)&&(!(a instanceof be)||void 0===a.retryAfterMs)&&bl(a)}),{kind:"ok"}}catch(a){if(bk(a))return{kind:"too-large"};if(bl(a)){let b=a instanceof be?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=bj(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await P(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=R(()=>{let a=N("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new bf(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new bf(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new be(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new bf(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof be&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return S((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof be||bh(a))))throw a;await bg(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=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(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let bp="[Circular]",bq="[Truncated]",br="[Unserializable]";function bs(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function bt(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=br}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bu=Object.prototype.propertyIsEnumerable;function bv(a,b){try{return bw(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bw(a,b,c,d){let e=[];for(let f in a)if(bu.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(w(g)||t(g))continue;e.push({key:bs(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bq};if(d.remainingNodes--,"[object Boolean]"===q.call(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:bs(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:bp};if(e>=20)return{stringValue:bq};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?bs(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(r(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(x(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:br})}return b.length>h&&f.push({stringValue:bq}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bw(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:bs(String(b))}}(g,b,c,d)})}catch{e.push({key:bs(f),value:{stringValue:br}})}}return e}function bx(a,b,c){return{...bt({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let by=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bz(a,b){let c=bt({},a),d={};for(let a of by)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bv(c,b),...bv(d,b)]}let bA={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 bB{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=R(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function bC(){return .75+.25*Math.random()*2}function bD(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}let bE="0000000000000000",bF=bE+bE,bG=/^[0-9a-f]+$/;function bH(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bI(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bG.test(a)}let bJ=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bK(a){let b=bL(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?bN:bO}}function bL(a){if("string"!=typeof a)return;let b=bJ.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bI(d,32,bF)&&bI(e,16,bE))return{version:c,traceId:d,spanId:e,flags:f}}function bM(a){return Array.isArray(a)&&1===a.length?a[0]:a}let bN="01",bO="00";function bP(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}let bQ=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bR(a){return String(a)+"000000"}function bS(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\0${b}\0${c??""}\0${e}`}class bT{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new bB(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new bd,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(a)}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(a){let b,c;if(this._instance.isDisabled||this._instance.optedOut)return;let d=this._runBeforeSend(a);if(null===d)return;if(!d.name||"string"!=typeof d.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof d.value||!Number.isFinite(d.value))return void this._logger.warn(`Dropping metric '${d.name}': value must be a finite number`);if("count"===d.type&&d.value<0)return void this._logger.warn(`Dropping count '${d.name}': counters are monotonic, value must be >= 0`);try{b=d.attributes?{...d.attributes}:void 0,c=bS(d.type,d.name,d.unit,b)}catch(a){this._logger.warn(`Dropping metric '${d.name}': attributes could not be serialized`,a);return}let e=this._series.get(c);if(!e){if(!this._admitNewSeries())return;e={name:d.name,type:d.type,unit:d.unit,attributes:b,windowStartMs:Date.now()},this._series.set(c,e)}let f=this._typeByName.get(d.name);void 0===f?this._typeByName.set(d.name,d.type):f===d.type||this._typeCollisionWarned.has(d.name)||(this._typeCollisionWarned.add(d.name),this._logger.warn(`Metric name '${d.name}' is already used as a ${f}; recording it as a ${d.type} too will blend both series in charts. Use a distinct name.`)),this._fold(e,d.value);let g=this._activeTraceContext();g&&(e.exemplar={...g,value:d.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let a=bK(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===bN)return{traceId:a.traceId,spanId:a.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(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{a.hist||(a.hist={count:0,sum:0,min:b,max:b,bucketCounts:Array(bQ.length+1).fill(0)});let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,bQ)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=r(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bD(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=bC()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),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:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bx(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bz(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bR(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bS(e.type,e.name,e.unit,void 0),f=c.get(a);f||(f={name:e.name,...e.unit&&{unit:e.unit}},"count"===e.type?f.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===e.type?f.gauge={dataPoints:[]}:f.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,f));let g=bv(e.attributes??{},this._logger),h=bR(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bR(d.timeMs),asDouble:d.value,traceId:d.traceId,spanId:d.spanId}]}:{};if("count"===e.type){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,asDouble:e.total??0,...i};f.sum.dataPoints.push(a)}else if("gauge"===e.type){let a={attributes:g,timeUnixNano:b,asDouble:e.last??0,...i};f.gauge.dataPoints.push(a)}else if(e.hist){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,count:e.hist.count,sum:e.hist.sum,min:e.hist.min,max:e.hist.max,bucketCounts:e.hist.bucketCounts,explicitBounds:bQ,...i};f.histogram.dataPoints.push(a)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.exemplar=a.exemplar??c.exemplar,a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":if(c.hist)if(a.hist){a.hist.count+=c.hist.count,a.hist.sum+=c.hist.sum,a.hist.min=Math.min(a.hist.min,c.hist.min),a.hist.max=Math.max(a.hist.max,c.hist.max);for(let b=0;b<a.hist.bucketCounts.length;b++)a.hist.bucketCounts[b]+=c.hist.bucketCounts[b]}else a.hist=c.hist}}}}let bU="unknown";function bV(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bU}"`),bU)}function bW(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bX(a,b,c,d){let e=bW(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bY(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bZ{constructor(a,b,c){for(let d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??bN,this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bY(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bY();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(x(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=b6(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bt({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&b7(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bV(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bX(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:b5(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=b9(a);return this.addEvent(b$,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bV(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=bN){return`00-${a}-${b}-${c}`}(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(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bX(a,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:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let b$="exception";function b_(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class b0{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 b1=new b0;class b2 extends b0{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function b3(a,b){var c;let d=bM(a?.parent)??b,e=bL(c="string"==typeof d||null==d?d:b4(d,"traceparent"))&&c.trim();return e?new b2(e,bP("string"==typeof d||null==d?a?.tracestate:b4(d,"tracestate"))):b1}function b4(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function b5(a,b){return a.length>b?a.slice(0,b):a}function b6(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return x(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?b5(b,c):b);if(d.ancestors.has(b))return bp;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return x(f.value)?String(f.value):a(f.value,c,d,e+1);if(r(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(br)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=br}f&&!x(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function b7(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=b6(a[h],c)}catch{d=br}x(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b8(a,b,c){return b===b1?c(b):a.with(b,()=>c(b))}function b9(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(B(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let ca={internal:1,server:2,client:3,producer:4,consumer:5},cb={ok:1,error:2};function cc(a){if("string"==typeof a)return bs(a);try{return bs(String(a))}catch{return br}}function cd(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function ce(){return bY()??Date.now()}function cf(a){try{return a instanceof bZ}catch{return!1}}function cg(a,b){let c=bK(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bP(b),traceFlags:c.flags,isRemote:!0}}function ch(a,b,c){a[b]!==c&&(a[b]=c)}class ci{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new bB(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new bd,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return b3(b,this._contextManager.active());let f=bM(b?.parent);if(f&&"string"!=typeof f&&!cf(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),b3(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);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`),b3(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bW(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.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"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bH(8);this._liveSpans.set(j,ce());let k=this._autoContextAttributes();return new bZ({traceId:g?.traceId??bH(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bV(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bt({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bW(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=b8(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}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(a,b){if("string"==typeof a){let c=cg(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(cf(a))return a.childContext();let c=this._contextManager.active();return cf(c)?c.childContext():c instanceof b2?cg(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bZ))return;let{type:c,message:d,stack:e}=b9(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=ce()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),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(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bV(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bW(j.startTime)??d.startTime,j.endTime=(l=bW(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bV(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bX(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!x(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:b6(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=b_(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=b7(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=b_(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=b_(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:b5(function(a){try{return"string"==typeof a?a:String(a)}catch{return br}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{ch(a,"traceId",b.traceId),ch(a,"spanId",b.spanId),ch(a,"parentSpanId",b.parentSpanId),ch(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),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(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:cc(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(ca,c)?ca[c]:ca.internal,startTimeUnixNano:cd(a.startTime),endTimeUnixNano:cd(a.endTime),flags:(Number.isFinite(d=parseInt(a.traceFlags,16))?255&d:1)|256|512*!!a.parentIsRemote};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=cc(a.traceState));let f=bv(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:cc(a.name),timeUnixNano:cd(a.timestamp)};if(a.attributes){let d=bv(a.attributes,b);d.length&&(c.attributes=d)}let d=b_(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=b_(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=b_(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:cb[a.status.code],...a.status.message&&{message:cc(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=b6(a[c],b);return a}((a=this._config,bx(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=ce()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bz(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=bC(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=ce()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).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(bD(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var cj=a.i(2157),ck=a.i(12714),cl=a.i(50227),cm=a.i(1457);let cn=new aS.ReduceableCache(25),co=new aS.ReduceableCache(20);async function cp(a,b=ck.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,cl.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=ct(a,d);if(void 0===f||co.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=cu(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=cu(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=cn.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(cn,f,{});i.push(cr(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=ct(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=cv(a);d<a;d++){let a=c[d];if(void 0===a)return void cs(b);b.pre_context.push(a)}if(void 0===c[a])return cs(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,cn,d),cn.reduce(),a}async function cq(a,b,c){let d,e=!1;try{d=await b(a,cj.constants.O_RDONLY|cj.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function cr(a,b,c,d,e,f){let g=await cq(a,e,f);return void 0===g?void co.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{co.set(d,1),i();return}try{f=(0,cm.createInterface)({input:e})}catch{co.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){co.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function cs(a){delete a.pre_context,delete a.context_line,delete a.post_context}function ct(a,b){return(0,cl.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function cu(a){return[cv(a),a+7]}function cv(a){return Math.max(1,a-7)}class cw{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let cx=["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"],cy=new Map,cz=function(a,b=[]){if(!a)return!1;let c=function(a,b){let c="";for(let a=0;a<b.length;a++){let d=b[a];c+=d.length+":"+d}return a.length+":"+a+"|"+b.length+":"+c}(a,b),d=cy.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=cx.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return cy.size>=256&&cy.clear(),cy.set(c,f),f};function cA(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cB=["service.name","service.version","deployment.environment"],cC={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"};a.s(["FeatureFlagError",0,cC],46539);class cD{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._unresolvedFlags=Object.freeze({...a.unresolvedFlags}),this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a),c?.enabled??b.defaultValue??!1}getFlag(a){let b=this._flags[a];if(this._recordAccess(a),b)return!!b.enabled&&(b.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new cD({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a){if(this._accessed.add(a),""===this._distinctId||this._isSlice&&!(a in this._flags))return;let b=this._flags[a],c=void 0===b?void 0:!1!==b.enabled&&(b.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:b?.id,$feature_flag_version:b?.version,$feature_flag_reason:b?.reason,locally_evaluated:b?.locallyEvaluated??!1,[`$feature/${a}`]:c,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:b?.locallyEvaluated?Date.now():this._evaluatedAt};b?.hasExperiment!==void 0&&(d.$feature_flag_has_experiment=b.hasExperiment),b?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(d.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let e=[];this._errorsWhileComputing&&e.push(cC.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(cC.QUOTA_LIMITED),void 0===b&&e.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,a)?cC.LOCAL_EVALUATION_INCONCLUSIVE:cC.FLAG_MISSING),e.length>0&&(d.$feature_flag_error=e.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:c,groups:this._groups,disableGeoip:this._disableGeoip,properties:d})}}let cE=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class cF extends Error{constructor(a,b="unsupported_definition"){super(a),this.name=this.constructor.name,this.reason=b,Object.setPrototypeOf(this,cF.prototype)}}function cG(a){try{return a()}catch(a){if(a instanceof cF)throw new cF(a.message,"missing_context");throw a}}function cH(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cH(b in a?a[b]:null))return!1;return!0}function cI(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cI(b in a?a[b]:null))return!1;return!0}function cJ(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cF("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cF("Cannot stringify an unpaired surrogate like the flags service")}}function cK(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cJ(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cF(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cF("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cK(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cF("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cF("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cJ(c),cK(a[c],b)}finally{b.delete(a)}return}throw new cF(`Cannot represent ${typeof a} like the flags service`)}}function cL(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function cM(a){return"string"==typeof a?(cJ(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cJ(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cF(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cF(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cF("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cF("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cF("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cJ),`{${d.sort(cL).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cF(`Cannot stringify ${typeof b} like the flags service`)}(a)}let cN=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function cO(a){let b=new cF(a);return Object.defineProperty(b,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),b}function cP(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cQ(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cF(`Invalid semver: ${b}`);return parseInt(a,10)}function cR(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cF(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cQ(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cS(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cT(a,b){let c=cR(a,b);return{lower:[c[0],c[1],c[2]],upper:[c[0],c[1]+1,0]}}function cU(a,b){let[c,d,e]=cR(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}function cV(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cF(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cQ(c,a,b)}catch{}throw new cF(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}function cW(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cF(`${a} is in an invalid date format`)}throw new cF(`The date provided ${a} must be a string, number, or date object`)}function cX(a){if("boolean"==typeof a)throw new cF("Date operations cannot be performed on boolean values");return function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e)c.setUTCMonth(c.getUTCMonth()-d);else{if("y"!==e)return null;c.setUTCFullYear(c.getUTCFullYear()-d)}return c}(String(a))??cW(a)}function cY(a,b={}){let c=a.value,d=b.semverParsingPolicy??"strict";switch(a.operator||"exact"){case"exact":case"is_not":for(let a of Array.isArray(c)?c:[c])cM(a);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":cX(c);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":cR(String(c),d);return;case"semver_tilde":cT(String(c),d);return;case"semver_caret":cU(String(c),d);return;case"semver_wildcard":cV(String(c),d);return;default:throw new cF(`Unknown operator: ${a.operator}`)}}async function cZ(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function c$(a,b,c="",d="."){return parseInt((await cZ(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function c_(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await c$("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function c0(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function c1(a,b,c){let d=await c$(a,b,"variant");return c0(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function c2(a){return"client"===a||"server"===a?a:"all"}class c3 extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,c3.prototype)}}class c4 extends Error{constructor(a){super(a),this.reason="unsupported_definition",this.name=c4.name,Error.captureStackTrace(this,c4),Object.setPrototypeOf(this,c4.prototype)}}let c5=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function c6(a,b){return void 0===a||c5.indexOf(b)<c5.indexOf(a)?b:a}function c7(a,b){return b instanceof cF&&Symbol.for("posthog.requiresServerRegexEvaluation")in b&&Object.defineProperty(a,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),a}class c8{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof c4||b instanceof cF?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e={},f=0==this.featureFlags.length,g=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,h=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(g.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,h,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof c4||b instanceof cF?(this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)),e[a.key]=b.reason):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),f=!0}})),{response:c,payloads:d,unresolved:e,fallbackToFlags:f}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:a4(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cF("Flag has experience continuity enabled","experience_continuity");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cF("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cF(`Can't compute feature flag: ${a.key} without $device_id`,c9(a,b.definitions)??"missing_context");return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cF("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cF(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cF(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cF(`Circular dependency detected for flag '${e}' (empty dependency chain)`);let g=f.find(a=>!(a in d)&&!c.definitions.featureFlagsByKey[a]&&!c.definitions.filteredOutFlagKeys.has(a));if(void 0!==g)throw new cF(`Missing flag dependency '${g}' for flag '${e}'`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){throw c7(new cF(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`,"unresolved_dependency"),b)}else d[a]=!1;else d[a]=!1}if(null==d[a])throw new cF(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let h=d[e];return this.flagEvaluatesToExpectedValue(a.value,h)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f,g;d=this.withEvaluationSnapshot(d);let h=a.filters||{},i=await c_(h.holdout,b);if(void 0!==i)return i;let j=h.groups||[],k=h.aggregation_group_type_index,l=h.early_exit??!1,{groups:m,groupProperties:n}=d,o=new Set;for(let i of j){let j=b;try{let b=void 0!==i.aggregation_group_type_index?i.aggregation_group_type_index:k,f=c;if(b!==k&&null!=b){let c=d.definitions.groupTypeMapping[String(b)];if(!c||!(c in m)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${b} not available`));continue}if(!(c in n)){e=c6(e,"missing_context");continue}f=n[c],j=m[c]}let o=await this.isConditionMatch(a,j,i,f,d);if("match"===o){let b=i.variant,c=h.multivariate?.variants||[];g=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,j)||!0;break}if(l&&"out_of_rollout_bound"===o){if(e)break;return!1}}catch(b){if(b instanceof c4)throw b;if(b instanceof cF){if(e=c6(e,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(f=b,l&&void 0!=i.rollout_percentage&&await c$(a.key,j)>i.rollout_percentage/100)o.add(!1);else{let b=h.multivariate?.variants||[],c=i.variant;o.add(c&&b.some(a=>a.key===c)?c:await this.getMatchingVariant(a,j)||!0)}}else throw b}}if(void 0!==g&&!(f&&[...o].some(a=>a!==g)))return g;if(e)throw c7(new cF("Can't determine if feature flag is enabled or not with given properties",e),f);return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){let b,i,j;for(let a of c.properties){let c=a.type,g=!1;try{if("cohort"===c){let b=await db(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);g="not_in"===a.operator?!b:b}else if("flag"===c)g=await this.evaluateFlagDependency(a,d,e);else if(Object.prototype.hasOwnProperty.call(d,a.key))g=da(a,d,h,f.propertyMatchingVersion);else{cY(a),b=c6(b,"missing_context");continue}}catch(a){if(a instanceof c4){void 0===b&&(j??=a),b=c6(b,a.reason);continue}if(a instanceof cF){Symbol.for("posthog.requiresServerRegexEvaluation")in a&&(i=a),b=c6(b,a.reason);continue}throw a}if(!g)return"no_match"}if(j)throw j;if(b)throw c7(new cF(`Can't determine if a condition of flag ${a.key} matches`,b),i);if(void 0==g)return"match"}return void 0!=g&&await c$(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return c1(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return c0(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?c2(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>{var c;return(c=c2(b.evaluation_runtime))===a||"all"===c||"all"===a}).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags),c=b.reduce((a,b)=>(a[b.key]=b,a),{}),d=new Set(b.map(a=>a.key)),e=new Set(a.flags.filter(a=>!d.has(a.key)).map(a=>a.key));this.featureFlags=b,this.featureFlagsByKey=c,this.filteredOutFlagKeys=e,this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(a){let b=[],c=[],d=new Map,e=this.currentDefinitions();for(let f of a){let a=c9(f,e);if(!a)continue;let g=JSON.stringify(f);d.set(f.key,g),this.warnedUnresolvableFlags.get(f.key)!==g&&("experience_continuity"===a?b.push(f.key):c.push(f.key))}if(this.warnedUnresolvableFlags=d,b.length>0){let a=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 ${b.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${b.join(", ")}. `+a)}if(c.length>0){let a=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 ${c.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): ${c.join(", ")}. ${a} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&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(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let a=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,a*2**this.backOffCount):a}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 a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new c3(`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 c3(`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 c3(`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 c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(a){a instanceof c3&&this.onError?.(a)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new c3("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=R(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await S(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function c9(a,b){if(!a.active)return;if(a.ensure_experience_continuity)return"experience_continuity";let c=a.filters||{},d=c.aggregation_group_type_index;return void 0==d||b.groupTypeMapping[String(d)]?(c.groups||[]).some(a=>(a.properties||[]).some(a=>(function a(b,c,d){if("flag"===b.type){let a=b.dependency_chain;return!Array.isArray(a)||0===a.length||a.some(a=>!c.featureFlagsByKey[a]&&!c.filteredOutFlagKeys.has(a))}if("cohort"!==b.type)try{return cY(b),!1}catch(a){if(a instanceof cF)return!0;throw a}let e=String(b.value);return!(e in c.cohorts)||!d.has(e)&&(d.add(e),function b(c,d,e){return(c?.values??[]).some(c=>"values"in c?b(c,d,e):a(c,d,e))}(c.cohorts[e],c,d))})(a,b,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function da(a,b,c,d){return function(a,b,c={}){try{return function(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cF(`Property ${d} not found in propertyValues`,"missing_context");let h=b[d];if(void 0===h)throw c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),new cF(`Property ${d} is undefined in propertyValues`);if(null===h&&!cE.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cH(a)||Array.isArray(a)&&0===a.length)return cG(()=>cK(b)),cI(a)===cI(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cH(a))return cG(()=>cK(b)),!1;if(Array.isArray(a)){let c=cG(()=>cM(b)).toLowerCase();return a.some(a=>cM(a).toLowerCase()===c)}return cM(a).toLowerCase()===cG(()=>cM(b)).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)},k=()=>cG(()=>cR(String(h),g)),l=()=>{let a=cR(String(e),g);return cS(k(),a)},m=({lower:a,upper:b})=>{let c=k();return cS(c,a)>=0&&0>cS(c,b)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cP(h).includes(cP(e));case"not_icontains":return!cP(h).includes(cP(e));case"starts_with":return cP(h).startsWith(cP(e));case"not_starts_with":return!cP(h).startsWith(cP(e));case"ends_with":return cP(h).endsWith(cP(e));case"not_ends_with":return!cP(h).endsWith(cP(e));case"regex":case"not_regex":{let a=function(a,b){let c;if(""===a)return!0;let d=function(a){let b=[],c=-1,d="";for(let e=0;e<a.length;e++){let f=a[e];if(f.charCodeAt(0)>127)return null;if("\\"===f){let b=a[++e];if(void 0===b)break;if("x"===b){if(!/^[\da-f]{2}$/i.test(a.slice(e+1,e+3)))return null;e+=2}else if(!"dDsSwWbBfnrtv".includes(b)&&!cN.test(b))return null;if(-1===c&&"bB".includes(b))return null;d="literal";continue}if("["===f){if(-1!==c)return null;c=e}else if("]"===f&&-1!==c){if(e===c+("^"===a[c+1]?2:1))return null;b.push(a.slice(c,e+1)),c=-1,d="literal";continue}else if(-1!==c){if(["&&","--","~~"].includes(a.slice(e,e+2)))return null;continue}else if("("===f&&"?"===a[e+1]){if(":"!==a[e+2])return null;e+=2}else if("{"===f){let b=/^\{(\d+)(?:,(\d*))?\}/.exec(a.slice(e));if(!b||["","|","("].includes(d)||b.slice(1).some(a=>Number(a)>0xffffffff))return null}else if("*+?}".includes(f)&&("+"===a[e+1]||"{"===a[e+1]))return null;if("*+?{".includes(f)&&["^","$","empty group"].includes(d))return null;d=")"===f&&["(","empty group"].includes(d)?"empty group":f}return b}(a);if(null===d)throw cO("Regex syntax requires server evaluation");try{c=new RegExp(a)}catch(a){if(a instanceof SyntaxError)return null;throw cO("Regex compilation requires server evaluation")}for(let a of d)try{RegExp(a,"u")}catch{throw cO("Regex character class syntax requires server evaluation")}for(let a=0;a<b.length;a++){let c=b[a];if(c.charCodeAt(0)>127||"\r"===c)throw cO("Regex matching for Unicode or carriage returns requires server evaluation")}try{return c.test(b)}catch{throw cO("Regex execution requires server evaluation")}}(String(e),String(h));if(null===a)return!1;return"regex"===f?a:!a}case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{let a=cX(e),b=cG(()=>cW(h));return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===l();case"semver_neq":return 0!==l();case"semver_gt":return l()>0;case"semver_gte":return l()>=0;case"semver_lt":return 0>l();case"semver_lte":return 0>=l();case"semver_tilde":return m(cT(String(e),g));case"semver_caret":return m(cU(String(e),g));case"semver_wildcard":return m(cV(String(e),g));default:throw new cF(`Unknown operator: ${f}`)}}(a,b,c)}catch(b){throw b instanceof cF&&"missing_context"===b.reason&&cY(a,c),b}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function db(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new c4(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);return dc(c[g],b,c,d,e,f)}async function dc(a,b,c,d=!1,e,f){let g,h;if(!a)return!0;let i=a.type,j=a.values;if(!j||0===j.length)return!0;if("values"in j[0]){for(let a of j)try{let g=await dc(a,b,c,d,e,f);if("AND"===i){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof c4)throw b;if(b instanceof cF)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c6(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c7(new cF("Can't match cohort without a given cohort property value",g),h);return"AND"===i}for(let a of j)try{let g;if("cohort"===a.type)g=await db(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cF(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=da(a,b,void 0,f);let h=a.negation||!1;if("AND"===i){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof c4)throw b;if(b instanceof cF)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=c6(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw c7(new cF("can't match cohort without a given cohort property value",g),h);return"AND"===i}let dd=["--unhandled-rejections","--unhandled_rejections"],de=new Set(["throw","strict","warn","warn-with-error-code","none"]),df=[...globalThis.process?.execArgv??[]],dg=globalThis.process?.env?.NODE_OPTIONS;function dh(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=dd.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);de.has(f)&&(b=f)}return b}let di=function(a=df,b=dg){return dh(a)??dh(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}();function dj(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function dk(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),y(a))if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),dk(e??c,b,c,d)}class dl{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=dk(a.bucketSize,0,100,a._logger),this._refillRate=dk(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=dk(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var dm=aS;let dn=class b{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new dl({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return s(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e){let f={...e},g=a.buildFromUnknown(b,c);g.$exception_list=await a.modifyFrames(g.$exception_list);let h=dm.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=di){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>dj(b,a,c));e.on("uncaughtException",(f=!1,Object.assign((d,e)=>{let g=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;dj(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=di){let c=globalThis.process;c&&"throw"!==b&&"strict"!==b&&"warn-with-error-code"!==b&&c.on("unhandledRejection",b=>{a(b,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(a,c){this.client.addPendingPromise((async()=>{if(!b.isPreviouslyCapturedError(a)){let d=await b.buildEventMessage(this.client.getErrorPropertiesBuilder(),a,c),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})())}async onFatalError(a){console.error(a),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}},dp=/^[0-9a-f]{32}$/i,dq=/^[0-9a-f]{16}$/i;async function dr(){try{let b=await (h??=a.A(38676)),c=b.trace.getActiveSpan()?.spanContext(),d=c?.traceId,e=c?.spanId;if("string"==typeof d&&"string"==typeof e&&dp.test(d)&&dq.test(e)&&!/^0+$/.test(d)&&!/^0+$/.test(e))return{$trace_id:d.toLowerCase(),$span_id:e.toLowerCase()}}catch{}return{}}class ds{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dt="analytics";class du extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(du.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function dv(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let dw=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dv},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dv},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dv},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dx=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function dy(a,b,c){void 0===c||b in a||(a[b]=c)}function dz(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of dw)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of dx)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,dy(c,"$set",a.$set),dy(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let dA=new Set([408,500,502,503,504]);class dB{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>R(b,a))),this.generateRequestId=b.generateRequestId??aX,this.compress=b.compress??ba}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(dz)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=n({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&dA.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new du({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=R(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new du({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new du({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let dC="ai-capture",dD="/i/v0/ai/batch/",dE=new TextEncoder;function dF(a){return dE.encode(n(a)).length}let dG=new Set;function dH(a,b){dG.has(a)||(dG.add(a),console.warn(`[PostHog] ${b}`))}class dI extends bo{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(a){this._distinctIdHasSentFlagCalls=new Map(Object.entries(a??{}))}constructor(a,b={}){var c,d;let e,f="string"==typeof a?a.trim():"",g={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:("string"==typeof(c=b.host)?c.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(d=b.secretKey??b.personalApiKey)?d.trim():"")||void 0};if(super(f,g),this._memoryStorage=new ds,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=g,this.captureMode="v0"===(e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===e?e:"v0",this.enableFullAiCapture=!0===g.enableFullAiCapture,this.privacyMode=!0===g.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof g.featureFlagsPollingInterval?Math.max(g.featureFlagsPollingInterval,100):null===g.featureFlagsPollingInterval?null:3e4,"number"==typeof g.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(g.waitUntilDebounceMs,0)),"number"==typeof g.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(g.waitUntilMaxWaitMs,0)),!this.disabled&&(g.personalApiKey||g.flagDefinitionCacheProvider)){if(g.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!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new c8({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:g.personalApiKey,projectApiKey:f,timeout:g.requestTimeout??1e4,host:this.host,fetch:g.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:g.flagDefinitionCacheProvider,strictLocalEvaluation:g.strictLocalEvaluation,evaluationContexts:g.evaluationContexts??g.evaluationEnvironments}))}this.errorTracking=new dn(this,g,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=g.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises();return!this._traces||a&&this._traces.throttled?b:T([b,this._traces.flush().catch(()=>{})]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=R(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":dt}persistedQueueKeyForRoute(a){return a===dC?l.AiCaptureQueue:"ai"===a?l.AiQueue:l.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dt,"ai"]:[dt];return this._aiCaptureRouteActive&&a.push(dC),a}getBatchEndpointPath(a){return a===dC?dD:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dt){if(c===dC)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=dF(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${dD}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,dC)}catch(d){if(!bk(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dF(b)} bytes) was rejected with 413 by ${dD} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new dB({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:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.57.1"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bT(this,(a=this.options.metrics,b=a?.resourceAttributes,{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new cw}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var a,b,c;let d,e;return this._traces||(this._traces=new ci(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=bt({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cB.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cB)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=cA(a?.maxExportBatchSize,512),{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:cA(a?.maxAttributesPerSpan,128),maxEventsPerSpan:cA(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:cA(a?.maxAttributeValueLength,8192),flushIntervalMs:cA(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(cA(a?.maxQueueSize,2048),e),maxLiveSpans:cA(a?.maxLiveSpans,1e4),maxSpanAgeMs:cA(a?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??b3(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):b8(this._spanContextManager,b3(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:f,options:g})=>{let h={timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid},i={distinctId:b,event:d,properties:{...f,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,i,h,e):this.enqueue(a,i,h,e)}).catch(a=>{a&&console.error(a)}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"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(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"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(a,!0)}captureAi(a){if(this.disabled)return;let b=M(a.uuid,aX);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=M(a.uuid,aX);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,dC)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l;if(this.disabled)return void this._logger.warn("The client is disabled");let m=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:n,disableGeoip:o}=c,{onlyEvaluateLocally:p,personProperties:q,groupProperties:r}=c,s=this.addLocalPersonAndGroupProperties(b,n,q,r);q=s.allPersonProperties,r=s.allGroupProperties;let t=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,q),r);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let u=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,t,{matchValue:d});if(c){u=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof c4||b instanceof cF)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!u&&!p){let b=await super.getFeatureFlagDetailsStateless(t.distinctId,t.groups,q,r,o,[a]);if(void 0===b)h=cC.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(cC.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(cC.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(cC.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code}}c.length>0&&(h=c.join(","))}}if(m){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:u,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),u&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:o,properties:d})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){dH("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(dH("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&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:e?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){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 b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){dH("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)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:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];let v={};for(let[a,b]of Object.entries(s?.unresolved??{}))Object.prototype.hasOwnProperty.call(p,a)||(v[a]=b);return new cD({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,unresolvedFlags:v,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",i=`${c}_${d}${h}`,j=this._distinctIdHasSentFlagCalls.get(b)??new Set;if(this._distinctIdHasSentFlagCalls.delete(b),this._distinctIdHasSentFlagCalls.set(b,j),!j.has(i)){for(j.add(i);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let a=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===a)break;this._distinctIdHasSentFlagCalls.delete(a)}this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f})}}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,b,c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b)}async _shutdown(a){let b=Date.now()+(a??3e4),c=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await S(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await S(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,b-Date.now()))}finally{this._distinctIdHasSentFlagCalls.clear(),c?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=R(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(A(f,"Object")&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!dn.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(dn.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!dn.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(dn.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){let{distinctId:c,event:d,properties:e,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k}=a,l=this.context?.get(),m=b.includeContextProperties??!0,n=c||l?.distinctId,o=m?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};"$exception"!==d||"$trace_id"in o||"$span_id"in o||Object.assign(o,await dr()),n||(n=aX(),o.$process_person_profile=!1),m&&l?.sessionId&&!o.$session_id&&(o.$session_id=l.sessionId);let p=this._shouldSendMinimalFlagCalledEvent(d,o)?a6(o):o,q=this._runBeforeSend({distinctId:n,event:d,properties:p,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!q)return Promise.reject(null);let r=await Promise.resolve().then(async()=>{if(g)return h&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),g._getEventProperties();if(h){dH("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 a=await this.getFeatureFlagsForEvent(q.distinctId,f,j,"object"==typeof h?h:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=q.groups||f;return{...a,...q.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===q.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof r.$raw_user_agent&&cz(r.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(q.event="$bot_pageview",r.$browser_type="bot"),{distinctId:q.distinctId,event:q.event,properties:r,options:{timestamp:q.timestamp,disableGeoip:q.disableGeoip,uuid:q.uuid}}}_runBeforeSend(a){let b=this.options.before_send;if(!b)return a;let c=Array.isArray(b)?b:[b],d=a;for(let b of c)try{if(!(d=b(d)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!d.properties||0===Object.keys(d.properties).length){let a=`Event '${d.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(b){return this._logger.error(`Error in before_send function for event '${a.event}':`,b),null}return d}}var dJ=a.i(78500);class dK{constructor(){this.storage=new dJ.AsyncLocalStorage}get(){return this.storage.getStore()}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){if(b?.fresh===!0)return a;let c=this.get()||{};return{distinctId:a.distinctId??c.distinctId,sessionId:a.sessionId??c.sessionId,properties:{...c.properties||{},...a.properties||{}}}}}class dL{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new dJ.AsyncLocalStorage}}var dM=a.i(27028);let dN=(0,a.i(12057).promisify)(dM.gzip);async function dO(a,b=!0){try{let b=await dN(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var dP=a.i(60526),dm=aS;let dQ="posthog-node";function dR(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[dT.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=dm.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function dS(a,b){let c=dR(a,b);return{name:dQ,processEvent:a=>c(a)}}class dT{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=dQ,this.name=dQ,this.setupOnce=function(f,g){f(dR(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,dT,"createEventProcessor",0,dR,"sentryIntegration",0,dS],9318);let dU=/[\x00-\x1f\x7f-\x9f]/g;function dV(a,b,c){null!=c&&""!==c&&(a[b]=c)}function dW(a){return Array.isArray(a)?a[0]:a}function dX(a){if(Array.isArray(a)){for(let b of a){let a=dX(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(dU,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function dY(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=dX(a["x-posthog-session-id"]),c=dX(a["x-posthog-distinct-id"]);return{...void 0!==b?{sessionId:b}:{},...void 0!==c?{distinctId:c}:{}}}(b.headers),h={},i=!0===a.options.disable_capture_url_hashes;return dV(h,"$current_url",(c=b.originalUrl||b.url,i?O(c):c)),dV(h,"$request_method",b.method),dV(h,"$request_path",(d=b.path,e=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),i?O(e):e)),dV(h,"$user_agent",dW(b.headers["user-agent"])),dV(h,"$ip",function(a){let b=dW(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{},properties:h}}function dZ(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(dY(c,a),()=>d())}))}function d$(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(dn.isPreviouslyCapturedError(a))return void e(a);let f=dY(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([dn.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,d$,"setupExpressRequestContext",0,dZ],40602),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,m,"FeatureFlagEvaluations",0,cD,"PostHogSentryIntegration",0,dT,"cookieStateToProperties",0,a1,"cookieStoreFromHeader",0,aZ,"createEventProcessor",0,dR,"getPostHogCookieName",0,a$,"parsePostHogCookie",0,a2,"readPostHogCookie",0,a0,"sentryIntegration",0,dS,"serializePostHogCookie",0,a_,"setupExpressErrorHandler",0,d$,"setupExpressRequestContext",0,dZ,"uuidv7",0,aX],80456),a.i(80456),a.s(["FeatureFlagError",0,m,"FeatureFlagEvaluations",0,cD,"PostHog",0,class extends dI{getLibraryId(){return"posthog-node"}compressPayload(a){return dO(a,this.isDebug)}initializeContext(){return new dK}initializeSpanContextManager(){return new dL}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,dP.platform)(),d=(0,dP.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bA,a)?bA[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new aS.ErrorPropertiesBuilder([new aS.EventCoercer,new aS.ErrorCoercer,new aS.ObjectCoercer,new aS.StringCoercer,new aS.PrimitiveCoercer],aS.createStackParser("node:javascript",aS.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,j.dirname)(process.argv[1]):process.cwd(),b="\\"===j.sep){let c=b?k(a):a;return a=>{if(!a)return;let d=b?k(a):a,{dir:e,base:f,ext:g}=j.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let h=decodeURIComponent(f);e||(e=".");let i=e.lastIndexOf("/node_modules");if(i>-1)return`${e.slice(i+14).replace(/\//g,".")}:${h}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${h}`:h}return h}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>cp(a,void 0,this._logger),function(a=process.cwd()){j.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,j.isAbsolute)(d.filename)&&(d.filename=b((0,j.relative)(c,b(d.filename))));return a}}()])}},"PostHogSentryIntegration",0,dT,"cookieStateToProperties",0,a1,"cookieStoreFromHeader",0,aZ,"createEventProcessor",0,dR,"getPostHogCookieName",0,a$,"parsePostHogCookie",0,a2,"readPostHogCookie",0,a0,"sentryIntegration",0,dS,"serializePostHogCookie",0,a_,"setupExpressErrorHandler",0,d$,"setupExpressRequestContext",0,dZ,"uuidv7",0,aX],74493)}];
1
+ module.exports=[74493,a=>{"use strict";let b,c,d,e,f,g;var h,i=a.i(14747);function j(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var k=((h={}).AnonymousId="anonymous_id",h.DistinctId="distinct_id",h.Props="props",h.EnablePersonProcessing="enable_person_processing",h.PersonMode="person_mode",h.FeatureFlagDetails="feature_flag_details",h.FeatureFlags="feature_flags",h.FeatureFlagPayloads="feature_flag_payloads",h.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",h.BootstrapFeatureFlags="bootstrap_feature_flags",h.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",h.OverrideFeatureFlags="override_feature_flags",h.Queue="queue",h.AiQueue="ai_queue",h.AiCaptureQueue="ai_capture_queue",h.LogsQueue="logs_queue",h.OptedOut="opted_out",h.SessionId="session_id",h.SessionStartTimestamp="session_start_timestamp",h.SessionLastTimestamp="session_timestamp",h.PersonProperties="person_properties",h.GroupProperties="group_properties",h.InstalledAppBuild="installed_app_build",h.InstalledAppVersion="installed_app_version",h.SessionReplay="session_replay",h.PushRegistered="push_registered",h.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",h.SurveyLastSeenDate="survey_last_seen_date",h.SurveysInProgress="surveys_in_progress",h.SurveysSeen="surveys_seen",h.Surveys="surveys",h.RemoteConfig="remote_config",h.FlagsEndpointWasHit="flags_endpoint_was_hit",h.DeviceId="device_id",h);let l={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:a=>`api_error_${a}`};function m(a,b){return -1!==a.indexOf(b)}function n(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let o=Array.isArray,p=Object.prototype;p.hasOwnProperty;let q=p.toString,r=o||function(a){return"[object Array]"===q.call(a)},s=a=>void 0===a,t=a=>"[object String]"==q.call(a),u=a=>t(a)&&0===a.trim().length,v=a=>null===a,w=a=>s(a)||v(a);function x(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return z(a,Error)}}function y(a){return"u">typeof Event&&z(a,Event)}function z(a,b){try{return a instanceof b}catch{return!1}}let A=[!0,"true",1,"1","yes"],B=[!1,"false",0,"0","no"];function C(a,b,c){return a&&c?b.length===Object.keys(c).length&&b.every(b=>a[b]===c[b]):a===c}class D{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&r(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let f=globalThis._posthogChunkIds,g=globalThis._debugIds;if(!f&&!g)return;let h=f?Object.keys(f):[],i=g?Object.keys(g):[];if(e&&C(f,h,c)&&C(g,i,d))return e;c=f?{...f}:void 0,d=g?{...g}:void 0,e={},b??={};let j=(c,d)=>{for(let f of c){let c=d[f];if(!c)continue;let g=b?.[f];if(g){e[g]=c;continue}let h=a(f);for(let a=h.length-1;a>=0;a--){let d=h[a]?.filename;if(d){e[d]=c,b[f]=d;break}}}};return g&&j(i,g),f&&j(h,f),e}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(x(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return r(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,D],6762),a.i(6762);let E=/^([a-z][a-z0-9.+-]+):/i,F=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function G(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=E.exec(a);return!b||F.includes(b[1].toLowerCase())}(b)};return s(d)||(f.lineno=d),s(e)||(f.colno=e),f}let H=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},I=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,J=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,K=/\((\S*)(?::(\d+))(?::(\d+))\)/,L=(a,b)=>{let c=I.exec(a);if(c){let[,a,d,e]=c;return G(b,a,"?",+d,+e)}let d=J.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=K.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=H(d[1]||"?",d[2]);return G(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},M=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,N=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,O=(a,b)=>{let c=M.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=N.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=H(d,a),G(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},P=/\(error: (.*)\)/;function Q(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function R(a,b){let c=b.start;for(;c>0&&Q(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function S(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&Q(a[d],a[d-b.length]);)d++;return d-c}function T(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=P.test(d)?d.replace(P,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!Q(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?R(a,c):0);for(let c of b)d-=S(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=R(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=S(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e);if(!e.length)return[];let k=Array.from(e);return k.reverse(),k.slice(0,50).map(a=>{var b;return{...a,filename:a.filename||((b=k)[b.length-1]||{}).filename,function:a.function||"?"}})}}let U=/^\s*[-]{4,}$/,V=/at (?:async (?!\((?!.*\)\s+\()))?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,W=/^Promise\.(?:all|any)$/,X=/^index \d+$/,Y=(a,b)=>{let c=a.match(V);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),W.test(e)&&X.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:Z(c[3]),colno:Z(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(U))return{filename:a,platform:b}};function Z(a){return parseInt(a||"",10)||void 0}a.s(["createStackParser",0,T,"nodeStackLineParser",0,Y],64583),a.i(64583),a.s([],51671),a.i(51671);class ${match(a){return x(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,$],10692),a.i(10692),a.s([],75368),a.i(75368);let _=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aa{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(_);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aa],57802),a.i(57802);let ab=["fatal","error","warning","log","info","debug"];function ac(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";for(let a=c.length;a>0;a--){let d=c.slice(0,a).join(", ");if(!(d.length>b)){if(a===c.length)return d;return d.length<=b?d:`${d.slice(0,b)}...`}}return""}class ad{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(y(a))return a.constructor.name;let b="name"in a?a.name:void 0;return t(b)&&!u(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=ac(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return t(a)&&!u(a)&&ab.indexOf(a)>=0}getStack(a){try{if(t(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return t(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(x(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,ad],93874),a.i(93874);class ae{match(a){return y(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${ac(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,ae],46980),a.i(46980);class af{match(a){return null===a||"object"!=typeof a}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,af],28150),a.i(28150),a.s([],98140),a.i(98140),a.s(["ErrorCoercer",0,$,"EventCoercer",0,ae,"ObjectCoercer",0,ad,"PrimitiveCoercer",0,af,"StringCoercer",0,aa],54253),a.i(54253);class ag{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,ag],98966),a.i(98966);function ah(){if("u">typeof process){let a=process.env.POSTHOG_RELEASE_ID?.trim();if(a)return a}let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s([],97383),a.i(97383),a.s(["getInjectedReleaseId",0,ah],28861),a.i(28861),a.s(["ErrorCoercer",0,$,"ErrorPropertiesBuilder",0,D,"EventCoercer",0,ae,"ObjectCoercer",0,ad,"PrimitiveCoercer",0,af,"ReduceableCache",0,ag,"StringCoercer",0,aa,"createStackParser",0,T,"getInjectedReleaseId",0,ah,"nodeStackLineParser",0,Y],60485);var ai=a.i(60485),ai=ai,aj=a.i(2157),ak=a.i(12714),al=a.i(50227),am=a.i(1457);let an=new ai.ReduceableCache(25),ao=new ai.ReduceableCache(20);async function ap(a,b=ak.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,al.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=at(a,d);if(void 0===f||ao.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=au(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=au(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=an.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(an,f,{});i.push(ar(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=at(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=av(a);d<a;d++){let a=c[d];if(void 0===a)return void as(b);b.pre_context.push(a)}if(void 0===c[a])return as(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,an,d),an.reduce(),a}async function aq(a,b,c){let d,e=!1;try{d=await b(a,aj.constants.O_RDONLY|aj.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function ar(a,b,c,d,e,f){let g=await aq(a,e,f);return void 0===g?void ao.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{ao.set(d,1),i();return}try{f=(0,am.createInterface)({input:e})}catch{ao.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){ao.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function as(a){delete a.pre_context,delete a.context_line,delete a.post_context}function at(a,b){return(0,al.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function au(a){return[av(a),a+7]}function av(a){return Math.max(1,a-7)}class aw{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let ax=a=>void 0===a?void 0:a.variant??a.enabled,ay=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},az=["$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"],aA=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return az.forEach(d),b.forEach(d),c},aB=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function aC(a,b){return"string"==typeof a&&aB.test(a)?a:b()}function aD(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function aE(a){return a?.replace(/\/+$/,"")}function aF(a){return a?a.split("#")[0]:a}async function aG(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function aH(){return new Date().toISOString()}function aI(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function aJ(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=aI(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function aK(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let aL=a=>{throw aD("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},aM=async(a,b)=>{a.size<18&&aL("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||aL("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(f)return f;f=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;f[a]=b>>>0}return f})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&aL("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&aL("invalid-size")};async function aN(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await aM(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}let aO="0123456789abcdef";class aP{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aP(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aP(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aP(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aO.charAt(this.bytes[b]>>>4),a+=aO.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aO.charAt(this.bytes[b]>>>4),a+=aO.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aP(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aQ{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aR()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aP.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 a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aP.ofInner(a)}}let aR=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aS=()=>aT().toString(),aT=()=>(g||(g=new aQ)).generate();class aU{add(a){let b=aS(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let aV=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>aV(`${a} ${d}`,b,c)}};function aW(a,b=Date.now(),c=3e5){if("string"!=typeof a||!a)return;let d=a.trim(),e=/^\d+\s*,/.test(d)?d.slice(0,d.indexOf(",")).trim():d;if(/^\d+$/.test(e)){let a=1e3*Math.min(Number(e),c/1e3);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(e))return;let f=Date.parse(/^\w{3} \w{3} /.test(e)?e+" GMT":e)-b;if(Number.isFinite(f)&&!(f<=0))return Math.min(f,c)}class aX{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class aY extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return aW(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 a=aD("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=aI(()=>{this._bodyReadTimedOut=!0;let a=aD("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class aZ extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function a$(a){if(a instanceof aY){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function a_(a){return a instanceof aZ}function a0(a){if(a instanceof aY)return 502===a.status||504===a.status;if(!(a instanceof aZ))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function a1(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function a2(a){return"object"==typeof a&&a instanceof aY&&413===a.status}function a3(a){return a instanceof aY?408===a.status||429===a.status||a.status>=500:a_(a)}function a4(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let a5="default";class a6{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new D([new $,new ad,new aa,new af],T("web:javascript",L,O))}getEvaluationRuntime(){}get apiKey(){return this.projectToken}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new aU,this._events=new aw,this._isInitialized=!1;let c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return aV(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project token. The client will be disabled."),this.projectToken=c,this.host=aE(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:a3},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.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)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(k.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(k.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c=this.mergeCommonEventProperties(b);var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=aA(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}mergeCommonEventProperties(a){return{...a,...this.getCommonEventProperties()}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.projectToken}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=`${this.host}/flags/?v=2${f?"&config=true":""}`,h={token:this.projectToken,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(h.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(h.evaluation_contexts=this.evaluationContexts);let i=this.getEvaluationRuntime();i&&(h.evaluation_runtime=i);let j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,j,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:a0},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,ax(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?ay(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,ay(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof aY)return{type:"api_error",statusCode:a.status};if(a instanceof aZ){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=ax(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.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"),i.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:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.projectToken}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(k.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(k.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(k.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return a5}persistedQueueKeyForRoute(a){return k.Queue}getActiveQueueRoutes(){return[a5]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=aI(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){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(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=a4(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=aC(e.uuid,aS),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:aH(),uuid:aC(b?.uuid,aS)};return(b?.disableGeoip??this.disableGeoip)&&(a4(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await a$(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>aK([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),aK([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return aN(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=a5){let d={api_key:this.projectToken,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:aH()};this.historicalMigration&&(d.historical_migration=!0);let e=n(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!a2(a)&&a3(a)};try{await this.sendBatch(g,i,a)}catch(a){if(a2(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof aZ||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=a1(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.projectToken)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.projectToken}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!a2(a)&&(!(a instanceof aY)||void 0===a.retryAfterMs)&&a3(a)}),{kind:"ok"}}catch(a){if(a2(a))return{kind:"too-large"};if(a3(a)){let b=a instanceof aY?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=a1(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await aG(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=aI(()=>{let a=aD("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new aZ(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new aZ(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new aY(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new aZ(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof aY&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return aJ((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof aY||a_(a))))throw a;await a$(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=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(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class a7{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=aI(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function a8(){return .75+.25*Math.random()*2}function a9(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}let ba="[Circular]",bb="[Truncated]",bc="[Unserializable]";function bd(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function be(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=bc}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let bf=Object.prototype.propertyIsEnumerable;function bg(a,b){try{return bh(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bh(a,b,c,d){let e=[];for(let f in a)if(bf.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(v(g)||s(g))continue;e.push({key:bd(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bb};if(d.remainingNodes--,"[object Boolean]"===q.call(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:bd(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:ba};if(e>=20)return{stringValue:bb};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?bd(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(r(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(w(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bc})}return b.length>h&&f.push({stringValue:bb}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bh(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:bd(String(b))}}(g,b,c,d)})}catch{e.push({key:bd(f),value:{stringValue:bc}})}}return e}let bi="0000000000000000",bj=bi+bi,bk=/^[0-9a-f]+$/;function bl(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bm(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bk.test(a)}let bn=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bo(a){let b=bp(a);return b&&{traceId:b.traceId,spanId:b.spanId,flags:1&parseInt(b.flags,16)?br:bs}}function bp(a){if("string"!=typeof a)return;let b=bn.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bm(d,32,bj)&&bm(e,16,bi))return{version:c,traceId:d,spanId:e,flags:f}}function bq(a){return Array.isArray(a)&&1===a.length?a[0]:a}let br="01",bs="00";function bt(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}function bu(a,b,c){return{...be({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let bv=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bw(a,b){let c=be({},a),d={};for(let a of bv)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bg(c,b),...bg(d,b)]}let bx={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"},by=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bz(a){return String(a)+"000000"}function bA(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\0${b}\0${c??""}\0${e}`}class bB{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new a7(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsByHistogram=new Map,this._boundsConflictWarned=new Set,this._boundsCapWarned=!1,this._retryAfter=new aX,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes,bounds:r(c?.bounds)?c.bounds.slice():c?.bounds})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._startWindow(),this._buildPayload(a)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._flushPromise=null,this._startWindow(),this._boundsByHistogram=new Map,this._boundsCapWarned=!1}_startWindow(){this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._boundsConflictWarned=new Set}_capture(a){var b;let c,d,e;if(this._instance.isDisabled||this._instance.optedOut)return;let f=this._runBeforeSend(a);if(null===f)return;if(!f.name||"string"!=typeof f.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof f.value||!Number.isFinite(f.value))return void this._logger.warn(`Dropping metric '${f.name}': value must be a finite number`);if("count"!==f.type&&"gauge"!==f.type&&"histogram"!==f.type)return void this._logger.warn(`Dropping metric '${f.name}': unknown type '${String(f.type)}'`);if("count"===f.type&&f.value<0)return void this._logger.warn(`Dropping count '${f.name}': counters are monotonic, value must be >= 0`);try{c=f.attributes?{...f.attributes}:void 0,d=bA(f.type,f.name,f.unit,c)}catch(a){this._logger.warn(`Dropping metric '${f.name}': attributes could not be serialized`,a);return}let g=this._series.get(d);if(!g&&!this._admitNewSeries()||"histogram"===f.type&&!(e=this._histogramBounds(f.name,f.unit,f.bounds)))return;g||(g={name:f.name,type:f.type,unit:f.unit,attributes:c,windowStartMs:Date.now(),hist:e&&{bounds:b=e,count:0,sum:0,min:1/0,max:-1/0,bucketCounts:Array(b.length+1).fill(0)}},this._series.set(d,g));let h=this._typeByName.get(f.name);void 0===h?this._typeByName.set(f.name,f.type):h===f.type||this._typeCollisionWarned.has(f.name)||(this._typeCollisionWarned.add(f.name),this._logger.warn(`Metric name '${f.name}' is already used as a ${h}; recording it as a ${f.type} too will blend both series in charts. Use a distinct name.`)),this._fold(g,f.value);let i=this._activeTraceContext();i&&(g.exemplar={...i,value:f.value,timeMs:Date.now()}),this._armFlushTimer()}_activeTraceContext(){try{let a=bo(this._instance.getActiveSpan?.()?.traceparent());if(a&&a.flags===br)return{traceId:a.traceId,spanId:a.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)}_histogramBounds(a,b,c){if(void 0!==c&&!function(a){if(!r(a)||0===a.length)return!1;for(let b=0;b<a.length;b++)if(!Number.isFinite(a[b])||b>0&&a[b]<=a[b-1])return!1;return!0}(c))return void this._logger.warn(`Dropping histogram '${a}': bounds must be a non-empty array of finite, strictly increasing numbers`);let d=bA("histogram",a,b,void 0),e=this._boundsByHistogram.get(d);if(e)return this._warnOnBoundsConflict(a,d,e,c),e;if(this._boundsByHistogram.size>=this._config.maxSeriesPerFlush){if(this._boundsCapWarned||(this._boundsCapWarned=!0,this._logger.warn(`Histogram bounds limit reached (${this._config.maxSeriesPerFlush} distinct histograms); new histograms that pass custom bounds are dropped. Reduce histogram name cardinality.`)),c&&!bC(c,by))return;return by}let f=c?c.slice():by;return this._boundsByHistogram.set(d,f),f}_warnOnBoundsConflict(a,b,c,d){bC(c,d??by)||this._boundsConflictWarned.has(b)||(this._boundsConflictWarned.add(b),this._logger.warn(`Histogram '${a}' already uses the bounds [${c.join(", ")}]; samples that pass different bounds are recorded in those buckets.`))}_fold(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,c.bounds)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=r(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(a9(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._startWindow();let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=a8()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),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:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bw(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bz(Date.now()),c=new Map;for(let e of a.values()){var d;let a=bA(e.type,e.name,e.unit,void 0),f=c.get(a);f||(f={name:e.name,...e.unit&&{unit:e.unit}},"count"===e.type?f.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===e.type?f.gauge={dataPoints:[]}:f.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,f));let g=bg(e.attributes??{},this._logger),h=bz(e.windowStartMs),i=(d=e.exemplar)?{exemplars:[{filteredAttributes:[],timeUnixNano:bz(d.timeMs),asDouble:d.value,traceId:d.traceId,spanId:d.spanId}]}:{};if("count"===e.type){let a={attributes:g,startTimeUnixNano:h,timeUnixNano:b,asDouble:e.total??0,...i};f.sum.dataPoints.push(a)}else if("gauge"===e.type){let a={attributes:g,timeUnixNano:b,asDouble:e.last??0,...i};f.gauge.dataPoints.push(a)}else{let a=e.hist,c={attributes:g,startTimeUnixNano:h,timeUnixNano:b,count:a.count,sum:a.sum,min:a.min,max:a.max,bucketCounts:a.bucketCounts,explicitBounds:a.bounds,...i};f.histogram.dataPoints.push(c)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.exemplar=a.exemplar??c.exemplar,a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":{let b=a.hist,d=c.hist;b.count+=d.count,b.sum+=d.sum,b.min=Math.min(b.min,d.min),b.max=Math.max(b.max,d.max);for(let a=0;a<b.bucketCounts.length;a++)b.bucketCounts[a]+=d.bucketCounts[a]}}}}}function bC(a,b){if(a===b)return!0;if(a.length!==b.length)return!1;for(let c=0;c<a.length;c++)if(a[c]!==b[c])return!1;return!0}let bD="unknown";function bE(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bD}"`),bD)}function bF(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bG(a,b,c,d){let e=bF(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bH(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bI{constructor(a,b,c){for(let d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??br,this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bH(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bH();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(w(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=bR(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=be({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&bS(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bE(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bG(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:bQ(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=bU(a);return this.addEvent(bJ,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bE(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c=br){return`00-${a}-${b}-${c}`}(this._traceId,this._spanId,this._traceFlags)}get traceId(){return this._traceId}get spanId(){return this._spanId}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bG(a,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:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let bJ="exception";function bK(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class bL{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}get traceId(){return null}get spanId(){return null}tracestate(){return null}end(){}}let bM=new bL;class bN extends bL{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}get traceId(){return this._traceparent.split("-")[1]??null}get spanId(){return this._traceparent.split("-")[2]??null}tracestate(){return this._tracestate??null}}function bO(a,b){var c;let d=bq(a?.parent)??b,e=bp(c="string"==typeof d||null==d?d:bP(d,"traceparent"))&&c.trim();return e?new bN(e,bt("string"==typeof d||null==d?a?.tracestate:bP(d,"tracestate"))):bM}function bP(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function bQ(a,b){return a.length>b?a.slice(0,b):a}function bR(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return w(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?bQ(b,c):b);if(d.ancestors.has(b))return ba;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return w(f.value)?String(f.value):a(f.value,c,d,e+1);if(r(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(bc)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=bc}f&&!w(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function bS(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=bR(a[h],c)}catch{d=bc}w(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function bT(a,b,c){return b===bM?c(b):a.with(b,()=>c(b))}function bU(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(x(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let bV={internal:1,server:2,client:3,producer:4,consumer:5},bW={ok:1,error:2};function bX(a){if("string"==typeof a)return bd(a);try{return bd(String(a))}catch{return bc}}function bY(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function bZ(){return bH()??Date.now()}function b$(a){try{return a instanceof bI}catch{return!1}}function b_(a,b){let c=bo(a);if(c)return{traceId:c.traceId,parentSpanId:c.spanId,traceState:bt(b),traceFlags:c.flags,isRemote:!0}}function b0(a,b,c){a[b]!==c&&(a[b]=c)}class b1{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new a7(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new aX,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return bO(b,this._contextManager.active());let f=bq(b?.parent);if(f&&"string"!=typeof f&&!b$(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),bO(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);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`),bO(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bF(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.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"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bl(8);this._liveSpans.set(j,bZ());let k=this._autoContextAttributes();return new bI({traceId:g?.traceId??bl(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bE(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:be({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bF(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=bT(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}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(a,b){if("string"==typeof a){let c=b_(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(b$(a))return a.childContext();let c=this._contextManager.active();return b$(c)?c.childContext():c instanceof bN?b_(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bI))return;let{type:c,message:d,stack:e}=bU(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=bZ()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),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(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bE(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bF(j.startTime)??d.startTime,j.endTime=(l=bF(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bE(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bG(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!w(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:bR(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=bK(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=bS(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=bK(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=bK(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:bQ(function(a){try{return"string"==typeof a?a:String(a)}catch{return bc}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{b0(a,"traceId",b.traceId),b0(a,"spanId",b.spanId),b0(a,"parentSpanId",b.parentSpanId),b0(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),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(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:bX(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(bV,c)?bV[c]:bV.internal,startTimeUnixNano:bY(a.startTime),endTimeUnixNano:bY(a.endTime),flags:(Number.isFinite(d=parseInt(a.traceFlags,16))?255&d:1)|256|512*!!a.parentIsRemote};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=bX(a.traceState));let f=bg(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:bX(a.name),timeUnixNano:bY(a.timestamp)};if(a.attributes){let d=bg(a.attributes,b);d.length&&(c.attributes=d)}let d=bK(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=bK(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=bK(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:bW[a.status.code],...a.status.message&&{message:bX(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=bR(a[c],b);return a}((a=this._config,bu(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=bZ()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bw(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=a8(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=bZ()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).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(a9(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}class b2{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let b3=["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","lightpanda","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"],b4=new Map,b5=function(a,b=[]){if(!a)return!1;let c=function(a,b){let c="";for(let a=0;a<b.length;a++){let d=b[a];c+=d.length+":"+d}return a.length+":"+a+"|"+b.length+":"+c}(a,b),d=b4.get(c);if(void 0!==d)return d;let e=a.toLowerCase(),f=b3.concat(b).some(a=>-1!==e.indexOf(a.toLowerCase()));return b4.size>=256&&b4.clear(),b4.set(c,f),f};function b6(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let b7=["service.name","service.version","deployment.environment"],b8={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"};a.s(["FeatureFlagError",0,b8],46539);class b9{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._unresolvedFlags=Object.freeze({...a.unresolvedFlags}),this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a,b.sendFeatureFlagEvents),c?.enabled??b.defaultValue??!1}getFlag(a,b={}){let c=this._flags[a];if(this._recordAccess(a,b.sendFeatureFlagEvents),c)return!!c.enabled&&(c.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}get unresolvedFlags(){return this._unresolvedFlags}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new b9({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a,b){if(this._accessed.add(a),!this._host.resolveSendFeatureFlagEvents(b)||""===this._distinctId||this._isSlice&&!(a in this._flags))return;let c=this._flags[a],d=void 0===c?void 0:!1!==c.enabled&&(c.variant??!0),e={$feature_flag:a,$feature_flag_response:d,$feature_flag_id:c?.id,$feature_flag_version:c?.version,$feature_flag_reason:c?.reason,locally_evaluated:c?.locallyEvaluated??!1,[`$feature/${a}`]:d,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:c?.locallyEvaluated?Date.now():this._evaluatedAt};c?.hasExperiment!==void 0&&(e.$feature_flag_has_experiment=c.hasExperiment),c?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(e.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let f=[];this._errorsWhileComputing&&f.push(b8.ERRORS_WHILE_COMPUTING),this._quotaLimited&&f.push(b8.QUOTA_LIMITED),void 0===c&&f.push(Object.prototype.hasOwnProperty.call(this._unresolvedFlags,a)?b8.LOCAL_EVALUATION_INCONCLUSIVE:b8.FLAG_MISSING),f.length>0&&(e.$feature_flag_error=f.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:d,groups:this._groups,disableGeoip:this._disableGeoip,properties:e})}}let ca=["exact","is_not","icontains","not_icontains","starts_with","not_starts_with","ends_with","not_ends_with","regex","not_regex"];class cb extends Error{constructor(a,b="unsupported_definition"){super(a),this.name=this.constructor.name,this.reason=b,Object.setPrototypeOf(this,cb.prototype)}}function cc(a){try{return a()}catch(a){if(a instanceof cb)throw new cb(a.message,"missing_context");throw a}}function cd(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cd(b in a?a[b]:null))return!1;return!0}function ce(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!ce(b in a?a[b]:null))return!1;return!0}function cf(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cb("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cb("Cannot stringify an unpaired surrogate like the flags service")}}function cg(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cf(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cb(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cb("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cg(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cb("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cb("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cf(c),cg(a[c],b)}finally{b.delete(a)}return}throw new cb(`Cannot represent ${typeof a} like the flags service`)}}function ch(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function ci(a){return"string"==typeof a?(cf(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cf(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cb(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cb(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cb("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cb("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cb("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cf),`{${d.sort(ch).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cb(`Cannot stringify ${typeof b} like the flags service`)}(a)}let cj=/[\x20-\x2f:;=?@\x5b-\x60\x7b-\x7e]/;function ck(a){let b=new cb(a);return Object.defineProperty(b,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),b}function cl(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cm(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cb(`Invalid semver: ${b}`);return parseInt(a,10)}function cn(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cb(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cm(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function co(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cp(a,b){let c=cn(a,b);return{lower:[c[0],c[1],c[2]],upper:[c[0],c[1]+1,0]}}function cq(a,b){let[c,d,e]=cn(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}function cr(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cb(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cm(c,a,b)}catch{}throw new cb(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}function cs(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cb(`${a} is in an invalid date format`)}throw new cb(`The date provided ${a} must be a string, number, or date object`)}function ct(a){if("boolean"==typeof a)throw new cb("Date operations cannot be performed on boolean values");return function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e)c.setUTCMonth(c.getUTCMonth()-d);else{if("y"!==e)return null;c.setUTCFullYear(c.getUTCFullYear()-d)}return c}(String(a))??cs(a)}function cu(a,b={}){let c=a.value,d=b.semverParsingPolicy??"strict";switch(a.operator||"exact"){case"exact":case"is_not":for(let a of Array.isArray(c)?c:[c])ci(a);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":ct(c);return;case"semver_eq":case"semver_neq":case"semver_gt":case"semver_gte":case"semver_lt":case"semver_lte":cn(String(c),d);return;case"semver_tilde":cp(String(c),d);return;case"semver_caret":cq(String(c),d);return;case"semver_wildcard":cr(String(c),d);return;default:throw new cb(`Unknown operator: ${a.operator}`)}}async function cv(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function cw(a,b,c="",d="."){return parseInt((await cv(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function cx(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await cw("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function cy(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function cz(a,b,c){let d=await cw(a,b,"variant");return cy(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function cA(a){return"client"===a||"server"===a?a:"all"}function cB(a,b){return a===b||"all"===a||"all"===b}class cC extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,cC.prototype)}}class cD extends Error{constructor(a,b="unsupported_definition"){super(a),this.reason=b,this.name=cD.name,Error.captureStackTrace(this,cD),Object.setPrototypeOf(this,cD.prototype)}}let cE=["experience_continuity","unsupported_definition","unresolved_dependency","missing_context"];function cF(a,b){return void 0===a||cE.indexOf(b)<cE.indexOf(a)?b:a}function cG(a,b){return b instanceof cb&&Symbol.for("posthog.requiresServerRegexEvaluation")in b&&Object.defineProperty(a,Symbol.for("posthog.requiresServerRegexEvaluation"),{value:!0}),a}class cH{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.warnedUnresolvableFlags=new Map,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}currentDefinitions(){return{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:this.currentDefinitions()}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof cD||b instanceof cb?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e={},f=0==this.featureFlags.length,g=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,h=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(g.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,h,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof cD||b instanceof cb?(this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)),e[a.key]=b.reason):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),cB(cA(a.evaluation_runtime),"server")&&(f=!0)}})),{response:c,payloads:d,unresolved:e,fallbackToFlags:f}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:ay(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cb("Flag has experience continuity enabled","experience_continuity");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cb("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cb(`Can't compute feature flag: ${a.key} without $device_id`,cI(a,b.definitions)??"missing_context");return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cb("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cb(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cb(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cb(`Circular dependency detected for flag '${e}' (empty dependency chain)`);let g=f.find(a=>!(a in d)&&!c.definitions.featureFlagsByKey[a]&&!c.definitions.filteredOutFlagKeys.has(a));if(void 0!==g)throw new cb(`Missing flag dependency '${g}' for flag '${e}'`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){if(b instanceof cD)throw new cD(`Flag dependency '${a}' for flag '${e}' requires server evaluation: ${b.message}`,"unresolved_dependency");throw cG(new cb(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`,"unresolved_dependency"),b)}else d[a]=!1;else d[a]=!1}if(null==d[a])throw new cb(`Dependency '${a}' could not be evaluated`,"unresolved_dependency")}let h=d[e];return this.flagEvaluatesToExpectedValue(a.value,h)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f,g;d=this.withEvaluationSnapshot(d);let h=a.filters||{},i=await cx(h.holdout,b);if(void 0!==i)return i;let j=h.groups||[],k=h.aggregation_group_type_index,l=h.early_exit??!1,{groups:m,groupProperties:n}=d,o=new Set;for(let i of j){let j=b;try{let b=void 0!==i.aggregation_group_type_index?i.aggregation_group_type_index:k,f=c;if(b!==k&&null!=b){let c=d.definitions.groupTypeMapping[String(b)];if(!c||!(c in m)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${b} not available`));continue}if(!(c in n)){e=cF(e,"missing_context");continue}f=n[c],j=m[c]}let o=await this.isConditionMatch(a,j,i,f,d);if("match"===o){let b=i.variant,c=h.multivariate?.variants||[];g=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,j)||!0;break}if(l&&"out_of_rollout_bound"===o){if(e)break;return!1}}catch(b){if(b instanceof cD){let c;try{c=cI(a,d.definitions)}catch{}let f=cF(cF(e,b.reason),c??b.reason);throw f===b.reason?b:new cD(b.message,f)}if(b instanceof cb){if(e=cF(e,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b)if(f=b,l&&void 0!=i.rollout_percentage&&await cw(a.key,j)>i.rollout_percentage/100)o.add(!1);else{let b=h.multivariate?.variants||[],c=i.variant;o.add(c&&b.some(a=>a.key===c)?c:await this.getMatchingVariant(a,j)||!0)}}else throw b}}if(void 0!==g&&!(f&&[...o].some(a=>a!==g)))return g;if(e)throw cG(new cb("Can't determine if feature flag is enabled or not with given properties",e),f);return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){let b,i,j;for(let a of c.properties){let c=a.type,g=!1;try{if("cohort"===c){let b=await cK(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);g="not_in"===a.operator?!b:b}else if("flag"===c)g=await this.evaluateFlagDependency(a,d,e);else if(Object.prototype.hasOwnProperty.call(d,a.key))g=cJ(a,d,h,f.propertyMatchingVersion);else{cu(a),b=cF(b,"missing_context");continue}}catch(a){if(a instanceof cD){void 0===b&&(j??=a),b=cF(b,a.reason);continue}if(a instanceof cb){Symbol.for("posthog.requiresServerRegexEvaluation")in a&&(i=a),b=cF(b,a.reason);continue}if(void 0!==b)break;throw a}if(!g)return"no_match"}if(j)throw j;if(b)throw cG(new cb(`Can't determine if a condition of flag ${a.key} matches`,b),i);if(void 0==g)return"match"}return void 0!=g&&await cw(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cz(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cy(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?cA(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>cB(cA(b.evaluation_runtime),a)).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags),c=b.reduce((a,b)=>(a[b.key]=b,a),{}),d=new Set(b.map(a=>a.key)),e=new Set(a.flags.filter(a=>!d.has(a.key)).map(a=>a.key));this.featureFlags=b,this.featureFlagsByKey=c,this.filteredOutFlagKeys=e,this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutUnresolvableFlags(a){let b=[],c=[],d=new Map,e=this.currentDefinitions();for(let f of a){if(!cB(cA(f.evaluation_runtime),"server"))continue;let a=cI(f,e);if(!a)continue;let g=JSON.stringify(f);d.set(f.key,g),this.warnedUnresolvableFlags.get(f.key)!==g&&("experience_continuity"===a?b.push(f.key):c.push(f.key))}if(this.warnedUnresolvableFlags=d,b.length>0){let a=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 ${b.length} flag(s) have experience continuity enabled and cannot be resolved locally (reason: experience_continuity): ${b.join(", ")}. `+a)}if(c.length>0){let a=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 ${c.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): ${c.join(", ")}. ${a} To evaluate them locally, change these flags in PostHog or upgrade posthog-node.`)}}async loadFromCache(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&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(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){let a=this.pollingInterval??3e4;return this.shouldBeginExponentialBackoff?Math.min(6e4,a*2**this.backOffCount):a}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 a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new cC(`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 cC(`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 cC(`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 c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutUnresolvableFlags(this.featureFlags);break}default:return}}catch(a){a instanceof cC&&this.onError?.(a)}finally{this.pollerStopped||null===this.pollingInterval||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){if(!this.personalApiKey)throw new cC("A secretKey or personalApiKey is required to fetch feature flag definitions from PostHog.");let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=aI(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await aJ(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function cI(a,b){if(!a.active)return;if(a.ensure_experience_continuity)return"experience_continuity";let c=a.filters||{},d=c.aggregation_group_type_index;return void 0==d||b.groupTypeMapping[String(d)]?(c.groups||[]).some(a=>(a.properties||[]).some(a=>(function a(b,c,d){if("flag"===b.type){let a=b.dependency_chain;return!Array.isArray(a)||0===a.length||a.some(a=>!c.featureFlagsByKey[a]&&!c.filteredOutFlagKeys.has(a))}if("cohort"!==b.type)try{return cu(b),!1}catch(a){if(a instanceof cb)return!0;throw a}let e=String(b.value);return!(e in c.cohorts)||!d.has(e)&&(d.add(e),function b(c,d,e){return(c?.values??[]).some(c=>"values"in c?b(c,d,e):a(c,d,e))}(c.cohorts[e],c,d))})(a,b,new Set)))?"unsupported_definition":void 0:"unsupported_definition"}function cJ(a,b,c,d){return function(a,b,c={}){try{return function(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cb(`Property ${d} not found in propertyValues`,"missing_context");let h=b[d];if(void 0===h)throw c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),new cb(`Property ${d} is undefined in propertyValues`);if(null===h&&!ca.includes(f))return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cd(a)||Array.isArray(a)&&0===a.length)return cc(()=>cg(b)),ce(a)===ce(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cd(a))return cc(()=>cg(b)),!1;if(Array.isArray(a)){let c=cc(()=>ci(b)).toLowerCase();return a.some(a=>ci(a).toLowerCase()===c)}return ci(a).toLowerCase()===cc(()=>ci(b)).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)},k=()=>cc(()=>cn(String(h),g)),l=()=>{let a=cn(String(e),g);return co(k(),a)},m=({lower:a,upper:b})=>{let c=k();return co(c,a)>=0&&0>co(c,b)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cl(h).includes(cl(e));case"not_icontains":return!cl(h).includes(cl(e));case"starts_with":return cl(h).startsWith(cl(e));case"not_starts_with":return!cl(h).startsWith(cl(e));case"ends_with":return cl(h).endsWith(cl(e));case"not_ends_with":return!cl(h).endsWith(cl(e));case"regex":case"not_regex":{let a=function(a,b){let c;if(""===a)return!0;let d=function(a){let b=[],c=-1,d="";for(let e=0;e<a.length;e++){let f=a[e];if(f.charCodeAt(0)>127)return null;if("\\"===f){let b=a[++e];if(void 0===b)break;if("x"===b){if(!/^[\da-f]{2}$/i.test(a.slice(e+1,e+3)))return null;e+=2}else if(!"dDsSwWbBfnrtv".includes(b)&&!cj.test(b))return null;if(-1===c&&"bB".includes(b))return null;d="literal";continue}if("["===f){if(-1!==c)return null;c=e}else if("]"===f&&-1!==c){if(e===c+("^"===a[c+1]?2:1))return null;b.push(a.slice(c,e+1)),c=-1,d="literal";continue}else if(-1!==c){if(["&&","--","~~"].includes(a.slice(e,e+2)))return null;continue}else if("("===f&&"?"===a[e+1]){if(":"!==a[e+2])return null;e+=2}else if("{"===f){let b=/^\{(\d+)(?:,(\d*))?\}/.exec(a.slice(e));if(!b||["","|","("].includes(d)||b.slice(1).some(a=>Number(a)>0xffffffff))return null}else if("*+?}".includes(f)&&("+"===a[e+1]||"{"===a[e+1]))return null;if("*+?{".includes(f)&&["^","$","empty group"].includes(d))return null;d=")"===f&&["(","empty group"].includes(d)?"empty group":f}return b}(a);if(null===d)throw ck("Regex syntax requires server evaluation");try{c=new RegExp(a)}catch(a){if(a instanceof SyntaxError)return null;throw ck("Regex compilation requires server evaluation")}for(let a of d)try{RegExp(a,"u")}catch{throw ck("Regex character class syntax requires server evaluation")}for(let a=0;a<b.length;a++){let c=b[a];if(c.charCodeAt(0)>127||"\r"===c)throw ck("Regex matching for Unicode or carriage returns requires server evaluation")}try{return c.test(b)}catch{throw ck("Regex execution requires server evaluation")}}(String(e),String(h));if(null===a)return!1;return"regex"===f?a:!a}case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{let a=ct(e),b=cc(()=>cs(h));return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===l();case"semver_neq":return 0!==l();case"semver_gt":return l()>0;case"semver_gte":return l()>=0;case"semver_lt":return 0>l();case"semver_lte":return 0>=l();case"semver_tilde":return m(cp(String(e),g));case"semver_caret":return m(cq(String(e),g));case"semver_wildcard":return m(cr(String(e),g));default:throw new cb(`Unknown operator: ${f}`)}}(a,b,c)}catch(b){throw b instanceof cb&&"missing_context"===b.reason&&cu(a,c),b}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function cK(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new cD(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);return cL(c[g],b,c,d,e,f)}async function cL(a,b,c,d=!1,e,f){let g,h;if(!a)return!0;let i=a.type,j=a.values;if(!j||0===j.length)return!0;if("values"in j[0]){for(let a of j)try{let g=await cL(a,b,c,d,e,f);if("AND"===i){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof cD)throw b;if(b instanceof cb)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=cF(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw cG(new cb("Can't match cohort without a given cohort property value",g),h);return"AND"===i}for(let a of j)try{let g;if("cohort"===a.type)g=await cK(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cb(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=cJ(a,b,void 0,f);let h=a.negation||!1;if("AND"===i){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof cD)throw b;if(b instanceof cb)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),g=cF(g,b.reason),Symbol.for("posthog.requiresServerRegexEvaluation")in b&&(h=b);else throw b}if(g)throw cG(new cb("can't match cohort without a given cohort property value",g),h);return"AND"===i}let cM=["--unhandled-rejections","--unhandled_rejections"],cN=new Set(["throw","strict","warn","warn-with-error-code","none"]),cO=[...globalThis.process?.execArgv??[]],cP=globalThis.process?.env?.NODE_OPTIONS;function cQ(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=cM.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);cN.has(f)&&(b=f)}return b}let cR=function(a=cO,b=cP){return cQ(a)??cQ(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}(),cS={mechanism:{type:"onunhandledrejection",handled:!1}},cT={mechanism:{type:"onuncaughtexception",handled:!1}},cU=new Set(["HANGING_PROMISE_REJECTION","NEXT_PRERENDER_INTERRUPTED","DYNAMIC_SERVER_USAGE","BAILOUT_TO_CLIENT_SIDE_RENDERING"]),cV=Symbol.for("react.postpone"),cW=Symbol.for("next.unhandledRejectionFilter"),cX=Symbol.for("posthog-node.exception-autocapture.v1"),cY=globalThis;function cZ(a){return"function"==typeof a&&!0===a._posthogErrorHandler}function c$(a){return"object"==typeof a&&null!==a||"function"==typeof a}function c_(a){return Object.assign(a,{_posthogErrorHandler:!0})}function c0(a){return a.listeners("unhandledRejection").some(a=>!cZ(a))}function c1(a,b){return function a(b,c=0){try{if(!c$(b))return!1;if(b.$$typeof===cV||"string"==typeof b.digest&&cU.has(b.digest))return!0;return c<5&&a(b.cause,c+1)}catch{return!1}}(a)||"unhandledRejection"===b&&function(a){try{return c$(a)&&"AbortError"===a.name}catch{return!1}}(a)}function c2(a){let b=new Map;for(let c of a.clients){let a=b.get(c.key);a&&(void 0!==a.getContext()||void 0===c.getContext())||b.set(c.key,c)}for(let[c,d]of a.retired)b.has(c)||b.set(c,d);return[...b.values()]}function c3(a){"function"==typeof globalThis.setImmediate?setImmediate(a):setTimeout(a,0)}function c4(a,b,c,d){let e=a.capturedThisTurn.get(b)??new Map;e.has(c)||e.set(c,d),a.capturedThisTurn.set(b,e),a.turnResetScheduled||(a.turnResetScheduled=!0,c3(()=>{c3(()=>{a.capturedThisTurn.clear(),a.turnResetScheduled=!1})}))}function c5(a,b,c,d){let e=a.capturedThisTurn.get(b),f=[];for(let g of c2(a))e?.has(g.key)||d?.has(g.key)||(c4(a,b,g.key,"autocapture"),g.capture(b,c),f.push(g));return f}function c6(a,b){return a.deferred.get(b.exception)!==b?[]:(a.deferred.delete(b.exception),b.runInContext(()=>c5(a,b.exception,b.hint,b.skipKeys)))}function c7(a,b,c){let d;if(void 0!==(d=a.capturedThisTurn.get(b))&&c2(a).every(a=>d.has(a.key))||a.deferred.has(b))return;let e={exception:b,hint:c,skipKeys:new Set(a.capturedThisTurn.get(b)?.keys()),runInContext:function(){try{let a=globalThis.process,b=a?.getBuiltinModule?.("node:async_hooks"),c=b?.AsyncLocalStorage?.snapshot?.();if(c)return c}catch{}return a=>a()}()};a.deferred.set(b,e),c3(()=>c6(a,e))}async function c8(a,b){try{console.error(b)}catch{}dd();let c=new Set([...a.clients,...a.retired.values()]);await Promise.all([...c].map(a=>a.shutdown().catch(()=>void 0))),globalThis.process.exit(1)}function c9(a,b,c,d){let e="unhandledRejection"===c?cS:cT;if(!d){c1(b,c)||c7(a,b,e);return}let f=a.deferred.get(b);f?c6(a,f):c5(a,b,e)}function da(a){try{return String(a)}catch{return typeof a}}function db(a){let b=globalThis.process;cY[cW]&&"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(a)&&(Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",a),b.listeners("unhandledRejection").includes(a)||b.prependListener("unhandledRejection",a))}function dc(a){let b=globalThis.process,c=[],d=(a,d)=>{b.on(a,d),c.push(()=>b.removeListener(a,d))},e=()=>c.forEach(a=>a());if("strict"===a.mode){let c=(b,c)=>c9(a,b,c,!0);return d("uncaughtExceptionMonitor",c),{remove:e,areInstalled:()=>b.listeners("uncaughtExceptionMonitor").includes(c)}}let f=c_((b,c)=>{let d=0===globalThis.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!cZ(a)).length;c9(a,b,c,d),d&&!a.calledFatalError&&(a.calledFatalError=!0,c8(a,b))});d("uncaughtException",f);let g="throw"===a.mode||"warn-with-error-code"===a.mode,h=g&&!b.versions?.bun,i=()=>b.listeners("unhandledRejection").includes(j),j=c_(b=>{g&&!c0(globalThis.process)&&i()?function(a,b){let c=globalThis.process;if("warn-with-error-code"===a.mode){c.emitWarning(`Unhandled promise rejection: ${da(b)}`,"UnhandledPromiseRejectionWarning"),c.exitCode=1,c1(b,"unhandledRejection")||c5(a,b,cS);return}if(c.versions?.bun){c.exitCode=1,c5(a,b,cS),a.calledFatalError||(a.calledFatalError=!0,c8(a,b));return}let d=b instanceof Error?b:Object.assign(Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "${da(b)}".`),{name:"UnhandledPromiseRejection",code:"ERR_UNHANDLED_REJECTION"}),e=c.emit;e.call(c,"uncaughtExceptionMonitor",d,"unhandledRejection"),e.call(c,"uncaughtException",d,"unhandledRejection")}(a,b):c1(b,"unhandledRejection")||c7(a,b,cS)});return d("newListener",c_((a,c)=>{cZ(c)||("unhandledRejection"===a?(i()||b.prependListener("unhandledRejection",j),queueMicrotask(()=>{let a;(a="function"==typeof b.rawListeners?b.rawListeners("unhandledRejection"):[]).includes(j)&&a[0]!==j&&(b.removeListener("unhandledRejection",j),b.prependListener("unhandledRejection",j)),db(j)})):"Next.UnhandledRejectionFilter.MacguffinEvent"===a&&queueMicrotask(()=>{i()||b.prependListener("unhandledRejection",j)}))})),h?(d("removeListener",c_(a=>{"unhandledRejection"===a&&i()&&!c0(b)&&b.removeListener("unhandledRejection",j)})),c0(b)&&b.prependListener("unhandledRejection",j)):b.prependListener("unhandledRejection",j),db(j),c.push(()=>{b.removeListener("unhandledRejection",j),"function"==typeof b.rawListeners&&b.rawListeners("unhandledRejection").includes(j)&&Object.getPrototypeOf(b).removeListener.call(b,"unhandledRejection",j)}),{remove:e,areInstalled:()=>b.listeners("uncaughtException").includes(f)&&(h||i())}}function dd(){let a=new Set,b=cY[cX];if(b)for(let c of[...b.deferred.values()])c6(b,c).forEach(b=>a.add(b));return a}let de=Symbol("capturedContext");function df(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),"[object Number]"==q.call(a)&&a==a)if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),df(e??c,b,c,d)}class dg{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=df(a.bucketSize,0,100,a._logger),this._refillRate=df(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=df(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var dh=ai;let di=class a{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new dg({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return a===Object(a)&&!r(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e,f){let g,h=(g=f?{...f,properties:{...f.properties}}:null,a=>Object.assign(a,{[de]:g})),i={...e},j=a.buildFromUnknown(b,c);j.$exception_list=await a.modifyFrames(j.$exception_list);let k=dh.getInjectedReleaseId();return k&&(i.$release_id=k),h({event:"$exception",distinctId:d,properties:{...j,...i},_originatedFromCaptureException:!0})}get destinationKey(){return`${this.client.apiKey}@${this.client.host}`}startAutocaptureIfEnabled(){this.isEnabled()&&(this._autocaptureClient={key:this.destinationKey,capture:(a,b)=>this.onException(a,b),getContext:()=>this.client.getContext(),flush:()=>this.client.flush(),shutdown:()=>this.client.shutdown(2e3)},this._stopAutocapture=function(a,b=cR){if(!globalThis.process?.on)return()=>void 0;let c=cY[cX];if(c)c.listeners.areInstalled()||(c.listeners.remove(),c.listeners=dc(c));else{let a={mode:b,clients:new Set,retired:new Map,capturedThisTurn:new Map,deferred:new Map,turnResetScheduled:!1,calledFatalError:!1,listeners:{remove:()=>void 0,areInstalled:()=>!0}};a.listeners=dc(a),cY[cX]=a,c=a}c.clients.add(a),c.retired.delete(a.key);let d=c;return()=>{d.clients.delete(a)&&([...d.clients].some(b=>b.key===a.key)||d.retired.set(a.key,a))}}(this._autocaptureClient))}claimExplicitCapture(a){var b;let c;return b=this.destinationKey,!(c=cY[cX])||c.capturedThisTurn.get(a)?.get(b)!=="autocapture"&&(c4(c,a,b,"app"),c.deferred.get(a)?.skipKeys.add(b),!0)}capturePendingExceptions(){for(let a of dd())a!==this._autocaptureClient&&this.client.addPendingPromise(a.flush().catch(()=>void 0))}onException(b,c){this.client.addPendingPromise((async()=>{if(!a.isPreviouslyCapturedError(b)){let d=await a.buildEventMessage(this.client.getErrorPropertiesBuilder(),b,c,void 0,void 0,this.client.getContext()),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})().catch(a=>{this._logger.error("Failed to capture an exception:",a)}))}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop(),this.capturePendingExceptions(),this._stopAutocapture?.(),this._stopAutocapture=void 0}},dj=/^[0-9a-f]{32}$/i,dk=/^[0-9a-f]{16}$/i,dl=Symbol.for("opentelemetry.js.api.1"),dm=Symbol.for("OpenTelemetry Context Key SPAN");async function dn(){try{let a=globalThis[dl],b=a?.context?.active().getValue(dm),c=b?.spanContext(),d=c?.traceId,e=c?.spanId;if("string"==typeof d&&"string"==typeof e&&dj.test(d)&&dk.test(e)&&!/^0+$/.test(d)&&!/^0+$/.test(e))return{$trace_id:d.toLowerCase(),$span_id:e.toLowerCase()}}catch{}return{}}class dp{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let dq=Symbol.for("posthog-node.context-listeners"),dr=globalThis,ds=dr[dq]??=new WeakMap;function dt(a,b=!1){for(let c of ds.get(a)??[])try{c(b)}catch{}}function du(a){dt(a,!0)}let dv="analytics";class dw extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(dw.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function dx(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let dy=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:dx},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:dx},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:dx},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],dz=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function dA(a,b,c){void 0===c||b in a||(a[b]=c)}function dB(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of dy)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of dz)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,dA(c,"$set",a.$set),dA(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let dC=new Set([408,500,502,503,504]);class dD{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>aI(b,a))),this.generateRequestId=b.generateRequestId??aS,this.compress=b.compress??aN}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(dB)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=n({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&dC.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new dw({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=aI(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new dw({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new dw({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let dE="ai-capture",dF="/i/v0/ai/batch/",dG=new TextEncoder;function dH(a){return dG.encode(n(a)).length}class dI extends Error{constructor(a){super(a.message,void 0===a.cause?void 0:{cause:a.cause}),this.name=function(a,b){if("missing_secret_key"===b||401===a)return"missing_api_key";if(void 0===a)return"network_error"===b?"service_unavailable":b.startsWith("invalid_")?"validation_error":"application_error";switch(a){case 400:return"validation_error";case 403:return"invalid_permission";case 404:return"not_found";case 409:return"template_outdated"===b?"validation_error":"concurrent_idempotent_requests";case 422:return"idempotency_key_reused"===b?"invalid_idempotent_request":"validation_error";case 429:return"quota_limited"===b?"monthly_quota_exceeded":"rate_limit_exceeded";case 503:return"service_unavailable";default:return"application_error"}}(a.statusCode,a.code),this.code=a.code,this.statusCode=a.statusCode,this.why=a.why,this.fix=a.fix,this.docsUrl=a.docsUrl,this.field=a.field,this.retryAfterMs=a.retryAfterMs}}let dJ="https://us.posthog.com",dK="https://eu.posthog.com",dL={"https://us.i.posthog.com":dJ,"https://us.posthog.com":dJ,"https://app.posthog.com":dJ,"https://eu.i.posthog.com":dK,"https://eu.posthog.com":dK},dM=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dN=/^[\x21-\x7e]{1,255}$/,dO=/^[a-zA-Z0-9_-]{1,400}$/,dP={to:!0,distinctId:!0,idempotencyKey:!0,maxRetries:!0},dQ={name:"templateId",fields:dV(dP,{templateId:!0,templateData:!0}),why:"A template made in PostHog sets its own sender, subject and content, and follows the project's engagement setting.",howToSend:"send a template made in PostHog with templateId"},dR={name:"templateKey",fields:dV(dP,{templateKey:!0,subject:!0,from:!0,replyTo:!0,captureEngagement:!0,html:!0,text:!0}),why:"A send with templateKey takes its content from your code.",howToSend:"send content from your code with templateKey"};class dS{constructor(a,b){this.inFlight=new Set,this.config=a,this.hooks=b}send(a,...b){return this.track(this.sendUntracked(a,b))}get(a){return this.track(this.getUntracked(a))}track(a){return this.inFlight.add(a),a.finally(()=>this.inFlight.delete(a)),a}async drain(){for(;this.inFlight.size>0;)await Promise.all(this.inFlight)}async sendUntracked(a,b){try{var c=b;if(c.some(a=>void 0!==a))throw new dI({code:"invalid_form",message:"send takes one options object, so no email was sent. Put idempotencyKey and every other option in it."});let d=function(a,b){let c=a??{},{to:d,distinctId:e,idempotencyKey:f,maxRetries:g}=c;if("string"!=typeof d||!d.trim())throw dW("invalid_recipient","to must be one email address as a nonempty string.","to");if(void 0!==e&&("string"!=typeof e||!e))throw dW("invalid_distinct_id","distinctId must be a nonempty string.","distinctId");let h=function(a,b){if(void 0===a.templateId==(void 0===a.templateKey))throw new dI({code:"invalid_form",message:"Send either templateId, or templateKey with subject and html or text."});return void 0===a.templateKey?function(a,b){let{templateId:c,templateData:d}=a;if("string"!=typeof c||!dM.test(c))throw dW("invalid_template_id","templateId must be the template's UUID.","templateId");if(void 0!==d&&("object"!=typeof d||null===d||Array.isArray(d)))throw dW("invalid_template_data","templateData must be an object.","templateData");return dU(a,dQ,dR),{template_id:c.toLowerCase(),message_data:d??{},...void 0!==b&&{distinct_id:b}}}(a,b):function(a,b){let{templateKey:c,subject:d,html:e,text:f,from:g,replyTo:h,captureEngagement:i}=a;if("string"!=typeof c||!dO.test(c))throw dW("invalid_template_key","templateKey can only have letters, digits, hyphens (-) and underscores (_), at most 400.","templateKey");if(dU(a,dR,dQ),"string"!=typeof d)throw dW("invalid_form","A send with templateKey needs a subject.","subject");if(void 0!==e&&"string"!=typeof e)throw dW("invalid_form","html must be a string.","html");if(void 0!==f&&"string"!=typeof f)throw dW("invalid_form","text must be a string.","text");if(void 0===e&&void 0===f)throw dW("invalid_form","A send with templateKey needs html, text or both.","html");let j=void 0!==h&&!(Array.isArray(h)&&0===h.length);return{template_key:c,subject:d,...void 0!==e&&{html:e},...void 0!==f&&{text:f},...void 0!==g&&{from:g},...j&&{reply_to:"string"==typeof h?[h]:h},capture_engagement:i??!0,...void 0!==b&&{distinct_id:b}}}(a,b)}(c,e);if(void 0!==f&&("string"!=typeof f||!dN.test(f)))throw dW("invalid_idempotency_key","idempotencyKey must be 1 to 255 visible ASCII characters without spaces.","idempotencyKey");if(void 0!==g&&!dT(g))throw dW("invalid_max_retries","maxRetries must be a nonnegative integer.","maxRetries");return{path:"/api/projects/@current/messaging/send/email/",body:n({...h,to:d}),idempotencyKey:f??globalThis.crypto.randomUUID(),maxRetries:dT(g)?g:b}}(a,this.config.maxRetries),{appHost:e,secretKey:f}=this.connect("no email was sent","Sending email needs secretKey, a project secret API key with the transactional_email:write scope."),g=this.headers(f,{"Content-Type":"application/json","Idempotency-Key":d.idempotencyKey}),h=await this.withRetries(d.maxRetries,async()=>(function({status:a,payload:b,retryAfterMs:c}){let d=dZ(b);if(a>=200&&a<300){let b=dY(d.message_id);if(!b)throw new dI({code:"api_error",message:"PostHog answered without a message ID.",statusCode:a});let c=[];if(Array.isArray(d.warnings))for(let a of d.warnings)null!==a&&"object"==typeof a&&c.push({code:dY(a.code)??"warning",message:dY(a.detail)??dY(a.message)??"",fix:dY(a.fix)});return{id:b,replayed:!0===d.replayed,warnings:c}}throw d$(d,a,c)})(await this.request(e+d.path,"POST",g,d.body)));for(let a of h.warnings)this.hooks.logger.warn(`PostHog email warning ${a.code}: ${a.message}`);return{data:h,error:null}}catch(a){return{data:null,error:d_(a,"Sending the email failed unexpectedly.")}}}async getUntracked(a){try{if("string"!=typeof a||!dM.test(a))throw dW("invalid_message_id","id must be the message ID that send() returned.","id");let{appHost:b,secretKey:c}=this.connect("no email status was read","Reading an email status needs secretKey, a project secret API key with the transactional_email:read or transactional_email:write scope."),d=b+"/api/projects/@current/messaging/emails/{messageId}/".replace("{messageId}",a.toLowerCase()),e=this.headers(c,{});return{data:await this.withRetries(this.config.maxRetries,async()=>(function({status:a,payload:b,retryAfterMs:c}){let d=dZ(b);if(a<200||a>=300)throw d$(d,a,c);let e=dY(d.id),f=dY(d.status),g=dY(d.created_at),h=dY(d.status_at);if(!e||!f||!g||!h)throw new dI({code:"api_error",message:"PostHog answered without an email status.",statusCode:a});return{id:e,status:f,createdAt:g,statusAt:h,reason:dY(d.reason)??null}})(await this.request(d,"GET",e))),error:null}}catch(a){return{data:null,error:d_(a,"Reading the email status failed unexpectedly.")}}}connect(a,b){var c,d;let e;if(this.hooks.isDisabled())throw new dI({code:"client_disabled",message:`The PostHog client is disabled, so ${a}.`});if(this.hooks.isClosed())throw new dI({code:"client_closed",message:`The PostHog client is shut down, so ${a}.`});let f=(c=this.config.host,(e="string"==typeof(d=this.config.appHost)?aE(d.trim()):"")?dL[e]??e:dL[aE(c)]);if(!f)throw new dI({code:"missing_app_host",message:"The client's host is not PostHog Cloud, so the client can't tell where to send email. Set appHost to your PostHog app host on the client."});let g=this.config.secretKey?.trim();if(!g)throw new dI({code:"missing_secret_key",message:b});return{appHost:f,secretKey:g}}headers(a,b){let c={Authorization:`Bearer ${a}`,Accept:"application/json",...b};return this.hooks.userAgent&&(c["User-Agent"]=this.hooks.userAgent),this.config.migratedFrom&&(c["X-PostHog-Migrated-From"]=this.config.migratedFrom),c}async withRetries(a,b){for(let c=0;;c++){let d;try{return await b()}catch(a){d=a instanceof dI?a:new dI({code:"network_error",message:"The request to PostHog failed.",cause:a})}let e=function(a,b,c){if(!(b>=c)&&(void 0===a.statusCode?"network_error"===a.code:409===a.statusCode?"idempotency_key_in_flight"===a.code:429===a.statusCode?"quota_limited"!==a.code:503===a.statusCode)&&(void 0===a.retryAfterMs||!(a.retryAfterMs>3e4)))return Math.max(Math.min(3e4,1e3*2**b*(.8+.4*Math.random())),a.retryAfterMs??0)}(d,c,a);if(void 0===e)throw d;await new Promise(a=>setTimeout(a,e))}}async request(a,b,c,d){let e,f,g=new AbortController,h=this.config.requestTimeoutMs,i=new Promise((a,b)=>{e=setTimeout(()=>{let a=Error(`Email request timed out after ${h}ms`);a.name="AbortError",b(a),g.abort(a)},h)}),j=Promise.resolve().then(()=>this.hooks.fetch(a,{method:b,headers:c,...void 0===d?{}:{body:d},signal:g.signal}));j.then(a=>{g.signal.aborted&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{let a;f=await Promise.race([j,i]);try{a=await Promise.race([f.text(),i])}catch(a){if(f.status>=200&&f.status<300)throw a;return{status:f.status,payload:null,retryAfterMs:dX(f)}}return{status:f.status,payload:function(a){try{return JSON.parse(a)}catch{return null}}(a),retryAfterMs:dX(f)}}finally{clearTimeout(e),g.signal.aborted&&f&&Promise.resolve(f.body?.cancel()).catch(()=>{})}}}function dT(a){return"number"==typeof a&&Number.isInteger(a)&&a>=0}function dU(a,b,c){let d=Object.entries(a).find(([a,c])=>void 0!==c&&!b.fields.has(a))?.[0];if(void 0===d)return;let e=`A send with ${b.name} doesn't take ${d}, so no email was sent.`;if(!c.fields.has(d))throw new dI({code:"invalid_form",message:e,field:d,fix:`Remove ${d} and send again.`});throw new dI({code:"invalid_form",message:e,field:d,why:b.why,fix:`Remove ${d}, or ${c.howToSend}.`})}function dV(...a){return new Set(a.flatMap(a=>Object.keys(a)))}function dW(a,b,c){return new dI({code:a,message:b,field:c})}function dX(a){try{return aW(a.headers?.get("retry-after"),Date.now(),Number.MAX_SAFE_INTEGER)}catch{return}}function dY(a){return"string"==typeof a&&a?a:void 0}function dZ(a){return null===a||"object"!=typeof a||Array.isArray(a)?{}:a}function d$(a,b,c){return new dI({code:dY(a.code)??"api_error",message:dY(a.detail)??`PostHog answered HTTP ${b}.`,statusCode:b,why:dY(a.why),fix:dY(a.fix),docsUrl:dY(a.docs_url),field:dY(a.attr),retryAfterMs:c})}function d_(a,b){return a instanceof dI?a:new dI({code:"unexpected_error",message:b,cause:a})}let d0=new Set;function d1(a,b){d0.has(a)||(d0.add(a),console.warn(`[PostHog] ${b}`))}class d2 extends a6{get distinctIdHasSentFlagCalls(){return Object.fromEntries(this._distinctIdHasSentFlagCalls)}set distinctIdHasSentFlagCalls(a){this._distinctIdHasSentFlagCalls=new Map(Object.entries(a??{}))}constructor(a,b={}){var c,d;let e,f="string"==typeof a?a.trim():"",g={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:("string"==typeof(c=b.host)?c.trim():"")||"https://us.i.posthog.com",personalApiKey:("string"==typeof(d=b.secretKey??b.personalApiKey)?d.trim():"")||void 0};if(super(f,g),this._memoryStorage=new dp,this._isShutdown=!1,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=g,this.captureMode="v0"===(e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0)||"v1"===e?e:"v0",this.enableFullAiCapture=!0===g.enableFullAiCapture,this.privacyMode=!0===g.privacyMode,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof g.featureFlagsPollingInterval?Math.max(g.featureFlagsPollingInterval,100):null===g.featureFlagsPollingInterval?null:3e4,"number"==typeof g.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(g.waitUntilDebounceMs,0)),"number"==typeof g.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(g.waitUntilMaxWaitMs,0)),!this.disabled&&(g.personalApiKey||g.flagDefinitionCacheProvider)){if(g.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!==g.enableLocalEvaluation&&(this.featureFlagsPoller=new cH({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:g.personalApiKey,projectApiKey:f,timeout:g.requestTimeout??1e4,host:this.host,fetch:g.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:g.flagDefinitionCacheProvider,strictLocalEvaluation:g.strictLocalEvaluation,evaluationContexts:g.evaluationContexts??g.evaluationEnvironments}))}this.errorTracking=new di(this,g,this._logger),this._distinctIdHasSentFlagCalls=new Map,this.maxCacheSize=g.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises();return!this._traces||a&&this._traces.throttled?b:aK([b,this._traces.flush().catch(()=>{})]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this.errorTracking.capturePendingExceptions(),this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=aI(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":dv}persistedQueueKeyForRoute(a){return a===dE?k.AiCaptureQueue:"ai"===a?k.AiQueue:k.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[dv,"ai"]:[dv];return this._aiCaptureRouteActive&&a.push(dE),a}getBatchEndpointPath(a){return a===dE?dF:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=dv){if(c===dE)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=dH(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${dF}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,dE)}catch(d){if(!a2(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dH(b)} bytes) was rejected with 413 by ${dF} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new dD({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:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.63.1"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bB(this,(a=this.options.metrics,b=a?.resourceAttributes,{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}get emails(){var a,b;return this._emails||(this._emails=new dS({secretKey:this.options.personalApiKey,host:this.host,appHost:this.options.appHost,requestTimeoutMs:"number"==typeof(a=this.options.emailRequestTimeoutMs)&&Number.isFinite(a)&&a>0?a:15e3,maxRetries:"number"==typeof(b=this.options.emailRequestMaxRetries)&&Number.isFinite(b)&&b>=0?Math.floor(b):2,migratedFrom:this.options.migratedFrom},{fetch:(a,b)=>this.fetch(a,b),isDisabled:()=>this.disabled,isClosed:()=>this._isShutdown,logger:this._logger,userAgent:this.getCustomUserAgent()||void 0})),this._emails}initializeSpanContextManager(){return new b2}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var a,b,c;let d,e;return this._traces||(this._traces=new b1(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=be({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(b7.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of b7)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=b6(a?.maxExportBatchSize,512),{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:b6(a?.maxAttributesPerSpan,128),maxEventsPerSpan:b6(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:b6(a?.maxAttributeValueLength,8192),flushIntervalMs:b6(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(b6(a?.maxQueueSize,2048),e),maxLiveSpans:b6(a?.maxLiveSpans,1e4),maxSpanAgeMs:b6(a?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??bO(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):bT(this._spanContextManager,bO(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:f,options:g})=>{let h={timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid},i={distinctId:b,event:d,properties:{...f,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,i,h,e):this.enqueue(a,i,h,e)}).catch(a=>{a&&console.error(a)}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"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(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"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(a,!0)}captureAi(a){if(this.disabled)return;let b=aC(a.uuid,aS);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=aC(a.uuid,aS);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,dE)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l;if(this.disabled)return void this._logger.warn("The client is disabled");let m=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:n,disableGeoip:o}=c,{onlyEvaluateLocally:p,personProperties:q,groupProperties:r}=c,s=this.addLocalPersonAndGroupProperties(b,n,q,r);q=s.allPersonProperties,r=s.allGroupProperties;let t=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,q),r);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let u=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,t,{matchValue:d});if(c){u=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof cD||b instanceof cb)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!u&&!p){let b=await super.getFeatureFlagDetailsStateless(t.distinctId,t.groups,q,r,o,[a]);if(void 0===b)h=b8.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(b8.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(b8.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(b8.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code}}c.length>0&&(h=c.join(","))}}if(m){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:u,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),u&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:o,properties:d})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){d1("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(d1("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&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(e?.sendFeatureFlagEvents)}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){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 b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){d1("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 d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:this._resolveSendFeatureFlagEvents(c?.sendFeatureFlagEvents)});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)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:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];let v={};for(let[a,b]of Object.entries(s?.unresolved??{}))Object.prototype.hasOwnProperty.call(p,a)||(v[a]=b);return new b9({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,unresolvedFlags:v,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",i=`${c}_${d}${h}`,j=this._distinctIdHasSentFlagCalls.get(b)??new Set;if(this._distinctIdHasSentFlagCalls.delete(b),this._distinctIdHasSentFlagCalls.set(b,j),!j.has(i)){for(j.add(i);this._distinctIdHasSentFlagCalls.size>Math.max(this.maxCacheSize,1);){let a=this._distinctIdHasSentFlagCalls.keys().next().value;if(void 0===a)break;this._distinctIdHasSentFlagCalls.delete(a)}this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f})}}_resolveSendFeatureFlagEvents(a){return a??this.options.sendFeatureFlagEvent??!0}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),resolveSendFeatureFlagEvents:a=>this._resolveSendFeatureFlagEvents(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,()=>(dt(this),b()),c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b),dt(this)}async _shutdown(a){let b=Date.now()+(a??3e4);this._isShutdown=!0;let c=this._emails?.drain(),d=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await aJ(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await aJ(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());let e=Math.max(0,b-Date.now()),f=c?aJ(c,e):void 0;try{return await super._shutdown(e)}finally{await f,this._distinctIdHasSentFlagCalls.clear(),d?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=aI(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(function(a){return"[object Object]"===Object.prototype.toString.call(a)}(f)&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!di.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(di.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c,this.getContext()).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!di.isPreviouslyCapturedError(a)&&this.errorTracking.claimExplicitCapture(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(di.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c,this.getContext()).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){var c;let{distinctId:d,event:e,properties:f,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l}=a,m=(c=this.context?.get(),de in a?a[de]??void 0:c),n=b.includeContextProperties??!0,o=d||m?.distinctId,p=n?{...this.props,...m?.properties||{},...f||{}}:{...f||{}};"$exception"!==e||"$trace_id"in p||"$span_id"in p||Object.assign(p,await dn()),o||(o=aS(),p.$process_person_profile=!1),n&&m?.sessionId&&!p.$session_id&&(p.$session_id=m.sessionId);let q=this._shouldSendMinimalFlagCalledEvent(e,p)?aA(p):p,r=this._runBeforeSend({distinctId:o,event:e,properties:q,groups:g,flags:h,sendFeatureFlags:i,timestamp:j,disableGeoip:k,uuid:l});if(!r)return Promise.reject(null);let s=await Promise.resolve().then(async()=>{if(h)return i&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),h._getEventProperties();if(i){d1("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 a=await this.getFeatureFlagsForEvent(r.distinctId,g,k,"object"==typeof i?i:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=r.groups||g;return{...a,...r.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===r.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof s.$raw_user_agent&&b5(s.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(r.event="$bot_pageview",s.$browser_type="bot"),{distinctId:r.distinctId,event:r.event,properties:s,options:{timestamp:r.timestamp,disableGeoip:r.disableGeoip,uuid:r.uuid}}}_runBeforeSend(a){let b=this.options.before_send;if(!b)return a;let c=Array.isArray(b)?b:[b],d=a;for(let b of c)try{if(!(d=b(d)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!d.properties||0===Object.keys(d.properties).length){let a=`Event '${d.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(b){return this._logger.error(`Error in before_send function for event '${a.event}':`,b),null}return d}}var d3=ai,d4=ai,d5=ai,d6=ai,d7=ai,d8=ai,d9=ai,ea=ai,eb=a.i(78500);let ec=new WeakMap;function ed(a,b,c){let d=a&&ec.get(a);return c?ec.set(b,{signal:c,parent:d}):d&&ec.set(b,d),b}class ee{constructor(){this.storage=new eb.AsyncLocalStorage}get(){let a=this.storage.getStore();return a&&function(a){let b=ec.get(a);for(;b;){if(b.signal.aborted)return!1;b=b.parent}return!0}(a)?a:void 0}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){let c=this.get();return b?.fresh===!0?ed(void 0,{...a},b.signal):ed(c,{distinctId:a.distinctId??c?.distinctId,sessionId:a.sessionId??c?.sessionId,properties:{...c?.properties||{},...a.properties||{}}},b?.signal)}}class ef{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new eb.AsyncLocalStorage}}var eg=a.i(27028);let eh=(0,a.i(12057).promisify)(eg.gzip);async function ei(a,b=!0){try{let b=await eh(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var ej=a.i(60526),dh=ai;let ek="posthog-node";function el(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[en.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=dh.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function em(a,b){let c=el(a,b);return{name:ek,processEvent:a=>c(a)}}class en{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=ek,this.name=ek,this.setupOnce=function(f,g){f(el(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}function eo(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function ep(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function eq(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aS(),b]})}function er(a,b){let c=ep(b),d=a.get(c);return d?et(d.value):null}function es(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function et(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=r(b.$sesid)?b.$sesid:[],d=c[1];return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof d?d:void 0,sessionLastActivityTimestamp:eu(c[0]),sessionStartTimestamp:eu(c[2]),deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}function eu(a){return"number"==typeof a&&Number.isFinite(a)?a:void 0}a.s(["PostHogSentryIntegration",0,en,"createEventProcessor",0,el,"sentryIntegration",0,em],9318);let ev=/[\x00-\x1f\x7f-\x9f]/g;function ew(a,b,c){null!=c&&""!==c&&(a[b]=c)}function ex(a){return Array.isArray(a)?a[0]:a}function ey(a){if(Array.isArray(a)){for(let b of a){let a=ey(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(ev,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function ez(a,b,c){return"number"==typeof a&&Number.isFinite(a)&&Math.abs(b-a)<=c}function eA(a,b){var c,d;let e,f,g=function(a,b){let c;if(!a)return{};let d=ey(a["x-posthog-session-id"]),e=ey(a["x-posthog-distinct-id"]),{sessionId:f,distinctId:g}=void 0===d&&void 0===e&&b?function(a,b,c=Date.now(),d=18e5,e=!1){try{let f;if("string"!=typeof a)return{};let g=eo(a.split(";").reverse().join(";")),h=g.get(ep(b))?.value,i=g.get("__ph_opt_in_out_"+b)?.value??"";if(!h||m(B,i)||e&&!m(A,i))return{};let j=JSON.parse(h);if(!j||"object"!=typeof j)return{};let k="identified"===j.$user_state?ey(j.distinct_id):void 0,l=j.$sesid;if(Array.isArray(l)&&(2===l.length||3===l.length)){let[a,b,e=a]=l;ez(a,c,d)&&ez(e,c,864e5)&&(f=ey(b))}return{...void 0!==f?{sessionId:f}:{},...void 0!==k?{distinctId:k}:{}}}catch{return{}}}(a.cookie,b.apiKey,Date.now(),"number"==typeof(c=b.sessionIdleTimeoutSeconds)&&Number.isFinite(c)&&0!==c?1e3*Math.min(Math.max(c,60),36e3):18e5,!0===b.optOutCapturingByDefault):{sessionId:d,distinctId:e};return{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{}}}(b.headers,!0===(e=a.options.readPostHogCookie)?{apiKey:a.apiKey}:e&&"object"==typeof e?{apiKey:a.apiKey,sessionIdleTimeoutSeconds:e.sessionIdleTimeoutSeconds,optOutCapturingByDefault:e.optOutCapturingByDefault}:null),h=a.getContext(),i=h?.sessionId??g.sessionId,j=h?.distinctId??g.distinctId,k={},l=!0===a.options.disable_capture_url_hashes;return ew(k,"$current_url",(c=b.originalUrl||b.url,l?aF(c):c)),ew(k,"$request_method",b.method),ew(k,"$request_path",(d=b.path,f=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),l?aF(f):f)),ew(k,"$user_agent",ex(b.headers["user-agent"])),ew(k,"$ip",function(a){let b=ex(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==i?{sessionId:i}:{},...void 0!==j?{distinctId:j}:{},properties:k}}function eB(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(eA(c,a),()=>{dt(c,!0),d()})}))}function eC(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(di.isPreviouslyCapturedError(a))return void e(a);let f=eA(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([di.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h,c.getContext()),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,eC,"setupExpressRequestContext",0,eB],40602),a.i(9318),a.i(40602),a.i(46539),a.s(["EmailError",0,dI,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,b9,"PostHogSentryIntegration",0,en,"cookieStateToProperties",0,es,"cookieStoreFromHeader",0,eo,"createEventProcessor",0,el,"enrichCurrentSpan",0,du,"getPostHogCookieName",0,ep,"parsePostHogCookie",0,et,"readPostHogCookie",0,er,"sentryIntegration",0,em,"serializePostHogCookie",0,eq,"setupExpressErrorHandler",0,eC,"setupExpressRequestContext",0,eB,"uuidv7",0,aS],80456),a.i(80456),a.s(["EmailError",0,dI,"FeatureFlagError",0,l,"FeatureFlagEvaluations",0,b9,"PostHog",0,class extends d2{getLibraryId(){return"posthog-node"}compressPayload(a){return ei(a,this.isDebug)}initializeContext(){return new ee}initializeSpanContextManager(){return new ef}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,ej.platform)(),d=(0,ej.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bx,a)?bx[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new d3.ErrorPropertiesBuilder([new d4.EventCoercer,new d5.ErrorCoercer,new d6.ObjectCoercer,new d7.StringCoercer,new d8.PrimitiveCoercer],d9.createStackParser("node:javascript",ea.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,i.dirname)(process.argv[1]):process.cwd(),b="\\"===i.sep){let c=b?j(a):a;return a=>{if(!a)return;let d=b?j(a):a,{dir:e,base:f,ext:g}=i.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let h=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${h}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${h}`:h}return h}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>ap(a,void 0,this._logger),function(a=process.cwd()){i.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,i.isAbsolute)(d.filename)&&(d.filename=b((0,i.relative)(c,b(d.filename))));return a}}()])}},"PostHogSentryIntegration",0,en,"cookieStateToProperties",0,es,"cookieStoreFromHeader",0,eo,"createEventProcessor",0,el,"enrichCurrentSpan",0,du,"getPostHogCookieName",0,ep,"parsePostHogCookie",0,et,"readPostHogCookie",0,er,"sentryIntegration",0,em,"serializePostHogCookie",0,eq,"setupExpressErrorHandler",0,eC,"setupExpressRequestContext",0,eB,"uuidv7",0,aS],74493)}];
3
2
 
4
3
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuznb72p7z._.js.map