failproofai 1.0.3 → 1.0.4-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/standalone/.grok/hooks/failproofai.json +172 -0
- package/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +5 -5
- package/.next/standalone/.next/prerender-manifest.json +4 -4
- package/.next/standalone/.next/required-server-files.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +7 -7
- package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +6 -6
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +1 -1
- package/.next/standalone/.next/server/app/_not-found.rsc +15 -15
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +15 -15
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/run/route.js +4 -4
- package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js +1 -1
- package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/index.html +1 -1
- package/.next/standalone/.next/server/app/index.rsc +15 -15
- package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +14 -14
- package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +15 -15
- package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
- package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
- package/.next/standalone/.next/server/app/policies/page.js +1 -1
- package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page.js +3 -3
- package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js +2 -2
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/server/app/projects/page.js +1 -1
- package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
- package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +4 -4
- package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/chunks/{[externals]__0u3wrvq._.js → [externals]__0_gzk8q._.js} +1 -1
- package/.next/standalone/.next/server/chunks/{[externals]__0-9ti7z._.js → [externals]__1zndo1i._.js} +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__07hor7h._.js +5 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__08dchfu._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0cuho4x._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0elsuli._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0gnj_qa._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0ljuzm_._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0o07qi9._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0w23bpg._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0x5c7sh._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__0yik9_w._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1adacul._.js +1 -1
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1jg6s9m._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1s6qci9._.js +3 -0
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1xfm05z._.js +3 -0
- package/.next/standalone/.next/server/chunks/_09dz7xv._.js +1 -1
- package/.next/standalone/.next/server/chunks/_0tdy_6l._.js +3 -0
- package/.next/standalone/.next/server/chunks/_0tovk6q._.js +1 -1
- package/.next/standalone/.next/server/chunks/_0trp3yc._.js +1 -1
- package/.next/standalone/.next/server/chunks/_1ek68ln._.js +21 -14
- package/.next/standalone/.next/server/chunks/lib_grok-projects_ts_1i2epl_._.js +3 -0
- package/.next/standalone/.next/server/chunks/lib_qwen-projects_ts_0wu_a8e._.js +3 -0
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js +2 -2
- package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_09z9-p7._.js +2 -2
- package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4v._.js +1 -1
- package/.next/standalone/.next/server/chunks/src_hooks_0iu54mz._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__013jr2b._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__01wy8d-._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__02npjtd._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0_4gcz8._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0d--wmy._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0da85px._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ftmoxc._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0oa1lav._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0p-5p8u._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0qqrlf_._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s11fx1._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0s740oi._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0n_lxhg._.js → [root-of-the-server]__0wvusu0._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1b5jzxr._.js → [root-of-the-server]__16gamwq._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1bbk-si._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1c3ybxr._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1izi7zn._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1p2otjt._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1qapotl._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1zl_r0t._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__21bj7uw._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/_0-yi74u._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_0v8eebd._.js → _00z5uuq._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_1if9ixi._.js → _08f0jd2._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0wso5d3._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/{_0j6gd_k._.js → _1byck5v._.js} +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_1es2j7i._.js +155 -1
- package/.next/standalone/.next/server/chunks/ssr/_1u8-lu2._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_1zopuov._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpc._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/app_settings_settings-client_tsx_20lq-mq._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/lib_cline-projects_ts_13_hbdd._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/lib_grok-projects_ts_0rc-d0o._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/lib_ori-projects_ts_04tofqo._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/lib_qwen-projects_ts_0w3i9o7._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_builtin-policies_ts_09j2ndl._.js +1 -1
- package/.next/standalone/.next/server/middleware-build-manifest.js +5 -5
- package/.next/standalone/.next/server/pages/404.html +1 -1
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +19 -19
- package/.next/standalone/.next/static/chunks/{0ollg-nnu3t3e.js → 00gv0v91mycm-.js} +1 -1
- package/.next/standalone/.next/static/chunks/{354-n7p7labpn.js → 01hvwwrhvbzyh.js} +1 -1
- package/.next/standalone/.next/static/chunks/0hzmxwb2pvk5p.js +6 -0
- package/.next/standalone/.next/static/chunks/{0nm11ysn0153h.js → 0j884dwnwtyrt.js} +1 -1
- package/.next/standalone/.next/static/chunks/0mr9dg3bnloa1.js +1 -0
- package/.next/standalone/.next/static/chunks/0qn9khv0oo9ex.js +1 -0
- package/.next/standalone/.next/static/chunks/{2xm5mj1d21b4n.js → 1_2jsatfuthrw.js} +1 -1
- package/.next/standalone/.next/static/chunks/1_bxotmf9qngs.js +1 -0
- package/.next/standalone/.next/static/chunks/1eyl7fzkmnkf_.js +1 -0
- package/.next/standalone/.next/static/chunks/{42yfkhekx440s.js → 1po3lirgk2riw.js} +1 -1
- package/.next/standalone/.next/static/chunks/{40lpt2o2b283e.js → 2bnf_4pgyk1rq.js} +1 -1
- package/.next/standalone/.next/static/chunks/{1a6u7l3giejch.js → 2bvwsyu6x__ia.js} +1 -1
- package/.next/standalone/.next/static/chunks/{3l36d73kj18zw.js → 3_--3ibia6ba1.js} +1 -1
- package/.next/standalone/.next/static/chunks/3gf1jg-5m-u1t.css +2 -0
- package/.next/standalone/.next/static/chunks/{3pibxnbhjza7n.js → 3ws7eljkq25wg.js} +1 -1
- package/.next/standalone/.next/static/chunks/{turbopack-2x-o099q64i8h.js → turbopack-18qf4jodtft6b.js} +1 -1
- package/.next/standalone/.qwen/settings.json +251 -0
- package/.next/standalone/app/project/[name]/page.tsx +24 -4
- package/.next/standalone/assets/logos/cline.png +0 -0
- package/.next/standalone/assets/logos/grok-dark.svg +1 -0
- package/.next/standalone/assets/logos/grok-light.svg +1 -0
- package/.next/standalone/assets/logos/ori-dark.svg +1 -0
- package/.next/standalone/assets/logos/ori-light.svg +1 -0
- package/.next/standalone/assets/logos/qwen.svg +1 -0
- package/.next/standalone/lib/cli-registry.ts +33 -1
- package/.next/standalone/lib/cline-projects.ts +155 -0
- package/.next/standalone/lib/cline-sessions.ts +268 -0
- package/.next/standalone/lib/download-session.ts +37 -0
- package/.next/standalone/lib/grok-projects.ts +123 -0
- package/.next/standalone/lib/grok-sessions.ts +355 -0
- package/.next/standalone/lib/ori-projects.ts +141 -0
- package/.next/standalone/lib/ori-sessions.ts +221 -0
- package/.next/standalone/lib/projects.ts +27 -3
- package/.next/standalone/lib/qwen-projects.ts +106 -0
- package/.next/standalone/lib/qwen-sessions.ts +313 -0
- package/.next/standalone/node_modules/@next/env/package.json +1 -1
- package/.next/standalone/node_modules/next/dist/build/swc/index.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo-experimental.runtime.prod.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-page-turbo.runtime.prod.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/app-route-turbo.runtime.prod.js +1 -1
- package/.next/standalone/node_modules/next/dist/compiled/next-server/pages-turbo.runtime.prod.js +5 -5
- package/.next/standalone/node_modules/next/dist/lib/patch-incorrect-lockfile.js +3 -3
- package/.next/standalone/node_modules/next/dist/server/config.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-turbopack.js +2 -2
- package/.next/standalone/node_modules/next/dist/server/dev/hot-reloader-webpack.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/image-optimizer.js +2 -2
- package/.next/standalone/node_modules/next/dist/server/lib/app-info-log.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/incremental-cache/file-system-cache.js +17 -4
- package/.next/standalone/node_modules/next/dist/server/lib/start-server.js +1 -1
- package/.next/standalone/node_modules/next/dist/shared/lib/router/utils/escape-path-delimiters.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/anonymous-meta.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/events/swc-load-failure.js +1 -1
- package/.next/standalone/node_modules/next/dist/telemetry/events/version.js +2 -2
- package/.next/standalone/node_modules/next/package.json +10 -10
- package/.next/standalone/package.json +11 -11
- package/.next/standalone/sdk/python/uv.lock +29 -29
- package/.next/standalone/server.js +1 -1
- package/README.md +38 -7
- package/bin/failproofai.mjs +24 -7
- package/dist/cli.mjs +20313 -17756
- package/dist/worker.mjs +8521 -6768
- package/lib/cli-registry.ts +33 -1
- package/lib/cline-projects.ts +155 -0
- package/lib/cline-sessions.ts +268 -0
- package/lib/download-session.ts +37 -0
- package/lib/grok-projects.ts +123 -0
- package/lib/grok-sessions.ts +355 -0
- package/lib/ori-projects.ts +141 -0
- package/lib/ori-sessions.ts +221 -0
- package/lib/projects.ts +27 -3
- package/lib/qwen-projects.ts +106 -0
- package/lib/qwen-sessions.ts +313 -0
- package/package.json +11 -11
- package/src/audit/cli-adapters/cline.ts +50 -0
- package/src/audit/cli-adapters/grok.ts +70 -0
- package/src/audit/cli-adapters/index.ts +24 -0
- package/src/audit/cli-adapters/ori.ts +55 -0
- package/src/audit/cli-adapters/qwen.ts +71 -0
- package/src/hooks/batch-expand.ts +380 -0
- package/src/hooks/batch-fanout.ts +142 -0
- package/src/hooks/builtin-policies.ts +6 -4
- package/src/hooks/enforcement-capability.ts +97 -0
- package/src/hooks/handler.ts +61 -5
- package/src/hooks/harness-cli.ts +3 -1
- package/src/hooks/integrations.ts +756 -2
- package/src/hooks/normalize-cli-payload.ts +126 -0
- package/src/hooks/policy-evaluator.ts +297 -6
- package/src/hooks/resolve-transcript-path.ts +10 -0
- package/src/hooks/risk-patterns.ts +26 -0
- package/src/hooks/tool-name-canonicalize.ts +64 -0
- package/src/hooks/types.ts +533 -2
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1le9jqc._.js +0 -3
- package/.next/standalone/.next/server/chunks/[root-of-the-server]__1p-qi2t._.js +0 -5
- package/.next/standalone/.next/server/chunks/_1-akg6w._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__00-s7h8._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__190won8._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1ctpynv._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1sc84bb._.js +0 -3
- package/.next/standalone/.next/static/chunks/03slu0c8_71y7.js +0 -1
- package/.next/standalone/.next/static/chunks/1-_zkmnm-jwei.js +0 -1
- package/.next/standalone/.next/static/chunks/1r9676mkvihto.js +0 -1
- package/.next/standalone/.next/static/chunks/30pct5s734jua.js +0 -6
- package/.next/standalone/.next/static/chunks/40nr6ehj4p3cw.css +0 -2
- package/.next/standalone/.next/static/chunks/41b5ptaocvi_l.js +0 -1
- /package/.next/standalone/.next/static/{JBYgkXkA1PS48m9P_hKNw → qJx3mbOQV-5ElrcRb4Sp7}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{JBYgkXkA1PS48m9P_hKNw → qJx3mbOQV-5ElrcRb4Sp7}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{JBYgkXkA1PS48m9P_hKNw → qJx3mbOQV-5ElrcRb4Sp7}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
module.exports=[39702,e=>{"use strict";let t,r,i,s,a;var n,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}let u=e=>void 0===e?void 0:e.variant??e.enabled,c=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},h=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],d=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return h.forEach(i),t.forEach(i),r};var g=((n={}).AnonymousId="anonymous_id",n.DistinctId="distinct_id",n.Props="props",n.EnablePersonProcessing="enable_person_processing",n.PersonMode="person_mode",n.FeatureFlagDetails="feature_flag_details",n.FeatureFlags="feature_flags",n.FeatureFlagPayloads="feature_flag_payloads",n.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",n.BootstrapFeatureFlags="bootstrap_feature_flags",n.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",n.OverrideFeatureFlags="override_feature_flags",n.Queue="queue",n.AiQueue="ai_queue",n.AiCaptureQueue="ai_capture_queue",n.LogsQueue="logs_queue",n.OptedOut="opted_out",n.SessionId="session_id",n.SessionStartTimestamp="session_start_timestamp",n.SessionLastTimestamp="session_timestamp",n.PersonProperties="person_properties",n.GroupProperties="group_properties",n.InstalledAppBuild="installed_app_build",n.InstalledAppVersion="installed_app_version",n.SessionReplay="session_replay",n.PushRegistered="push_registered",n.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",n.SurveyLastSeenDate="survey_last_seen_date",n.SurveysSeen="surveys_seen",n.Surveys="surveys",n.RemoteConfig="remote_config",n.FlagsEndpointWasHit="flags_endpoint_was_hit",n.DeviceId="device_id",n);let p={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`},f=e=>{let t=Error(`Native gzip produced invalid output: ${e}`);throw t.name="NativeGzipValidationError",t},y=async(e,r)=>{e.size<18&&f("too-short");let i=new Uint8Array(await e.slice(0,10).arrayBuffer());i.length>=2&&31===i[0]&&139===i[1]&&8===i[2]||f("invalid-header");let s=new DataView(await e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{let r=(()=>{if(t)return t;t=[];for(let e=0;e<256;e++){let r=e;for(let e=0;e<8;e++)r=1&r?0xedb88320^r>>>1:r>>>1;t[e]=r>>>0}return t})(),i=0xffffffff;for(let t=0;t<e.length;t++)i=r[(i^e[t])&255]^i>>>8;return(0xffffffff^i)>>>0})(r)&&f("invalid-crc");let a=r.length>>>0;s.getUint32(4,!0)!==a&&f("invalid-size")};async function m(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),a=new Response(r.readable).blob(),[n]=await Promise.all([a,s]);return await y(n,t),n}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}let _="[Truncated]",v="[Unserializable]";function b(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function w(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let E=Array.isArray,F=Object.prototype;F.hasOwnProperty;let P=F.toString,x=E||function(e){return"[object Array]"===P.call(e)},S=e=>e===Object(e)&&!x(e),$=e=>void 0===e,C=e=>"[object String]"==P.call(e),I=e=>C(e)&&0===e.trim().length,k=e=>null===e,A=e=>$(e)||k(e),O=e=>"[object Number]"==P.call(e)&&e==e;function T(e){return null===e||"object"!=typeof e}function R(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function M(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return D(e,Error)}}function L(e){return"u">typeof Event&&D(e,Event)}function D(e,t){try{return e instanceof t}catch{return!1}}let j="Android",B="BlackBerry",N="Nintendo",U="PlayStation",q="Xbox",H="Windows",W="(\\d+(\\.\\d+)?)";RegExp("Version/"+W),RegExp(q,"i"),RegExp(U+" \\w+","i"),RegExp(N+" \\w+","i"),RegExp(B+"|PlayBook|BB10","i");RegExp("rv:"+W),RegExp("Edge?\\/"+W),RegExp("(Chrome|CrMo)\\/"+W),RegExp("CriOS\\/"+W),RegExp("(UCBrowser|UCWEB)\\/"+W),RegExp("(Opera|OPR)\\/"+W),RegExp("Firefox\\/"+W),RegExp("FxiOS\\/"+W),RegExp("Konqueror[:/]?"+W,"i"),RegExp(B+" "+W),RegExp("android\\s"+W,"i"),RegExp("SamsungBrowser\\/"+W),RegExp("OculusBrowser\\/"+W),RegExp("Vivaldi\\/"+W),RegExp("YaBrowser\\/"+W),RegExp("Whale\\/"+W),RegExp("Brave\\/"+W),RegExp("(DuckDuckGo|Ddg)\\/"+W),RegExp("PaleMoon\\/"+W),RegExp("Waterfox\\/"+W),RegExp("GSA\\/"+W),RegExp("(rv:|MSIE )"+W),RegExp("rv:"+W),RegExp(q+"; "+q+" (.*?)[);]","i"),RegExp(N,"i"),RegExp(U,"i"),RegExp(H,"i"),RegExp("("+j+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+j+")","i");let z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function V(e,t){return"string"==typeof e&&z.test(e)?e:t()}function G(e){return e?e.split("#")[0]:e}async function K(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function Q(){return new Date().toISOString()}function J(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function Z(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=J(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function Y(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}let X=Object.prototype.propertyIsEnumerable;function ee(e,t){try{return et(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function et(e,t,r,i){let s=[];for(let a in e)if(X.call(e,a)){if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let n=e[a];if(k(n)||$(n))continue;s.push({key:b(a),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:_};if(i.remainingNodes--,"[object Boolean]"===P.call(t))return{boolValue:t};if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:b(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:"[Circular]"};if(s>=20)return{stringValue:_};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?b(e):String(e)}}i.ancestors.add(t);try{try{let a=t.toJSON;if("function"==typeof a)return e(a.call(t),r,i,s+1)}catch{}if(x(t))return{arrayValue:{values:function(t,r,i,s){let a=[],n=Math.min(t.length,1e3),o=0;for(;o<n&&i.remainingNodes>0;o++)try{let n=o in t?t[o]:void 0;if(A(n))continue;a.push(e(n,r,i,s))}catch{a.push({stringValue:v})}return t.length>o&&a.push({stringValue:_}),a}(t,r,i,s+1)}};return{kvlistValue:{values:et(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:b(String(t))}}(n,t,r,i)})}catch{s.push({key:b(a),value:{stringValue:v}})}}return s}let er=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ei(e){return String(e)+"000000"}function es(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\u0000${t}\u0000${r??""}\u0000${s}`}class ea{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=es(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let a=this._typeByName.get(i.name);void 0===a?this._typeByName.set(i.name,i.type):a===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${a}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(er.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,er)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=x(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer||(this._flushTimer=J(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){var t,r,i,s,a,n,o;return s=this._buildMetrics(e),t=this._config,r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),a={...t.resourceAttributes,"service.name":t.serviceName||"unknown_service",...t.environment&&{"deployment.environment":t.environment},...t.serviceVersion&&{"service.version":t.serviceVersion},"telemetry.sdk.name":r,"telemetry.sdk.version":i},n=this._instance.getLibraryId(),o=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:ee(a)},scopeMetrics:[{scope:{name:n,version:o},metrics:s}]}]}}_buildMetrics(e){let t=ei(Date.now()),r=new Map;for(let i of e.values()){let e=es(i.type,i.name,i.unit,void 0),s=r.get(e);s||(s={name:i.name,...i.unit&&{unit:i.unit}},"count"===i.type?s.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===i.type?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,s));let a=ee(i.attributes??{},this._logger),n=ei(i.windowStartMs);if("count"===i.type){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(e)}else if("gauge"===i.type){let e={attributes:a,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(e)}else if(i.hist){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:er};s.histogram.dataPoints.push(e)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}let en="0123456789abcdef";class eo{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new eo(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new eo(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new eo(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=en.charAt(this.bytes[t]>>>4),e+=en.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=en.charAt(this.bytes[t]>>>4),e+=en.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new eo(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class el{constructor(e){this.timestamp=0,this.counter=0,this.random=e??eu()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return eo.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),this.counter&0x40000000-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,eo.ofInner(e)}}let eu=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ec=()=>eh().toString(),eh=()=>(r||(r=new el)).generate();function ed(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function eg(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function ep(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,ec(),t]})}function ef(e,t){let r=eg(t),i=e.get(r);return i?em(i.value):null}function ey(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function em(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=x(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}class e_{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}class ev{add(e){let t=ec(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let eb=(e,t,r)=>{function i(s,...a){t(()=>{(0,r[s])(e,...a)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>eb(`${e} ${i}`,t,r)}};class ew{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(a,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&x(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;return null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(r.stacktrace={type:"raw",frames:e.stack});let i=[r];return null!=e.cause&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:function(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return a&&r.length===s?a:(s=r.length,a=r.reduce((r,s)=>{i||(i={});let a=i[s];if(a)r[a[0]]=a[1];else{let a=e(s);for(let e=a.length-1;e>=0;e--){let n=a[e],o=n?.filename,l=t[s];if(o&&l){r[o]=l,i[s]=[o,l];break}}}return r},{}))}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(r,i)=>{if(i<=4){let s=this.buildCoercingContext(e,t,i);return this.applyCoercers(r,s)}};return{...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:e,apply:e=>i(e,r),next:e=>i(e,r+1)}}}function eE(e,t,r,i,s){let a={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:!t?.startsWith("webkit-masked-url://")&&"<anonymous>"!==t};return $(i)||(a.lineno=i),$(s)||(a.colno=s),a}e.s(["ErrorPropertiesBuilder",0,ew],69309);let eF=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},eP=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ex=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,eS=/\((\S*)(?::(\d+))(?::(\d+))\)/,e$=(e,t)=>{let r=eP.exec(e);if(r){let[,e,i,s]=r;return eE(t,e,"?",+i,+s)}let i=ex.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=eS.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=eF(i[1]||"?",i[2]);return eE(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},eC=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,eI=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ek=(e,t)=>{let r=eC.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=eI.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=eF(i,e),eE(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},eA=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,eO=(e,t)=>{let r=eA.exec(e);return r?eE(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},eT=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,eR=(e,t)=>{let r=eT.exec(e);return r?eE(t,r[2],r[3]||"?",+r[1]):void 0},eM=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eL=(e,t)=>{let r=eM.exec(e);return r?eE(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},eD=/^\s*[-]{4,}$/,ej=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,eB=/^Promise\.(?:all|any)$/,eN=/^index \d+$/,eU=(e,t)=>{let r=e.match(ej);if(r){let e,i,s,a,n;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}a=void 0}i&&(a=e,n=i),"<anonymous>"===i&&(n=void 0,s=void 0),void 0===s&&(n=n||"?",s=a?`${a}.${n}`:n);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),eB.test(s)&&eN.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:eq(r[3]),colno:eq(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(eD))return{filename:e,platform:t}};function eq(e){return parseInt(e||"",10)||void 0}let eH=/\(error: (.*)\)/;function eW(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function ez(){return eV("web:javascript",e$,ek)}function eV(e,...t){return(r,i=0)=>{let s=[],a=r.split("\n");for(let r=i;r<a.length;r++){let i=a[r];if(i.length>1024)continue;let n=eH.test(i)?i.replace(eH,"$1"):i;if(!n.match(/\S*Error: /)){for(let r of t){let t=r(n,e);if(t){s.push(t);break}}if(s.length>=50)break}}return eW(s)}}e.s(["createDefaultStackParser",0,ez,"createStackParser",0,eV,"reverseAndStripFrames",0,eW],10728);class eG{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=C(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return R(e,"DOMException")}isDOMError(e){return R(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,eG],33603);class eK{match(e){return!!R(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return C(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(C(e.filename)&&0!==e.filename.length&&0!==t)return`Error
|
|
2
|
-
at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,eK],60887);let eQ=["fatal","error","warning","log","info","debug"];function eJ(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class eZ{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(L(e))return e.constructor.name;let t="name"in e?e.name:void 0;return C(t)&&!I(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=eJ(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return C(e)&&!I(e)&&eQ.indexOf(e)>=0}getStack(e){try{if(C(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return C(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(M(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,eZ],12154);class eY{match(e){return L(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${eJ(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,eY],41324);class eX{match(e){return T(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,eX],79478);class e0{match(e){return R(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!L(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return T(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,e0],1802),e.s([],59567);let e1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},e2=new Set([e1.MESSAGE,e1.TIMESTAMP]),e4={enabled:!0,max_bytes:32768};function e3(e){return e?{enabled:e.enabled??e4.enabled,max_bytes:function(e,t){if(!O(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,e4.max_bytes)}:{...e4}}function e5(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(e2.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class e8{constructor(e){this._entries=[],this._totalBytes=0,this._config=e3(e)}setConfig(e){this._config=e3(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=w(e)}catch{return}try{let e=JSON.parse(t);if(!S(e))return;let r=e[e1.MESSAGE],i=e[e1.TIMESTAMP];if(!C(r)||0===r.trim().length||!C(i)&&!O(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=e6(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function e6(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,e4,"EXCEPTION_STEP_INTERNAL_FIELDS",0,e1,"ExceptionStepsBuffer",0,e8,"getUtf8ByteLength",0,e6,"resolveExceptionStepsConfig",0,e3,"stripReservedExceptionStepFields",0,e5],45162),e.s([],21754);class e9{match(e){return M(e)}coerce(e,t){let r=this.getStack(e);return{type:this.getType(e),value:this.getMessage(e,t),stack:r??t.syntheticException?.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:void 0===r}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,e9],13446);let e7=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class te{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(e7);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,te],22175);class tt extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=Error("Response body read timed out");e.name="AbortError",this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=J(()=>{this._bodyReadTimedOut=!0;let e=Error("Response body read timed out");e.name="AbortError",t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class tr extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function ti(e){if(e instanceof tt){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function ts(e){return e instanceof tr}function ta(e){if(e instanceof tt)return 502===e.status||504===e.status;if(!(e instanceof tr))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function tn(e){return"object"==typeof e&&e instanceof tt&&413===e.status}function to(e){return e instanceof tt?408===e.status||429===e.status||e.status>=500:ts(e)}function tl(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let tu="default";class tc{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new ew([new e9,new eZ,new te,new eX],ez())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new ev,this._events=new e_,this._isInitialized=!1;const r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return eb(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=r,this.host=function(e){return e?.replace(/\/+$/,"")}(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:to},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(g.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(g.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=d(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});this.enqueue("capture",n,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,a){let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});await this.sendImmediate("capture",n,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:ta},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,u(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?c(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,c(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof tt)return{type:"api_error",statusCode:e.status};if(e instanceof tr){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,r,i,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=u(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,r,i,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,r,i,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n={geoip_disable:s??this.disableGeoip};a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,r,i,n);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(g.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(g.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(g.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tu}persistedQueueKeyForRoute(e){return g.Queue}getActiveQueueRoutes(){return[tu]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let a=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),n=this.getPersistedProperty(a)||[];n.length>=this.maxQueueSize&&(n.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),n.push({message:s}),this.setPersistedProperty(a,n),this._events.emit(e,s),n.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=J(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,a=tl(s.properties)?s.properties:void 0;return void 0!==r&&a?.$lib===void 0&&(a={...a||{},$lib:r}),void 0!==i&&a?.$lib_version===void 0&&(a={...a||{},$lib_version:i}),a&&(s.properties=a),s.uuid=V(s.uuid,ec),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:Q(),uuid:V(t?.uuid,ec)};return(t?.disableGeoip??this.disableGeoip)&&(tl(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await ti(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>Y([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),Y([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return m(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=tu){let i={api_key:this.apiKey,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:Q()};this.historicalMigration&&(i.historical_migration=!0);let s=w(i),a=`${this.host}${this.getBatchEndpointPath(r)}`,n=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==n&&{"Content-Encoding":"gzip"}},body:n||s};await this.fetchWithRetry(a,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,a=0;for(;i.length>0&&a<s;){let s=i.slice(0,this.maxBatchSize),n=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],a=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,a),i=a,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!tn(e)&&to(e)};try{await this.sendBatch(n,l,e)}catch(e){if(tn(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),this._logger.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof tr||await o(),this._events.emit("error",e),e}await o(),t.push(...n),a+=n.length}}async _sendOtlpBatch({path:e,payload:t}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let r=JSON.stringify(t),i=`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,s=this.disableCompression?null:await this.compressPayload(r),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==s&&{"Content-Encoding":"gzip"}},body:s||r};try{return await this.fetchWithRetry(i,a,{type:"successful-write"},{retryCheck:e=>!tn(e)&&to(e)}),{kind:"ok"}}catch(e){if(tn(e))return{kind:"too-large"};if(to(e))return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",payload:e})}async fetchWithRetry(e,t,r,i,s){let a=t.body?t.body:"",n=-1;try{n=a instanceof Blob?a.size:a instanceof Uint8Array?a.byteLength:Buffer.byteLength(a,"utf8")}catch{n=a instanceof Blob?a.size:a instanceof Uint8Array?a.byteLength:new TextEncoder().encode(a).length}let o={...this._retryOptions,...i},l=0;return await K(async()=>{let i,a,o;l++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=J(()=>{let e=Error(`Request timed out after ${c}ms`);e.name="AbortError",t(e),u.abort(e)},c)}),g=!1,p=()=>o??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new tr(e)}i.then(e=>{u.signal.aborted&&!g&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),g=!0}catch(e){throw new tr(e)}if("no-cors"!==t.mode&&(a.status<200||a.status>=400))throw new tt(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new tr(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...o,retryCheck:e=>{let t=o.retryCheck(e);return t&&l<=o.retryCount&&e instanceof tt&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return Z((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof tt||ts(e))))throw e;await ti(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}e.i(21754),e.i(69309),e.i(10728),e.s(["chromeStackLineParser",0,e$,"createDefaultStackParser",0,ez,"createStackParser",0,eV,"geckoStackLineParser",0,ek,"nodeStackLineParser",0,eU,"opera10StackLineParser",0,eR,"opera11StackLineParser",0,eL,"reverseAndStripFrames",0,eW,"winjsStackLineParser",0,eO],22546),e.i(22546),e.i(59567),e.i(33603),e.i(13446),e.i(60887),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,eG,"ErrorCoercer",0,e9,"ErrorEventCoercer",0,eK,"EventCoercer",0,eY,"ObjectCoercer",0,eZ,"PrimitiveCoercer",0,eX,"PromiseRejectionEventCoercer",0,e0,"StringCoercer",0,te],90166),e.i(90166);class th{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function td(){let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,th],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,td],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,e4,"DOMExceptionCoercer",0,eG,"EXCEPTION_STEP_INTERNAL_FIELDS",0,e1,"ErrorCoercer",0,e9,"ErrorEventCoercer",0,eK,"ErrorPropertiesBuilder",0,ew,"EventCoercer",0,eY,"ExceptionStepsBuffer",0,e8,"ObjectCoercer",0,eZ,"PrimitiveCoercer",0,eX,"PromiseRejectionEventCoercer",0,e0,"ReduceableCache",0,th,"StringCoercer",0,te,"chromeStackLineParser",0,e$,"createDefaultStackParser",0,ez,"createStackParser",0,eV,"geckoStackLineParser",0,ek,"getInjectedReleaseId",0,td,"getUtf8ByteLength",0,e6,"nodeStackLineParser",0,eU,"opera10StackLineParser",0,eR,"opera11StackLineParser",0,eL,"resolveExceptionStepsConfig",0,e3,"reverseAndStripFrames",0,eW,"stripReservedExceptionStepFields",0,e5,"winjsStackLineParser",0,eO],11168);var tg=e.i(11168),tp=tg,tf=e.i(2157),ty=e.i(12714),tm=e.i(50227),t_=e.i(1457);let tv=new tp.ReduceableCache(25),tb=new tp.ReduceableCache(20);async function tw(e,t=ty.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var a,n;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(a=o).startsWith("node:")||a.endsWith(".min.js")||a.endsWith(".min.cjs")||a.endsWith(".min.mjs")||a.startsWith("data:")||void 0!==(n=r).lineno&&n.lineno>1e4||void 0!==n.colno&&n.colno>1e3)&&((0,tm.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let a=tx(e,i);if(void 0===a||tb.get(a))continue;let n=s[e];if(!n)continue;n.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=tS(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=tS(r)),t++}return s}(n);if(o.every(e=>(function(e,t){let r=tv.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(a,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(tv,a,{});l.push(tF(e,o,u,a,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=tx(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=t$(e);i<e;i++){let e=r[i];if(void 0===e)return void tP(t);t.pre_context.push(e)}if(void 0===r[e])return tP(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,tv,i),tv.reduce(),e}async function tE(e,t,r){let i,s=!1;try{i=await t(e,tf.constants.O_RDONLY|tf.constants.O_NONBLOCK);let a=await i.stat();if(!a.isFile())return;if(a.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${a.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function tF(e,t,r,i,s,a){let n=await tE(e,s,a);return void 0===n?void tb.set(i,1):new Promise(e=>{let s,a,o=!1;function l(t){o||(o=!0,t?.destroy(),n.close().then(e,e))}try{s=n.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{tb.set(i,1),l();return}try{a=(0,t_.createInterface)({input:s})}catch{tb.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],g=h[1];function p(){tb.set(i,1),a.close(),a.removeAllListeners(),l(s)}s.on("error",p),a.on("error",p),a.on("close",()=>l(s)),a.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let a=Math.min(s+140,i);return a>i-5&&(a=i),a===i&&(s=Math.max(a-140,0)),r=r.slice(s,a),s>0&&(r=`...${r}`),a<i&&(r+="..."),r}(e,0),u>=g)){if(c===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++c];if(void 0===e){a.close(),a.removeAllListeners();return}d=e[0],g=e[1]}})})}function tP(e){delete e.pre_context,delete e.context_line,delete e.post_context}function tx(e,t){return(0,tm.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function tS(e){return[t$(e),e+7]}function t$(e){return Math.max(1,e-7)}let tC=["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","pinterest","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"],tI=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return tC.concat(t).some(e=>{let t=e.toLowerCase();return -1!==r.indexOf(t)})},tk={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,tk],88096);class tA{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return r.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new tA({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(tk.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(tk.QUOTA_LIMITED),void 0===t&&s.push(tk.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}async function tO(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}let tT=["is_not","is_set"];class tR extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,tR.prototype)}}function tM(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}class tL extends Error{constructor(e){super(e),tM(this,tL)}}class tD extends Error{constructor(e){super(e),tM(this,tD)}}class tj{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:a,...n}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.onMinimalFlagCalledEvents=n.onMinimalFlagCalledEvents,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof tD||t instanceof tL?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof tD||t instanceof tL?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:a=!1}=r;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,i);return{value:i,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:a}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new tL("Flag has experience continuity enabled");let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let r=this.groupTypeMapping[String(n)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new tL("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=a[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new tL(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}getFeatureFlagPayload(e,t){let r=null;if(!1!==t&&null!=t&&("boolean"==typeof t?r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t.toString()]||null:"string"==typeof t&&(r=this.featureFlagsByKey?.[e]?.filters?.payloads?.[t]||null),null!=r)){if("object"==typeof r)return r;if("string"==typeof r)try{return JSON.parse(r)}catch{}return r}return null}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!this.featureFlagsByKey)throw new tL("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new tL(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new tL(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new tL(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in i)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new tL(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else throw new tL(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new tL(`Dependency '${e}' could not be evaluated`)}let n=i[s];return this.flagEvaluatesToExpectedValue(e.value,n)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,a=e.filters||{},n=a.groups||[],o=a.aggregation_group_type_index,l=a.early_exit??!1,{groups:u,groupProperties:c}=i,h=!1;for(let d of n)try{let n=void 0!==d.aggregation_group_type_index?d.aggregation_group_type_index:o,g=r,p=t;if(n!==o&&null!=n){let t=this.groupTypeMapping[String(n)];if(!t||!(t in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${n} not available`));continue}if(!(t in c)){h=!0;continue}g=c[t],p=u[t]}let f=await this.isConditionMatch(e,p,d,g,i);if("match"===f){let t=d.variant,r=a.multivariate?.variants||[];s=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,p)||!0;break}if(l&&"out_of_rollout_bound"===f)return!1}catch(e){if(e instanceof tD)throw e;if(e instanceof tL)h=!0;else throw e}if(void 0!==s)return s;if(h)throw new tL("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let a=r.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type,r=!1;if("cohort"===t){let t=await tU(e,i,this.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s));r="not_in"===e.operator?!t:t}else r="flag"===t?await this.evaluateFlagDependency(e,i,s):tN(e,i,n);if(!r)return"no_match"}if(void 0==a)return"match"}return void 0!=a&&await tB(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){let r=await tB(e.key,t,"variant"),i=this.variantLookupTable(e).find(e=>r>=e.valueMin&&r<e.valueMax);if(i)return i.key}variantLookupTable(e){let t=[],r=0,i=0,s=e.filters||{};return(s.multivariate?.variants||[]).forEach(e=>{i=r+e.rollout_percentage/100,t.push({valueMin:r,valueMax:i,key:e.key}),r=i}),t}updateFlagState(e){this.featureFlags=e.flags,this.featureFlagsByKey=e.flags.reduce((e,t)=>(e[t.key]=t,e),{}),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===e.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(t.flags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new tR(`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.groupTypeMapping={},this.cohorts={},this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new tR(`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 tR(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:!0===r.minimal_flag_called_events};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(i.flags);break}default:return}}catch(e){e instanceof tR&&this.onError?.(e)}finally{this.pollerStopped||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=J(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await Z(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}async function tB(e,t,r=""){return parseInt((await tO(`${e}.${t}${r}`)).slice(0,15),16)/0x1000000000000000}function tN(e,t,r){let i=e.key,s=e.value,a=e.operator||"exact";if(i in t){if("is_not_set"===a)return!1}else{if("is_not_set"===a)return!0;throw new tL(`Property ${i} not found in propertyValues`)}let n=t[i];if(null==n&&!tT.includes(a))return r&&r(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;function o(e,t){return Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase()}function l(e,t,r){if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)}switch(a){case"exact":return o(s,n);case"is_not":return!o(s,n);case"is_set":return i in t;case"icontains":return String(n).toLowerCase().includes(String(s).toLowerCase());case"not_icontains":return!String(n).toLowerCase().includes(String(s).toLowerCase());case"starts_with":return String(n).toLowerCase().startsWith(String(s).toLowerCase());case"not_starts_with":return!String(n).toLowerCase().startsWith(String(s).toLowerCase());case"ends_with":return String(n).toLowerCase().endsWith(String(s).toLowerCase());case"not_ends_with":return!String(n).toLowerCase().endsWith(String(s).toLowerCase());case"regex":return tH(String(s))&&null!==String(n).match(String(s));case"not_regex":return tH(String(s))&&null===String(n).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e,t="number"==typeof s?s:parseFloat(String(s));if(e="number"==typeof n?n:null!=n?parseFloat(String(n)):NaN,Number.isFinite(t)&&Number.isFinite(e))return l(e,t,a);return l(String(n),String(s),a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new tL("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t)return null;{if(!t.groups)return null;let e=parseInt(t.groups.number);if(e>=1e4)return null;let i=t.groups.interval;if("h"==i)r.setUTCHours(r.getUTCHours()-e);else if("d"==i)r.setUTCDate(r.getUTCDate()-e);else if("w"==i)r.setUTCDate(r.getUTCDate()-7*e);else if("m"==i)r.setUTCMonth(r.getUTCMonth()-e);else{if("y"!=i)return null;r.setUTCFullYear(r.getUTCFullYear()-e)}return r}}(String(s));if(null==e&&(e=tG(s)),null==e)throw new tL(`Invalid date: ${s}`);let t=tG(n);if(["is_date_before"].includes(a))return t<e;return t>e}case"semver_eq":return 0===tV(tz(String(n)),tz(String(s)));case"semver_neq":return 0!==tV(tz(String(n)),tz(String(s)));case"semver_gt":return tV(tz(String(n)),tz(String(s)))>0;case"semver_gte":return tV(tz(String(n)),tz(String(s)))>=0;case"semver_lt":return 0>tV(tz(String(n)),tz(String(s)));case"semver_lte":return 0>=tV(tz(String(n)),tz(String(s)));case"semver_tilde":{let e,t=tz(String(n)),{lower:r,upper:i}={lower:[(e=tz(String(s)))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return tV(t,r)>=0&&0>tV(t,i)}case"semver_caret":{let e=tz(String(n)),{lower:t,upper:r}=function(e){let[t,r,i]=tz(e);return{lower:[t,r,i],upper:t>0?[t+1,0,0]:r>0?[0,r+1,0]:[0,0,i+1]}}(String(s));return tV(e,t)>=0&&0>tV(e,r)}case"semver_wildcard":{let e=tz(String(n)),{lower:t,upper:r}=function(e){let t,r,i=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!i)throw new tL(`Invalid wildcard semver: ${e}`);let s=i.split("."),a=t=>{try{return tW(t,e)}catch{throw new tL(`Invalid wildcard semver: ${e}`)}},n=a(s[0]);if(1===s.length)t=[n,0,0],r=[n+1,0,0];else{let e=a(s[1]);t=[n,e,0],r=[n,e+1,0]}return{lower:t,upper:r}}(String(s));return tV(e,t)>=0&&0>tV(e,r)}default:throw new tL(`Unknown operator: ${a}`)}}async function tU(e,t,r,i=!1,s){let a=String(e.value);if(!(a in r))throw new tD(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return tq(r[a],t,r,i,s)}async function tq(e,t,r,i=!1,s){if(!e)return!0;let a=e.type,n=e.values;if(!n||0===n.length)return!0;let o=!1;if("values"in n[0]){for(let e of n)try{let n=await tq(e,t,r,i,s);if("AND"===a){if(!n)return!1}else if(n)return!0}catch(t){if(t instanceof tD)throw t;if(t instanceof tL)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tL("Can't match cohort without a given cohort property value");return"AND"===a}for(let e of n)try{let n;if("cohort"===e.type)n=await tU(e,t,r,i,s);else if("flag"===e.type){if(!s)throw new tL(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);n=await s(e)}else n=tN(e,t);let o=e.negation||!1;if("AND"===a){if(!n&&!o||n&&o)return!1}else if(n&&!o||!n&&o)return!0}catch(t){if(t instanceof tD)throw t;if(t instanceof tL)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new tL("can't match cohort without a given cohort property value");return"AND"===a}function tH(e){try{return new RegExp(e),!0}catch(e){return!1}}function tW(e,t){if(!/^\d+$/.test(e)||e.length>1&&"0"===e[0])throw new tL(`Invalid semver: ${t}`);return parseInt(e,10)}function tz(e){let t=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!t||t.startsWith("."))throw new tL(`Invalid semver: ${e}`);let r=t.split("."),i=t=>void 0===t||""===t?0:tW(t,e);return[i(r[0]),i(r[1]),i(r[2])]}function tV(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function tG(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new tL(`${e} is in an invalid date format`)}throw new tL(`The date provided ${e} must be a string, number, or date object`)}let tK=["--unhandled-rejections","--unhandled_rejections"],tQ=new Set(["throw","strict","warn","warn-with-error-code","none"]),tJ=[...globalThis.process?.execArgv??[]],tZ=globalThis.process?.env?.NODE_OPTIONS;function tY(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=tK.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let a=i===s?e[++r]:i.slice(s.length+1);tQ.has(a)&&(t=a)}return t}let tX=function(e=tJ,t=tZ){return tY(e)??tY(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];"\\"===a&&i&&s+1<e.length?r+=e[++s]:" "!==a||i?'"'===a?i=!i:r+=a:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}();function t0(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function t1(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),O(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),t1(s||r,t,r,i)}class t2{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=t1(e.bucketSize,0,100,e._logger),this._refillRate=t1(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=t1(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var tp=tg;class t4{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new t2({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return S(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let a={...s},n=e.buildFromUnknown(t,r);n.$exception_list=await e.modifyFrames(n.$exception_list);let o=tp.getInjectedReleaseId();return o&&(a.$release_id=o),{event:"$exception",distinctId:i,properties:{...n,...a},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=tX){let s=globalThis.process;if(s){let a;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>t0(t,e,r));s.on("uncaughtException",(a=!1,Object.assign((i,s)=>{let n=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t0(t,i,s),a||0!==n||(a=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=tX){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!t4.isPreviouslyCapturedError(e)){let r=await t4.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=r.properties,s=i?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class t3{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let t5="analytics";class t8 extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(t8.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function t6(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let t9=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:t6},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:t6},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:t6},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],t7=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function re(e,t,r){void 0===r||t in e||(e[t]=r)}function rt(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of t9)if(e in r){let a=s(r[e]);void 0!==a&&(i[t]=a),delete r[e]}let s={};for(let{property:e,field:t}of t7)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,re(r,"$set",e.$set),re(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let rr=new Set([408,500,502,503,504]);class ri{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>J(t,e))),this.generateRequestId=t.generateRequestId??ec,this.compress=t.compress??m}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(rt)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,a=[],n=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=w({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:n});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&rr.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,a,n,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,a,n,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(n,s,a);if(0===c.length)return this.surfacePartialDrops(t,a);if(u)return void this.onError(new t8({requestId:t,drops:a,retryExhausted:c.map(e=>e.uuid)}));n=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,a,n,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,a=this.buildHeaders(r,i),n=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(n=e,a["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=J(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:a,body:n,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r:Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new t8({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new t8({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let rs="ai-capture",ra="/i/v0/ai/batch/",rn=new TextEncoder;function ro(e){return rn.encode(w(e)).length}let rl=new Set;function ru(e,t){rl.has(e)||(rl.add(e),console.warn(`[PostHog] ${t}`))}class rc extends tc{constructor(e,t={}){const r=function(e){return"string"==typeof e?e.trim():""}(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:function(e){return("string"==typeof e?e.trim():"")||"https://us.i.posthog.com"}(t.host),personalApiKey:function(e){return("string"==typeof e?e.trim():"")||void 0}(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new t3,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=function(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===e||"v1"===e?e:"v0"}(),this.enableFullAiCapture=!0===i.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof i.featureFlagsPollingInterval?Math.max(i.featureFlagsPollingInterval,100):3e4,"number"==typeof i.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),"number"==typeof i.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==i.enableLocalEvaluation&&(this.featureFlagsPoller=new tj({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation}))}this.errorTracking=new t4(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=J(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":t5}persistedQueueKeyForRoute(e){return e===rs?g.AiCaptureQueue:"ai"===e?g.AiQueue:g.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[t5,"ai"]:[t5];return this._aiCaptureRouteActive&&e.push(rs),e}getBatchEndpointPath(e){return e===rs?ra:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=t5){if(r===rs)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],a=[],n=0;for(let o of e){if(void 0===o)continue;let e=ro(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}a.length>0&&n+e>r&&(i.push(a),a=[],n=0),a.push(o),n+=e}return a.length>0&&i.push(a),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${ra}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,rs)}catch(i){if(!tn(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${ro(t)} bytes) was rejected with 413 by ${ra} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new ri({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.50.0"}get metrics(){var e;let t;return this._metrics||(this._metrics=new ea(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:a,options:n})=>{let o={timestamp:n.timestamp,disableGeoip:n.disableGeoip,uuid:n.uuid},l={distinctId:t,event:i,properties:{...a,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=V(e.uuid,ec);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=V(e.uuid,ec);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,rs)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,a,n,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:g,disableGeoip:p}=r,{onlyEvaluateLocally:f,personProperties:y,groupProperties:m}=r,_=this.addLocalPersonAndGroupProperties(t,g,y,m);y=_.allPersonProperties,m=_.allGroupProperties;let v=this.createFeatureFlagEvaluationContext(t,g,this.personPropertiesForLocalEvaluation(t,y),m);void 0==f&&(f=this.options.strictLocalEvaluation??!1);let b=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,v,{matchValue:i});if(r){b=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0}}}catch(t){if(t instanceof tD||t instanceof tL)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!b&&!f){let t=await super.getFeatureFlagDetailsStateless(v.distinctId,v.groups,y,m,p,[e]);if(void 0===t)o=tk.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,a=t.requestId,n=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(tk.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(tk.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(tk.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:b,[`$feature/${e}`]:r,$feature_flag_request_id:a,$feature_flag_evaluated_at:b?Date.now():n};if(void 0!==h&&(i.$feature_flag_has_experiment=h),b&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:g,disableGeoip:p,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){ru("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(ru("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){ru("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:a,flagKeys:n}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,n),g={},p={},f=!0;if(d&&(g=d.response,p=d.payloads,f=d.fallbackToFlags),f&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,a,n);g={...g,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:a}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new tA({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new tA({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:n,disableGeoip:o,flagKeys:l}=a||{},{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=a||{},d=this.addLocalPersonAndGroupProperties(s,n,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(s,n,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p={},f=!1,y=!1,m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,l),_=new Set;if(m)for(let[e,t]of Object.entries(m.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];p[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:m.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},_.add(e)}if((!m||m.fallbackToFlags)&&!u){let e=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,f=!!e.errorsWhileComputingFlags,y=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!_.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}p[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete p[e];continue}let r=p[e];p[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=p[e];r&&(p[e]={...r,payload:t})}return new tA({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:p,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:f,quotaLimited:y})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:a,properties:n}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:n,groups:s,disableGeoip:a}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await Z(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=J(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,a]of Object.entries(e))if(R(a,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(a))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(a);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},a=i?.groupProperties||{},n=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!t4.isPreviouslyCapturedError(e)){let a=Error("PostHog syntheticException");this.addPendingPromise(t4.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:a},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!t4.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(t4.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),g=t.includeContextProperties??!0,p=r||h?.distinctId,f=g?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};p||(p=ec(),f.$process_person_profile=!1),g&&h?.sessionId&&!f.$session_id&&(f.$session_id=h.sessionId);let y=this._shouldSendMinimalFlagCalledEvent(i,f)?d(f):f,m=this._runBeforeSend({distinctId:p,event:i,properties:y,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let _=await Promise.resolve().then(async()=>{if(n)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),n._getEventProperties();if(o){ru("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,a,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||a;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof _.$raw_user_agent&&tI(_.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",_.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:_,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var tp=tg,rh=e.i(78500);class rd{constructor(){this.storage=new rh.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}var rg=e.i(27028);let rp=(0,e.i(12057).promisify)(rg.gzip);async function rf(e,t=!0){try{let t=await rp(e);return new Blob([new Uint8Array(t)])}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var tp=tg;let ry="posthog-node";function rm(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[rv.POSTHOG_ID_TAG];if(void 0===o)return n;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();n.tags["PostHog Person URL"]=u;let c=n.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||n.message,$exception_type:c[0]?.type,$exception_level:n.level,$exception_list:h,$sentry_event_id:n.event_id,$sentry_exception:n.exception,$sentry_exception_message:c[0]?.value||n.message,$sentry_exception_type:c[0]?.type,$sentry_tags:n.tags},g=tp.getInjectedReleaseId();return g&&(d.$release_id=g),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function r_(e,t){let r=rm(e,t);return{name:ry,processEvent:e=>r(e)}}class rv{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,s){this.name=ry,this.name=ry,this.setupOnce=function(a,n){a(rm(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,rv,"createEventProcessor",0,rm,"sentryIntegration",0,r_],92164);let rb=/[\x00-\x1f\x7f-\x9f]/g;function rw(e,t,r){null!=r&&""!==r&&(e[t]=r)}function rE(e){return Array.isArray(e)?e[0]:e}function rF(e){if(Array.isArray(e)){for(let t of e){let e=rF(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(rb,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function rP(e,t){var r,i;let s,{sessionId:a,distinctId:n}=function(e){if(!e)return{};let t=rF(e["x-posthog-session-id"]),r=rF(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return rw(o,"$current_url",(r=t.originalUrl||t.url,l?G(r):r)),rw(o,"$request_method",t.method),rw(o,"$request_path",(i=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),l?G(s):s)),rw(o,"$user_agent",rE(t.headers["user-agent"])),rw(o,"$ip",function(e){let t=rE(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==a?{sessionId:a}:{},...void 0!==n?{distinctId:n}:{},properties:o}}function rx(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(rP(r,e),()=>i())}))}function rS(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(t4.isPreviouslyCapturedError(e))return void s(e);let a=rP(r,t),n=Error("Synthetic exception"),o={...void 0!==a.sessionId?{$session_id:a.sessionId}:{},...a.properties||{},$response_status_code:i.statusCode};r.addPendingPromise(t4.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:n},a.distinctId,o).then(e=>r._capturePreparedEvent(e,!1))),s(e)}))}e.s(["setupExpressErrorHandler",0,rS,"setupExpressRequestContext",0,rx],88512),e.s([],52538);class r$ extends rc{getLibraryId(){return"posthog-node"}compressPayload(e){return rf(e,this.isDebug)}initializeContext(){return new rd}createErrorPropertiesBuilder(){let e;return new tp.ErrorPropertiesBuilder([new tp.EventCoercer,new tp.ErrorCoercer,new tp.ObjectCoercer,new tp.StringCoercer,new tp.PrimitiveCoercer],tp.createStackParser("node:javascript",tp.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let r=t?l(e):e;return e=>{if(!e)return;let i=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(i);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>tw(e,void 0,this._logger),function(e=process.cwd()){o.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,o.isAbsolute)(i.filename)&&(i.filename=t((0,o.relative)(r,t(i.filename))));return e}}()])}}e.s(["PostHog",0,r$],89767),e.i(89767),e.i(52538),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,p,"FeatureFlagEvaluations",0,tA,"PostHogSentryIntegration",0,rv,"cookieStateToProperties",0,ey,"cookieStoreFromHeader",0,ed,"createEventProcessor",0,rm,"getPostHogCookieName",0,eg,"parsePostHogCookie",0,em,"readPostHogCookie",0,ef,"sentryIntegration",0,r_,"serializePostHogCookie",0,ep,"setupExpressErrorHandler",0,rS,"setupExpressRequestContext",0,rx,"uuidv7",0,ec],92349),e.i(92349),e.s(["FeatureFlagError",0,p,"FeatureFlagEvaluations",0,tA,"PostHog",0,r$,"PostHogSentryIntegration",0,rv,"cookieStateToProperties",0,ey,"cookieStoreFromHeader",0,ed,"createEventProcessor",0,rm,"getPostHogCookieName",0,eg,"parsePostHogCookie",0,em,"readPostHogCookie",0,ef,"sentryIntegration",0,r_,"serializePostHogCookie",0,ep,"setupExpressErrorHandler",0,rS,"setupExpressRequestContext",0,rx,"uuidv7",0,ec],39702)}];
|
|
1
|
+
module.exports=[39702,e=>{"use strict";let t,r,i,s,a;var n,o=e.i(14747);function l(e){return e.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}let u=e=>void 0===e?void 0:e.variant??e.enabled,c=e=>{if("string"!=typeof e)return e;try{return JSON.parse(e)}catch{return e}},h=["$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","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],d=(e,t=[])=>{let r={},i=t=>{void 0!==e[t]&&(r[t]=e[t])};return h.forEach(i),t.forEach(i),r},g=["is_not","is_set"];class p extends Error{constructor(e){super(e),this.name=this.constructor.name,Object.setPrototypeOf(this,p.prototype)}}function f(e){try{return new RegExp(e),!0}catch{return!1}}function y(e,t,r){if(!/^\d+$/.test(e)||"strict"===r&&e.length>1&&"0"===e[0])throw new p(`Invalid semver: ${t}`);return parseInt(e,10)}function m(e,t="strict"){let r=String(e).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!r||r.startsWith("."))throw new p(`Invalid semver: ${e}`);let i=r.split("."),s=r=>void 0===r||""===r?0:y(r,e,t);return[s(i[0]),s(i[1]),s(i[2])]}function v(e,t){for(let r=0;r<3;r++){if(e[r]<t[r])return -1;if(e[r]>t[r])return 1}return 0}function _(e){if(e instanceof Date)return e;if("string"==typeof e||"number"==typeof e){let t=new Date(e);if(!isNaN(t.valueOf()))return t;throw new p(`${e} is in an invalid date format`)}throw new p(`The date provided ${e} must be a string, number, or date object`)}async function b(e){let t=globalThis.crypto?.subtle;if(!t)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await t.digest("SHA-1",new TextEncoder().encode(e)))).map(e=>e.toString(16).padStart(2,"0")).join("")}async function w(e,t,r=""){return parseInt((await b(`${e}.${t}${r}`)).slice(0,15),16)/0x1000000000000000}function E(e){let t=[],r=0;for(let i of e){let e=r+i.rollout_percentage/100;t.push({valueMin:r,valueMax:e,key:i.key}),r=e}return t}async function F(e,t,r){let i=await w(e,t,"variant");return E(r).find(e=>i>=e.valueMin&&i<e.valueMax)?.key}var P=((n={}).AnonymousId="anonymous_id",n.DistinctId="distinct_id",n.Props="props",n.EnablePersonProcessing="enable_person_processing",n.PersonMode="person_mode",n.FeatureFlagDetails="feature_flag_details",n.FeatureFlags="feature_flags",n.FeatureFlagPayloads="feature_flag_payloads",n.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",n.BootstrapFeatureFlags="bootstrap_feature_flags",n.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",n.OverrideFeatureFlags="override_feature_flags",n.Queue="queue",n.AiQueue="ai_queue",n.AiCaptureQueue="ai_capture_queue",n.LogsQueue="logs_queue",n.OptedOut="opted_out",n.SessionId="session_id",n.SessionStartTimestamp="session_start_timestamp",n.SessionLastTimestamp="session_timestamp",n.PersonProperties="person_properties",n.GroupProperties="group_properties",n.InstalledAppBuild="installed_app_build",n.InstalledAppVersion="installed_app_version",n.SessionReplay="session_replay",n.PushRegistered="push_registered",n.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",n.SurveyLastSeenDate="survey_last_seen_date",n.SurveysSeen="surveys_seen",n.Surveys="surveys",n.RemoteConfig="remote_config",n.FlagsEndpointWasHit="flags_endpoint_was_hit",n.DeviceId="device_id",n);let x={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",TIMEOUT:"timeout",CONNECTION_ERROR:"connection_error",UNKNOWN_ERROR:"unknown_error",apiError:e=>`api_error_${e}`},S="[Truncated]",$="[Unserializable]";function C(e){let t="";for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(t+=e[r]+e[r+1],r++):t+="�"}else t+=i>=56320&&i<=57343?"�":e[r]}return t}function I(e){let t=[];return JSON.stringify(e,function(e,r){if("bigint"==typeof r)return r.toString();if("function"!=typeof r&&"symbol"!=typeof r){if(r instanceof Error)return{name:r.name,message:r.message,stack:r.stack};if(r&&"object"==typeof r){for(;t.length>0&&t[t.length-1]!==this;)t.pop();if(t.includes(r))return"[Circular]";t.push(r)}return r}})??"null"}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let k=Array.isArray,A=Object.prototype;A.hasOwnProperty;let O=A.toString,R=k||function(e){return"[object Array]"===O.call(e)},T=e=>e===Object(e)&&!R(e),M=e=>void 0===e,L=e=>"[object String]"==O.call(e),j=e=>L(e)&&0===e.trim().length,D=e=>null===e,B=e=>M(e)||D(e),N=e=>"[object Number]"==O.call(e)&&e==e;function U(e){return null===e||"object"!=typeof e}function q(e,t){return Object.prototype.toString.call(e)===`[object ${t}]`}function H(e){switch(Object.prototype.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return z(e,Error)}}function W(e){return"u">typeof Event&&z(e,Event)}function z(e,t){try{return e instanceof t}catch{return!1}}let V="Android",G="BlackBerry",K="Nintendo",Q="PlayStation",J="Xbox",Z="Windows",Y="(\\d+(\\.\\d+)?)";RegExp("Version/"+Y),RegExp(J,"i"),RegExp(Q+" \\w+","i"),RegExp(K+" \\w+","i"),RegExp(G+"|PlayBook|BB10","i");RegExp("rv:"+Y),RegExp("Edge?\\/"+Y),RegExp("(Chrome|CrMo)\\/"+Y),RegExp("CriOS\\/"+Y),RegExp("(UCBrowser|UCWEB)\\/"+Y),RegExp("(Opera|OPR)\\/"+Y),RegExp("Firefox\\/"+Y),RegExp("FxiOS\\/"+Y),RegExp("Konqueror[:/]?"+Y,"i"),RegExp(G+" "+Y),RegExp("android\\s"+Y,"i"),RegExp("SamsungBrowser\\/"+Y),RegExp("OculusBrowser\\/"+Y),RegExp("Vivaldi\\/"+Y),RegExp("YaBrowser\\/"+Y),RegExp("Whale\\/"+Y),RegExp("Brave\\/"+Y),RegExp("(DuckDuckGo|Ddg)\\/"+Y),RegExp("PaleMoon\\/"+Y),RegExp("Waterfox\\/"+Y),RegExp("GSA\\/"+Y),RegExp("(rv:|MSIE )"+Y),RegExp("rv:"+Y),RegExp(J+"; "+J+" (.*?)[);]","i"),RegExp(K,"i"),RegExp(Q,"i"),RegExp(Z,"i"),RegExp("("+V+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+V+")","i");let X=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ee(e,t){return"string"==typeof e&&X.test(e)?e:t()}function et(e,t){let r=Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function er(e){return e?e.split("#")[0]:e}async function ei(e,t){let r=null;for(let i=0;i<t.retryCount+1;i++){i>0&&await new Promise(e=>setTimeout(e,t.retryDelay));try{return await e()}catch(e){if(r=e,!t.retryCheck(e))throw e}}throw r}function es(){return new Date().toISOString()}function ea(e,t){let r=setTimeout(e,t);return r?.unref&&r?.unref(),r}async function en(e,t,r){let i;try{return await Promise.race([e,new Promise((e,s)=>{i=ea(()=>{try{r?.(),e()}catch(e){s(e)}},t)})])}finally{clearTimeout(i)}}function eo(e){return Promise.all(e.map(e=>(e??Promise.resolve()).then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}let el=e=>{throw et("NativeGzipValidationError",`Native gzip produced invalid output: ${e}`)},eu=async(e,r)=>{e.size<18&&el("too-short");let i=new Uint8Array(await e.slice(0,10).arrayBuffer());i.length>=2&&31===i[0]&&139===i[1]&&8===i[2]||el("invalid-header");let s=new DataView(await e.slice(e.size-8).arrayBuffer());s.getUint32(0,!0)!==(e=>{let r=(()=>{if(t)return t;t=[];for(let e=0;e<256;e++){let r=e;for(let e=0;e<8;e++)r=1&r?0xedb88320^r>>>1:r>>>1;t[e]=r>>>0}return t})(),i=0xffffffff;for(let t=0;t<e.length;t++)i=r[(i^e[t])&255]^i>>>8;return(0xffffffff^i)>>>0})(r)&&el("invalid-crc");let a=r.length>>>0;s.getUint32(4,!0)!==a&&el("invalid-size")};async function ec(e,t=!0,r){try{let t=new TextEncoder().encode(e),r=new globalThis.CompressionStream("gzip"),i=r.writable.getWriter(),s=i.write(t).then(()=>i.close()).catch(async e=>{try{await i.abort(e)}catch{}throw e}),a=new Response(r.readable).blob(),[n]=await Promise.all([a,s]);return await eu(n,t),n}catch(e){if(r?.rethrow)throw e;return t&&console.error("Failed to gzip compress data",e),null}}let eh=Object.prototype.propertyIsEnumerable;function ed(e,t){try{return eg(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function eg(e,t,r,i){let s=[];for(let a in e)if(eh.call(e,a)){if(s.length>=1e3||r.remainingNodes<=0){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let n=e[a];if(D(n)||M(n))continue;s.push({key:C(a),value:function e(t,r,i,s){if(i.remainingNodes<=0)return{stringValue:S};if(i.remainingNodes--,"[object Boolean]"===O.call(t))return{boolValue:t};if("number"==typeof t){if(!Number.isFinite(t))return{stringValue:String(t)};if(Number.isInteger(t)){if(Number.isSafeInteger(t))return{intValue:String(t)};if("u"<typeof BigInt)return{stringValue:String(t)};let e=BigInt(t).toString();return t>=0x8000000000000000||t<-0x8000000000000000?(r?.debug(`Attribute ${e} is outside the int64 range; encoding it as a string`),{stringValue:e}):{intValue:e}}return{doubleValue:t}}if("string"==typeof t)return{stringValue:C(t)};if("function"==typeof t)return{stringValue:"[Function]"};if("symbol"==typeof t)return{stringValue:String(t)};if("object"==typeof t&&null!==t){if(i.ancestors.has(t))return{stringValue:"[Circular]"};if(s>=20)return{stringValue:S};if(t instanceof Date){let e=Number.isFinite(t.getTime())?t.toISOString():String(t);return{stringValue:"string"==typeof e?C(e):String(e)}}i.ancestors.add(t);try{try{let a=t.toJSON;if("function"==typeof a)return e(a.call(t),r,i,s+1)}catch{}if(R(t))return{arrayValue:{values:function(t,r,i,s){let a=[],n=Math.min(t.length,1e3),o=0;for(;o<n&&i.remainingNodes>0;o++)try{let n=o in t?t[o]:void 0;if(B(n))continue;a.push(e(n,r,i,s))}catch{a.push({stringValue:$})}return t.length>o&&a.push({stringValue:S}),a}(t,r,i,s+1)}};return{kvlistValue:{values:eg(t,r,i,s+1)}}}finally{i.ancestors.delete(t)}}return{stringValue:C(String(t))}}(n,t,r,i)})}catch{s.push({key:C(a),value:{stringValue:$}})}}return s}let ep=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function ef(e){return String(e)+"000000"}function ey(e,t,r,i){let s="";return i&&(s=Object.keys(i).sort().map(e=>`${JSON.stringify(e)}:${JSON.stringify(i[e])}`).join(",")),`${e}\u0000${t}\u0000${r??""}\u0000${s}`}class em{constructor(e,t,r){this._instance=e,this._config=t,this._logger=r,this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._generation=0}count(e,t=1,r){this._capture({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this._capture({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this._capture({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){let e=this._flushPromise,t=(async()=>{e&&await e.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===t&&(this._flushPromise=null)});return this._flushPromise=t,t}drainWindow(){if(0===this._series.size)return null;let e=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(e)}reset(){this._generation++,this._clearFlushTimer(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(e){let t,r;if(this._instance.isDisabled||this._instance.optedOut)return;let i=this._runBeforeSend(e);if(null===i)return;if(!i.name||"string"!=typeof i.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof i.value||!Number.isFinite(i.value))return void this._logger.warn(`Dropping metric '${i.name}': value must be a finite number`);if("count"===i.type&&i.value<0)return void this._logger.warn(`Dropping count '${i.name}': counters are monotonic, value must be >= 0`);try{t=i.attributes?{...i.attributes}:void 0,r=ey(i.type,i.name,i.unit,t)}catch(e){this._logger.warn(`Dropping metric '${i.name}': attributes could not be serialized`,e);return}let s=this._series.get(r);if(!s){if(!this._admitNewSeries())return;s={name:i.name,type:i.type,unit:i.unit,attributes:t,windowStartMs:Date.now()},this._series.set(r,s)}let a=this._typeByName.get(i.name);void 0===a?this._typeByName.set(i.name,i.type):a===i.type||this._typeCollisionWarned.has(i.name)||(this._typeCollisionWarned.add(i.name),this._logger.warn(`Metric name '${i.name}' is already used as a ${a}; recording it as a ${i.type} too will blend both series in charts. Use a distinct name.`)),this._fold(s,i.value),this._armFlushTimer()}_admitNewSeries(){return this._series.size<this._config.maxSeriesPerFlush||(this._seriesCapWarned||(this._seriesCapWarned=!0,this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}_fold(e,t){switch(e.type){case"count":e.total=(e.total??0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:Array(ep.length+1).fill(0)});let r=e.hist;r.count+=1,r.sum+=t,r.min=Math.min(r.min,t),r.max=Math.max(r.max,t),r.bucketCounts[function(e,t){for(let r=0;r<t.length;r++)if(e<=t[r])return r;return t.length}(t,ep)]+=1}}}_runBeforeSend(e){let t=this._config.beforeSend;if(!t)return e;let r=R(t)?t:[t],i=e;for(let e of r)try{let t=e(i);if(!t)return this._logger.info("Metric was rejected in beforeSend function"),null;i=t}catch(e){return this._logger.error("Error in beforeSend function for metric:",e),null}return i}_armFlushTimer(){this._flushTimer||(this._flushTimer=ea(()=>{this._flushTimer=void 0,this.flush().catch(e=>{this._logger.error("Metrics flush failed:",e)})},this._config.flushIntervalMs))}_clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}async _doFlush(){if(0===this._series.size)return;let e=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let t=this._generation,r=await this._instance._sendMetricsBatch(this._buildPayload(e));if(t===this._generation)switch(r.kind){case"ok":return;case"retry-later":this._mergeWindowBack(e),this._armFlushTimer();return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",r.error);return}}_buildPayload(e){var t,r,i,s,a,n,o;return s=this._buildMetrics(e),t=this._config,r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),a={...t.resourceAttributes,"service.name":t.serviceName||"unknown_service",...t.environment&&{"deployment.environment":t.environment},...t.serviceVersion&&{"service.version":t.serviceVersion},"telemetry.sdk.name":r,"telemetry.sdk.version":i},n=this._instance.getLibraryId(),o=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:ed(a)},scopeMetrics:[{scope:{name:n,version:o},metrics:s}]}]}}_buildMetrics(e){let t=ef(Date.now()),r=new Map;for(let i of e.values()){let e=ey(i.type,i.name,i.unit,void 0),s=r.get(e);s||(s={name:i.name,...i.unit&&{unit:i.unit}},"count"===i.type?s.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===i.type?s.gauge={dataPoints:[]}:s.histogram={aggregationTemporality:1,dataPoints:[]},r.set(e,s));let a=ed(i.attributes??{},this._logger),n=ef(i.windowStartMs);if("count"===i.type){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,asDouble:i.total??0};s.sum.dataPoints.push(e)}else if("gauge"===i.type){let e={attributes:a,timeUnixNano:t,asDouble:i.last??0};s.gauge.dataPoints.push(e)}else if(i.hist){let e={attributes:a,startTimeUnixNano:n,timeUnixNano:t,count:i.hist.count,sum:i.hist.sum,min:i.hist.min,max:i.hist.max,bucketCounts:i.hist.bucketCounts,explicitBounds:ep};s.histogram.dataPoints.push(e)}}return Array.from(r.values())}_mergeWindowBack(e){for(let[t,r]of e){let e=this._series.get(t);if(!e){this._admitNewSeries()&&this._series.set(t,r);continue}switch(e.windowStartMs=Math.min(e.windowStartMs,r.windowStartMs),e.type){case"count":e.total=(e.total??0)+(r.total??0);break;case"gauge":break;case"histogram":if(r.hist)if(e.hist){e.hist.count+=r.hist.count,e.hist.sum+=r.hist.sum,e.hist.min=Math.min(e.hist.min,r.hist.min),e.hist.max=Math.max(e.hist.max,r.hist.max);for(let t=0;t<e.hist.bucketCounts.length;t++)e.hist.bucketCounts[t]+=r.hist.bucketCounts[t]}else e.hist=r.hist}}}}let ev="0123456789abcdef";class e_{constructor(e){this.bytes=e}static ofInner(e){if(16===e.length)return new e_(e);throw TypeError("not 128-bit length")}static fromFieldsV7(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>0x3fffffff||i>0xffffffff)throw RangeError("invalid field value");let s=new Uint8Array(16);return s[0]=e/0x10000000000,s[1]=e/0x100000000,s[2]=e/0x1000000,s[3]=e/65536,s[4]=e/256,s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new e_(s)}static parse(e){let t;switch(e.length){case 32:t=/^[0-9a-f]{32}$/i.exec(e)?.[0];break;case 36:t=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("");break;case 38:t=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(e)?.slice(1,6).join("");break;case 45:t=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(e)?.slice(1,6).join("")}if(t){let e=new Uint8Array(16);for(let r=0;r<16;r+=4){let i=parseInt(t.substring(2*r,2*r+8),16);e[r+0]=i>>>24,e[r+1]=i>>>16,e[r+2]=i>>>8,e[r+3]=i}return new e_(e)}throw SyntaxError("could not parse UUID string")}toString(){let e="";for(let t=0;t<this.bytes.length;t++)e+=ev.charAt(this.bytes[t]>>>4),e+=ev.charAt(15&this.bytes[t]),(3===t||5===t||7===t||9===t)&&(e+="-");return e}toHex(){let e="";for(let t=0;t<this.bytes.length;t++)e+=ev.charAt(this.bytes[t]>>>4),e+=ev.charAt(15&this.bytes[t]);return e}toJSON(){return this.toString()}getVariant(){let e=this.bytes[8]>>>4;if(e<0)throw Error("unreachable");if(e<=7)return this.bytes.every(e=>0===e)?"NIL":"VAR_0";if(e<=11)return"VAR_10";if(e<=13)return"VAR_110";if(e<=15)return this.bytes.every(e=>255===e)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new e_(this.bytes.slice(0))}equals(e){return 0===this.compareTo(e)}compareTo(e){for(let t=0;t<16;t++){let r=this.bytes[t]-e.bytes[t];if(0!==r)return Math.sign(r)}return 0}}class eb{constructor(e){this.timestamp=0,this.counter=0,this.random=e??ew()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(e,t){let r=this.generateOrAbortCore(e,t);return void 0===r&&(this.timestamp=0,r=this.generateOrAbortCore(e,t)),r}generateOrAbortCore(e,t){if(!Number.isInteger(e)||e<1||e>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(t<0||t>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+t>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return e_.fromFieldsV7(this.timestamp,Math.trunc(this.counter/0x40000000),this.counter&0x40000000-1,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let e=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return e[6]=64|e[6]>>>4,e[8]=128|e[8]>>>2,e_.ofInner(e)}}let ew=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),eE=()=>eF().toString(),eF=()=>(r||(r=new eb)).generate();function eP(e){let t={};if(e)for(let r of e.split(";")){let[e,...i]=r.trim().split("=");if(e){let r=i.join("=").trim();try{t[e.trim()]=decodeURIComponent(r)}catch{t[e.trim()]=r}}}return{get:e=>e in t?{value:t[e]}:void 0}}function ex(e){let t=e.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${t}_posthog`}function eS(e){let t=Date.now();return JSON.stringify({distinct_id:e,$device_id:e,$user_state:"anonymous",$sesid:[t,eE(),t]})}function e$(e,t){let r=ex(t),i=e.get(r);return i?eI(i.value):null}function eC(e){if(!e)return;let t={};return e.sessionId&&(t.$session_id=e.sessionId),e.deviceId&&(t.$device_id=e.deviceId),Object.keys(t).length>0?t:void 0}function eI(e){if(!e)return null;try{let t=JSON.parse(e);if(!t||"object"!=typeof t||!t.distinct_id)return null;let r=R(t.$sesid)?t.$sesid[1]:void 0;return{distinctId:String(t.distinct_id),isIdentified:"identified"===t.$user_state,sessionId:"string"==typeof r?r:void 0,deviceId:"string"==typeof t.$device_id?t.$device_id:void 0}}catch{return null}}class ek{constructor(){this.events={},this.events={}}on(e,t){return this.events[e]||(this.events[e]=[]),this.events[e].push(t),()=>{this.events[e]=this.events[e].filter(e=>e!==t)}}emit(e,t){for(let r of this.events[e]||[])r(t);for(let r of this.events["*"]||[])r(e,t)}}class eA{add(e){let t=eE(),r=++this.nextId;return this.promiseByIds[t]={id:r,promise:e},e.catch(()=>{}).finally(()=>{delete this.promiseByIds[t]}),e}async join(){let e=Object.values(this.promiseByIds).map(e=>e.promise),t=e.length;for(;t>0;)await Promise.all(e),t=(e=Object.values(this.promiseByIds).map(e=>e.promise)).length}getPromises(e=[],t=this.nextId){let r=new Set(e);return Object.values(this.promiseByIds).filter(e=>e.id<=t&&!r.has(e.promise)).map(e=>e.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let eO=(e,t,r)=>{function i(s,...a){t(()=>{(0,r[s])(e,...a)})}return{debug:(...e)=>{i("debug",...e)},info:(...e)=>{i("log",...e)},warn:(...e)=>{i("warn",...e)},error:(...e)=>{i("error",...e)},critical:(...t)=>{r.error(e,...t)},createLogger:i=>eO(`${e} ${i}`,t,r)}};class eR{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){let r=t&&t.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,t,0).apply(e),s=this.buildParsingContext(t),a=this.parseStacktrace(i,s);return{$exception_list:this.convertToExceptionList(a,r),$exception_level:"error"}}async modifyFrames(e){for(let t of e)t.stacktrace&&t.stacktrace.frames&&R(t.stacktrace.frames)&&(t.stacktrace.frames=await this.applyModifiers(t.stacktrace.frames));return e}coerceFallback(e){return{type:"Error",value:"Unknown error",stack:e.syntheticException?.stack,synthetic:!0}}parseStacktrace(e,t){let r,i;return null!=e.cause&&(r=this.parseStacktrace(e.cause,t)),""!=e.stack&&null!=e.stack&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)),{...e,cause:r,stack:i}}applyChunkIds(e,t){return e.map(e=>(e.filename&&t&&(e.chunk_id=t[e.filename]),e))}applyCoercers(e,t){for(let r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}async applyModifiers(e){let t=e;for(let e of this.modifiers)t=await e(t);return t}convertToExceptionList(e,t){let r={type:e.type,value:e.value,mechanism:{type:t.type??"generic",handled:t.handled??!0,synthetic:e.synthetic??!1}};e.stack&&(r.stacktrace={type:"raw",frames:e.stack});let i=[r];return null!=e.cause&&i.push(...this.convertToExceptionList(e.cause,{...t,handled:!0})),i}buildParsingContext(e){return{chunkIdMap:function(e){let t=globalThis._posthogChunkIds;if(!t)return;let r=Object.keys(t);return a&&r.length===s?a:(s=r.length,a=r.reduce((r,s)=>{i||(i={});let a=i[s];if(a)r[a[0]]=a[1];else{let a=e(s);for(let e=a.length-1;e>=0;e--){let n=a[e],o=n?.filename,l=t[s];if(o&&l){r[o]=l,i[s]=[o,l];break}}}return r},{}))}(this.stackParser),skipFirstLines:e.skipFirstLines??1}}buildCoercingContext(e,t,r=0){let i=(r,i)=>{if(i<=4){let s=this.buildCoercingContext(e,t,i);return this.applyCoercers(r,s)}};return{...t,syntheticException:0==r?t.syntheticException:void 0,mechanism:e,apply:e=>i(e,r),next:e=>i(e,r+1)}}}function eT(e,t,r,i,s){let a={platform:e,filename:t,function:"<anonymous>"===r?"?":r,in_app:!t?.startsWith("webkit-masked-url://")&&"<anonymous>"!==t};return M(i)||(a.lineno=i),M(s)||(a.colno=s),a}e.s(["ErrorPropertiesBuilder",0,eR],69309);let eM=(e,t)=>{let r=-1!==e.indexOf("safari-extension"),i=-1!==e.indexOf("safari-web-extension");return r||i?[-1!==e.indexOf("@")?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},eL=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ej=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,eD=/\((\S*)(?::(\d+))(?::(\d+))\)/,eB=(e,t)=>{let r=eL.exec(e);if(r){let[,e,i,s]=r;return eT(t,e,"?",+i,+s)}let i=ej.exec(e);if(i){if(i[2]&&0===i[2].indexOf("eval")){let e=eD.exec(i[2]);e&&(i[2]=e[1],i[3]=e[2],i[4]=e[3])}let[e,r]=eM(i[1]||"?",i[2]);return eT(t,r,e,i[3]?+i[3]:void 0,i[4]?+i[4]:void 0)}},eN=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,eU=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,eq=(e,t)=>{let r=eN.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){let e=eU.exec(r[3]);e&&(r[1]=r[1]||"eval",r[3]=e[1],r[4]=e[2],r[5]="")}let e=r[3],i=r[1]||"?";return[i,e]=eM(i,e),eT(t,e,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},eH=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,eW=(e,t)=>{let r=eH.exec(e);return r?eT(t,r[2],r[1]||"?",+r[3],r[4]?+r[4]:void 0):void 0},ez=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,eV=(e,t)=>{let r=ez.exec(e);return r?eT(t,r[2],r[3]||"?",+r[1]):void 0},eG=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,eK=(e,t)=>{let r=eG.exec(e);return r?eT(t,r[5],r[3]||r[4]||"?",+r[1],+r[2]):void 0},eQ=/^\s*[-]{4,}$/,eJ=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,eZ=/^Promise\.(?:all|any)$/,eY=/^index \d+$/,eX=(e,t)=>{let r=e.match(eJ);if(r){let e,i,s,a,n;if(r[1]){let t=(s=r[1]).lastIndexOf(".");if("."===s[t-1]&&t--,t>0){e=s.slice(0,t),i=s.slice(t+1);let r=e.indexOf(".Module");r>0&&(s=s.slice(r+1),e=e.slice(0,r))}a=void 0}i&&(a=e,n=i),"<anonymous>"===i&&(n=void 0,s=void 0),void 0===s&&(n=n||"?",s=a?`${a}.${n}`:n);let o=r[2]?.startsWith("file://")?r[2].slice(7):r[2],l="native"===r[5];return o?.match(/\/[A-Z]:/)&&(o=o.slice(1)),o||!r[5]||l||(o=r[5]),eZ.test(s)&&eY.test(o||"")&&(o="node:internal/promise"),{filename:o?decodeURI(o):void 0,module:void 0,function:s,lineno:e0(r[3]),colno:e0(r[4]),in_app:function(e,t=!1){return!(t||e&&!e.startsWith("/")&&!e.match(/^[A-Z]:/)&&!e.startsWith(".")&&!e.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==e&&!e.includes("node_modules/")}(o||"",l),platform:t}}if(e.match(eQ))return{filename:e,platform:t}};function e0(e){return parseInt(e||"",10)||void 0}let e1=/\(error: (.*)\)/;function e2(e){if(!e.length)return[];let t=Array.from(e);return t.reverse(),t.slice(0,50).map(e=>{var r;return{...e,filename:e.filename||((r=t)[r.length-1]||{}).filename,function:e.function||"?"}})}function e4(){return e3("web:javascript",eB,eq)}function e3(e,...t){return(r,i=0)=>{let s=[],a=r.split("\n");for(let r=i;r<a.length;r++){let i=a[r];if(i.length>1024)continue;let n=e1.test(i)?i.replace(e1,"$1"):i;if(!n.match(/\S*Error: /)){for(let r of t){let t=r(n,e);if(t){s.push(t);break}}if(s.length>=50)break}}return e2(s)}}e.s(["createDefaultStackParser",0,e4,"createStackParser",0,e3,"reverseAndStripFrames",0,e2],10728);class e5{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){let r=L(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){let t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return q(e,"DOMException")}isDOMError(e){return q(e,"DOMError")}}e.s(["DOMExceptionCoercer",0,e5],33603);class e8{match(e){return!!q(e,"ErrorEvent")&&(void 0!=e.error||this._hasUsableMessage(e))}coerce(e,t){if(void 0!=e.error)return t.apply(e.error);let r=t.apply(e.message);return{...r,stack:this._buildLocationStack(e)??r.stack,synthetic:!0}}_hasUsableMessage(e){return L(e.message)&&e.message.length>0}_buildLocationStack(e){let t=e.lineno??0,r=e.colno??0;if(L(e.filename)&&0!==e.filename.length&&0!==t)return`Error
|
|
2
|
+
at ${e.filename}:${t}:${r}`}}e.s(["ErrorEventCoercer",0,e8],60887);let e6=["fatal","error","warning","log","info","debug"];function e9(e,t=40){let r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let e=r.length;e>0;e--){let i=r.slice(0,e).join(", ");if(!(i.length>t)){if(e===r.length)return i;return i.length<=t?i:`${i.slice(0,t)}...`}}return""}class e7{match(e){return"object"==typeof e&&null!==e}coerce(e,t){let r=this.getErrorPropertyFromObject(e);return r?t.apply(r):{type:this.getType(e),value:this.getValue(e),stack:this.getStack(e)??t.syntheticException?.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(W(e))return e.constructor.name;let t="name"in e?e.name:void 0;return L(t)&&!j(t)?t:"Error"}getValue(e){if("name"in e&&"string"==typeof e.name){let t=`'${e.name}' captured as exception`;return"message"in e&&"string"==typeof e.message&&(t+=` with message: '${e.message}'`),t}if("message"in e&&"string"==typeof e.message)return e.message;let t=this.getObjectClassName(e),r=e9(e);return`${t&&"Object"!==t?`'${t}'`:"Object"} captured as exception with keys: ${r}`}isSeverityLevel(e){return L(e)&&!j(e)&&e6.indexOf(e)>=0}getStack(e){try{if(L(e.stacktrace)&&e.stacktrace.length>0)return e.stacktrace;return L(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t)){let r=e[t];if(H(r))return r}}getObjectClassName(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch(e){return}}}e.s(["ObjectCoercer",0,e7],12154);class te{match(e){return W(e)}coerce(e,t){let r=e.constructor.name;return{type:r,value:`${r} captured as exception with keys: ${e9(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["EventCoercer",0,te],41324);class tt{match(e){return U(e)}coerce(e,t){return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:t.syntheticException?.stack,synthetic:!0}}}e.s(["PrimitiveCoercer",0,tt],79478);class tr{match(e){return q(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!W(e))return!1;try{let t=e.detail;return null!=t&&"object"==typeof t&&"reason"in t}catch{return!1}}coerce(e,t){let r=this.getUnhandledRejectionReason(e);return U(r)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(r)}`,stack:t.syntheticException?.stack,synthetic:!0}:t.apply(r)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&null!=e.detail&&"object"==typeof e.detail&&"reason"in e.detail)return e.detail.reason}catch{}return e}}e.s(["PromiseRejectionEventCoercer",0,tr],1802),e.s([],59567);let ti={MESSAGE:"$message",TIMESTAMP:"$timestamp"},ts=new Set([ti.MESSAGE,ti.TIMESTAMP]),ta={enabled:!0,max_bytes:32768};function tn(e){return e?{enabled:e.enabled??ta.enabled,max_bytes:function(e,t){if(!N(e)||e===1/0||e===-1/0)return t;let r=Math.floor(e);return r<0?t:r}(e.max_bytes,ta.max_bytes)}:{...ta}}function to(e){if(!e)return{sanitizedProperties:{},droppedKeys:[]};let t=[];return{sanitizedProperties:Object.keys(e).reduce((r,i)=>(ts.has(i)?t.push(i):r[i]=e[i],r),{}),droppedKeys:t}}class tl{constructor(e){this._entries=[],this._totalBytes=0,this._config=tn(e)}setConfig(e){this._config=tn(e),this._trimToMaxBytes()}add(e){let t=function(e){let t;try{t=I(e)}catch{return}try{let e=JSON.parse(t);if(!T(e))return;let r=e[ti.MESSAGE],i=e[ti.TIMESTAMP];if(!L(r)||0===r.trim().length||!L(i)&&!N(i))return;return{step:e,json:t}}catch{return}}(e);if(!t)return;let r=tu(t.json);r>this._config.max_bytes||(this._entries.push({step:t.step,bytes:r}),this._totalBytes+=r,this._trimToMaxBytes())}getAttachable(){return this._entries.map(e=>e.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let e=this._entries.shift();e&&(this._totalBytes-=e.bytes)}}}function tu(e){if("u">typeof TextEncoder)return new TextEncoder().encode(e).length;let t=encodeURIComponent(e),r=0;for(let e=0;e<t.length;e++)"%"===t[e]?(r+=1,e+=2):r+=1;return r}e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,ta,"EXCEPTION_STEP_INTERNAL_FIELDS",0,ti,"ExceptionStepsBuffer",0,tl,"getUtf8ByteLength",0,tu,"resolveExceptionStepsConfig",0,tn,"stripReservedExceptionStepFields",0,to],45162),e.s([],21754);class tc{match(e){return H(e)}coerce(e,t){let r=this.getStack(e);return{type:this.getType(e),value:this.getMessage(e,t),stack:r??t.syntheticException?.stack,cause:e.cause?t.next(e.cause):void 0,synthetic:void 0===r}}getType(e){return e.name||e.constructor.name}getMessage(e,t){let r=e.message;return r.error&&"string"==typeof r.error.message?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}e.s(["ErrorCoercer",0,tc],13446);let th=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class td{match(e){return"string"==typeof e}coerce(e,t){let[r,i]=this.getInfos(e);return{type:r??"Error",value:i??e,stack:t.syntheticException?.stack,synthetic:!0}}getInfos(e){let t="Error",r=e,i=e.match(th);return i&&(t=i[1],r=i[2]),[t,r]}}e.s(["StringCoercer",0,td],22175);class tg extends Error{constructor(e,t,r,i){super("HTTP error while fetching PostHog: status="+e.status+", reqByteLength="+t),this.response=e,this.reqByteLength=t,this.responseBodyDeadline=r,this.abortController=i,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let e=et("AbortError","Response body read timed out");this.cancelResponseBody(e),this.responseBodyTextPromise=Promise.reject(e)}else{let e,t=new Promise((e,t)=>{this.responseBodyTimer=ea(()=>{this._bodyReadTimedOut=!0;let e=et("AbortError","Response body read timed out");t(e),this.cancelResponseBody(e)},this.responseBodyDeadline-Date.now())});try{e=Promise.resolve(this.response.text())}catch(t){e=Promise.reject(t)}this.responseBodyTextPromise=Promise.race([e,t]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(e=>JSON.parse(e))}cancelResponseBody(e){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(e),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class tp extends Error{constructor(e){super("Network error while fetching PostHog",e instanceof Error?{cause:e}:{}),this.error=e,this.name="PostHogFetchNetworkError"}}async function tf(e){if(e instanceof tg){let t="";try{t=await e.text}catch{e.bodyReadTimedOut&&(t="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${e.message}, response body=${t}`,e)}else console.error("Error while flushing PostHog",e);return Promise.resolve()}function ty(e){return e instanceof tp}function tm(e){if(e instanceof tg)return 502===e.status||504===e.status;if(!(e instanceof tp))return!1;let t=e.error;return"ECONNREFUSED"!==(t?.code??t?.cause?.code)}function tv(e){return"object"==typeof e&&e instanceof tg&&413===e.status}function t_(e){return e instanceof tg?408===e.status||429===e.status||e.status>=500:ty(e)}function tb(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}let tw="default";class tE{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new eR([new tc,new e7,new td,new tt],e4())}constructor(e,t={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new eA,this._events=new ek,this._isInitialized=!1;const r="string"==typeof e?e.trim():"",i="string"==typeof t.host?t.host.trim():"",s=!r;this._logger=function(e,t=e=>e()){return eO(e,t,function(e=console){return{log:e.log.bind(e),warn:e.warn.bind(e),error:e.error.bind(e),debug:e.debug.bind(e)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),s&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=r,this.host=function(e){return e?.replace(/\/+$/,"")}(i||"https://us.i.posthog.com"),this.flushAt=t.flushAt?Math.max(t.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,t.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,t.maxQueueSize??1e3),this.flushInterval=t.flushInterval??1e4,this.preloadFeatureFlags=t.preloadFeatureFlags??!0,this.defaultOptIn=t.defaultOptIn??!0,this.disableSurveys=t.disableSurveys??!1,this._retryOptions={retryCount:t.fetchRetryCount??3,retryDelay:t.fetchRetryDelay??3e3,retryCheck:t_},this.requestTimeout=t.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=t.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=t.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=t.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=t.disableGeoip??!0,this.disabled=(t.disabled??!1)||s,this.historicalMigration=t?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=t?.evaluationContexts??t?.evaluationEnvironments,t?.evaluationEnvironments&&!t?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(t?.disableCompression??!1)}logMsgIfDebug(e){this.isDebug&&e()}wrap(e){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?e():void this._initPromise.then(()=>e())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(P.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(P.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(P.OptedOut,!0)})}on(e,t){return this._events.on(e,t)}debug(e=!0){if(this.removeDebugCallback?.(),e){let e=this.on("*",(e,t)=>this._logger.info(e,t));this.removeDebugCallback=()=>{e(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(e){let t=e.properties||{},r={...t,...this.getCommonEventProperties()};var i=r;for(let e of Object.keys(t))(e.startsWith("$feature/")||"$active_feature_flags"===e)&&(i[e]=t[e]);return"$feature_flag_called"===e.event&&!1===r.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(r=d(r)),{distinct_id:e.distinct_id,event:e.event,properties:r}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(e){return this.promiseQueue.add(e)}identifyStateless(e,t,r){this.wrap(()=>{let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};this.enqueue("identify",i,r)})}async identifyStatelessImmediate(e,t,r){let i={...this.buildPayload({distinct_id:e,event:"$identify",properties:t})};await this.sendImmediate("identify",i,r)}captureStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({distinct_id:e,event:t,properties:r});this.enqueue("capture",s,i)})}async captureStatelessImmediate(e,t,r,i){let s=this.buildPayload({distinct_id:e,event:t,properties:r});await this.sendImmediate("capture",s,i)}aliasStateless(e,t,r,i){this.wrap(()=>{let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});this.enqueue("alias",s,i)})}async aliasStatelessImmediate(e,t,r,i){let s=this.buildPayload({event:"$create_alias",distinct_id:t,properties:{...r||{},distinct_id:t,alias:e}});await this.sendImmediate("alias",s,i)}groupIdentifyStateless(e,t,r,i,s,a){this.wrap(()=>{let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});this.enqueue("capture",n,i)})}async groupIdentifyStatelessImmediate(e,t,r,i,s,a){let n=this.buildPayload({distinct_id:s||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{},...a||{}}});await this.sendImmediate("capture",n,i)}async getRemoteConfig(){await this._initPromise;let e=this.host;"https://us.i.posthog.com"===e?e="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===e&&(e="https://eu-assets.i.posthog.com");let t=`${e}/array/${this.apiKey}/config`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(t,r,{type:"required",consume:e=>e.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(e=>{this._logger.error("Remote config could not be loaded",e),this._events.emit("error",e)})}async getFlags(e,t={},r={},i={},s={},a=!1){await this._initPromise;let n=`${this.host}/flags/?v=2${a?"&config=true":""}`,o={token:this.apiKey,distinct_id:e,groups:t,person_properties:r,group_properties:i,...s};r.$device_id&&(o.$device_id=r.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(o.evaluation_contexts=this.evaluationContexts);let l={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(o)};return this._logger.info("Flags URL",n),this.fetchWithRetry(n,l,{type:"required",consume:e=>e.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:tm},this.featureFlagsRequestTimeoutMs).then(e=>({success:!0,response:(e=>{if("flags"in e){let t,r=Object.fromEntries(Object.entries(e.flags??{}).map(([e,t])=>[e,u(t)]).filter(([,e])=>void 0!==e)),i=Object.fromEntries(Object.keys(t=e.flags??{}).filter(e=>{let r=t[e];return r.enabled&&r.metadata&&void 0!==r.metadata.payload}).map(e=>{let r=t[e].metadata?.payload;return[e,r?c(r):void 0]}));return{...e,featureFlags:r,featureFlagPayloads:i}}{let t=e.featureFlags??{},r=Object.fromEntries(Object.entries(e.featureFlagPayloads||{}).map(([e,t])=>[e,c(t)])),i=Object.fromEntries(Object.entries(t).map(([e,t])=>{var i,s;return[e,{key:e,enabled:"string"==typeof(i=t)||i,variant:"string"==typeof i?i:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(s=r[e])?JSON.stringify(s):void 0,description:void 0}}]}));return{...e,featureFlags:t,featureFlagPayloads:r,flags:i}}})(e)})).catch(e=>(this._events.emit("error",e),{success:!1,error:this.categorizeRequestError(e)}))}categorizeRequestError(e){if(e instanceof tg)return{type:"api_error",statusCode:e.status};if(e instanceof tp){let t=e.error;return t instanceof Error&&("AbortError"===t.name||"TimeoutError"===t.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailStateless(e,t,r,i,s,a);if(void 0===n)return{response:void 0,requestId:void 0};let o=u(n.response);return void 0===o&&(o=!1),{response:o,requestId:n.requestId}}async getFeatureFlagDetailStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(t,r,i,s,a,[e]);if(void 0!==n)return{response:n.flags[e],requestId:n.requestId,evaluatedAt:n.evaluatedAt}}async getFeatureFlagPayloadStateless(e,t,r={},i={},s={},a){await this._initPromise;let n=await this.getFeatureFlagPayloadsStateless(t,r,i,s,a,[e]);if(!n)return;let o=n[e];return void 0===o?null:o}async getFeatureFlagPayloadsStateless(e,t={},r={},i={},s,a){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)).payloads}async getFeatureFlagsStateless(e,t={},r={},i={},s,a){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(e,t,r,i,s,a)}async getFeatureFlagsAndPayloadsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n=await this.getFeatureFlagDetailsStateless(e,t,r,i,s,a);return n?{flags:n.featureFlags,payloads:n.featureFlagPayloads,requestId:n.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(e,t={},r={},i={},s,a){await this._initPromise;let n={geoip_disable:s??this.disableGeoip};a&&(n.flag_keys_to_evaluate=a);let o=await this.getFlags(e,t,r,i,n);if(!o.success)return;let l=o.response;return(l.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),l.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:l?.requestId,quotaLimited:l.quotaLimited}):l}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let e=`${this.host}/api/surveys/?token=${this.apiKey}`,t={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},r=await this.fetchWithRetry(e,t,{type:"required",consume:e=>{if(200!==e.status||!e.json){let t=`Surveys API could not be loaded: ${e.status}`,r=Error(t);return this._logger.error(r),this._events.emit("error",Error(t)),Promise.resolve(void 0)}return e.json()}}).catch(e=>{this._logger.error("Surveys API could not be loaded",e),this._events.emit("error",e)}),i=r?.surveys;return i&&this._logger.info("Surveys fetched from API: ",JSON.stringify(i)),i??[]}get props(){return this._props||(this._props=this.getPersistedProperty(P.Props)),this._props||{}}set props(e){this._props=e}async register(e){this.wrap(()=>{this.props={...this.props,...e},this.setPersistedProperty(P.Props,this.props)})}async unregister(e){this.wrap(()=>{delete this.props[e],this.setPersistedProperty(P.Props,this.props)})}processBeforeEnqueue(e){return e}async flushStorage(){}getQueueRouteKey(e){return tw}persistedQueueKeyForRoute(e){return P.Queue}getActiveQueueRoutes(){return[tw]}getRouteQueue(e){return this.getPersistedProperty(this.persistedQueueKeyForRoute(e))||[]}enqueue(e,t,r,i){this.wrap(()=>{if(this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null===(s=this.processBeforeEnqueue(s)))return;s=this.normalizeMessage(s);let a=this.persistedQueueKeyForRoute(i??this.getQueueRouteKey(s)),n=this.getPersistedProperty(a)||[];n.length>=this.maxQueueSize&&(n.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),n.push({message:s}),this.setPersistedProperty(a,n),this._events.emit(e,s),n.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=ea(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(e,t,r,i){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(e,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let s=this.prepareMessage(t,r);if(null!==(s=this.processBeforeEnqueue(s))){s=this.normalizeMessage(s);try{await this.sendBatch([s],void 0,i??this.getQueueRouteKey(s))}catch(e){this._events.emit("error",e)}}}normalizeMessage(e){let{type:t,library:r,library_version:i,...s}=e,a=tb(s.properties)?s.properties:void 0;return void 0!==r&&a?.$lib===void 0&&(a={...a||{},$lib:r}),void 0!==i&&a?.$lib_version===void 0&&(a={...a||{},$lib_version:i}),a&&(s.properties=a),s.uuid=ee(s.uuid,eE),s}normalizeTimestampForWire(e){let t=e instanceof Date?e:"string"==typeof e?new Date(e):null;if(!t||Number.isNaN(t.getTime()))return e;let r=t.toISOString(),i="string"==typeof e?e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}prepareMessage(e,t){let r={...e,timestamp:t?.timestamp?t?.timestamp:es(),uuid:ee(t?.uuid,eE)};return(t?.disableGeoip??this.disableGeoip)&&(tb(r.properties)||(r.properties={}),r.properties.$geoip_disable=!0),r.distinctId&&(r.distinct_id=r.distinctId,delete r.distinctId),r}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flush().catch(async e=>{await tf(e)})}async waitForPendingPromises(e,t=[]){let r=t.filter(e=>!!e),i=0;for(;;){let t=this.promiseQueue.getPromises([...r,...this.flushPromises],e);if(0===t.length)return;i>0&&this._logger.debug(`flush() re-checking ${t.length} pending promise(s) before flushing`),await Promise.all(t.map(e=>e.catch(()=>{}))),i++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(e){if(this.disabled)return Promise.resolve();if(!e&&this.pendingFlushPromise)return this.pendingFlushPromise;let t=this.flushPromise,r=this.promiseQueue.maxId,i=Promise.resolve().then(()=>{if(e)return this.waitForPendingPromises(r,[t,i])}).then(()=>eo([t])).then(()=>(this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=i,this.flushPromise=i,this.flushPromises.add(i),this.addPendingPromise(i),eo([i]).then(()=>{this.flushPromises.delete(i),this.pendingFlushPromise===i&&(this.pendingFlushPromise=null),this.flushPromise===i&&(this.flushPromise=null)}),i}getCustomHeaders(){let e=this.getCustomUserAgent(),t={};return e&&""!==e&&(t["User-Agent"]=e),t}compressPayload(e){return ec(e,this.isDebug)}getBatchEndpointPath(e){return"/batch/"}async sendBatch(e,t,r=tw){let i={api_key:this.apiKey,batch:e.map(e=>{if(!e)return e;let t=this.normalizeTimestampForWire(e.timestamp);return t===e.timestamp?e:{...e,timestamp:t}}),sent_at:es()};this.historicalMigration&&(i.historical_migration=!0);let s=I(i),a=`${this.host}${this.getBatchEndpointPath(r)}`,n=this.disableCompression?null:await this.compressPayload(s),o={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==n&&{"Content-Encoding":"gzip"}},body:n||s};await this.fetchWithRetry(a,o,{type:"successful-write"},t)}async _flush(){let e;this.clearFlushTimer(),await this._initPromise;let t=this.getActiveQueueRoutes();if(!t.some(e=>this.getRouteQueue(e).length>0))return;let r=[];for(let i of t)try{await this._flushRoute(i,r)}catch(t){void 0===e&&(e=t)}if(void 0!==e)throw e;this._events.emit("flush",r)}async _flushRoute(e,t){let r=this.persistedQueueKeyForRoute(e),i=this.getPersistedProperty(r)||[];if(!i.length)return;let s=i.length,a=0;for(;i.length>0&&a<s;){let s=i.slice(0,this.maxBatchSize),n=s.map(e=>void 0===e.message?e.message:this.normalizeMessage(e.message)),o=async()=>{let e=this.getPersistedProperty(r)||[],t=[...s],a=e.filter(e=>{let r=e.message?.uuid,i=t.findIndex(t=>t===e||"string"==typeof r&&r.length>0&&t.message?.uuid===r);return -1===i||(t.splice(i,1),!1)});this.setPersistedProperty(r,a),i=a,this._dequeuedMessagesCount+=s.length,await this.flushStorage()},l={retryCheck:e=>!tv(e)&&t_(e)};try{await this.sendBatch(n,l,e)}catch(e){if(tv(e)&&n.length>1){this.maxBatchSize=Math.max(1,Math.floor(n.length/2)),this._logger.warn(`Received 413 when sending batch of size ${n.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw e instanceof tp||await o(),this._events.emit("error",e),e}await o(),t.push(...n),a+=n.length}}async _sendOtlpBatch({path:e,payload:t}){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let r=JSON.stringify(t),i=`${this.host}/i/v1/${e}?token=${encodeURIComponent(this.apiKey)}`,s=this.disableCompression?null:await this.compressPayload(r),a={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==s&&{"Content-Encoding":"gzip"}},body:s||r};try{return await this.fetchWithRetry(i,a,{type:"successful-write"},{retryCheck:e=>!tv(e)&&t_(e)}),{kind:"ok"}}catch(e){if(tv(e))return{kind:"too-large"};if(t_(e))return{kind:"retry-later",error:e};return{kind:"fatal",error:e}}}async _sendLogsBatch(e){return this._sendOtlpBatch({path:"logs",payload:e})}async _sendMetricsBatch(e){return this._sendOtlpBatch({path:"metrics",payload:e})}async fetchWithRetry(e,t,r,i,s){let a=t.body?t.body:"",n=-1;try{n=a instanceof Blob?a.size:a instanceof Uint8Array?a.byteLength:Buffer.byteLength(a,"utf8")}catch{n=a instanceof Blob?a.size:a instanceof Uint8Array?a.byteLength:new TextEncoder().encode(a).length}let o={...this._retryOptions,...i},l=0;return await ei(async()=>{let i,a,o;l++;let u=new AbortController,c=s??this.requestTimeout,h=Date.now()+c,d=new Promise((e,t)=>{i=ea(()=>{let e=et("AbortError",`Request timed out after ${c}ms`);t(e),u.abort(e)},c)}),g=!1,p=()=>o??=(async()=>{try{await a?.body?.cancel()}catch{}})();try{let i;try{i=this.fetch(e,{signal:u.signal,...t})}catch(e){throw new tp(e)}i.then(e=>{u.signal.aborted&&!g&&Promise.resolve(e.body?.cancel()).catch(()=>{})}).catch(()=>{});try{a=await Promise.race([i,d]),g=!0}catch(e){throw new tp(e)}if("no-cors"!==t.mode&&(a.status<200||a.status>=400))throw new tg(a,n,h,u);if("successful-write"===r.type){try{await Promise.race([p(),d])}catch{}return}try{return await Promise.race([r.consume(a),d])}catch(e){if(u.signal.aborted)throw new tp(e);throw e}}finally{clearTimeout(i),u.signal.aborted&&a&&p()}},{...o,retryCheck:e=>{let t=o.retryCheck(e);return t&&l<=o.retryCount&&e instanceof tg&&e.cancelResponseBody(),t}})}async _shutdown(e=3e4){await this._initPromise;let t=!1;if(this.clearFlushTimer(),!this.disabled)return en((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(e=>this.getRouteQueue(e).length>0);){let e=this._dequeuedMessagesCount;if(await this.flush(),t)break;if(this._dequeuedMessagesCount===e){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(e){if(!("object"==typeof e&&(e instanceof tg||ty(e))))throw e;await tf(e)}})(),e,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:e}),t=!0})}async shutdown(e=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(e).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}e.i(21754),e.i(69309),e.i(10728),e.s(["chromeStackLineParser",0,eB,"createDefaultStackParser",0,e4,"createStackParser",0,e3,"geckoStackLineParser",0,eq,"nodeStackLineParser",0,eX,"opera10StackLineParser",0,eV,"opera11StackLineParser",0,eK,"reverseAndStripFrames",0,e2,"winjsStackLineParser",0,eW],22546),e.i(22546),e.i(59567),e.i(33603),e.i(13446),e.i(60887),e.i(22175),e.i(12154),e.i(41324),e.i(79478),e.i(1802),e.s(["DOMExceptionCoercer",0,e5,"ErrorCoercer",0,tc,"ErrorEventCoercer",0,e8,"EventCoercer",0,te,"ObjectCoercer",0,e7,"PrimitiveCoercer",0,tt,"PromiseRejectionEventCoercer",0,tr,"StringCoercer",0,td],90166),e.i(90166);class tF{constructor(e){this._maxSize=e,this._cache=new Map}get(e){let t=this._cache.get(e);if(void 0!==t)return this._cache.delete(e),this._cache.set(e,t),t}set(e,t){this._cache.set(e,t)}reduce(){for(;this._cache.size>=this._maxSize;){let e=this._cache.keys().next().value;e&&this._cache.delete(e)}}}function tP(){let e=globalThis._posthogReleaseId;return"string"==typeof e&&e.length>0?e:void 0}e.s(["ReduceableCache",0,tF],45294),e.i(45294),e.i(45162),e.s(["getInjectedReleaseId",0,tP],56168),e.i(56168),e.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,ta,"DOMExceptionCoercer",0,e5,"EXCEPTION_STEP_INTERNAL_FIELDS",0,ti,"ErrorCoercer",0,tc,"ErrorEventCoercer",0,e8,"ErrorPropertiesBuilder",0,eR,"EventCoercer",0,te,"ExceptionStepsBuffer",0,tl,"ObjectCoercer",0,e7,"PrimitiveCoercer",0,tt,"PromiseRejectionEventCoercer",0,tr,"ReduceableCache",0,tF,"StringCoercer",0,td,"chromeStackLineParser",0,eB,"createDefaultStackParser",0,e4,"createStackParser",0,e3,"geckoStackLineParser",0,eq,"getInjectedReleaseId",0,tP,"getUtf8ByteLength",0,tu,"nodeStackLineParser",0,eX,"opera10StackLineParser",0,eV,"opera11StackLineParser",0,eK,"resolveExceptionStepsConfig",0,tn,"reverseAndStripFrames",0,e2,"stripReservedExceptionStepFields",0,to,"winjsStackLineParser",0,eW],11168);var tx=e.i(11168),tS=tx,t$=e.i(2157),tC=e.i(12714),tI=e.i(50227),tk=e.i(1457);let tA=new tS.ReduceableCache(25),tO=new tS.ReduceableCache(20);async function tR(e,t=tC.open,r){let i,s={};try{i=process.cwd()}catch{}for(let t=e.length-1;t>=0;t--){var a,n;let r=e[t],o=r?.filename;!(!r||"string"!=typeof o||"number"!=typeof r.lineno||(a=o).startsWith("node:")||a.endsWith(".min.js")||a.endsWith(".min.cjs")||a.endsWith(".min.mjs")||a.startsWith("data:")||void 0!==(n=r).lineno&&n.lineno>1e4||void 0!==n.colno&&n.colno>1e3)&&((0,tI.isAbsolute)(o)||void 0!==i)&&(s[o]||(s[o]=[]),s[o].push(r.lineno))}let o=Object.keys(s);if(0==o.length)return e;let l=[];for(let e of o){let a=tj(e,i);if(void 0===a||tO.get(a))continue;let n=s[e];if(!n)continue;n.sort((e,t)=>e-t);let o=function(e){if(!e.length)return[];let t=0,r=e[0];if("number"!=typeof r)return[];let i=tD(r),s=[];for(;;){if(t===e.length-1){s.push(i);break}let r=e[t+1];if("number"!=typeof r)break;r<=i[1]?i[1]=r+7:(s.push(i),i=tD(r)),t++}return s}(n);if(o.every(e=>(function(e,t){let r=tA.get(e);if(void 0===r)return!1;for(let e=t[0];e<=t[1];e++)if(void 0===r[e])return!1;return!0})(a,e)))continue;let u=function(e,t,r){let i=e.get(t);return void 0===i?(e.set(t,r),r):i}(tA,a,{});l.push(tM(e,o,u,a,t,r))}return await Promise.all(l).catch(()=>{}),e&&e.length>0&&function(e,t,r){for(let i of e)if(i.filename&&void 0===i.context_line&&"number"==typeof i.lineno){let e=tj(i.filename,r),s=void 0===e?void 0:t.get(e);if(void 0===s)continue;!function(e,t,r){if(void 0===t.lineno||void 0===r)return;t.pre_context=[];for(let i=tB(e);i<e;i++){let e=r[i];if(void 0===e)return void tL(t);t.pre_context.push(e)}if(void 0===r[e])return tL(t);t.context_line=r[e];let i=function(e){return e+7}(e);t.post_context=[];for(let s=e+1;s<=i;s++){let e=r[s];if(void 0===e)break;t.post_context.push(e)}}(i.lineno,i,s)}}(e,tA,i),tA.reduce(),e}async function tT(e,t,r){let i,s=!1;try{i=await t(e,t$.constants.O_RDONLY|t$.constants.O_NONBLOCK);let a=await i.stat();if(!a.isFile())return;if(a.size>0xa00000)return void r?.debug(`Skipping source context for oversized file ${e}: ${a.size} bytes exceeds 10485760`);return s=!0,i}catch{return}finally{i&&!s&&await i.close().catch(()=>{})}}async function tM(e,t,r,i,s,a){let n=await tT(e,s,a);return void 0===n?void tO.set(i,1):new Promise(e=>{let s,a,o=!1;function l(t){o||(o=!0,t?.destroy(),n.close().then(e,e))}try{s=n.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{tO.set(i,1),l();return}try{a=(0,tk.createInterface)({input:s})}catch{tO.set(i,1),l(s);return}let u=0,c=0,h=t[0];if(void 0===h)return void l(s);let d=h[0],g=h[1];function p(){tO.set(i,1),a.close(),a.removeAllListeners(),l(s)}s.on("error",p),a.on("error",p),a.on("close",()=>l(s)),a.on("line",e=>{if(!(++u<d)&&(r[u]=function(e,t){let r=e,i=r.length;if(i<=150)return r;t>i&&(t=i);let s=Math.max(t-60,0);s<5&&(s=0);let a=Math.min(s+140,i);return a>i-5&&(a=i),a===i&&(s=Math.max(a-140,0)),r=r.slice(s,a),s>0&&(r=`...${r}`),a<i&&(r+="..."),r}(e,0),u>=g)){if(c===t.length-1){a.close(),a.removeAllListeners();return}let e=t[++c];if(void 0===e){a.close(),a.removeAllListeners();return}d=e[0],g=e[1]}})})}function tL(e){delete e.pre_context,delete e.context_line,delete e.post_context}function tj(e,t){return(0,tI.isAbsolute)(e)?JSON.stringify([null,e]):void 0===t?void 0:JSON.stringify([t,e])}function tD(e){return[tB(e),e+7]}function tB(e){return Math.max(1,e-7)}let tN=["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"],tU=function(e,t=[]){if(!e)return!1;let r=e.toLowerCase();return tN.concat(t).some(e=>{let t=e.toLowerCase();return -1!==r.indexOf(t)})},tq={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};e.s(["FeatureFlagError",0,tq],88096);class tH{constructor(e){this._host=e.host,this._distinctId=e.distinctId,this._groups=e.groups,this._disableGeoip=e.disableGeoip,this._flags=e.flags,this._requestId=e.requestId,this._evaluatedAt=e.evaluatedAt,this._flagDefinitionsLoadedAt=e.flagDefinitionsLoadedAt,this._errorsWhileComputing=e.errorsWhileComputing??!1,this._quotaLimited=e.quotaLimited??!1,this._accessed=e.accessed??new Set,this._isSlice=e.isSlice??!1}isEnabled(e,t={}){let r=this._flags[e];return this._recordAccess(e),r?.enabled??t.defaultValue??!1}getFlag(e){let t=this._flags[e];if(this._recordAccess(e),t)return!!t.enabled&&(t.variant??!0)}getFlagPayload(e){return this._flags[e]?.payload}onlyAccessed(){let e={};for(let t of this._accessed){let r=this._flags[t];r&&(e[t]=r)}return this._cloneWith(e)}only(e){let t={},r=[];for(let i of e){let e=this._flags[i];e?t[i]=e:r.push(i)}return r.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${r.join(", ")}`),this._cloneWith(t)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let e={},t=[];for(let[r,i]of Object.entries(this._flags)){let s=!1!==i.enabled&&(i.variant??!0);e[`$feature/${r}`]=s,i.enabled&&t.push(r)}return t.length>0&&(t.sort(),e.$active_feature_flags=t),e}_cloneWith(e){return new tH({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:e,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(e){if(this._accessed.add(e),""===this._distinctId||this._isSlice&&!(e in this._flags))return;let t=this._flags[e],r=void 0===t?void 0:!1!==t.enabled&&(t.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:t?.id,$feature_flag_version:t?.version,$feature_flag_reason:t?.reason,locally_evaluated:t?.locallyEvaluated??!1,[`$feature/${e}`]:r,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:t?.locallyEvaluated?Date.now():this._evaluatedAt};t?.hasExperiment!==void 0&&(i.$feature_flag_has_experiment=t.hasExperiment),t?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(i.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let s=[];this._errorsWhileComputing&&s.push(tq.ERRORS_WHILE_COMPUTING),this._quotaLimited&&s.push(tq.QUOTA_LIMITED),void 0===t&&s.push(tq.FLAG_MISSING),s.length>0&&(i.$feature_flag_error=s.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:e,response:r,groups:this._groups,disableGeoip:this._disableGeoip,properties:i})}}class tW extends Error{constructor(e){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=e,Object.setPrototypeOf(this,tW.prototype)}}class tz extends Error{constructor(e){super(e),function(e,t){e.name=t.name,Error.captureStackTrace(e,t),Object.setPrototypeOf(e,t.prototype)}(this,tz)}}class tV{constructor({pollingInterval:e,personalApiKey:t,projectApiKey:r,timeout:i,host:s,customHeaders:a,...n}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=e,this.personalApiKey=t,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=i,this.projectApiKey=r,this.host=s,this.poller=void 0,this.fetch=n.fetch||fetch,this.onError=n.onError,this.customHeaders=a,this.onLoad=n.onLoad,this.onMinimalFlagCalledEvents=n.onMinimalFlagCalledEvents,this.cacheProvider=n.cacheProvider,this.strictLocalEvaluation=n.strictLocalEvaluation??!1,this.evaluationContexts=n.evaluationContexts,this.loadFeatureFlags()}debug(e=!0){this.debugMode=e}logMsgIfDebug(e){this.debugMode&&e()}createEvaluationContext(e,t={},r={},i={},s={}){return{distinctId:e,groups:t,personProperties:r,groupProperties:i,evaluationCache:s}}async getFeatureFlag(e,t,r={},i={},s={}){let a,n;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return a;if(void 0!==(n=this.featureFlagsByKey[e])){let o=this.createEvaluationContext(t,r,i,s);try{a=(await this.computeFlagAndPayloadLocally(n,o)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${e} -> ${a}`))}catch(t){t instanceof tz||t instanceof p?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e}: ${t}`))}}return a}async getAllFlagsAndPayloads(e,t){await this.loadFeatureFlags();let r={},i={},s=0==this.featureFlags.length,a=t?t.map(e=>this.featureFlagsByKey[e]).filter(Boolean):this.featureFlags,n={...e,evaluationCache:e.evaluationCache??{}};return await Promise.all(a.map(async e=>{try{let{value:t,payload:s}=await this.computeFlagAndPayloadLocally(e,n);r[e.key]=t,s&&(i[e.key]=s)}catch(t){t instanceof tz||t instanceof p?this.logMsgIfDebug(()=>console.debug(`${t.name} when computing flag locally: ${e.key}: ${t.message}`)):t instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${e.key}: ${t}`)),s=!0}})),{response:r,payloads:i,fallbackToFlags:s}}async computeFlagAndPayloadLocally(e,t,r={}){let i,{matchValue:s,skipLoadCheck:a=!1}=r;if(a||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};i=void 0!==s?s:await this.computeFlagValueLocally(e,t);let n=this.getFeatureFlagPayload(e.key,i);return{value:i,payload:n}}async computeFlagValueLocally(e,t){let{distinctId:r,groups:i,personProperties:s,groupProperties:a}=t;if(!e.active)return!1;if(e.ensure_experience_continuity)throw new p("Flag has experience continuity enabled");let n=(e.filters||{}).aggregation_group_type_index;if(void 0!=n){let r=this.groupTypeMapping[String(n)];if(!r)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${n} for feature flag ${e.key}`)),new p("Flag has unknown group type index");if(!(r in i))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${e.key} without group names passed in`)),!1;"device_id"===e.bucketing_identifier&&(s?.$device_id===void 0||s?.$device_id===null||s?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${e.key}`));let o=a[r];return await this.matchFeatureFlagProperties(e,i[r],o,t)}{let i=this.getBucketingValueForFlag(e,r,s);if(void 0===i)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${e.key} without $device_id, falling back to server evaluation`)),new p(`Can't compute feature flag: ${e.key} without $device_id`);return await this.matchFeatureFlagProperties(e,i,s,t)}}getBucketingValueForFlag(e,t,r){if(e.filters?.aggregation_group_type_index!=void 0)return t;if("device_id"===e.bucketing_identifier){let e=r?.$device_id;if(null==e||""===e)return;return e}return t}getFeatureFlagPayload(e,t){var r=this.featureFlagsByKey?.[e]?.filters?.payloads;if(!1===t||null==t||!r)return null;let i=r["boolean"==typeof t?t.toString():t]||null;return null==i?null:c(i)}async evaluateFlagDependency(e,t,r){let{evaluationCache:i}=r,s=e.key;if(!this.featureFlagsByKey)throw new p("Feature flags not available for dependency evaluation");if(!("dependency_chain"in e))throw new p(`Flag dependency property for '${s}' is missing required 'dependency_chain' field`);let a=e.dependency_chain;if(!Array.isArray(a))throw new p(`Flag dependency property for '${s}' has an invalid 'dependency_chain' (expected array, got ${typeof a})`);if(0===a.length)throw new p(`Circular dependency detected for flag '${s}' (empty dependency chain)`);for(let e of a){if(!(e in i)){let t=this.featureFlagsByKey[e];if(t)if(t.active)try{let s=await this.computeFlagValueLocally(t,r);i[e]=s}catch(t){throw new p(`Error evaluating flag dependency '${e}' for flag '${s}': ${t}`)}else i[e]=!1;else if(this.filteredOutFlagKeys.has(e))i[e]=!1;else throw new p(`Missing flag dependency '${e}' for flag '${s}'`)}if(null==i[e])throw new p(`Dependency '${e}' could not be evaluated`)}let n=i[s];return this.flagEvaluatesToExpectedValue(e.value,n)}flagEvaluatesToExpectedValue(e,t){return"boolean"==typeof e?e===t||"string"==typeof t&&""!==t&&!0===e:"string"==typeof e&&t===e}async matchFeatureFlagProperties(e,t,r,i){let s,a=e.filters||{},n=a.groups||[],o=a.aggregation_group_type_index,l=a.early_exit??!1,{groups:u,groupProperties:c}=i,h=!1;for(let d of n)try{let n=void 0!==d.aggregation_group_type_index?d.aggregation_group_type_index:o,g=r,p=t;if(n!==o&&null!=n){let t=this.groupTypeMapping[String(n)];if(!t||!(t in u)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${e.key}': group type index ${n} not available`));continue}if(!(t in c)){h=!0;continue}g=c[t],p=u[t]}let f=await this.isConditionMatch(e,p,d,g,i);if("match"===f){let t=d.variant,r=a.multivariate?.variants||[];s=t&&r.some(e=>e.key===t)?t:await this.getMatchingVariant(e,p)||!0;break}if(l&&"out_of_rollout_bound"===f){if(h)break;return!1}}catch(e){if(e instanceof tz)throw e;if(e instanceof p)h=!0;else throw e}if(void 0!==s)return s;if(h)throw new p("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(e,t,r,i,s){let a=r.rollout_percentage,n=e=>{this.logMsgIfDebug(()=>console.warn(e))};if((r.properties||[]).length>0){for(let e of r.properties){let t=e.type,r=!1;if("cohort"===t){let t=await tK(e,i,this.cohorts,this.debugMode,e=>this.evaluateFlagDependency(e,i,s));r="not_in"===e.operator?!t:t}else r="flag"===t?await this.evaluateFlagDependency(e,i,s):tG(e,i,n);if(!r)return"no_match"}if(void 0==a)return"match"}return void 0!=a&&await w(e.key,t)>a/100?"out_of_rollout_bound":"match"}async getMatchingVariant(e,t){return F(e.key,t,e.filters?.multivariate?.variants||[])}variantLookupTable(e){return E(e.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(e){if(!this.evaluationContexts||0===this.evaluationContexts.length)return e;let t=new Set(this.evaluationContexts);return e.filter(e=>{let r=e.evaluation_contexts??e.evaluation_tags;return!r||0===r.length||r.some(e=>t.has(e))})}updateFlagState(e){let t=this.filterFlagsByEvaluationContexts(e.flags);this.featureFlags=t,this.featureFlagsByKey=t.reduce((e,t)=>(e[t.key]=t,e),{});let r=new Set(t.map(e=>e.key));this.filteredOutFlagKeys=new Set(e.flags.filter(e=>!r.has(e.key)).map(e=>e.key)),this.groupTypeMapping=e.groupTypeMapping,this.cohorts=e.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===e.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(e){if(this.strictLocalEvaluation)return;let t=e.filter(e=>e.ensure_experience_continuity);t.length>0&&console.warn(`[PostHog] You are using local evaluation but ${t.length} flag(s) have experience continuity enabled: ${t.map(e=>e.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(e){if(!this.cacheProvider)return!1;try{let t=await this.cacheProvider.getFlagDefinitions();if(t)return this.updateFlagState(t),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${e} (${t.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(e){return this.onError?.(Error(`Failed to load from cache: ${e}`)),!1}}async loadFeatureFlags(e=!1){if(!this.loadedSuccessfullyOnce||e)return!e&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(e=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${e}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){return this.shouldBeginExponentialBackoff?Math.min(6e4,this.pollingInterval*2**this.backOffCount):this.pollingInterval}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){this.poller&&(clearTimeout(this.poller),this.poller=void 0);try{let e=!0;if(this.cacheProvider)try{e=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(e){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${e}`))}if(!e&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let t=await this._requestFeatureFlagDefinitions();if(!t)return;switch(t.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=t.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new tW(`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.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new tW(`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 tW(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let r=await t.json()??{};if(!("flags"in r))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(r)}`));this.flagsEtag=t.headers?.get("ETag")??void 0;let i={flags:r.flags??[],groupTypeMapping:r.group_type_mapping||{},cohorts:r.cohorts||{},minimalFlagCalledEvents:!0===r.minimal_flag_called_events};if(this.updateFlagState(i),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&e)try{await this.cacheProvider.onFlagDefinitionsReceived(i)}catch(e){this.onError?.(Error(`Failed to store in cache: ${e}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(e){e instanceof tW&&this.onError?.(e)}finally{this.pollerStopped||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(e="GET",t){let r={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return t&&(r["If-None-Match"]=t),{method:e,headers:r}}async _requestFeatureFlagDefinitions(){let e=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,t=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),r=null;if(this.timeout&&"number"==typeof this.timeout){let e=new AbortController;r=ea(()=>{e.abort()},this.timeout),t.signal=e.signal}try{let i=this.fetch,s=await i(e,t);if(200!==s.status)return clearTimeout(r),s;return{status:s.status,headers:s.headers,body:s.body,text:async()=>{try{return await s.text()}finally{clearTimeout(r)}},json:async()=>{try{return await s.json()}finally{clearTimeout(r)}}}}catch(e){throw clearTimeout(r),e}}async stopPoller(e=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let t=this.cacheProvider.shutdown();t instanceof Promise&&await en(t,e,()=>{throw Error(`Cache shutdown timeout after ${e}ms`)})}catch(e){this.onError?.(Error(`Error during cache shutdown: ${e}`))}}}function tG(e,t,r){return function(e,t,r={}){let i=e.key,s=e.value,a=e.operator||"exact",n=r.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(t,i)){if("is_not_set"===a)return!1}else throw new p(`Property ${i} not found in propertyValues`);let o=t[i];if(null==o&&!g.includes(a))return r.warnFunction?.(`Property ${i} cannot have a value of null/undefined with the ${a} operator`),!1;let l=(e,t)=>Array.isArray(e)?e.map(e=>String(e).toLowerCase()).includes(String(t).toLowerCase()):String(e).toLowerCase()===String(t).toLowerCase(),u=(e,t,r)=>{if("gt"===r)return e>t;if("gte"===r)return e>=t;if("lt"===r)return e<t;if("lte"===r)return e<=t;throw Error(`Invalid operator: ${r}`)};switch(a){case"exact":return l(s,o);case"is_not":return!l(s,o);case"is_set":return!0;case"icontains":return String(o).toLowerCase().includes(String(s).toLowerCase());case"not_icontains":return!String(o).toLowerCase().includes(String(s).toLowerCase());case"starts_with":return String(o).toLowerCase().startsWith(String(s).toLowerCase());case"not_starts_with":return!String(o).toLowerCase().startsWith(String(s).toLowerCase());case"ends_with":return String(o).toLowerCase().endsWith(String(s).toLowerCase());case"not_ends_with":return!String(o).toLowerCase().endsWith(String(s).toLowerCase());case"regex":return f(String(s))&&null!==String(o).match(String(s));case"not_regex":return f(String(s))&&null===String(o).match(String(s));case"gt":case"gte":case"lt":case"lte":{let e="number"==typeof s?s:parseFloat(String(s)),t="number"==typeof o?o:null!=o?parseFloat(String(o)):NaN;if(Number.isFinite(e)&&Number.isFinite(t))return u(t,e,a);return u(String(o),String(s),a)}case"is_date_after":case"is_date_before":{if("boolean"==typeof s)throw new p("Date operations cannot be performed on boolean values");let e=function(e){let t=e.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),r=new Date(new Date().toISOString());if(!t||!t.groups)return null;let i=parseInt(t.groups.number);if(i>=1e4)return null;let s=t.groups.interval;if("h"===s)r.setUTCHours(r.getUTCHours()-i);else if("d"===s)r.setUTCDate(r.getUTCDate()-i);else if("w"===s)r.setUTCDate(r.getUTCDate()-7*i);else if("m"===s)r.setUTCMonth(r.getUTCMonth()-i);else{if("y"!==s)return null;r.setUTCFullYear(r.getUTCFullYear()-i)}return r}(String(s));null==e&&(e=_(s));let t=_(o);return"is_date_before"===a?t<e:t>e}case"semver_eq":return 0===v(m(String(o),n),m(String(s),n));case"semver_neq":return 0!==v(m(String(o),n),m(String(s),n));case"semver_gt":return v(m(String(o),n),m(String(s),n))>0;case"semver_gte":return v(m(String(o),n),m(String(s),n))>=0;case"semver_lt":return 0>v(m(String(o),n),m(String(s),n));case"semver_lte":return 0>=v(m(String(o),n),m(String(s),n));case"semver_tilde":{let e,t=m(String(o),n),{lower:r,upper:i}={lower:[(e=m(String(s),n))[0],e[1],e[2]],upper:[e[0],e[1]+1,0]};return v(t,r)>=0&&0>v(t,i)}case"semver_caret":{let e=m(String(o),n),{lower:t,upper:r}=function(e,t){let[r,i,s]=m(e,t);return{lower:[r,i,s],upper:r>0?[r+1,0,0]:i>0?[0,i+1,0]:[0,0,s+1]}}(String(s),n);return v(e,t)>=0&&0>v(e,r)}case"semver_wildcard":{let e=m(String(o),n),{lower:t,upper:r}=function(e,t){let r=String(e).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!r)throw new p(`Invalid wildcard semver: ${e}`);let i=r.split("."),s=r=>{if("legacy-permissive"===t){let e=parseInt(r,10);if(!isNaN(e))return e}else try{return y(r,e,t)}catch{}throw new p(`Invalid wildcard semver: ${e}`)},a=s(i[0]);if(1===i.length)return{lower:[a,0,0],upper:[a+1,0,0]};let n=s(i[1]);return{lower:[a,n,0],upper:[a,n+1,0]}}(String(s),n);return v(e,t)>=0&&0>v(e,r)}default:throw new p(`Unknown operator: ${a}`)}}(e,t,{warnFunction:r})}async function tK(e,t,r,i=!1,s){let a=String(e.value);if(!(a in r))throw new tz(`cohort ${a} not found in local cohorts - likely a static cohort that requires server evaluation`);return tQ(r[a],t,r,i,s)}async function tQ(e,t,r,i=!1,s){if(!e)return!0;let a=e.type,n=e.values;if(!n||0===n.length)return!0;let o=!1;if("values"in n[0]){for(let e of n)try{let n=await tQ(e,t,r,i,s);if("AND"===a){if(!n)return!1}else if(n)return!0}catch(t){if(t instanceof tz)throw t;if(t instanceof p)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new p("Can't match cohort without a given cohort property value");return"AND"===a}for(let e of n)try{let n;if("cohort"===e.type)n=await tK(e,t,r,i,s);else if("flag"===e.type){if(!s)throw new p(`Flag dependency '${e.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);n=await s(e)}else n=tG(e,t);let o=e.negation||!1;if("AND"===a){if(!n&&!o||n&&o)return!1}else if(n&&!o||!n&&o)return!0}catch(t){if(t instanceof tz)throw t;if(t instanceof p)i&&console.debug(`Failed to compute property ${e} locally: ${t}`),o=!0;else throw t}if(o)throw new p("can't match cohort without a given cohort property value");return"AND"===a}let tJ=["--unhandled-rejections","--unhandled_rejections"],tZ=new Set(["throw","strict","warn","warn-with-error-code","none"]),tY=[...globalThis.process?.execArgv??[]],tX=globalThis.process?.env?.NODE_OPTIONS;function t0(e){let t;for(let r=0;r<e.length;r++){let i=e[r],s=tJ.find(e=>i===e||i.startsWith(`${e}=`));if(!s)continue;let a=i===s?e[++r]:i.slice(s.length+1);tZ.has(a)&&(t=a)}return t}let t1=function(e=tY,t=tX){return t0(e)??t0(function(e){let t=[],r="",i=!1;for(let s=0;s<e.length;s++){let a=e[s];"\\"===a&&i&&s+1<e.length?r+=e[++s]:" "!==a||i?'"'===a?i=!i:r+=a:r&&(t.push(r),r="")}return r&&t.push(r),t}(t??""))??"throw"}();function t2(e,t,r){e(t,{mechanism:{type:"unhandledRejection"===r?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function t4(e,t,r,i,s){if(t>r&&(i.warn("min cannot be greater than max."),t=r),N(e))if(e>r)return i.warn(" cannot be greater than max: "+r+". Using max value instead."),r;else return e<t?(i.warn(" cannot be less than min: "+t+". Using min value instead."),t):e;return i.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+s),t4(s||r,t,r,i)}class t3{constructor(e){this._buckets={},this._onBucketRateLimited=e._onBucketRateLimited,this._bucketSize=t4(e.bucketSize,0,100,e._logger),this._refillRate=t4(e.refillRate,0,this._bucketSize,e._logger),this._refillInterval=t4(e.refillInterval,0,864e5,e._logger)}_applyRefill(e,t){let r=Math.floor((t-e.lastAccess)/this._refillInterval);if(r>0){let t=r*this._refillRate;e.tokens=Math.min(e.tokens+t,this._bucketSize),e.lastAccess=e.lastAccess+r*this._refillInterval}}consumeRateLimit(e){let t=Date.now(),r=String(e),i=this._buckets[r];return i?this._applyRefill(i,t):(i={tokens:this._bucketSize,lastAccess:t},this._buckets[r]=i),0===i.tokens||(i.tokens--,0===i.tokens&&this._onBucketRateLimited?.(e),0===i.tokens)}stop(){this._buckets={}}}var tS=tx;class t5{constructor(e,t,r){this.client=e,this._exceptionAutocaptureEnabled=t.enableExceptionAutocapture||!1,this._logger=r,this._rateLimiter=new t3({...function(e={}){return{refillRate:e.exceptionRateLimiterRefillRate??e.__exceptionRateLimiterRefillRate??1,bucketSize:e.exceptionRateLimiterBucketSize??e.__exceptionRateLimiterBucketSize??10}}(t),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(e){return T(e)&&"__posthog_previously_captured_error"in e&&!0===e.__posthog_previously_captured_error}static async buildEventMessage(e,t,r,i,s){let a={...s},n=e.buildFromUnknown(t,r);n.$exception_list=await e.modifyFrames(n.$exception_list);let o=tS.getInjectedReleaseId();return o&&(a.$release_id=o),{event:"$exception",distinctId:i,properties:{...n,...a},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(t,r,i=t1){let s=globalThis.process;if(s){let a;if("strict"===i)return s.on("uncaughtExceptionMonitor",(e,r)=>t2(t,e,r));s.on("uncaughtException",(a=!1,Object.assign((i,s)=>{let n=e.g.process.listeners("uncaughtException").filter(e=>"domainUncaughtExceptionClear"!==e.name&&!0!==e._posthogErrorHandler).length;t2(t,i,s),a||0!==n||(a=!0,r(i))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(e,t=t1){let r=globalThis.process;r&&"throw"!==t&&"strict"!==t&&"warn-with-error-code"!==t&&r.on("unhandledRejection",t=>{e(t,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(e,t){this.client.addPendingPromise((async()=>{if(!t5.isPreviouslyCapturedError(e)){let r=await t5.buildEventMessage(this.client.getErrorPropertiesBuilder(),e,t),i=r.properties,s=i?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(s)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:s}):this.client._capturePreparedEvent(r,!1)}})())}async onFatalError(e){console.error(e),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}class t8{getProperty(e){return this._memoryStorage[e]}setProperty(e,t){this._memoryStorage[e]=null!==t?t:void 0}constructor(){this._memoryStorage={}}}let t6="analytics";class t9 extends Error{constructor({requestId:e,drops:t,retryExhausted:r,cause:i}){super(t9.buildMessage(e,t,r,i)),this.name="CaptureV1Error",this.requestId=e,this.drops=t,this.retryExhausted=r,this.cause=i}static buildMessage(e,t,r,i){let s=`Capture V1 batch ${e} did not fully deliver: ${t.length} dropped, ${r.length} undelivered`;return i instanceof Error&&(s+=` (${i.message})`),s}}function t7(e){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if("true"===t||"1"===t)return!0;if("false"===t||"0"===t)return!1}}let re=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:t7},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:t7},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:t7},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(e){return"string"==typeof e?e:void 0}}],rt=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function rr(e,t,r){void 0===r||t in e||(e[t]=r)}function ri(e){var t;let r={..."object"==typeof(t=e.properties)&&null!==t&&!Array.isArray(t)?e.properties:{}},i={};for(let{property:e,optionKey:t,coerce:s}of re)if(e in r){let a=s(r[e]);void 0!==a&&(i[t]=a),delete r[e]}let s={};for(let{property:e,field:t}of rt)if(e in r){let i=r[e];"string"==typeof i&&(s[t]=i),delete r[e]}return delete r.$lib,delete r.$lib_version,rr(r,"$set",e.$set),rr(r,"$set_once",e.$set_once),{event:String(e.event??""),uuid:String(e.uuid??""),distinct_id:String(e.distinct_id??""),timestamp:function(e){if("string"==typeof e){let t=new Date(e);if(Number.isNaN(t.getTime()))return new Date().toISOString();let r=t.toISOString(),i=e.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return i&&i.length>3?r.replace(/\.\d{3}Z$/,`.${i}Z`):r}if(e instanceof Date)return Number.isNaN(e.getTime())?new Date().toISOString():e.toISOString();let t=null==e?new Date:new Date(e);return Number.isNaN(t.getTime())?new Date().toISOString():t.toISOString()}(e.timestamp),...s,options:i,properties:r}}let rs=new Set([408,500,502,503,504]);class ra{constructor(e,t){this.config=e,this.maxBackoffMs=e.maxBackoffMs??3e4,this.fetchFn=t.fetch,this.onError=t.onError,this.now=t.now??Date.now,this.sleep=t.sleep??(e=>new Promise(t=>ea(t,e))),this.generateRequestId=t.generateRequestId??eE,this.compress=t.compress??ec}async sendV1Batch(e){if(0===e.length)return;let t=this.generateRequestId(),r=new Date(this.now()).toISOString(),{batch:i}=function(e,{createdAt:t,historicalMigration:r}){let i={created_at:t,batch:e.map(ri)};return r&&(i.historical_migration=!0),i}(e,{createdAt:r,historicalMigration:this.config.historicalMigration}),s=`${this.config.host}/i/v1/analytics/events`,a=[],n=i,o=Math.max(1,this.config.maxAttempts);for(let e=1;e<=o;e++){let i,l,u=e===o,c=I({created_at:r,...this.config.historicalMigration?{historical_migration:!0}:{},batch:n});try{let{response:r,signal:o}=i=await this.sendOnce(s,c,e,t),{status:h}=r;if(h<200||h>=300)if(!u&&rs.has(h)){let t=this.parseRetryAfter(r);await i.waitFor(i.cancelBody()).catch(()=>{}),l=this.backoffDelay(e,t)}else{let e=await this.buildHttpError(r,h,i.waitFor);return this.surfaceBatchFailure(t,a,n,e)}else{let s;try{s=await i.waitFor(this.parseResponse(r))}catch(e){if(o.aborted)throw e;return this.surfaceBatchFailure(t,a,n,Error(`Capture V1 returned an unparseable ${h} response body`))}let c=this.classify(n,s,a);if(0===c.length)return this.surfacePartialDrops(t,a);if(u)return void this.onError(new t9({requestId:t,drops:a,retryExhausted:c.map(e=>e.uuid)}));n=c;let d=this.parseRetryAfter(r);l=this.backoffDelay(e,d)}}catch(r){if(i&&!i.signal.aborted)throw r;if(u)return this.surfaceBatchFailure(t,a,n,r);l=this.backoffDelay(e)}finally{i?.cleanup()}void 0!==l&&await this.sleep(l)}}async sendOnce(e,t,r,i){let s,a=this.buildHeaders(r,i),n=t;if(this.config.compressionEnabled){let e=await this.compress(t,this.config.isDebug);null!==e&&(n=e,a["Content-Encoding"]="gzip")}let o=new AbortController,l="waiting for response headers",u=new Promise((e,t)=>{s=ea(()=>{let e=Error(`Capture V1 request timed out ${l} after ${this.config.requestTimeoutMs}ms`);e.name="AbortError",t(e),o.abort(e)},this.config.requestTimeoutMs)});try{let t,r=this.fetchFn(e,{method:"POST",headers:a,body:n,signal:o.signal}),i=!1;r.then(e=>{o.signal.aborted&&!i&&this.cancelBody(e)}).catch(()=>{});let c=await Promise.race([r,u]);i=!0,l="while reading the response body";let h=!1,d=()=>t??=this.cancelBody(c);return{response:c,signal:o.signal,waitFor:e=>Promise.race([e,u]),cancelBody:d,cleanup:()=>{!h&&(h=!0,clearTimeout(s),o.signal.aborted&&d())}}}catch(e){throw clearTimeout(s),e}}buildHeaders(e,t){let r=`${this.config.libraryId}/${this.config.libraryVersion}`,i={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":r,"PostHog-Attempt":String(e),"PostHog-Request-Id":t,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(i["User-Agent"]=this.config.userAgent),i}classify(e,t,r){let i=t.results??{},s=[];for(let t of e){let e=i[t.uuid];e&&("drop"===e.result?r.push({uuid:t.uuid,details:e.details??void 0}):"retry"===e.result&&s.push(t))}return s}backoffDelay(e,t){let r=Math.min(this.config.initialRetryDelayMs*2**(e-1),this.maxBackoffMs);return void 0===t?r:Math.max(r,Math.min(t,this.maxBackoffMs))}parseRetryAfter(e){let t=e.headers?.get("Retry-After");if(!t)return;let r=t.trim();if(/^\d+$/.test(r)){let e=parseInt(r,10);return Number.isFinite(e)&&e>0?1e3*e:void 0}let i=Date.parse(r);if(Number.isNaN(i))return;let s=i-this.now();return s>0?s:void 0}async parseResponse(e){let t=JSON.parse(await e.text());if("object"!=typeof t||null===t||Array.isArray(t))throw Error("unexpected response shape");let r=t.results;if(void 0!==r&&("object"!=typeof r||null===r||Array.isArray(r)))throw Error("unexpected results shape");return{results:r??{}}}async buildHttpError(e,t,r){let i="";try{i=(await r(e.text())).slice(0,512)}catch{}let s=i?`: ${i}`:"";return Error(`Capture V1 request failed with HTTP ${t}${s}`)}surfaceBatchFailure(e,t,r,i){this.onError(new t9({requestId:e,drops:t,retryExhausted:r.map(e=>e.uuid),cause:i}))}surfacePartialDrops(e,t){t.length>0&&this.onError(new t9({requestId:e,drops:t,retryExhausted:[]}))}async cancelBody(e){try{await e.body?.cancel()}catch{}}}let rn="ai-capture",ro="/i/v0/ai/batch/",rl=new TextEncoder;function ru(e){return rl.encode(I(e)).length}let rc=new Set;function rh(e,t){rc.has(e)||(rc.add(e),console.warn(`[PostHog] ${t}`))}class rd extends tE{constructor(e,t={}){const r=function(e){return"string"==typeof e?e.trim():""}(e),i={...t,maxQueueSize:t.maxQueueSize??1e4,flushInterval:t.flushInterval??5e3,host:function(e){return("string"==typeof e?e.trim():"")||"https://us.i.posthog.com"}(t.host),personalApiKey:function(e){return("string"==typeof e?e.trim():"")||void 0}(t.secretKey??t.personalApiKey)};if(super(r,i),this._memoryStorage=new t8,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=i,this.captureMode=function(){let e="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===e||"v1"===e?e:"v0"}(),this.enableFullAiCapture=!0===i.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof i.featureFlagsPollingInterval?Math.max(i.featureFlagsPollingInterval,100):3e4,"number"==typeof i.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(i.waitUntilDebounceMs,0)),"number"==typeof i.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(i.waitUntilMaxWaitMs,0)),!this.disabled&&i.personalApiKey){if(i.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');!1!==i.enableLocalEvaluation&&(this.featureFlagsPoller=new tV({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:i.personalApiKey,projectApiKey:r,timeout:i.requestTimeout??1e4,host:this.host,fetch:i.fetch,onError:e=>{this._events.emit("error",e)},onLoad:e=>{this._events.emit("localEvaluationFlagsLoaded",e)},onMinimalFlagCalledEvents:e=>{this._minimalFlagCalledEvents=e},customHeaders:this.getCustomHeaders(),cacheProvider:i.flagDefinitionCacheProvider,strictLocalEvaluation:i.strictLocalEvaluation,evaluationContexts:i.evaluationContexts??i.evaluationEnvironments}))}this.errorTracking=new t5(this,i,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=i.maxCacheSize||5e4}enqueue(e,t,r,i){super.enqueue(e,t,r,i),this.scheduleDebouncedFlush()}async flush(){let e=this.flushWithPendingPromises(),t=this.options.waitUntil;if(t&&!this._waitUntilCycle)try{t(e.catch(()=>{}))}catch{}return e}scheduleDebouncedFlush(){let e=this.options.waitUntil;if(!e||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let t,r=new Promise(e=>{t=e});try{e(r)}catch{return}this._waitUntilCycle={resolve:t,startedAt:Date.now(),timer:void 0}}let t=Date.now()-this._waitUntilCycle.startedAt,r=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),t>=r)return void this.resolveWaitUntilFlush();let i=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=ea(()=>{this.resolveWaitUntilFlush()},i)}_consumeWaitUntilCycle(){let e=this._waitUntilCycle;return e&&(clearTimeout(e.timer),this._waitUntilCycle=void 0),e?.resolve}async resolveWaitUntilFlush(){let e=this._consumeWaitUntilCycle();try{await this.flushWithPendingPromises()}catch{}finally{e?.()}}getPersistedProperty(e){return this._memoryStorage.getProperty(e)}setPersistedProperty(e,t){return this._memoryStorage.setProperty(e,t)}fetch(e,t){return this.options.fetch?this.options.fetch(e,t):fetch(e,t)}getQueueRouteKey(e){var t;return"v1"===this.captureMode&&"string"==typeof(t=e).event&&t.event.startsWith("$ai_")?"ai":t6}persistedQueueKeyForRoute(e){return e===rn?P.AiCaptureQueue:"ai"===e?P.AiQueue:P.Queue}getActiveQueueRoutes(){let e="v1"===this.captureMode?[t6,"ai"]:[t6];return this._aiCaptureRouteActive&&e.push(rn),e}getBatchEndpointPath(e){return e===rn?ro:super.getBatchEndpointPath(e)}async sendBatch(e,t,r=t6){if(r===rn)return this.sendAiCaptureBatch(e,t);if("v1"!==this.captureMode||"ai"===r)return super.sendBatch(e,t,r);let i=e.filter(e=>void 0!==e);await this.getV1Sender().sendV1Batch(i)}async sendAiCaptureBatch(e,t){let{batches:r,dropped:i}=function(e,t=8388608,r=5242880){let i=[],s=[],a=[],n=0;for(let o of e){if(void 0===o)continue;let e=ru(o);if(e>t){s.push({event:"string"==typeof o.event?o.event:"unknown",bytes:e});continue}a.length>0&&n+e>r&&(i.push(a),a=[],n=0),a.push(o),n+=e}return a.length>0&&i.push(a),{batches:i,dropped:s}}(e);for(let{event:e,bytes:t}of i){let r=`Event ${e} (${t} bytes) exceeds the 8MiB limit for ${ro}, dropping.`;this._logger.error(r),this._events.emit("error",Error(r))}for(let e of r)await this.sendAiSubBatch(e,t)}async sendAiSubBatch(e,t){try{await super.sendBatch(e,t,rn)}catch(i){if(!tv(i))throw i;if(1===e.length){let[t]=e,r="string"==typeof t.event?t.event:"unknown",i=`Event ${r} (${ru(t)} bytes) was rejected with 413 by ${ro} on its own, dropping.`;this._logger.error(i),this._events.emit("error",Error(i));return}let r=Math.ceil(e.length/2);await this.sendAiSubBatch(e.slice(0,r),t),await this.sendAiSubBatch(e.slice(r),t)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new ra({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(e,t)=>this.fetch(e,t),onError:e=>this._events.emit("error",e),compress:e=>this.compressPayload(e)})),this._v1Sender}getLibraryVersion(){return"5.51.4"}get metrics(){var e;let t;return this._metrics||(this._metrics=new em(this,(e=this.options.metrics,t=e?.resourceAttributes,{serviceName:t?.["service.name"]??e?.serviceName,serviceVersion:t?.["service.version"]??e?.serviceVersion,environment:t?.["deployment.environment"]??e?.environment,resourceAttributes:t,beforeSend:e?.beforeSend,flushIntervalMs:e?.flushIntervalMs??1e4,maxSeriesPerFlush:e?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getCommonEventProperties(){let e=super.getCommonEventProperties();return(this.options.isServer??!0)&&(e.$is_server=!0),e}enable(){return super.optIn()}disable(){return super.optOut()}debug(e=!0){super.debug(e),this.featureFlagsPoller?.debug(e)}_warnIfInvalidCapture(e,t,r){"string"==typeof e&&this._logger.warn(t),"$exception"!==e.event||e._originatedFromCaptureException||this._logger.warn(r)}_sendPreparedEvent(e,t,r,i,s){return this.addPendingPromise(this._prepareEventMessage(t,i).then(({distinctId:t,event:i,properties:a,options:n})=>{let o={timestamp:n.timestamp,disableGeoip:n.disableGeoip,uuid:n.uuid},l={distinctId:t,event:i,properties:{...a,...this.getCommonEventProperties()}};return r?this.sendImmediate(e,l,o,s):this.enqueue(e,l,o,s)}).catch(e=>{e&&console.error(e)}))}_capturePreparedEvent(e,t){return this._sendPreparedEvent("capture",e,t)}capture(e){this._warnIfInvalidCapture(e,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(e,!1)}async captureImmediate(e){return this._warnIfInvalidCapture(e,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(e,!0)}captureAi(e){if(this.disabled)return;let t=ee(e.uuid,eE);return this._sendPreparedAiEvent({...e,uuid:t},!1),t}async captureAiImmediate(e){if(this.disabled)return;let t=ee(e.uuid,eE);return await this._sendPreparedAiEvent({...e,uuid:t},!0),t}_sendPreparedAiEvent(e,t){return"string"!=typeof e?.event||e.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${e.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",e,t,void 0,rn)}identify({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:r},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:e,properties:t={},disableGeoip:r}){let{$set:i,$set_once:s,$anon_distinct_id:a,...n}=t;await this._sendPreparedEvent("identify",{distinctId:e,event:"$identify",properties:{$set:i||n,$set_once:s||{},$anon_distinct_id:a??void 0},disableGeoip:r},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:e,properties:t={},propertiesOnce:r={}}){if(0===Object.keys(t).length&&0===Object.keys(r).length)return;let i={};Object.keys(t).length>0&&(i.$set=t),Object.keys(r).length>0&&(i.$set_once=r),this.capture({distinctId:e,event:"$set",properties:i})}unsetPersonProperties({distinctId:e,properties:t}){let r=(Array.isArray(t)?t:[t]).filter(e=>"string"==typeof e&&e.trim().length>0);0!==r.length&&this.capture({distinctId:e,event:"$set",properties:{$unset:r}})}alias(e){this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(e){await this._sendPreparedEvent("alias",{distinctId:e.distinctId,event:"$create_alias",properties:{distinct_id:e.distinctId,alias:e.alias},disableGeoip:e.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(e=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(t=>{let r=setTimeout(()=>{i(),t(!1)},e),i=this._events.on("localEvaluationFlagsLoaded",e=>{clearTimeout(r),i(),t(e>0)})})}_resolveDistinctId(e,t){return"string"==typeof e?{distinctId:e,options:t}:{distinctId:this.context?.get()?.distinctId,options:e}}async _getFeatureFlagResult(e,t,r={},i){let s,a,n,o,l,u,c,h;if(this.disabled)return void this._logger.warn("The client is disabled");let d=r.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&e in this._flagOverrides){let t=this._flagOverrides[e];if(void 0===t)return;let r=this._payloadOverrides?.[e];return{key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r}}let{groups:g,disableGeoip:f}=r,{onlyEvaluateLocally:y,personProperties:m,groupProperties:v}=r,_=this.addLocalPersonAndGroupProperties(t,g,m,v);m=_.allPersonProperties,v=_.allGroupProperties;let b=this.createFeatureFlagEvaluationContext(t,g,this.personPropertiesForLocalEvaluation(t,m),v);void 0==y&&(y=this.options.strictLocalEvaluation??!1);let w=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let t=this.featureFlagsPoller?.featureFlagsByKey[e];if(t)try{let r=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(t,b,{matchValue:i});if(r){w=!0;let i=r.value;l=t.id,c="Evaluated locally",h=t.has_experiment,s={key:e,enabled:!1!==i,variant:"string"==typeof i?i:void 0,payload:r.payload??void 0}}}catch(t){if(t instanceof tz||t instanceof p)this._logger?.info(`${t.name} when computing flag locally: ${e}: ${t.message}`);else throw t}}if(!w&&!y){let t=await super.getFeatureFlagDetailsStateless(b.distinctId,b.groups,m,v,f,[e]);if(void 0===t)o=tq.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===t.minimalFlagCalledEvents,a=t.requestId,n=t.evaluatedAt;let r=[];t.errorsWhileComputingFlags&&r.push(tq.ERRORS_WHILE_COMPUTING),t.quotaLimited?.includes("feature_flags")&&r.push(tq.QUOTA_LIMITED);let i=t.flags[e];if(void 0===i)r.push(tq.FLAG_MISSING);else{let t;if(l=i.metadata?.id,u=i.metadata?.version,c=i.reason?.description??i.reason?.code,h=i.metadata?.has_experiment,i.metadata?.payload!==void 0)try{t=JSON.parse(i.metadata.payload)}catch{t=i.metadata.payload}s={key:e,enabled:i.enabled,variant:i.variant??void 0,payload:t}}r.length>0&&(o=r.join(","))}}if(d){let r=void 0===s?void 0:!1!==s.enabled&&(s.variant??!0),i={$feature_flag:e,$feature_flag_response:r,$feature_flag_id:l,$feature_flag_version:u,$feature_flag_reason:c,locally_evaluated:w,[`$feature/${e}`]:r,$feature_flag_request_id:a,$feature_flag_evaluated_at:w?Date.now():n};if(void 0!==h&&(i.$feature_flag_has_experiment=h),w&&this.featureFlagsPoller){let e=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==e&&(i.$feature_flag_definitions_loaded_at=e)}o&&(i.$feature_flag_error=o),this._captureFlagCalledEventIfNeeded({distinctId:t,key:e,response:r,groups:g,disableGeoip:f,properties:i})}return void 0!==s&&void 0!==this._payloadOverrides&&e in this._payloadOverrides&&(s={...s,payload:this._payloadOverrides[e]}),s}async getFeatureFlag(e,t,r){rh("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==i)return!1!==i.enabled&&(i.variant??!0)}async getFeatureFlagPayload(e,t,r,i){if(rh("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&e in this._payloadOverrides)return this._payloadOverrides[e];let s=await this._getFeatureFlagResult(e,t,{...i,sendFeatureFlagEvents:!1},r);if(void 0!==s)return s.payload??null}async getFeatureFlagResult(e,t,r){let{distinctId:i,options:s}=this._resolveDistinctId(t,r);return i?this._getFeatureFlagResult(e,i,{...s,sendFeatureFlagEvents:s?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(e){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let t=await this._requestRemoteConfigPayload(e);if(!t)return;let r=await t.json();if("string"==typeof r)try{return JSON.parse(r)}catch(e){}return r}async isFeatureEnabled(e,t,r){rh("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let i=await this._getFeatureFlagResult(e,t,{...r,sendFeatureFlagEvents:r?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===i?void 0:!1!==i.enabled&&!!(i.variant??!0)}async getAllFlags(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);return r?(await this.getAllFlagsAndPayloads(r,i)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(e,t){let{distinctId:r,options:i}=this._resolveDistinctId(e,t);if(!r)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:s,disableGeoip:a,flagKeys:n}=i||{},{onlyEvaluateLocally:o,personProperties:l,groupProperties:u}=i||{},c=this.addLocalPersonAndGroupProperties(r,s,l,u);l=c.allPersonProperties,u=c.allGroupProperties;let h=this.createFeatureFlagEvaluationContext(r,s,this.personPropertiesForLocalEvaluation(r,l),u);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let d=await this.featureFlagsPoller?.getAllFlagsAndPayloads(h,n),g={},p={},f=!0;if(d&&(g=d.response,p=d.payloads,f=d.fallbackToFlags),f&&!o){let e=await super.getFeatureFlagsAndPayloadsStateless(h.distinctId,h.groups,l,u,a,n);g={...g,...e.flags||{}},p={...p,...e.payloads||{}}}return void 0!==this._flagOverrides&&(g={...g,...this._flagOverrides}),void 0!==this._payloadOverrides&&(p={...p,...this._payloadOverrides}),{featureFlags:g,featureFlagPayloads:p}}async evaluateFlags(e,t){let r,i,{distinctId:s,options:a}=this._resolveDistinctId(e,t);if(!s)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new tH({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new tH({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,flags:{}});let{groups:n,disableGeoip:o}=a||{},l=a?.flagKeys??void 0;if(l?.length===0)return new tH({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:{}});let{onlyEvaluateLocally:u,personProperties:c,groupProperties:h}=a||{},d=this.addLocalPersonAndGroupProperties(s,n,c,h);c=d.allPersonProperties,h=d.allGroupProperties;let g=this.createFeatureFlagEvaluationContext(s,n,this.personPropertiesForLocalEvaluation(s,c),h);void 0==u&&(u=this.options.strictLocalEvaluation??!1);let p=l?new Set(l):void 0,f={},y=!1,m=!1,v=await this.featureFlagsPoller?.getAllFlagsAndPayloads(g,l),_=new Set;if(v)for(let[e,t]of Object.entries(v.response)){let r=this.featureFlagsPoller?.featureFlagsByKey[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:v.payloads[e],id:r?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:r?.has_experiment},_.add(e)}let b=void 0!==p&&Array.from(p).some(e=>this.featureFlagsPoller?.featureFlagsByKey[e]===void 0);if((!v||v.fallbackToFlags||b)&&!u){let e=await super.getFeatureFlagDetailsStateless(g.distinctId,g.groups,c,h,o,l);if(e)for(let[t,s]of(this._minimalFlagCalledEvents=!0===e.minimalFlagCalledEvents,r=e.requestId,i=e.evaluatedAt,y=!!e.errorsWhileComputingFlags,m=Array.isArray(e.quotaLimited)&&e.quotaLimited.includes("feature_flags"),Object.entries(e.flags))){let e;if(!_.has(t)){if(s.metadata?.payload!==void 0)try{e=JSON.parse(s.metadata.payload)}catch{e=s.metadata.payload}f[t]={key:t,enabled:s.enabled,variant:s.variant,payload:e,id:s.metadata?.id,version:s.metadata?.version,reason:s.reason?.description??s.reason?.code,locallyEvaluated:!1,hasExperiment:s.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[e,t]of Object.entries(this._flagOverrides)){if(void 0===t){delete f[e];continue}let r=f[e];f[e]={key:e,enabled:!1!==t,variant:"string"==typeof t?t:void 0,payload:r?.payload,id:r?.id,version:r?.version,reason:r?.reason,locallyEvaluated:r?.locallyEvaluated??!1,hasExperiment:r?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[e,t]of Object.entries(this._payloadOverrides)){let r=f[e];r&&(f[e]={...r,payload:t})}if(void 0!==p)for(let e of Object.keys(f))p.has(e)||delete f[e];return new tH({host:this._getFeatureFlagEvaluationsHost(),distinctId:s,groups:n,disableGeoip:o,flags:f,requestId:r,evaluatedAt:i,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:y,quotaLimited:m})}_shouldSendMinimalFlagCalledEvent(e,t){return"$feature_flag_called"===e&&this._minimalFlagCalledEvents&&!1===t.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(e){let{distinctId:t,key:r,response:i,groups:s,disableGeoip:a,properties:n}=e,o=s&&Object.keys(s).length>0?`_${JSON.stringify(Object.entries(s).sort(([e],[t])=>e<t?-1:+(e>t)))}`:"",l=`${r}_${i}${o}`;t in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[t].has(l)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[t]instanceof Set?this.distinctIdHasSentFlagCalls[t].add(l):this.distinctIdHasSentFlagCalls[t]=new Set([l]),this.capture({distinctId:t,event:"$feature_flag_called",properties:n,groups:s,disableGeoip:a}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:e=>this._captureFlagCalledEventIfNeeded(e),logWarning:e=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${e}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:e,groupKey:t,properties:r,distinctId:i,disableGeoip:s}){await this._sendPreparedEvent("capture",{distinctId:i||`$${e}_${t}`,event:"$groupidentify",properties:{$group_type:e,$group_key:t,$group_set:r||{}},disableGeoip:s},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(e){let t=e=>Object.fromEntries(e.map(e=>[e,!0]));if(!1===e){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(e)){this._flagOverrides=t(e);return}if(this._isFeatureFlagOverrideOptions(e)){"flags"in e&&(!1===e.flags?this._flagOverrides=void 0:Array.isArray(e.flags)?this._flagOverrides=t(e.flags):void 0!==e.flags&&(this._flagOverrides={...e.flags})),"payloads"in e&&(!1===e.payloads?this._payloadOverrides=void 0:void 0!==e.payloads&&(this._payloadOverrides={...e.payloads}));return}this._flagOverrides={...e}}_isFeatureFlagOverrideOptions(e){if("object"!=typeof e||null===e||Array.isArray(e))return!1;if("flags"in e){let t=e.flags;if(!1===t||Array.isArray(t)||"object"==typeof t&&null!==t)return!0}if("payloads"in e){let t=e.payloads;if(!1===t||"object"==typeof t&&null!==t)return!0}return!1}withContext(e,t,r){return this.context?this.context.run(e,t,r):t()}getContext(){return this.context?.get()}enterContext(e,t){this.context?.enter(e,t)}async _shutdown(e){let t=Date.now()+(e??3e4),r=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(e),this.errorTracking.shutdown(),this._metrics&&(await en(this._metrics.flush().catch(()=>{}),Math.max(0,t-Date.now())),this._metrics.reset());try{return await super._shutdown(Math.max(0,t-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},r?.()}}async _requestRemoteConfigPayload(e){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let t=`${this.host}/api/projects/@current/feature_flags/${e}/remote_config?token=${encodeURIComponent(this.apiKey)}`,r={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},i=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let e=new AbortController;i=ea(()=>{e.abort()},this.options.requestTimeout),r.signal=e.signal}try{return await this.fetch(t,r)}catch(e){this._events.emit("error",e);return}finally{i&&clearTimeout(i)}}extractPropertiesFromEvent(e,t){if(!e)return{personProperties:{},groupProperties:{}};let r={},i={};for(let[s,a]of Object.entries(e))if(q(a,"Object")&&t&&s in t){let e={};for(let[t,r]of Object.entries(a))e[String(t)]=String(r);i[String(s)]=e}else r[String(s)]=String(a);return{personProperties:r,groupProperties:i}}async getFeatureFlagsForEvent(e,t,r,i){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let s=i?.personProperties||{},a=i?.groupProperties||{},n=i?.flagKeys;if(i?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let i={};for(let[e,r]of Object.entries(t||{}))i[e]=String(r);return await this.getAllFlags(e,{groups:i,personProperties:s,groupProperties:a,disableGeoip:r,onlyEvaluateLocally:!0,flagKeys:n})}return(await super.getFeatureFlagsStateless(e,t,s,a,r)).flags}addLocalPersonAndGroupProperties(e,t,r,i){let s={...r||{}},a={};if(t)for(let e of Object.keys(t))a[e]={$group_key:t[e],...i?.[e]||{}};return{allPersonProperties:s,allGroupProperties:a}}personPropertiesForLocalEvaluation(e,t){return{distinct_id:e,...t||{}}}createFeatureFlagEvaluationContext(e,t,r,i){return{distinctId:e,groups:t||{},personProperties:r||{},groupProperties:i||{},evaluationCache:{}}}captureException(e,t,r,i,s){if(!t5.isPreviouslyCapturedError(e)){let a=Error("PostHog syntheticException");this.addPendingPromise(t5.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:a},t,r).then(e=>this._capturePreparedEvent({...e,uuid:i,flags:s},!1)))}}async captureExceptionImmediate(e,t,r,i){if(!t5.isPreviouslyCapturedError(e)){let s=Error("PostHog syntheticException");return this.addPendingPromise(t5.buildEventMessage(this.getErrorPropertiesBuilder(),e,{syntheticException:s},t,r).then(e=>this.captureImmediate({...e,flags:i})))}}async prepareEventMessage(e){return this._prepareEventMessage(e)}async _prepareEventMessage(e,t={}){let{distinctId:r,event:i,properties:s,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c}=e,h=this.context?.get(),g=t.includeContextProperties??!0,p=r||h?.distinctId,f=g?{...this.props,...h?.properties||{},...s||{}}:{...s||{}};p||(p=eE(),f.$process_person_profile=!1),g&&h?.sessionId&&!f.$session_id&&(f.$session_id=h.sessionId);let y=this._shouldSendMinimalFlagCalledEvent(i,f)?d(f):f,m=this._runBeforeSend({distinctId:p,event:i,properties:y,groups:a,flags:n,sendFeatureFlags:o,timestamp:l,disableGeoip:u,uuid:c});if(!m)return Promise.reject(null);let v=await Promise.resolve().then(async()=>{if(n)return o&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),n._getEventProperties();if(o){rh("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var e=await this.getFeatureFlagsForEvent(m.distinctId,a,u,"object"==typeof o?o:void 0);if(!e)return{};let t={};for(let[r,i]of Object.entries(e))t[`$feature/${r}`]=i;let r=Object.keys(e).filter(t=>!1!==e[t]).sort();return r.length>0&&(t.$active_feature_flags=r),t}return{}}).catch(()=>({})).then(e=>{let t=m.groups||a;return{...e,...m.properties||{},...void 0!==t&&Object.keys(t).length>0?{$groups:t}:{}}});return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof v.$raw_user_agent&&tU(v.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",v.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:v,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.uuid}}}_runBeforeSend(e){let t=this.options.before_send;if(!t)return e;let r=Array.isArray(t)?t:[t],i=e;for(let t of r)try{if(!(i=t(i)))return this._logger.info(`Event '${e.event}' was rejected in beforeSend function`),null;if(!i.properties||0===Object.keys(i.properties).length){let e=`Event '${i.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(e)}}catch(t){return this._logger.error(`Error in before_send function for event '${e.event}':`,t),null}return i}}var tS=tx,rg=e.i(78500);class rp{constructor(){this.storage=new rg.AsyncLocalStorage}get(){return this.storage.getStore()}run(e,t,r){return this.storage.run(this.resolve(e,r),t)}enter(e,t){this.storage.enterWith(this.resolve(e,t))}resolve(e,t){if(t?.fresh===!0)return e;let r=this.get()||{};return{distinctId:e.distinctId??r.distinctId,sessionId:e.sessionId??r.sessionId,properties:{...r.properties||{},...e.properties||{}}}}}var rf=e.i(27028);let ry=(0,e.i(12057).promisify)(rf.gzip);async function rm(e,t=!0){try{let t=await ry(e);return new Uint8Array(t)}catch(e){return t&&console.error("Failed to gzip compress data",e),null}}var tS=tx;let rv="posthog-node";function r_(e,{organization:t,projectId:r,prefix:i,severityAllowList:s=["error"],sendExceptionsToPostHog:a=!0}={}){return n=>{if(!("*"===s||s.includes(n.level)))return n;n.tags||(n.tags={});let o=n.tags[rw.POSTHOG_ID_TAG];if(void 0===o)return n;let l=e.options.host??"https://us.i.posthog.com",u=new URL(`/project/${e.apiKey}/person/${o}`,l).toString();n.tags["PostHog Person URL"]=u;let c=n.exception?.values||[],h=c.map(e=>({...e,stacktrace:e.stacktrace?{...e.stacktrace,type:"raw",frames:(e.stacktrace.frames||[]).map(e=>({...e,platform:"node:javascript"}))}:void 0})),d={$exception_message:c[0]?.value||n.message,$exception_type:c[0]?.type,$exception_level:n.level,$exception_list:h,$sentry_event_id:n.event_id,$sentry_exception:n.exception,$sentry_exception_message:c[0]?.value||n.message,$sentry_exception_type:c[0]?.type,$sentry_tags:n.tags},g=tS.getInjectedReleaseId();return g&&(d.$release_id=g),t&&r&&(d.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+n.event_id),a&&e.capture({event:"$exception",distinctId:o,properties:d}),n}}function rb(e,t){let r=r_(e,t);return{name:rv,processEvent:e=>r(e)}}class rw{static #e=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(e,t,r,i,s){this.name=rv,this.name=rv,this.setupOnce=function(a,n){a(r_(e,{organization:t,projectId:n()?.getClient()?.getDsn()?.projectId,prefix:r,severityAllowList:i,sendExceptionsToPostHog:s??!0}))}}}e.s(["PostHogSentryIntegration",0,rw,"createEventProcessor",0,r_,"sentryIntegration",0,rb],92164);let rE=/[\x00-\x1f\x7f-\x9f]/g;function rF(e,t,r){null!=r&&""!==r&&(e[t]=r)}function rP(e){return Array.isArray(e)?e[0]:e}function rx(e){if(Array.isArray(e)){for(let t of e){let e=rx(t);if(void 0!==e)return e}return}if("string"!=typeof e)return;let t=e.replace(rE,"").trim();if(t)return t.length>1e3?t.slice(0,1e3):t}function rS(e,t){var r,i;let s,{sessionId:a,distinctId:n}=function(e){if(!e)return{};let t=rx(e["x-posthog-session-id"]),r=rx(e["x-posthog-distinct-id"]);return{...void 0!==t?{sessionId:t}:{},...void 0!==r?{distinctId:r}:{}}}(t.headers),o={},l=!0===e.options.disable_capture_url_hashes;return rF(o,"$current_url",(r=t.originalUrl||t.url,l?er(r):r)),rF(o,"$request_method",t.method),rF(o,"$request_path",(i=t.path,s=function(e){if(!e)return e;let t=e.indexOf("?"),r=e.indexOf("#");return -1===t||-1!==r&&r<t?e:`${e.slice(0,t)}${-1===r?"":e.slice(r)}`}(i),l?er(s):s)),rF(o,"$user_agent",rP(t.headers["user-agent"])),rF(o,"$ip",function(e){let t=rP(e.headers["x-forwarded-for"]);if(t){let e=t.split(",")[0].trim();if(e)return e}return e.socket?.remoteAddress}(t)),{...void 0!==a?{sessionId:a}:{},...void 0!==n?{distinctId:n}:{},properties:o}}function r$(e,t){var r;t.use((r=e,(e,t,i)=>{r.withContext(rS(r,e),()=>i())}))}function rC(e,t){var r;t.use((r=e,(e,t,i,s)=>{if(t5.isPreviouslyCapturedError(e))return void s(e);let a=rS(r,t),n=Error("Synthetic exception"),o={...void 0!==a.sessionId?{$session_id:a.sessionId}:{},...a.properties||{},$response_status_code:i.statusCode};r.addPendingPromise(t5.buildEventMessage(r.getErrorPropertiesBuilder(),e,{mechanism:{type:"middleware",handled:!1},syntheticException:n},a.distinctId,o).then(e=>r._capturePreparedEvent(e,!1))),s(e)}))}e.s(["setupExpressErrorHandler",0,rC,"setupExpressRequestContext",0,r$],88512),e.s([],52538);class rI extends rd{getLibraryId(){return"posthog-node"}compressPayload(e){return rm(e,this.isDebug)}initializeContext(){return new rp}createErrorPropertiesBuilder(){let e;return new tS.ErrorPropertiesBuilder([new tS.EventCoercer,new tS.ErrorCoercer,new tS.ObjectCoercer,new tS.StringCoercer,new tS.PrimitiveCoercer],tS.createStackParser("node:javascript",tS.nodeStackLineParser),[(e=function(e=process.argv[1]?(0,o.dirname)(process.argv[1]):process.cwd(),t="\\"===o.sep){let r=t?l(e):e;return e=>{if(!e)return;let i=t?l(e):e,{dir:s,base:a,ext:n}=o.posix.parse(i);(".js"===n||".mjs"===n||".cjs"===n)&&(a=a.slice(0,-1*n.length));let u=decodeURIComponent(a);s||(s=".");let c=s.lastIndexOf("/node_modules");if(c>-1)return`${s.slice(c+14).replace(/\//g,".")}:${u}`;if(s.startsWith(r)){let e=s.slice(r.length+1).replace(/\//g,".");return e?`${e}:${u}`:u}return u}}(),async t=>{for(let r of t)r.module=e(r.filename);return t}),e=>tR(e,void 0,this._logger),function(e=process.cwd()){o.sep;let t=e=>e,r=t(e);return async e=>{for(let i of e)!(!i.filename||i.filename.startsWith("node:")||i.filename.startsWith("data:"))&&(0,o.isAbsolute)(i.filename)&&(i.filename=t((0,o.relative)(r,t(i.filename))));return e}}()])}}e.s(["PostHog",0,rI],89767),e.i(89767),e.i(52538),e.i(92164),e.i(88512),e.i(88096),e.s(["FeatureFlagError",0,x,"FeatureFlagEvaluations",0,tH,"PostHogSentryIntegration",0,rw,"cookieStateToProperties",0,eC,"cookieStoreFromHeader",0,eP,"createEventProcessor",0,r_,"getPostHogCookieName",0,ex,"parsePostHogCookie",0,eI,"readPostHogCookie",0,e$,"sentryIntegration",0,rb,"serializePostHogCookie",0,eS,"setupExpressErrorHandler",0,rC,"setupExpressRequestContext",0,r$,"uuidv7",0,eE],92349),e.i(92349),e.s(["FeatureFlagError",0,x,"FeatureFlagEvaluations",0,tH,"PostHog",0,rI,"PostHogSentryIntegration",0,rw,"cookieStateToProperties",0,eC,"cookieStoreFromHeader",0,eP,"createEventProcessor",0,r_,"getPostHogCookieName",0,ex,"parsePostHogCookie",0,eI,"readPostHogCookie",0,e$,"sentryIntegration",0,rb,"serializePostHogCookie",0,eS,"setupExpressErrorHandler",0,rC,"setupExpressRequestContext",0,r$,"uuidv7",0,eE],39702)}];
|
|
3
3
|
|
|
4
4
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_01r25oi._.js.map
|