failproofai 1.0.8 → 1.0.9-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/.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.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.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 +4 -4
- 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.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.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.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 +8 -8
- 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/[root-of-the-server]__0o07qi9._.js +1 -1
- package/.next/standalone/.next/server/chunks/_09dz7xv._.js +20 -20
- 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 +2 -2
- 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_1aveq0u._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__03m2iw6._.js +3 -0
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__04usis8._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__056wjo4._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0n0xg95._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0rwtwpm._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__12e7nhs._.js → [root-of-the-server]__1-bm5zf._.js} +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__11mayhe._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15578wp._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1m_svbe._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1pprgri._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1q4p5b8._.js +2 -2
- package/.next/standalone/.next/server/chunks/ssr/_042cgl1._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_08x1r5t._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_0bqoto4._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/_11ilmst._.js +23 -0
- package/.next/standalone/.next/server/chunks/ssr/_1gb0ifp._.js +3 -3
- package/.next/standalone/.next/server/chunks/ssr/{_0-vcssj._.js → _1jatlmf._.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 +3 -3
- package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9sni._.js +1 -1
- 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_02tf1h4._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_effective-reviewers_ts_1h4wtvo._.js +1 -1
- package/.next/standalone/.next/server/chunks/ssr/src_hooks_semantic_pack-policies_ts_0gh_bu_._.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 +23 -23
- package/.next/standalone/.next/static/chunks/{06jxjnw8bfczc.js → 0542cuk_va8g1.js} +1 -1
- package/.next/standalone/.next/static/chunks/{0wbjy0zo-m7is.js → 08ckontevw-0w.js} +1 -1
- package/.next/standalone/.next/static/chunks/0pefjgvu4x-sx.js +1 -0
- package/.next/standalone/.next/static/chunks/{21uv-uusw329x.js → 1-d48e9k-7e1a.js} +1 -1
- package/.next/standalone/.next/static/chunks/{0m-9d6yn9hx4j.js → 1r74hmr1wm_sd.js} +1 -1
- package/.next/standalone/.next/static/chunks/1uec0n0lcx5h1.js +1 -0
- package/.next/standalone/.next/static/chunks/21-pqc3-l9ak2.js +6 -0
- package/.next/standalone/.next/static/chunks/21qlo00jis4w-.js +1 -0
- package/.next/standalone/.next/static/chunks/2n00c3zqyloy9.js +1 -0
- package/.next/standalone/.next/static/chunks/{0bhidk90e-07f.css → 3_e_wg5_oay87.css} +1 -1
- package/.next/standalone/.next/static/chunks/{3c3qbmosdjl6w.js → 3tv107_for_n7.js} +1 -1
- package/.next/standalone/.next/static/chunks/{2qdpj67x6ifk_.js → 3vp54x0dyrrm6.js} +1 -1
- package/.next/standalone/.next/static/chunks/{turbopack-38nzuvp95_2rv.js → turbopack-11dn2pegmg9_9.js} +1 -1
- package/.next/standalone/app/actions/get-jev-config.ts +2 -2
- package/.next/standalone/app/actions/update-jev-config.ts +12 -9
- package/.next/standalone/app/components/jev-notices.tsx +10 -10
- package/.next/standalone/app/settings/jev-panel.tsx +11 -11
- package/.next/standalone/fp-cloud-cli/CHANGELOG.md +2 -0
- package/.next/standalone/fp-cloud-cli/fp_cli/output.py +26 -0
- package/.next/standalone/fp-cloud-cli/tests/test_output.py +27 -0
- package/.next/standalone/fp-cloud-cli/uv.lock +3 -3
- package/.next/standalone/hermes-plugin/README.md +18 -8
- 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/pages-turbo.runtime.prod.js +1 -1
- 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/lib/app-info-log.js +1 -1
- package/.next/standalone/node_modules/next/dist/server/lib/start-server.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 +12 -12
- package/.next/standalone/sdk/python/uv.lock +18 -18
- package/.next/standalone/server.js +1 -1
- package/bin/failproofai.mjs +33 -7
- package/dist/cli.mjs +1385 -1158
- package/dist/worker.mjs +59 -375
- package/hermes-plugin/README.md +18 -8
- package/package.json +12 -12
- package/scripts/build-policy-pack.mjs +6 -9
- package/src/hooks/cloud-connection.ts +12 -6
- package/src/hooks/custom-hooks-loader.ts +1 -1
- package/src/hooks/effective-reviewers.ts +50 -43
- package/src/hooks/handler.ts +25 -16
- package/src/hooks/hermes-update.ts +74 -0
- package/src/hooks/hook-activity-store.ts +3 -3
- package/src/hooks/integrations.ts +472 -68
- package/src/hooks/jev-activity.ts +8 -3
- package/src/hooks/jev-cli.ts +17 -17
- package/src/hooks/jev-cloud-connection.ts +4 -4
- package/src/hooks/manager.ts +3 -2
- package/src/hooks/pack-cli.ts +24 -23
- package/src/hooks/pack-manifest.ts +25 -2
- package/src/hooks/pack-store.ts +2 -2
- package/src/hooks/policy-authority.ts +51 -32
- package/src/hooks/policy-evaluator.ts +5 -5
- package/src/hooks/policy-registry.ts +5 -7
- package/src/hooks/policy-reviewability.ts +30 -12
- package/src/hooks/policy-types.ts +4 -4
- package/src/hooks/safe-config-write.ts +119 -0
- package/src/hooks/semantic/combine.ts +13 -13
- package/src/hooks/semantic/evaluator.ts +5 -5
- package/src/hooks/semantic/jev-client.ts +1 -1
- package/src/hooks/semantic/jev-config.ts +21 -12
- package/src/hooks/semantic/jev-review.ts +3 -3
- package/src/hooks/semantic/jev-stats.ts +17 -17
- package/src/hooks/semantic/pack-policies.ts +48 -48
- package/src/hooks/semantic/policies.ts +13 -425
- package/src/hooks/semantic/precondition-names.ts +1 -1
- package/src/hooks/semantic/preconditions.ts +1 -1
- package/src/hooks/semantic/types.ts +1 -1
- package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__13t1zkw._.js +0 -3
- package/.next/standalone/.next/server/chunks/ssr/_13kfn90._.js +0 -23
- package/.next/standalone/.next/static/chunks/06dnzbolj00mc.js +0 -6
- package/.next/standalone/.next/static/chunks/16f3fa-lx38hk.js +0 -1
- package/.next/standalone/.next/static/chunks/2g2tki08kdhie.js +0 -1
- package/.next/standalone/.next/static/chunks/3-nbtkhg9y-1j.js +0 -1
- package/.next/standalone/.next/static/chunks/355km0ihuqo1p.js +0 -1
- /package/.next/standalone/.next/static/{5yKM8NoTOpUI0MoQl8eo5 → ozuWoyIwOTqeUUjKqOKiH}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{5yKM8NoTOpUI0MoQl8eo5 → ozuWoyIwOTqeUUjKqOKiH}/_clientMiddlewareManifest.js +0 -0
- /package/.next/standalone/.next/static/{5yKM8NoTOpUI0MoQl8eo5 → ozuWoyIwOTqeUUjKqOKiH}/_ssgManifest.js +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
module.exports=[74493,a=>{"use strict";let b,c,d,e,f;var g,h=a.i(14747);function i(a){return a.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var j=((g={}).AnonymousId="anonymous_id",g.DistinctId="distinct_id",g.Props="props",g.EnablePersonProcessing="enable_person_processing",g.PersonMode="person_mode",g.FeatureFlagDetails="feature_flag_details",g.FeatureFlags="feature_flags",g.FeatureFlagPayloads="feature_flag_payloads",g.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",g.BootstrapFeatureFlags="bootstrap_feature_flags",g.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",g.OverrideFeatureFlags="override_feature_flags",g.Queue="queue",g.AiQueue="ai_queue",g.AiCaptureQueue="ai_capture_queue",g.LogsQueue="logs_queue",g.OptedOut="opted_out",g.SessionId="session_id",g.SessionStartTimestamp="session_start_timestamp",g.SessionLastTimestamp="session_timestamp",g.PersonProperties="person_properties",g.GroupProperties="group_properties",g.InstalledAppBuild="installed_app_build",g.InstalledAppVersion="installed_app_version",g.SessionReplay="session_replay",g.PushRegistered="push_registered",g.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",g.SurveyLastSeenDate="survey_last_seen_date",g.SurveysInProgress="surveys_in_progress",g.SurveysSeen="surveys_seen",g.Surveys="surveys",g.RemoteConfig="remote_config",g.FlagsEndpointWasHit="flags_endpoint_was_hit",g.DeviceId="device_id",g);let k={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:a=>`api_error_${a}`};function l(a){let b=[];return JSON.stringify(a,function(a,c){if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){for(;b.length>0&&b[b.length-1]!==this;)b.pop();if(b.includes(c))return"[Circular]";b.push(c)}return c}})??"null"}let m=Array.isArray,n=Object.prototype;n.hasOwnProperty;let o=n.toString,p=m||function(a){return"[object Array]"===o.call(a)},q=a=>a===Object(a)&&!p(a),r=a=>void 0===a,s=a=>"[object String]"==o.call(a),t=a=>s(a)&&0===a.trim().length,u=a=>null===a,v=a=>r(a)||u(a),w=a=>"[object Number]"==o.call(a)&&a==a;function x(a){return null===a||"object"!=typeof a}function y(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function z(a){switch(Object.prototype.toString.call(a)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return B(a,Error)}}function A(a){return"u">typeof Event&&B(a,Event)}function B(a,b){try{return a instanceof b}catch{return!1}}let C="Android",D="BlackBerry",E="Nintendo",F="PlayStation",G="Xbox",H="Windows",I="(\\d+(\\.\\d+)?)";RegExp("Version/"+I),RegExp("(Claude|Codex|ChatGPT)\\/"+I),RegExp(G,"i"),RegExp(F+" \\w+","i"),RegExp(E+" \\w+","i"),RegExp(D+"|PlayBook|BB10","i");RegExp("rv:"+I),RegExp("Edge?\\/"+I),RegExp("(Chrome|CrMo)\\/"+I),RegExp("CriOS\\/"+I),RegExp("(UCBrowser|UCWEB)\\/"+I),RegExp("(Opera|OPR)\\/"+I),RegExp("Firefox\\/"+I),RegExp("FxiOS\\/"+I),RegExp("Konqueror[:/]?"+I,"i"),RegExp(D+" "+I),RegExp("android\\s"+I,"i"),RegExp("SamsungBrowser\\/"+I),RegExp("OculusBrowser\\/"+I),RegExp("Vivaldi\\/"+I),RegExp("YaBrowser\\/"+I),RegExp("Whale\\/"+I),RegExp("Brave\\/"+I),RegExp("(DuckDuckGo|Ddg)\\/"+I),RegExp("PaleMoon\\/"+I),RegExp("Waterfox\\/"+I),RegExp("GSA\\/"+I),RegExp("(rv:|MSIE )"+I),RegExp("rv:"+I),RegExp(G+"; "+G+" (.*?)[);]","i"),RegExp(E,"i"),RegExp(F,"i"),RegExp(H,"i"),RegExp("("+C+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+C+")","i");let J=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function K(a,b){return"string"==typeof a&&J.test(a)?a:b()}function L(a,b){let c=Error(b);try{Object.defineProperty(c,"name",{value:a,writable:!0,enumerable:!0,configurable:!0})}catch{}return c}function M(a){return a?a.split("#")[0]:a}async function N(a,b){let c=null;for(let d=0;d<b.retryCount+1;d++){d>0&&await new Promise(a=>setTimeout(a,b.retryDelay));try{return await a()}catch(a){if(c=a,!b.retryCheck(a))throw a}}throw c}function O(){return new Date().toISOString()}function P(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}async function Q(a,b,c){let d;try{return await Promise.race([a,new Promise((a,e)=>{d=P(()=>{try{c?.(),a()}catch(a){e(a)}},b)})])}finally{clearTimeout(d)}}function R(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}class S{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&p(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;if(null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack)try{d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)}catch{}return{...a,cause:c,stack:d,errors:a.errors?.map(a=>this.parseStacktrace(a,b))}}applyChunkIds(a,b){return a.map(a=>(a.filename&&b&&(a.chunk_id=b[a.filename]),a))}applyCoercers(a,b){for(let c of this.coercers)if(c.match(a))return c.coerce(a,b);return this.coerceFallback(b)}async applyModifiers(a){let b=a;for(let a of this.modifiers)b=await a(b);return b}convertToExceptionList(a,b){let c=[],d=(a,e,f)=>{let g=c.length,h=void 0===e?{type:"string"==typeof b.type&&b.type.length>0?b.type:"generic",..."boolean"==typeof b.handled?{handled:b.handled}:void 0===b.handled?{handled:!0}:{},synthetic:"boolean"==typeof b.synthetic?b.synthetic:a.synthetic,exception_id:g}:{type:"chained",source:f,synthetic:a.synthetic,exception_id:g,parent_id:e},i={type:a.type,value:a.value,mechanism:h};for(let b of(a.stack&&(i.stacktrace={type:"raw",frames:a.stack}),c.push(i),a.cause&&d(a.cause,g,"cause"),a.errors??[]))d(b,g,"member")};return d(a),c}buildParsingContext(a){return{chunkIdMap:function(a){let e=globalThis._posthogChunkIds;if(!e)return;let f=Object.keys(e);return d&&f.length===c?d:(c=f.length,d=f.reduce((c,d)=>{b||(b={});let f=b[d];if(f)c[f[0]]=f[1];else{let f=a(d);for(let a=f.length-1;a>=0;a--){let g=f[a],h=g?.filename,i=e[d];if(h&&i){c[h]=i,b[d]=[h,i];break}}}return c},{}))}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}getAggregateErrors(a){try{if(z(a)){let b=Object.getPrototypeOf(a);for(let c=0;b&&c<100;c++){let c=Object.getOwnPropertyDescriptor(b,"constructor")?.value;if("function"==typeof c&&"AggregateError"===c.name){let b=a.errors;return p(b)?b:void 0}b=Object.getPrototypeOf(b)}}}catch{}}buildCoercingContext(a,b,c=0){let d=0,e=0,f=!1,g=new Set,h=[],i={},j=(a,b,c=0)=>{let j,l,m=k(b,c),n=m.apply;if(m.apply=b=>{h.push(a);try{return n(b)}finally{h.pop()}},c>4||c>0&&-1!==h.indexOf(a))return this.coerceFallback(m);let o="object"==typeof a&&null!==a||"function"==typeof a;if(0===c&&d>=50||o&&g.has(a))return;o&&g.add(a),0===c&&d++;let p=this.getAggregateErrors(a);f||=!!p;try{if(!(j=this.applyCoercers(a,m)))throw i}catch(a){if(a===i){0===c&&d--;return}if(!f)throw a;j=this.coerceFallback(m)}if(!p||d>=50)return j;try{l=p.length}catch{return j}if(!Number.isInteger(l)||l<0||l>0xffffffff)return j;let q=[];for(let a=0;d<50&&e<1e3&&a<l;a++){let c;e++;try{c=m.next(p[a])}catch{d++,c=this.coerceFallback(k(b+1))}c&&q.push(c)}return{...j,errors:q}},k=(c,d=0)=>({...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:0==c?a:{},apply:a=>{let b=j(a,c,d+1);if(!b)throw i;return b},next:a=>j(a,c+1)}),l=k(c);return{...l,apply:a=>j(a,c)??this.coerceFallback(l)}}}a.s(["ErrorPropertiesBuilder",0,S],6762);let T=/^([a-z][a-z0-9.+-]+):/i,U=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function V(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:function(a){if(!a||"<anonymous>"===a)return!1;let b=T.exec(a);return!b||U.includes(b[1].toLowerCase())}(b)};return r(d)||(f.lineno=d),r(e)||(f.colno=e),f}let W=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},X=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Y=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Z=/\((\S*)(?::(\d+))(?::(\d+))\)/,$=(a,b)=>{let c=X.exec(a);if(c){let[,a,d,e]=c;return V(b,a,"?",+d,+e)}let d=Y.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=Z.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=W(d[1]||"?",d[2]);return V(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},_=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,aa=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,ab=(a,b)=>{let c=_.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=aa.exec(c[3]);a&&(c[1]=c[1]||"eval",c[3]=a[1],c[4]=a[2],c[5]="")}let a=c[3],d=c[1]||"?";return[d,a]=W(d,a),V(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},ac=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ad=(a,b)=>{let c=ac.exec(a);return c?V(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ae=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,af=(a,b)=>{let c=ae.exec(a);return c?V(b,c[2],c[3]||"?",+c[1]):void 0},ag=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,ah=(a,b)=>{let c=ag.exec(a);return c?V(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},ai=/^\s*[-]{4,}$/,aj=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ak=/^Promise\.(?:all|any)$/,al=/^index \d+$/,am=(a,b)=>{let c=a.match(aj);if(c){let a,d,e,f,g;if(c[1]){let b=(e=c[1]).lastIndexOf(".");if("."===e[b-1]&&b--,b>0){a=e.slice(0,b),d=e.slice(b+1);let c=a.indexOf(".Module");c>0&&(e=e.slice(c+1),a=a.slice(0,c))}f=void 0}d&&(f=a,g=d),"<anonymous>"===d&&(g=void 0,e=void 0),void 0===e&&(g=g||"?",e=f?`${f}.${g}`:g);let h=c[2]?.startsWith("file://")?c[2].slice(7):c[2],i="native"===c[5];return h?.match(/\/[A-Z]:/)&&(h=h.slice(1)),h||!c[5]||i||(h=c[5]),ak.test(e)&&al.test(h||"")&&(h="node:internal/promise"),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:an(c[3]),colno:an(c[4]),in_app:function(a,b=!1){return!(b||a&&!a.startsWith("/")&&!a.match(/^[A-Z]:/)&&!a.startsWith(".")&&!a.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&void 0!==a&&!a.includes("node_modules/")}(h||"",i),platform:b}}if(a.match(ai))return{filename:a,platform:b}};function an(a){return parseInt(a||"",10)||void 0}let ao=/\(error: (.*)\)/;function ap(a,b){return a.filename===b.filename&&a.function===b.function&&a.module===b.module&&a.lineno===b.lineno&&a.colno===b.colno}function aq(a,b){let c=b.start;for(;c>0&&ap(a[c-1],a[c-1+b.length]);)c--;return b.start-c}function ar(a,b){let c=b.start+b.length,d=c;for(;d<a.length&&ap(a[d],a[d-b.length]);)d++;return d-c}function as(a){if(!a.length)return[];let b=Array.from(a);return b.reverse(),b.slice(0,50).map(a=>{var c;return{...a,filename:a.filename||((c=b)[c.length-1]||{}).filename,function:a.function||"?"}})}function at(){return au("web:javascript",$,ab)}function au(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n"),g=Math.min(f.length,d+1e3),h=[];for(let c=d;c<g;c++){let d=f[c];if(d.length>1024)continue;let g=ao.test(d)?d.replace(ao,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);let a=function(a){for(let b=1;b<=10;b++){let c=a.length-2*b;if(c<0)break;let d=!0;for(let e=0;e<b;e++)if(!ap(a[c+e],a[c+b+e])){d=!1;break}if(d){for(let d=0;d<b;d++)a[c+d]=a[c+b+d];return a.length=c+b,{start:c,length:b}}}}(e);if(a){for(let b=h.length-1;b>=0;b--){let c=h[b];if(c.start+c.length<=a.start)break;h.pop()}h.push(a)}break}}if(function(a,b){let c=b[0],d=a.length-(c?aq(a,c):0);for(let c of b)d-=ar(a,c);return d}(e,h)>=50)break}}let i=[...h].sort((a,b)=>b.start-a.start),j=i[i.length-1];if(j){let a=aq(e,j);for(let b of(e.splice(j.start-a,a),i))b.start-=a}for(let a of i)!function(a,b){let c=b.start+b.length,d=ar(a,b);d&&a.splice(c+d===a.length?c:b.start,d)}(e,a);return h.some(a=>0===a.start&&e.length===a.length)&&function(a){let b=a.map(a=>`${a.function}|${a.filename}|${a.lineno}|${a.colno}|${a.module}`),c=0;for(let a=1;a<b.length;a++)(function(a,b,c){for(let d=0;d<a.length;d++){let e=a[(b+d)%a.length],f=a[(c+d)%a.length];if(e!==f)return e<f}return!1})(b,a,c)&&(c=a);a.push(...a.splice(0,c))}(e),as(e)}}a.s(["createDefaultStackParser",0,at,"createStackParser",0,au,"reverseAndStripFrames",0,as],67970);class av{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=s(a.stack);return{type:this.getType(a),value:this.getValue(a),stack:c?a.stack:void 0,cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}getType(a){return this.isDOMError(a)?"DOMError":"DOMException"}getValue(a){let b=a.name||(this.isDOMError(a)?"DOMError":"DOMException");return a.message?`${b}: ${a.message}`:b}isDOMException(a){return y(a,"DOMException")}isDOMError(a){return y(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,av],51671);class aw{match(a){return!!y(a,"ErrorEvent")&&(void 0!=a.error||this._hasUsableMessage(a))}coerce(a,b){if(void 0!=a.error)return b.apply(a.error);let c=b.apply(a.message);return{...c,stack:this._buildLocationStack(a)??c.stack,synthetic:!0}}_hasUsableMessage(a){return s(a.message)&&a.message.length>0}_buildLocationStack(a){let b=a.lineno??0,c=a.colno??0;if(s(a.filename)&&0!==a.filename.length&&0!==b)return`Error
|
|
2
|
-
at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,aw],75368);let ax=["fatal","error","warning","log","info","debug"];function ay(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";for(let a=c.length;a>0;a--){let d=c.slice(0,a).join(", ");if(!(d.length>b)){if(a===c.length)return d;return d.length<=b?d:`${d.slice(0,b)}...`}}return""}class az{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(A(a))return a.constructor.name;let b="name"in a?a.name:void 0;return s(b)&&!t(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=ay(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return s(a)&&!t(a)&&ax.indexOf(a)>=0}getStack(a){try{if(s(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return s(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(z(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,az],93874);class aA{match(a){return A(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${ay(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aA],46980);class aB{match(a){return x(a)}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,aB],28150);class aC{match(a){return y(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!A(a))return!1;try{let b=a.detail;return null!=b&&"object"==typeof b&&"reason"in b}catch{return!1}}coerce(a,b){let c=this.getUnhandledRejectionReason(a);return x(c)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(c)}`,stack:b.syntheticException?.stack,synthetic:!0}:b.apply(c)}getUnhandledRejectionReason(a){try{if("reason"in a)return a.reason;if("detail"in a&&null!=a.detail&&"object"==typeof a.detail&&"reason"in a.detail)return a.detail.reason}catch{}return a}}a.s(["PromiseRejectionEventCoercer",0,aC],98140),a.s([],7610);let aD={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aE=new Set([aD.MESSAGE,aD.TIMESTAMP]),aF={enabled:!0,max_bytes:32768};function aG(a){return a?{enabled:a.enabled??aF.enabled,max_bytes:function(a,b){if(!w(a)||1/0===a||-1/0===a)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aF.max_bytes)}:{...aF}}function aH(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aE.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aI{constructor(a){this._entries=[],this._totalBytes=0,this._config=aG(a)}setConfig(a){this._config=aG(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=l(a)}catch{return}try{let a=JSON.parse(b);if(!q(a))return;let c=a[aD.MESSAGE],d=a[aD.TIMESTAMP];if(!s(c)||0===c.trim().length||!s(d)&&!w(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aJ(b.json);c>this._config.max_bytes||(this._entries.push({step:b.step,bytes:c}),this._totalBytes+=c,this._trimToMaxBytes())}getAttachable(){return this._entries.map(a=>a.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let a=this._entries.shift();a&&(this._totalBytes-=a.bytes)}}}function aJ(a){if("u">typeof TextEncoder)return new TextEncoder().encode(a).length;let b=encodeURIComponent(a),c=0;for(let a=0;a<b.length;a++)"%"===b[a]?(c+=1,a+=2):c+=1;return c}a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aF,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aD,"ExceptionStepsBuffer",0,aI,"getUtf8ByteLength",0,aJ,"resolveExceptionStepsConfig",0,aG,"stripReservedExceptionStepFields",0,aH],97383),a.s([],48153),a.i(48153),a.i(6762),a.i(67970),a.s(["chromeStackLineParser",0,$,"createDefaultStackParser",0,at,"createStackParser",0,au,"geckoStackLineParser",0,ab,"nodeStackLineParser",0,am,"opera10StackLineParser",0,af,"opera11StackLineParser",0,ah,"reverseAndStripFrames",0,as,"winjsStackLineParser",0,ad],64583),a.i(64583),a.i(7610),a.i(51671);class aK{match(a){return z(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,aK],10692),a.i(10692),a.i(75368);let aL=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aM{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(aL);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aM],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,av,"ErrorCoercer",0,aK,"ErrorEventCoercer",0,aw,"EventCoercer",0,aA,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"StringCoercer",0,aM],54253),a.i(54253);class aN{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}function aO(){let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s(["ReduceableCache",0,aN],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,aO],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aF,"DOMExceptionCoercer",0,av,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aD,"ErrorCoercer",0,aK,"ErrorEventCoercer",0,aw,"ErrorPropertiesBuilder",0,S,"EventCoercer",0,aA,"ExceptionStepsBuffer",0,aI,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"ReduceableCache",0,aN,"StringCoercer",0,aM,"chromeStackLineParser",0,$,"createDefaultStackParser",0,at,"createStackParser",0,au,"geckoStackLineParser",0,ab,"getInjectedReleaseId",0,aO,"getUtf8ByteLength",0,aJ,"nodeStackLineParser",0,am,"opera10StackLineParser",0,af,"opera11StackLineParser",0,ah,"resolveExceptionStepsConfig",0,aG,"reverseAndStripFrames",0,as,"stripReservedExceptionStepFields",0,aH,"winjsStackLineParser",0,ad],60485);var aP=a.i(60485);let aQ="0123456789abcdef";class aR{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aR(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aR(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aR(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aQ.charAt(this.bytes[b]>>>4),a+=aQ.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aQ.charAt(this.bytes[b]>>>4),a+=aQ.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aR(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aS{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aT()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aR.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 a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aR.ofInner(a)}}let aT=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aU=()=>aV().toString(),aV=()=>(e||(e=new aS)).generate();function aW(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function aX(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function aY(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aU(),b]})}function aZ(a,b){let c=aX(b),d=a.get(c);return d?a_(d.value):null}function a$(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function a_(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=p(b.$sesid)?b.$sesid[1]:void 0;return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof c?c:void 0,deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}let a0=a=>void 0===a?void 0:a.variant??a.enabled,a1=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},a2=["$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"],a3=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return a2.forEach(d),b.forEach(d),c};class a4{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let a5=a=>{throw L("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},a6=async(a,b)=>{a.size<18&&a5("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||a5("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(f)return f;f=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;f[a]=b>>>0}return f})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&a5("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&a5("invalid-size")};async function a7(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await a6(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}class a8{add(a){let b=aU(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let a9=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>a9(`${a} ${d}`,b,c)}};class ba{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class bb extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(a,b=Date.now()){if("string"!=typeof a||!a)return;let c=a.trim(),d=/^\d+\s*,/.test(c)?c.slice(0,c.indexOf(",")).trim():c;if(/^\d+$/.test(d)){let a=1e3*Math.min(Number(d),300);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(d))return;let e=Date.parse(/^\w{3} \w{3} /.test(d)?d+" GMT":d)-b;if(Number.isFinite(e)&&!(e<=0))return Math.min(e,3e5)}(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let a=L("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=P(()=>{this._bodyReadTimedOut=!0;let a=L("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class bc extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bd(a){if(a instanceof bb){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function be(a){return a instanceof bc}function bf(a){if(a instanceof bb)return 502===a.status||504===a.status;if(!(a instanceof bc))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bg(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function bh(a){return"object"==typeof a&&a instanceof bb&&413===a.status}function bi(a){return a instanceof bb?408===a.status||429===a.status||a.status>=500:be(a)}function bj(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bk="default";class bl{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new S([new aK,new az,new aM,new aB],at())}getEvaluationRuntime(){}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new a8,this._events=new a4,this._isInitialized=!1;const c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return a9(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=c,this.host=function(a){return a?.replace(/\/+$/,"")}(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:bi},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(j.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(j.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(j.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c={...b,...this.getCommonEventProperties()};var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=a3(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.apiKey}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=`${this.host}/flags/?v=2${f?"&config=true":""}`,h={token:this.apiKey,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(h.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(h.evaluation_contexts=this.evaluationContexts);let i=this.getEvaluationRuntime();i&&(h.evaluation_runtime=i);let j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,j,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:bf},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,a0(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?a1(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,a1(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof bb)return{type:"api_error",statusCode:a.status};if(a instanceof bc){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=a0(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),i.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.apiKey}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(j.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(j.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(j.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return bk}persistedQueueKeyForRoute(a){return j.Queue}getActiveQueueRoutes(){return[bk]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=P(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=bj(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=K(e.uuid,aU),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:O(),uuid:K(b?.uuid,aU)};return(b?.disableGeoip??this.disableGeoip)&&(bj(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await bd(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>R([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),R([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return a7(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bk){let d={api_key:this.apiKey,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:O()};this.historicalMigration&&(d.historical_migration=!0);let e=l(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!bh(a)&&bi(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bh(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof bc||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=bg(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.apiKey)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.apiKey}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!bh(a)&&(!(a instanceof bb)||void 0===a.retryAfterMs)&&bi(a)}),{kind:"ok"}}catch(a){if(bh(a))return{kind:"too-large"};if(bi(a)){let b=a instanceof bb?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=bg(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await N(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=P(()=>{let a=L("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new bc(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new bc(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new bb(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new bc(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof bb&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return Q((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof bb||be(a))))throw a;await bd(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let bm="[Circular]",bn="[Truncated]",bo="[Unserializable]";function bp(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function bq(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=bo}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let br=Object.prototype.propertyIsEnumerable;function bs(a,b){try{return bt(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bt(a,b,c,d){let e=[];for(let f in a)if(br.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(u(g)||r(g))continue;e.push({key:bp(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bn};if(d.remainingNodes--,"[object Boolean]"===o.call(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:bp(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:bm};if(e>=20)return{stringValue:bn};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?bp(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(p(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(v(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bo})}return b.length>h&&f.push({stringValue:bn}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bt(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:bp(String(b))}}(g,b,c,d)})}catch{e.push({key:bp(f),value:{stringValue:bo}})}}return e}function bu(a,b,c){return{...bq({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let bv=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bw(a,b){let c=bq({},a),d={};for(let a of bv)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bs(c,b),...bs(d,b)]}let bx={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};class by{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=P(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function bz(){return .75+.25*Math.random()*2}function bA(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}let bB=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bC(a){return String(a)+"000000"}function bD(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\u0000${b}\u0000${c??""}\u0000${e}`}class bE{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new by(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new ba,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(a)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(a){let b,c;if(this._instance.isDisabled||this._instance.optedOut)return;let d=this._runBeforeSend(a);if(null===d)return;if(!d.name||"string"!=typeof d.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof d.value||!Number.isFinite(d.value))return void this._logger.warn(`Dropping metric '${d.name}': value must be a finite number`);if("count"===d.type&&d.value<0)return void this._logger.warn(`Dropping count '${d.name}': counters are monotonic, value must be >= 0`);try{b=d.attributes?{...d.attributes}:void 0,c=bD(d.type,d.name,d.unit,b)}catch(a){this._logger.warn(`Dropping metric '${d.name}': attributes could not be serialized`,a);return}let e=this._series.get(c);if(!e){if(!this._admitNewSeries())return;e={name:d.name,type:d.type,unit:d.unit,attributes:b,windowStartMs:Date.now()},this._series.set(c,e)}let f=this._typeByName.get(d.name);void 0===f?this._typeByName.set(d.name,d.type):f===d.type||this._typeCollisionWarned.has(d.name)||(this._typeCollisionWarned.add(d.name),this._logger.warn(`Metric name '${d.name}' is already used as a ${f}; recording it as a ${d.type} too will blend both series in charts. Use a distinct name.`)),this._fold(e,d.value),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(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{a.hist||(a.hist={count:0,sum:0,min:b,max:b,bucketCounts:Array(bB.length+1).fill(0)});let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,bB)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=p(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bA(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=bz()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bw(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bC(Date.now()),c=new Map;for(let d of a.values()){let a=bD(d.type,d.name,d.unit,void 0),e=c.get(a);e||(e={name:d.name,...d.unit&&{unit:d.unit}},"count"===d.type?e.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===d.type?e.gauge={dataPoints:[]}:e.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,e));let f=bs(d.attributes??{},this._logger),g=bC(d.windowStartMs);if("count"===d.type){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,asDouble:d.total??0};e.sum.dataPoints.push(a)}else if("gauge"===d.type){let a={attributes:f,timeUnixNano:b,asDouble:d.last??0};e.gauge.dataPoints.push(a)}else if(d.hist){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,count:d.hist.count,sum:d.hist.sum,min:d.hist.min,max:d.hist.max,bucketCounts:d.hist.bucketCounts,explicitBounds:bB};e.histogram.dataPoints.push(a)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":if(c.hist)if(a.hist){a.hist.count+=c.hist.count,a.hist.sum+=c.hist.sum,a.hist.min=Math.min(a.hist.min,c.hist.min),a.hist.max=Math.max(a.hist.max,c.hist.max);for(let b=0;b<a.hist.bucketCounts.length;b++)a.hist.bucketCounts[b]+=c.hist.bucketCounts[b]}else a.hist=c.hist}}}}let bF="0".repeat(32),bG="0".repeat(16),bH=/^[0-9a-f]+$/;function bI(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bJ(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bH.test(a)}let bK=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bL(a){if("string"!=typeof a)return;let b=bK.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bJ(d,32,bF)&&bJ(e,16,bG))return{version:c,traceId:d,spanId:e,flags:f}}function bM(a){return Array.isArray(a)&&1===a.length?a[0]:a}function bN(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}let bO="unknown";function bP(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bO}"`),bO)}function bQ(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bR(a,b,c,d){let e=bQ(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bS(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bT{constructor(a,b,c){for(const d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??"01",this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bS(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bS();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(v(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=b0(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bq({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&b1(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bP(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bR(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:b_(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=b3(a);return this.addEvent(bU,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bP(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c="01"){return`00-${a}-${b}-${c}`}(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bR(a,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let bU="exception";function bV(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class bW{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}let bX=new bW;class bY extends bW{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function bZ(a,b){var c;let d=bM(a?.parent)??b,e=bL(c="string"==typeof d||null==d?d:b$(d,"traceparent"))&&c.trim();return e?new bY(e,bN("string"==typeof d||null==d?a?.tracestate:b$(d,"tracestate"))):bX}function b$(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function b_(a,b){return a.length>b?a.slice(0,b):a}function b0(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return v(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?b_(b,c):b);if(d.ancestors.has(b))return bm;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return v(f.value)?String(f.value):a(f.value,c,d,e+1);if(p(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(bo)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=bo}f&&!v(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function b1(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=b0(a[h],c)}catch{d=bo}v(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b2(a,b,c){return b===bX?c(b):a.with(b,()=>c(b))}function b3(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(z(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let b4={internal:1,server:2,client:3,producer:4,consumer:5},b5={ok:1,error:2};function b6(a){if("string"==typeof a)return bp(a);try{return bp(String(a))}catch{return bo}}function b7(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function b8(){return bS()??Date.now()}function b9(a){try{return a instanceof bT}catch{return!1}}function ca(a,b){let c,d=(c=bL(a))&&{traceId:c.traceId,spanId:c.spanId,flags:1&parseInt(c.flags,16)?"01":"00"};if(d)return{traceId:d.traceId,parentSpanId:d.spanId,traceState:bN(b),traceFlags:d.flags,isRemote:!0}}function cb(a,b,c){a[b]!==c&&(a[b]=c)}class cc{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new by(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new ba,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return bZ(b,this._contextManager.active());let f=bM(b?.parent);if(f&&"string"!=typeof f&&!b9(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),bZ(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),bZ(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bQ(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bI(8);this._liveSpans.set(j,b8());let k=this._autoContextAttributes();return new bT({traceId:g?.traceId??bI(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bP(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bq({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bQ(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=b2(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(a,b){if("string"==typeof a){let c=ca(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(b9(a))return a.childContext();let c=this._contextManager.active();return b9(c)?c.childContext():c instanceof bY?ca(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bT))return;let{type:c,message:d,stack:e}=b3(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=b8()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bP(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bQ(j.startTime)??d.startTime,j.endTime=(l=bQ(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bP(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bR(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!v(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:b0(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=bV(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=b1(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=bV(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=bV(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:b_(function(a){try{return"string"==typeof a?a:String(a)}catch{return bo}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{cb(a,"traceId",b.traceId),cb(a,"spanId",b.spanId),cb(a,"parentSpanId",b.parentSpanId),cb(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:b6(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(b4,c)?b4[c]:b4.internal,startTimeUnixNano:b7(a.startTime),endTimeUnixNano:b7(a.endTime),flags:(d=parseInt(a.traceFlags,16),(Number.isFinite(d)?255&d:1)|256|512*!!a.parentIsRemote)};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=b6(a.traceState));let f=bs(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:b6(a.name),timeUnixNano:b7(a.timestamp)};if(a.attributes){let d=bs(a.attributes,b);d.length&&(c.attributes=d)}let d=bV(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=bV(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=bV(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:b5[a.status.code],...a.status.message&&{message:b6(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=b0(a[c],b);return a}((a=this._config,bu(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=b8()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bw(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=bz(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=b8()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bA(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var cd=aP,ce=a.i(2157),cf=a.i(12714),cg=a.i(50227),ch=a.i(1457);let ci=new cd.ReduceableCache(25),cj=new cd.ReduceableCache(20);async function ck(a,b=cf.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,cg.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=co(a,d);if(void 0===f||cj.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=cp(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=cp(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=ci.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(ci,f,{});i.push(cm(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=co(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=cq(a);d<a;d++){let a=c[d];if(void 0===a)return void cn(b);b.pre_context.push(a)}if(void 0===c[a])return cn(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,ci,d),ci.reduce(),a}async function cl(a,b,c){let d,e=!1;try{d=await b(a,ce.constants.O_RDONLY|ce.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function cm(a,b,c,d,e,f){let g=await cl(a,e,f);return void 0===g?void cj.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{cj.set(d,1),i();return}try{f=(0,ch.createInterface)({input:e})}catch{cj.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){cj.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function cn(a){delete a.pre_context,delete a.context_line,delete a.post_context}function co(a,b){return(0,cg.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function cp(a){return[cq(a),a+7]}function cq(a){return Math.max(1,a-7)}class cr{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let cs=["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"],ct=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return cs.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})};function cu(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cv=["service.name","service.version","deployment.environment"],cw={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,cw],46539);class cx{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a),c?.enabled??b.defaultValue??!1}getFlag(a){let b=this._flags[a];if(this._recordAccess(a),b)return!!b.enabled&&(b.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new cx({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a){if(this._accessed.add(a),""===this._distinctId||this._isSlice&&!(a in this._flags))return;let b=this._flags[a],c=void 0===b?void 0:!1!==b.enabled&&(b.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:b?.id,$feature_flag_version:b?.version,$feature_flag_reason:b?.reason,locally_evaluated:b?.locallyEvaluated??!1,[`$feature/${a}`]:c,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:b?.locallyEvaluated?Date.now():this._evaluatedAt};b?.hasExperiment!==void 0&&(d.$feature_flag_has_experiment=b.hasExperiment),b?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(d.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let e=[];this._errorsWhileComputing&&e.push(cw.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(cw.QUOTA_LIMITED),void 0===b&&e.push(cw.FLAG_MISSING),e.length>0&&(d.$feature_flag_error=e.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:c,groups:this._groups,disableGeoip:this._disableGeoip,properties:d})}}let cy=["is_not","is_set"];class cz extends Error{constructor(a){super(a),this.name=this.constructor.name,Object.setPrototypeOf(this,cz.prototype)}}function cA(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cA(b in a?a[b]:null))return!1;return!0}function cB(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cB(b in a?a[b]:null))return!1;return!0}function cC(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cz("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cz("Cannot stringify an unpaired surrogate like the flags service")}}function cD(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cC(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cz(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cz("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cD(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cz("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cz("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cC(c),cD(a[c],b)}finally{b.delete(a)}return}throw new cz(`Cannot represent ${typeof a} like the flags service`)}}function cE(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function cF(a){return"string"==typeof a?(cC(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cC(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cz(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cz(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cz("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cz("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cz("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cC),`{${d.sort(cE).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cz(`Cannot stringify ${typeof b} like the flags service`)}(a)}function cG(a){try{return new RegExp(a),!0}catch{return!1}}function cH(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cI(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cz(`Invalid semver: ${b}`);return parseInt(a,10)}function cJ(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cz(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cI(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cK(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cL(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cz(`${a} is in an invalid date format`)}throw new cz(`The date provided ${a} must be a string, number, or date object`)}async function cM(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function cN(a,b,c=""){return parseInt((await cM(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function cO(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function cP(a,b,c){let d=await cN(a,b,"variant");return cO(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}class cQ extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,cQ.prototype)}}class cR extends Error{constructor(a){super(a),function(a,b){a.name=b.name,Error.captureStackTrace(a,b),Object.setPrototypeOf(a,b.prototype)}(this,cR)}}class cS{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof cR||b instanceof cz?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e=0==this.featureFlags.length,f=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,g={...a,evaluationCache:a.evaluationCache??{}};return await Promise.all(f.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,g);c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof cR||b instanceof cz?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),e=!0}})),{response:c,payloads:d,fallbackToFlags:e}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=this.getFeatureFlagPayload(a.key,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cz("Flag has experience continuity enabled");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=this.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cz("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cz(`Can't compute feature flag: ${a.key} without $device_id`);return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}getFeatureFlagPayload(a,b){var c=this.featureFlagsByKey?.[a]?.filters?.payloads;if(!1===b||null==b||!c)return null;let d=c["boolean"==typeof b?b.toString():b]||null;return null==d?null:a1(d)}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!this.featureFlagsByKey)throw new cz("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cz(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cz(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cz(`Circular dependency detected for flag '${e}' (empty dependency chain)`);for(let a of f){if(!(a in d)){let b=this.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){throw new cz(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else if(this.filteredOutFlagKeys.has(a))d[a]=!1;else throw new cz(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new cz(`Dependency '${a}' could not be evaluated`)}let g=d[e];return this.flagEvaluatesToExpectedValue(a.value,g)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e,f=a.filters||{},g=f.groups||[],h=f.aggregation_group_type_index,i=f.early_exit??!1,{groups:j,groupProperties:k}=d,l=!1;for(let m of g)try{let g=void 0!==m.aggregation_group_type_index?m.aggregation_group_type_index:h,n=c,o=b;if(g!==h&&null!=g){let b=this.groupTypeMapping[String(g)];if(!b||!(b in j)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${g} not available`));continue}if(!(b in k)){l=!0;continue}n=k[b],o=j[b]}let p=await this.isConditionMatch(a,o,m,n,d);if("match"===p){let b=m.variant,c=f.multivariate?.variants||[];e=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,o)||!0;break}if(i&&"out_of_rollout_bound"===p){if(l)break;return!1}}catch(a){if(a instanceof cR)throw a;if(a instanceof cz)l=!0;else throw a}if(void 0!==e)return e;if(l)throw new cz("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(a,b,c,d,e){let f=c.rollout_percentage,g=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){for(let a of c.properties){let b=a.type,c=!1;if("cohort"===b){let b=await cU(a,d,this.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e));c="not_in"===a.operator?!b:b}else c="flag"===b?await this.evaluateFlagDependency(a,d,e):cT(a,d,g);if(!c)return"no_match"}if(void 0==f)return"match"}return void 0!=f&&await cN(a.key,b)>f/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cP(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cO(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags);this.featureFlags=b,this.featureFlagsByKey=b.reduce((a,b)=>(a[b.key]=b,a),{});let c=new Set(b.map(a=>a.key));this.filteredOutFlagKeys=new Set(a.flags.filter(a=>!c.has(a.key)).map(a=>a.key)),this.groupTypeMapping=a.groupTypeMapping,this.cohorts=a.cohorts,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.(!0===a.minimalFlagCalledEvents)}warnAboutExperienceContinuityFlags(a){if(this.strictLocalEvaluation)return;let b=a.filter(a=>a.ensure_experience_continuity);b.length>0&&console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled: ${b.map(a=>a.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(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){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 a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new cQ(`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 cQ(`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 cQ(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d={flags:c.flags??[],groupTypeMapping:c.group_type_mapping||{},cohorts:c.cohorts||{},minimalFlagCalledEvents:!0===c.minimal_flag_called_events};if(this.updateFlagState(d),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(d)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(a){a instanceof cQ&&this.onError?.(a)}finally{this.pollerStopped||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=P(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await Q(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function cT(a,b,c){return function(a,b,c={}){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cz(`Property ${d} not found in propertyValues`);let h=b[d];if(void 0===h)return c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),"is_not"===f;if(null===h&&!cy.includes(f)&&"exact"!==f&&"is_not"!==f)return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cA(a)||Array.isArray(a)&&0===a.length)return cD(b),cB(a)===cB(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cA(a))return cD(b),!1;if(Array.isArray(a)){let c=cF(b).toLowerCase();return a.some(a=>cF(a).toLowerCase()===c)}return cF(a).toLowerCase()===cF(b).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cH(h).includes(cH(e));case"not_icontains":return!cH(h).includes(cH(e));case"starts_with":return cH(h).startsWith(cH(e));case"not_starts_with":return!cH(h).startsWith(cH(e));case"ends_with":return cH(h).endsWith(cH(e));case"not_ends_with":return!cH(h).endsWith(cH(e));case"regex":return cG(String(e))&&null!==String(h).match(String(e));case"not_regex":return cG(String(e))&&null===String(h).match(String(e));case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{if("boolean"==typeof e)throw new cz("Date operations cannot be performed on boolean values");let a=function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e)c.setUTCMonth(c.getUTCMonth()-d);else{if("y"!==e)return null;c.setUTCFullYear(c.getUTCFullYear()-d)}return c}(String(e));null==a&&(a=cL(e));let b=cL(h);return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===cK(cJ(String(h),g),cJ(String(e),g));case"semver_neq":return 0!==cK(cJ(String(h),g),cJ(String(e),g));case"semver_gt":return cK(cJ(String(h),g),cJ(String(e),g))>0;case"semver_gte":return cK(cJ(String(h),g),cJ(String(e),g))>=0;case"semver_lt":return 0>cK(cJ(String(h),g),cJ(String(e),g));case"semver_lte":return 0>=cK(cJ(String(h),g),cJ(String(e),g));case"semver_tilde":{let a,b=cJ(String(h),g),{lower:c,upper:d}={lower:[(a=cJ(String(e),g))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return cK(b,c)>=0&&0>cK(b,d)}case"semver_caret":{let a=cJ(String(h),g),{lower:b,upper:c}=function(a,b){let[c,d,e]=cJ(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}(String(e),g);return cK(a,b)>=0&&0>cK(a,c)}case"semver_wildcard":{let a=cJ(String(h),g),{lower:b,upper:c}=function(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cz(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cI(c,a,b)}catch{}throw new cz(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}(String(e),g);return cK(a,b)>=0&&0>cK(a,c)}default:throw new cz(`Unknown operator: ${f}`)}}(a,b,{warnFunction:c})}async function cU(a,b,c,d=!1,e){let f=String(a.value);if(!(f in c))throw new cR(`cohort ${f} not found in local cohorts - likely a static cohort that requires server evaluation`);return cV(c[f],b,c,d,e)}async function cV(a,b,c,d=!1,e){if(!a)return!0;let f=a.type,g=a.values;if(!g||0===g.length)return!0;let h=!1;if("values"in g[0]){for(let a of g)try{let g=await cV(a,b,c,d,e);if("AND"===f){if(!g)return!1}else if(g)return!0}catch(b){if(b instanceof cR)throw b;if(b instanceof cz)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new cz("Can't match cohort without a given cohort property value");return"AND"===f}for(let a of g)try{let g;if("cohort"===a.type)g=await cU(a,b,c,d,e);else if("flag"===a.type){if(!e)throw new cz(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);g=await e(a)}else g=cT(a,b);let h=a.negation||!1;if("AND"===f){if(!g&&!h||g&&h)return!1}else if(g&&!h||!g&&h)return!0}catch(b){if(b instanceof cR)throw b;if(b instanceof cz)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),h=!0;else throw b}if(h)throw new cz("can't match cohort without a given cohort property value");return"AND"===f}let cW=["--unhandled-rejections","--unhandled_rejections"],cX=new Set(["throw","strict","warn","warn-with-error-code","none"]),cY=[...globalThis.process?.execArgv??[]],cZ=globalThis.process?.env?.NODE_OPTIONS;function c$(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=cW.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);cX.has(f)&&(b=f)}return b}let c_=function(a=cY,b=cZ){return c$(a)??c$(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}();function c0(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function c1(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),w(a))if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),c1(e??c,b,c,d)}class c2{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=c1(a.bucketSize,0,100,a._logger),this._refillRate=c1(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=c1(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var cd=aP;let c3=class b{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new c2({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return q(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e){let f={...e},g=a.buildFromUnknown(b,c);g.$exception_list=await a.modifyFrames(g.$exception_list);let h=cd.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=c_){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>c0(b,a,c));e.on("uncaughtException",(f=!1,Object.assign((d,e)=>{let g=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;c0(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=c_){let c=globalThis.process;c&&"throw"!==b&&"strict"!==b&&"warn-with-error-code"!==b&&c.on("unhandledRejection",b=>{a(b,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(a,c){this.client.addPendingPromise((async()=>{if(!b.isPreviouslyCapturedError(a)){let d=await b.buildEventMessage(this.client.getErrorPropertiesBuilder(),a,c),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})())}async onFatalError(a){console.error(a),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};class c4{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let c5="analytics";class c6 extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(c6.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function c7(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let c8=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:c7},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:c7},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:c7},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],c9=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function da(a,b,c){void 0===c||b in a||(a[b]=c)}function db(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of c8)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of c9)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,da(c,"$set",a.$set),da(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let dc=new Set([408,500,502,503,504]);class dd{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>P(b,a))),this.generateRequestId=b.generateRequestId??aU,this.compress=b.compress??a7}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(db)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=l({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&dc.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new c6({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=P(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new c6({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new c6({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let de="ai-capture",df="/i/v0/ai/batch/",dg=new TextEncoder;function dh(a){return dg.encode(l(a)).length}let di=new Set;function dj(a,b){di.has(a)||(di.add(a),console.warn(`[PostHog] ${b}`))}class dk extends bl{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:function(a){return("string"==typeof a?a.trim():"")||"https://us.i.posthog.com"}(b.host),personalApiKey:function(a){return("string"==typeof a?a.trim():"")||void 0}(b.secretKey??b.personalApiKey)};if(super(c,d),this._memoryStorage=new c4,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=d,this.captureMode=function(){let a="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===a||"v1"===a?a:"v0"}(),this.enableFullAiCapture=!0===d.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof d.featureFlagsPollingInterval?Math.max(d.featureFlagsPollingInterval,100):3e4,"number"==typeof d.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(d.waitUntilDebounceMs,0)),"number"==typeof d.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(d.waitUntilMaxWaitMs,0)),!this.disabled&&d.personalApiKey){if(d.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!==d.enableLocalEvaluation&&(this.featureFlagsPoller=new cS({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:d.personalApiKey,projectApiKey:c,timeout:d.requestTimeout??1e4,host:this.host,fetch:d.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation,evaluationContexts:d.evaluationContexts??d.evaluationEnvironments}))}this.errorTracking=new c3(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises();return!this._traces||a&&this._traces.throttled?b:R([b,this._traces.flush().catch(()=>{})]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=P(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":c5}persistedQueueKeyForRoute(a){return a===de?j.AiCaptureQueue:"ai"===a?j.AiQueue:j.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[c5,"ai"]:[c5];return this._aiCaptureRouteActive&&a.push(de),a}getBatchEndpointPath(a){return a===de?df:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=c5){if(c===de)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=dh(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${df}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,de)}catch(d){if(!bh(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dh(b)} bytes) was rejected with 413 by ${df} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new dd({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.52.4"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bE(this,(a=this.options.metrics,b=a?.resourceAttributes,{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new cr}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var a,b,c;let d,e;return this._traces||(this._traces=new cc(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=bq({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cv.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cv)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=cu(a?.maxExportBatchSize,512),{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:cu(a?.maxAttributesPerSpan,128),maxEventsPerSpan:cu(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:cu(a?.maxAttributeValueLength,8192),flushIntervalMs:cu(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(cu(a?.maxQueueSize,2048),e),maxLiveSpans:cu(a?.maxLiveSpans,1e4),maxSpanAgeMs:cu(a?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??bZ(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):b2(this._spanContextManager,bZ(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:f,options:g})=>{let h={timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid},i={distinctId:b,event:d,properties:{...f,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,i,h,e):this.enqueue(a,i,h,e)}).catch(a=>{a&&console.error(a)}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(a,!0)}captureAi(a){if(this.disabled)return;let b=K(a.uuid,aU);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=K(a.uuid,aU);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,de)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l;if(this.disabled)return void this._logger.warn("The client is disabled");let m=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:n,disableGeoip:o}=c,{onlyEvaluateLocally:p,personProperties:q,groupProperties:r}=c,s=this.addLocalPersonAndGroupProperties(b,n,q,r);q=s.allPersonProperties,r=s.allGroupProperties;let t=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,q),r);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let u=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,t,{matchValue:d});if(c){u=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0}}}catch(b){if(b instanceof cR||b instanceof cz)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!u&&!p){let b=await super.getFeatureFlagDetailsStateless(t.distinctId,t.groups,q,r,o,[a]);if(void 0===b)h=cw.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(cw.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(cw.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(cw.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b}}c.length>0&&(h=c.join(","))}}if(m){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:u,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),u&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:o,properties:d})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){dj("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(dj("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:e?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){dj("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];return new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",i=`${c}_${d}${h}`;b in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[b].has(i)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[b]instanceof Set?this.distinctIdHasSentFlagCalls[b].add(i):this.distinctIdHasSentFlagCalls[b]=new Set([i]),this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,b,c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b)}async _shutdown(a){let b=Date.now()+(a??3e4),c=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await Q(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await Q(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,b-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},c?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=P(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(y(f,"Object")&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!c3.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(c3.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!c3.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(c3.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){let{distinctId:c,event:d,properties:e,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k}=a,l=this.context?.get(),m=b.includeContextProperties??!0,n=c||l?.distinctId,o=m?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};n||(n=aU(),o.$process_person_profile=!1),m&&l?.sessionId&&!o.$session_id&&(o.$session_id=l.sessionId);let p=this._shouldSendMinimalFlagCalledEvent(d,o)?a3(o):o,q=this._runBeforeSend({distinctId:n,event:d,properties:p,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!q)return Promise.reject(null);let r=await Promise.resolve().then(async()=>{if(g)return h&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),g._getEventProperties();if(h){dj("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var a=await this.getFeatureFlagsForEvent(q.distinctId,f,j,"object"==typeof h?h:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=q.groups||f;return{...a,...q.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===q.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof r.$raw_user_agent&&ct(r.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(q.event="$bot_pageview",r.$browser_type="bot"),{distinctId:q.distinctId,event:q.event,properties:r,options:{timestamp:q.timestamp,disableGeoip:q.disableGeoip,uuid:q.uuid}}}_runBeforeSend(a){let b=this.options.before_send;if(!b)return a;let c=Array.isArray(b)?b:[b],d=a;for(let b of c)try{if(!(d=b(d)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!d.properties||0===Object.keys(d.properties).length){let a=`Event '${d.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(b){return this._logger.error(`Error in before_send function for event '${a.event}':`,b),null}return d}}var cd=aP,dl=a.i(78500);class dm{constructor(){this.storage=new dl.AsyncLocalStorage}get(){return this.storage.getStore()}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){if(b?.fresh===!0)return a;let c=this.get()||{};return{distinctId:a.distinctId??c.distinctId,sessionId:a.sessionId??c.sessionId,properties:{...c.properties||{},...a.properties||{}}}}}class dn{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new dl.AsyncLocalStorage}}var dp=a.i(27028);let dq=(0,a.i(12057).promisify)(dp.gzip);async function dr(a,b=!0){try{let b=await dq(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var ds=a.i(60526),cd=aP;let dt="posthog-node";function du(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[dw.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=cd.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function dv(a,b){let c=du(a,b);return{name:dt,processEvent:a=>c(a)}}class dw{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=dt,this.name=dt,this.setupOnce=function(f,g){f(du(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,dw,"createEventProcessor",0,du,"sentryIntegration",0,dv],9318);let dx=/[\x00-\x1f\x7f-\x9f]/g;function dy(a,b,c){null!=c&&""!==c&&(a[b]=c)}function dz(a){return Array.isArray(a)?a[0]:a}function dA(a){if(Array.isArray(a)){for(let b of a){let a=dA(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(dx,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function dB(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=dA(a["x-posthog-session-id"]),c=dA(a["x-posthog-distinct-id"]);return{...void 0!==b?{sessionId:b}:{},...void 0!==c?{distinctId:c}:{}}}(b.headers),h={},i=!0===a.options.disable_capture_url_hashes;return dy(h,"$current_url",(c=b.originalUrl||b.url,i?M(c):c)),dy(h,"$request_method",b.method),dy(h,"$request_path",(d=b.path,e=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),i?M(e):e)),dy(h,"$user_agent",dz(b.headers["user-agent"])),dy(h,"$ip",function(a){let b=dz(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{},properties:h}}function dC(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(dB(c,a),()=>d())}))}function dD(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(c3.isPreviouslyCapturedError(a))return void e(a);let f=dB(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([c3.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,dD,"setupExpressRequestContext",0,dC],40602),a.s([],51328);class dE extends dk{getLibraryId(){return"posthog-node"}compressPayload(a){return dr(a,this.isDebug)}initializeContext(){return new dm}initializeSpanContextManager(){return new dn}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,ds.platform)(),d=(0,ds.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bx,a)?bx[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new cd.ErrorPropertiesBuilder([new cd.EventCoercer,new cd.ErrorCoercer,new cd.ObjectCoercer,new cd.StringCoercer,new cd.PrimitiveCoercer],cd.createStackParser("node:javascript",cd.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,h.dirname)(process.argv[1]):process.cwd(),b="\\"===h.sep){let c=b?i(a):a;return a=>{if(!a)return;let d=b?i(a):a,{dir:e,base:f,ext:g}=h.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let j=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${j}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${j}`:j}return j}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>ck(a,void 0,this._logger),function(a=process.cwd()){h.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,h.isAbsolute)(d.filename)&&(d.filename=b((0,h.relative)(c,b(d.filename))));return a}}()])}}a.s(["PostHog",0,dE],81035),a.i(81035),a.i(51328),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,k,"FeatureFlagEvaluations",0,cx,"PostHogSentryIntegration",0,dw,"cookieStateToProperties",0,a$,"cookieStoreFromHeader",0,aW,"createEventProcessor",0,du,"getPostHogCookieName",0,aX,"parsePostHogCookie",0,a_,"readPostHogCookie",0,aZ,"sentryIntegration",0,dv,"serializePostHogCookie",0,aY,"setupExpressErrorHandler",0,dD,"setupExpressRequestContext",0,dC,"uuidv7",0,aU],80456),a.i(80456),a.s(["FeatureFlagError",0,k,"FeatureFlagEvaluations",0,cx,"PostHog",0,dE,"PostHogSentryIntegration",0,dw,"cookieStateToProperties",0,a$,"cookieStoreFromHeader",0,aW,"createEventProcessor",0,du,"getPostHogCookieName",0,aX,"parsePostHogCookie",0,a_,"readPostHogCookie",0,aZ,"sentryIntegration",0,dv,"serializePostHogCookie",0,aY,"setupExpressErrorHandler",0,dD,"setupExpressRequestContext",0,dC,"uuidv7",0,aU],74493)}];
|
|
2
|
+
at ${a.filename}:${b}:${c}`}}a.s(["ErrorEventCoercer",0,aw],75368);let ax=["fatal","error","warning","log","info","debug"];function ay(a,b=40){let c=Object.keys(a);if(c.sort(),!c.length)return"[object has no keys]";for(let a=c.length;a>0;a--){let d=c.slice(0,a).join(", ");if(!(d.length>b)){if(a===c.length)return d;return d.length<=b?d:`${d.slice(0,b)}...`}}return""}class az{match(a){return"object"==typeof a&&null!==a}coerce(a,b){let c=this.getErrorPropertyFromObject(a);return c?b.apply(c):{type:this.getType(a),value:this.getValue(a),stack:this.getStack(a)??b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){if(A(a))return a.constructor.name;let b="name"in a?a.name:void 0;return s(b)&&!t(b)?b:"Error"}getValue(a){if("name"in a&&"string"==typeof a.name){let b=`'${a.name}' captured as exception`;return"message"in a&&"string"==typeof a.message&&(b+=` with message: '${a.message}'`),b}if("message"in a&&"string"==typeof a.message)return a.message;let b=this.getObjectClassName(a),c=ay(a);return`${b&&"Object"!==b?`'${b}'`:"Object"} captured as exception with keys: ${c}`}isSeverityLevel(a){return s(a)&&!t(a)&&ax.indexOf(a)>=0}getStack(a){try{if(s(a.stacktrace)&&a.stacktrace.length>0)return a.stacktrace;return s(a.stack)&&a.stack.length>0?a.stack:void 0}catch{return}}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(z(c))return c}}getObjectClassName(a){try{let b=Object.getPrototypeOf(a);return b?b.constructor.name:void 0}catch(a){return}}}a.s(["ObjectCoercer",0,az],93874);class aA{match(a){return A(a)}coerce(a,b){let c=a.constructor.name;return{type:c,value:`${c} captured as exception with keys: ${ay(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["EventCoercer",0,aA],46980);class aB{match(a){return x(a)}coerce(a,b){return{type:"Error",value:`Primitive value captured as exception: ${String(a)}`,stack:b.syntheticException?.stack,synthetic:!0}}}a.s(["PrimitiveCoercer",0,aB],28150);class aC{match(a){return y(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!A(a))return!1;try{let b=a.detail;return null!=b&&"object"==typeof b&&"reason"in b}catch{return!1}}coerce(a,b){let c=this.getUnhandledRejectionReason(a);return x(c)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(c)}`,stack:b.syntheticException?.stack,synthetic:!0}:b.apply(c)}getUnhandledRejectionReason(a){try{if("reason"in a)return a.reason;if("detail"in a&&null!=a.detail&&"object"==typeof a.detail&&"reason"in a.detail)return a.detail.reason}catch{}return a}}a.s(["PromiseRejectionEventCoercer",0,aC],98140),a.s([],7610);let aD={MESSAGE:"$message",TIMESTAMP:"$timestamp"},aE=new Set([aD.MESSAGE,aD.TIMESTAMP]),aF={enabled:!0,max_bytes:32768};function aG(a){return a?{enabled:a.enabled??aF.enabled,max_bytes:function(a,b){if(!w(a)||1/0===a||-1/0===a)return b;let c=Math.floor(a);return c<0?b:c}(a.max_bytes,aF.max_bytes)}:{...aF}}function aH(a){if(!a)return{sanitizedProperties:{},droppedKeys:[]};let b=[];return{sanitizedProperties:Object.keys(a).reduce((c,d)=>(aE.has(d)?b.push(d):c[d]=a[d],c),{}),droppedKeys:b}}class aI{constructor(a){this._entries=[],this._totalBytes=0,this._config=aG(a)}setConfig(a){this._config=aG(a),this._trimToMaxBytes()}add(a){let b=function(a){let b;try{b=l(a)}catch{return}try{let a=JSON.parse(b);if(!q(a))return;let c=a[aD.MESSAGE],d=a[aD.TIMESTAMP];if(!s(c)||0===c.trim().length||!s(d)&&!w(d))return;return{step:a,json:b}}catch{return}}(a);if(!b)return;let c=aJ(b.json);c>this._config.max_bytes||(this._entries.push({step:b.step,bytes:c}),this._totalBytes+=c,this._trimToMaxBytes())}getAttachable(){return this._entries.map(a=>a.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){for(;this._totalBytes>this._config.max_bytes&&this._entries.length>0;){let a=this._entries.shift();a&&(this._totalBytes-=a.bytes)}}}function aJ(a){if("u">typeof TextEncoder)return new TextEncoder().encode(a).length;let b=encodeURIComponent(a),c=0;for(let a=0;a<b.length;a++)"%"===b[a]?(c+=1,a+=2):c+=1;return c}a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aF,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aD,"ExceptionStepsBuffer",0,aI,"getUtf8ByteLength",0,aJ,"resolveExceptionStepsConfig",0,aG,"stripReservedExceptionStepFields",0,aH],97383),a.s([],48153),a.i(48153),a.i(6762),a.i(67970),a.s(["chromeStackLineParser",0,$,"createDefaultStackParser",0,at,"createStackParser",0,au,"geckoStackLineParser",0,ab,"nodeStackLineParser",0,am,"opera10StackLineParser",0,af,"opera11StackLineParser",0,ah,"reverseAndStripFrames",0,as,"winjsStackLineParser",0,ad],64583),a.i(64583),a.i(7610),a.i(51671);class aK{match(a){return z(a)}coerce(a,b){let c=this.getStack(a),d=void 0===c?b.syntheticException?.stack:void 0;return{type:this.getType(a),value:this.getMessage(a,b),stack:c??d,cause:a.cause?b.next(a.cause):void 0,synthetic:!!d}}getType(a){return a.name||a.constructor.name}getMessage(a,b){let c=a.message;return c.error&&"string"==typeof c.error.message?String(c.error.message):String(c)}getStack(a){try{let b=a.stacktrace;if("string"==typeof b&&b.length>0)return b;let c=a.stack;return"string"==typeof c&&c.length>0?c:void 0}catch{return}}}a.s(["ErrorCoercer",0,aK],10692),a.i(10692),a.i(75368);let aL=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aM{match(a){return"string"==typeof a}coerce(a,b){let[c,d]=this.getInfos(a);return{type:c??"Error",value:d??a,stack:b.syntheticException?.stack,synthetic:!0}}getInfos(a){let b="Error",c=a,d=a.match(aL);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aM],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,av,"ErrorCoercer",0,aK,"ErrorEventCoercer",0,aw,"EventCoercer",0,aA,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"StringCoercer",0,aM],54253),a.i(54253);class aN{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}function aO(){let a=globalThis._posthogReleaseId;return"string"==typeof a&&a.length>0?a:void 0}a.s(["ReduceableCache",0,aN],98966),a.i(98966),a.i(97383),a.s(["getInjectedReleaseId",0,aO],28861),a.i(28861),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aF,"DOMExceptionCoercer",0,av,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aD,"ErrorCoercer",0,aK,"ErrorEventCoercer",0,aw,"ErrorPropertiesBuilder",0,S,"EventCoercer",0,aA,"ExceptionStepsBuffer",0,aI,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"ReduceableCache",0,aN,"StringCoercer",0,aM,"chromeStackLineParser",0,$,"createDefaultStackParser",0,at,"createStackParser",0,au,"geckoStackLineParser",0,ab,"getInjectedReleaseId",0,aO,"getUtf8ByteLength",0,aJ,"nodeStackLineParser",0,am,"opera10StackLineParser",0,af,"opera11StackLineParser",0,ah,"resolveExceptionStepsConfig",0,aG,"reverseAndStripFrames",0,as,"stripReservedExceptionStepFields",0,aH,"winjsStackLineParser",0,ad],60485);var aP=a.i(60485);let aQ="0123456789abcdef";class aR{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new aR(a);throw TypeError("not 128-bit length")}static fromFieldsV7(a,b,c,d){if(!Number.isInteger(a)||!Number.isInteger(b)||!Number.isInteger(c)||!Number.isInteger(d)||a<0||b<0||c<0||d<0||a>0xffffffffffff||b>4095||c>0x3fffffff||d>0xffffffff)throw RangeError("invalid field value");let e=new Uint8Array(16);return e[0]=a/0x10000000000,e[1]=a/0x100000000,e[2]=a/0x1000000,e[3]=a/65536,e[4]=a/256,e[5]=a,e[6]=112|b>>>8,e[7]=b,e[8]=128|c>>>24,e[9]=c>>>16,e[10]=c>>>8,e[11]=c,e[12]=d>>>24,e[13]=d>>>16,e[14]=d>>>8,e[15]=d,new aR(e)}static parse(a){let b;switch(a.length){case 32:b=/^[0-9a-f]{32}$/i.exec(a)?.[0];break;case 36:b=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("");break;case 38:b=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(a)?.slice(1,6).join("");break;case 45:b=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(a)?.slice(1,6).join("")}if(b){let a=new Uint8Array(16);for(let c=0;c<16;c+=4){let d=parseInt(b.substring(2*c,2*c+8),16);a[c+0]=d>>>24,a[c+1]=d>>>16,a[c+2]=d>>>8,a[c+3]=d}return new aR(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aQ.charAt(this.bytes[b]>>>4),a+=aQ.charAt(15&this.bytes[b]),(3===b||5===b||7===b||9===b)&&(a+="-");return a}toHex(){let a="";for(let b=0;b<this.bytes.length;b++)a+=aQ.charAt(this.bytes[b]>>>4),a+=aQ.charAt(15&this.bytes[b]);return a}toJSON(){return this.toString()}getVariant(){let a=this.bytes[8]>>>4;if(a<0)throw Error("unreachable");if(a<=7)return this.bytes.every(a=>0===a)?"NIL":"VAR_0";if(a<=11)return"VAR_10";if(a<=13)return"VAR_110";if(a<=15)return this.bytes.every(a=>255===a)?"MAX":"VAR_RESERVED";throw Error("unreachable")}getVersion(){return"VAR_10"===this.getVariant()?this.bytes[6]>>>4:void 0}clone(){return new aR(this.bytes.slice(0))}equals(a){return 0===this.compareTo(a)}compareTo(a){for(let b=0;b<16;b++){let c=this.bytes[b]-a.bytes[b];if(0!==c)return Math.sign(c)}return 0}}class aS{constructor(a){this.timestamp=0,this.counter=0,this.random=a??aT()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(a,b){let c=this.generateOrAbortCore(a,b);return void 0===c&&(this.timestamp=0,c=this.generateOrAbortCore(a,b)),c}generateOrAbortCore(a,b){if(!Number.isInteger(a)||a<1||a>0xffffffffffff)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(b<0||b>0xffffffffffff)throw RangeError("`rollbackAllowance` out of reasonable range");if(a>this.timestamp)this.timestamp=a,this.resetCounter();else{if(!(a+b>=this.timestamp))return;this.counter++,this.counter>0x3ffffffffff&&(this.timestamp++,this.resetCounter())}return aR.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 a=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return a[6]=64|a[6]>>>4,a[8]=128|a[8]>>>2,aR.ofInner(a)}}let aT=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())>>>0}),aU=()=>aV().toString(),aV=()=>(e||(e=new aS)).generate();function aW(a){let b={};if(a)for(let c of a.split(";")){let[a,...d]=c.trim().split("=");if(a){let c=d.join("=").trim();try{b[a.trim()]=decodeURIComponent(c)}catch{b[a.trim()]=c}}}return{get:a=>a in b?{value:b[a]}:void 0}}function aX(a){let b=a.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ");return`ph_${b}_posthog`}function aY(a){let b=Date.now();return JSON.stringify({distinct_id:a,$device_id:a,$user_state:"anonymous",$sesid:[b,aU(),b]})}function aZ(a,b){let c=aX(b),d=a.get(c);return d?a_(d.value):null}function a$(a){if(!a)return;let b={};return a.sessionId&&(b.$session_id=a.sessionId),a.deviceId&&(b.$device_id=a.deviceId),Object.keys(b).length>0?b:void 0}function a_(a){if(!a)return null;try{let b=JSON.parse(a);if(!b||"object"!=typeof b||!b.distinct_id)return null;let c=p(b.$sesid)?b.$sesid[1]:void 0;return{distinctId:String(b.distinct_id),isIdentified:"identified"===b.$user_state,sessionId:"string"==typeof c?c:void 0,deviceId:"string"==typeof b.$device_id?b.$device_id:void 0}}catch{return null}}let a0=a=>void 0===a?void 0:a.variant??a.enabled,a1=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}},a2=["$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"],a3=(a,b=[])=>{let c={},d=b=>{void 0!==a[b]&&(c[b]=a[b])};return a2.forEach(d),b.forEach(d),c};class a4{constructor(){this.events={},this.events={}}on(a,b){return this.events[a]||(this.events[a]=[]),this.events[a].push(b),()=>{this.events[a]=this.events[a].filter(a=>a!==b)}}emit(a,b){for(let c of this.events[a]||[])c(b);for(let c of this.events["*"]||[])c(a,b)}}let a5=a=>{throw L("NativeGzipValidationError",`Native gzip produced invalid output: ${a}`)},a6=async(a,b)=>{a.size<18&&a5("too-short");let c=new Uint8Array(await a.slice(0,10).arrayBuffer());c.length>=2&&31===c[0]&&139===c[1]&&8===c[2]||a5("invalid-header");let d=new DataView(await a.slice(a.size-8).arrayBuffer());d.getUint32(0,!0)!==(a=>{let b=(()=>{if(f)return f;f=[];for(let a=0;a<256;a++){let b=a;for(let a=0;a<8;a++)b=1&b?0xedb88320^b>>>1:b>>>1;f[a]=b>>>0}return f})(),c=0xffffffff;for(let d=0;d<a.length;d++)c=b[(c^a[d])&255]^c>>>8;return(0xffffffff^c)>>>0})(b)&&a5("invalid-crc");let e=b.length>>>0;d.getUint32(4,!0)!==e&&a5("invalid-size")};async function a7(a,b=!0,c){try{let b=new TextEncoder().encode(a),c=new globalThis.CompressionStream("gzip"),d=c.writable.getWriter(),e=d.write(b).then(()=>d.close()).catch(async a=>{try{await d.abort(a)}catch{}throw a}),f=new Response(c.readable).blob(),[g]=await Promise.all([f,e]);return await a6(g,b),g}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}class a8{add(a){let b=aU(),c=++this.nextId;return this.promiseByIds[b]={id:c,promise:a},a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds).map(a=>a.promise),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds).map(a=>a.promise)).length}getPromises(a=[],b=this.nextId){let c=new Set(a);return Object.values(this.promiseByIds).filter(a=>a.id<=b&&!c.has(a.promise)).map(a=>a.promise)}get maxId(){return this.nextId}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={},this.nextId=0}}let a9=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{debug:(...a)=>{d("debug",...a)},info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>a9(`${a} ${d}`,b,c)}};class ba{record(a){if("too-large"===a.kind)return;if("retry-later"!==a.kind)return void this.reset();if(!a.retryAfterMs)return;let b=this.isOpen(),c=Date.now(),d=Math.min(a.retryAfterMs,3e5);if(!b){this._installedAt=c,this._until=c+d;return}this._until=Math.max(this._until,Math.min(c+d,this._installedAt+3e5))}remainingMs(){let a=Date.now();if(a<this._installedAt-5e3)return this.reset(),0;let b=Math.min(3e5,Math.max(0,this._until-a));return 0===b&&this.reset(),b}isOpen(){return this.remainingMs()>0}reset(){this._until=0,this._installedAt=0}constructor(){this._until=0,this._installedAt=0}}class bb extends Error{constructor(a,b,c,d){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.responseBodyDeadline=c,this.abortController=d,this.name="PostHogFetchHttpError",this._bodyReadTimedOut=!1}get status(){return this.response.status}get retryAfterMs(){try{return function(a,b=Date.now()){if("string"!=typeof a||!a)return;let c=a.trim(),d=/^\d+\s*,/.test(c)?c.slice(0,c.indexOf(",")).trim():c;if(/^\d+$/.test(d)){let a=1e3*Math.min(Number(d),300);return a>0?a:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(d))return;let e=Date.parse(/^\w{3} \w{3} /.test(d)?d+" GMT":d)-b;if(Number.isFinite(e)&&!(e<=0))return Math.min(e,3e5)}(this.response.headers?.get("retry-after"))}catch{return}}get bodyReadTimedOut(){return this._bodyReadTimedOut}get text(){if(!this.responseBodyTextPromise)if(Date.now()>=this.responseBodyDeadline){this._bodyReadTimedOut=!0;let a=L("AbortError","Response body read timed out");this.cancelResponseBody(a),this.responseBodyTextPromise=Promise.reject(a)}else{let a,b=new Promise((a,b)=>{this.responseBodyTimer=P(()=>{this._bodyReadTimedOut=!0;let a=L("AbortError","Response body read timed out");b(a),this.cancelResponseBody(a)},this.responseBodyDeadline-Date.now())});try{a=Promise.resolve(this.response.text())}catch(b){a=Promise.reject(b)}this.responseBodyTextPromise=Promise.race([a,b]).finally(()=>clearTimeout(this.responseBodyTimer))}return this.responseBodyTextPromise}get json(){return this.text.then(a=>JSON.parse(a))}cancelResponseBody(a){clearTimeout(this.responseBodyTimer),this.abortController.signal.aborted||this.abortController.abort(a),(async()=>{try{await this.response.body?.cancel()}catch{}})()}}class bc extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function bd(a){if(a instanceof bb){let b="";try{b=await a.text}catch{a.bodyReadTimedOut&&(b="<response body read timed out>")}console.error(`Error while flushing PostHog: message=${a.message}, response body=${b}`,a)}else console.error("Error while flushing PostHog",a);return Promise.resolve()}function be(a){return a instanceof bc}function bf(a){if(a instanceof bb)return 502===a.status||504===a.status;if(!(a instanceof bc))return!1;let b=a.error;return"ECONNREFUSED"!==(b?.code??b?.cause?.code)}function bg(a){try{if("string"!=typeof a)return a instanceof Uint8Array?a.byteLength:a.size;if("u">typeof Buffer)return Buffer.byteLength(a,"utf8");return new TextEncoder().encode(a).length}catch{return 0}}function bh(a){return"object"==typeof a&&a instanceof bb&&413===a.status}function bi(a){return a instanceof bb?408===a.status||429===a.status||a.status>=500:be(a)}function bj(a){return null!==a&&"object"==typeof a&&!Array.isArray(a)}let bk="default";class bl{getErrorPropertiesBuilder(){return this._errorPropertiesBuilder||(this._errorPropertiesBuilder=this.createErrorPropertiesBuilder()),this._errorPropertiesBuilder}createErrorPropertiesBuilder(){return new S([new aK,new az,new aM,new aB],at())}getEvaluationRuntime(){}constructor(a,b={}){this.flushPromise=null,this.pendingFlushPromise=null,this.flushPromises=new Set,this._dequeuedMessagesCount=0,this.shutdownPromise=null,this.promiseQueue=new a8,this._events=new a4,this._isInitialized=!1;const c="string"==typeof a?a.trim():"",d="string"==typeof b.host?b.host.trim():"",e=!c;this._logger=function(a,b=a=>a()){return a9(a,b,function(a=console){return{log:a.log.bind(a),warn:a.warn.bind(a),error:a.error.bind(a),debug:a.debug.bind(a)}}())}("[PostHog]",this.logMsgIfDebug.bind(this)),e&&this._logger.error("You must pass your PostHog project's api key. The client will be disabled."),this.apiKey=c,this.host=function(a){return a?.replace(/\/+$/,"")}(d||"https://us.i.posthog.com"),this.flushAt=b.flushAt?Math.max(b.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,b.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,b.maxQueueSize??1e3),this.flushInterval=b.flushInterval??1e4,this.preloadFeatureFlags=b.preloadFeatureFlags??!0,this.defaultOptIn=b.defaultOptIn??!0,this.disableSurveys=b.disableSurveys??!1,this._retryOptions={retryCount:b.fetchRetryCount??3,retryDelay:b.fetchRetryDelay??3e3,retryCheck:bi},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,this.featureFlagsRequestMaxRetries=b.featureFlagsRequestMaxRetries??1,this.remoteConfigRequestTimeoutMs=b.remoteConfigRequestTimeoutMs??3e3,this.disableGeoip=b.disableGeoip??!0,this.disabled=(b.disabled??!1)||e,this.historicalMigration=b?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=b?.evaluationContexts??b?.evaluationEnvironments,b?.evaluationEnvironments&&!b?.evaluationContexts&&this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version."),this.disableCompression=!("CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&"function"==typeof Response.prototype.blob)||(b?.disableCompression??!1)}logMsgIfDebug(a){this.isDebug&&a()}wrap(a){return this.disabled?void this._logger.warn("The client is disabled"):this._isInitialized?a():void this._initPromise.then(()=>a())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(j.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(j.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(j.OptedOut,!0)})}on(a,b){return this._events.on(a,b)}debug(a=!0){if(this.removeDebugCallback?.(),a){let a=this.on("*",(a,b)=>this._logger.info(a,b));this.removeDebugCallback=()=>{a(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(a){let b=a.properties||{},c={...b,...this.getCommonEventProperties()};var d=c;for(let a of Object.keys(b))(a.startsWith("$feature/")||"$active_feature_flags"===a)&&(d[a]=b[a]);return"$feature_flag_called"===a.event&&!1===c.$feature_flag_has_experiment&&this.isMinimalFlagCalledEventsEnabled()&&(c=a3(c)),{distinct_id:a.distinct_id,event:a.event,properties:c}}isMinimalFlagCalledEventsEnabled(){return!1}addPendingPromise(a){return this.promiseQueue.add(a)}identifyStateless(a,b,c){this.wrap(()=>{let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};this.enqueue("identify",d,c)})}async identifyStatelessImmediate(a,b,c){let d={...this.buildPayload({distinct_id:a,event:"$identify",properties:b})};await this.sendImmediate("identify",d,c)}captureStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({distinct_id:a,event:b,properties:c});this.enqueue("capture",e,d)})}async captureStatelessImmediate(a,b,c,d){let e=this.buildPayload({distinct_id:a,event:b,properties:c});await this.sendImmediate("capture",e,d)}aliasStateless(a,b,c,d){this.wrap(()=>{let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});this.enqueue("alias",e,d)})}async aliasStatelessImmediate(a,b,c,d){let e=this.buildPayload({event:"$create_alias",distinct_id:b,properties:{...c||{},distinct_id:b,alias:a}});await this.sendImmediate("alias",e,d)}groupIdentifyStateless(a,b,c,d,e,f){this.wrap(()=>{let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});this.enqueue("capture",g,d)})}async groupIdentifyStatelessImmediate(a,b,c,d,e,f){let g=this.buildPayload({distinct_id:e||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{},...f||{}}});await this.sendImmediate("capture",g,d)}async getRemoteConfig(){await this._initPromise;let a=this.host;"https://us.i.posthog.com"===a?a="https://us-assets.i.posthog.com":"https://eu.i.posthog.com"===a&&(a="https://eu-assets.i.posthog.com");let b=`${a}/array/${this.apiKey}/config`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(b,c,{type:"required",consume:a=>a.json()},{retryCount:0},this.remoteConfigRequestTimeoutMs).catch(a=>{this._logger.error("Remote config could not be loaded",a),this._events.emit("error",a)})}async getFlags(a,b={},c={},d={},e={},f=!1){await this._initPromise;let g=`${this.host}/flags/?v=2${f?"&config=true":""}`,h={token:this.apiKey,distinct_id:a,groups:b,person_properties:c,group_properties:d,...e};c.$device_id&&(h.$device_id=c.$device_id),this.evaluationContexts&&this.evaluationContexts.length>0&&(h.evaluation_contexts=this.evaluationContexts);let i=this.getEvaluationRuntime();i&&(h.evaluation_runtime=i);let j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,j,{type:"required",consume:a=>a.json()},{retryCount:this.featureFlagsRequestMaxRetries,retryCheck:bf},this.featureFlagsRequestTimeoutMs).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,a0(b)]).filter(([,a])=>void 0!==a)),d=Object.fromEntries(Object.keys(b=a.flags??{}).filter(a=>{let c=b[a];return c.enabled&&c.metadata&&void 0!==c.metadata.payload}).map(a=>{let c=b[a].metadata?.payload;return[a,c?a1(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,a1(b)])),d=Object.fromEntries(Object.entries(b).map(([a,b])=>{var d,e;return[a,{key:a,enabled:"string"==typeof(d=b)||d,variant:"string"==typeof d?d:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:(e=c[a])?JSON.stringify(e):void 0,description:void 0}}]}));return{...a,featureFlags:b,featureFlagPayloads:c,flags:d}}})(a)})).catch(a=>(this._events.emit("error",a),{success:!1,error:this.categorizeRequestError(a)}))}categorizeRequestError(a){if(a instanceof bb)return{type:"api_error",statusCode:a.status};if(a instanceof bc){let b=a.error;return b instanceof Error&&("AbortError"===b.name||"TimeoutError"===b.name)?{type:"timeout"}:{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailStateless(a,b,c,d,e,f);if(void 0===g)return{response:void 0,requestId:void 0};let h=a0(g.response);return void 0===h&&(h=!1),{response:h,requestId:g.requestId}}async getFeatureFlagDetailStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(b,c,d,e,f,[a]);if(void 0!==g)return{response:g.flags[a],requestId:g.requestId,evaluatedAt:g.evaluatedAt}}async getFeatureFlagPayloadStateless(a,b,c={},d={},e={},f){await this._initPromise;let g=await this.getFeatureFlagPayloadsStateless(b,c,d,e,f,[a]);if(!g)return;let h=g[a];return void 0===h?null:h}async getFeatureFlagPayloadsStateless(a,b={},c={},d={},e,f){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)).payloads}async getFeatureFlagsStateless(a,b={},c={},d={},e,f){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(a,b,c,d,e,f)}async getFeatureFlagsAndPayloadsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g=await this.getFeatureFlagDetailsStateless(a,b,c,d,e,f);return g?{flags:g.featureFlags,payloads:g.featureFlagPayloads,requestId:g.requestId}:{flags:void 0,payloads:void 0,requestId:void 0}}async getFeatureFlagDetailsStateless(a,b={},c={},d={},e,f){await this._initPromise;let g={geoip_disable:e??this.disableGeoip};f&&(g.flag_keys_to_evaluate=f);let h=await this.getFlags(a,b,c,d,g);if(!h.success)return;let i=h.response;return(i.errorsWhileComputingFlags&&console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices"),i.quotaLimited?.includes("feature_flags"))?(console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:i?.requestId,quotaLimited:i.quotaLimited}):i}async getSurveysStateless(){if(await this._initPromise,this.disabled)return[];if(!0===this.disableSurveys)return this._logger.info("Loading surveys is disabled."),[];let a=`${this.host}/api/surveys/?token=${this.apiKey}`,b={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},c=await this.fetchWithRetry(a,b,{type:"required",consume:a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);return this._logger.error(c),this._events.emit("error",Error(b)),Promise.resolve(void 0)}return a.json()}}).catch(a=>{this._logger.error("Surveys API could not be loaded",a),this._events.emit("error",a)}),d=c?.surveys;return d&&this._logger.info("Surveys fetched from API: ",JSON.stringify(d)),d??[]}get props(){return this._props||(this._props=this.getPersistedProperty(j.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(j.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(j.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}getQueueRouteKey(a){return bk}persistedQueueKeyForRoute(a){return j.Queue}getActiveQueueRoutes(){return[bk]}getRouteQueue(a){return this.getPersistedProperty(this.persistedQueueKeyForRoute(a))||[]}enqueue(a,b,c,d){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null===(e=this.processBeforeEnqueue(e)))return;e=this.normalizeMessage(e);let f=this.persistedQueueKeyForRoute(d??this.getQueueRouteKey(e)),g=this.getPersistedProperty(f)||[];g.length>=this.maxQueueSize&&(g.shift(),this._logger.warn("Queue is full, the oldest event is dropped.")),g.push({message:e}),this.setPersistedProperty(f,g),this._events.emit(a,e),g.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=P(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c,d){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized||await this._initPromise,this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let e=this.prepareMessage(b,c);if(null!==(e=this.processBeforeEnqueue(e))){e=this.normalizeMessage(e);try{await this.sendBatch([e],void 0,d??this.getQueueRouteKey(e))}catch(a){this._events.emit("error",a)}}}normalizeMessage(a){let{type:b,library:c,library_version:d,...e}=a,f=bj(e.properties)?e.properties:void 0;return void 0!==c&&f?.$lib===void 0&&(f={...f||{},$lib:c}),void 0!==d&&f?.$lib_version===void 0&&(f={...f||{},$lib_version:d}),f&&(e.properties=f),e.uuid=K(e.uuid,aU),e}normalizeTimestampForWire(a){let b=a instanceof Date?a:"string"==typeof a?new Date(a):null;if(!b||Number.isNaN(b.getTime()))return a;let c=b.toISOString(),d="string"==typeof a?a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1]:void 0;return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}prepareMessage(a,b){let c={...a,timestamp:b?.timestamp?b?.timestamp:O(),uuid:K(b?.uuid,aU)};return(b?.disableGeoip??this.disableGeoip)&&(bj(c.properties)||(c.properties={}),c.properties.$geoip_disable=!0),c.distinctId&&(c.distinct_id=c.distinctId,delete c.distinctId),c}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.pendingFlushPromise||this.flushAutomatic().catch(async a=>{await bd(a)})}flushAutomatic(){return this.flush()}async waitForPendingPromises(a,b=[]){let c=b.filter(a=>!!a),d=0;for(;;){let b=this.promiseQueue.getPromises([...c,...this.flushPromises],a);if(0===b.length)return;d>0&&this._logger.debug(`flush() re-checking ${b.length} pending promise(s) before flushing`),await Promise.all(b.map(a=>a.catch(()=>{}))),d++}}flushWithPendingPromises(){return this.flushInternal(!0)}flush(){return this.flushInternal(!1)}flushInternal(a){if(this.disabled)return Promise.resolve();if(!a&&this.pendingFlushPromise)return this.pendingFlushPromise;let b=this.flushPromise,c=this.promiseQueue.maxId,d=Promise.resolve().then(()=>{if(a)return this.waitForPendingPromises(c,[b,d])}).then(()=>R([b])).then(()=>(this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this._flush()));return this.pendingFlushPromise=d,this.flushPromise=d,this.flushPromises.add(d),this.addPendingPromise(d),R([d]).then(()=>{this.flushPromises.delete(d),this.pendingFlushPromise===d&&(this.pendingFlushPromise=null),this.flushPromise===d&&(this.flushPromise=null)}),d}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}compressPayload(a){return a7(a,this.isDebug)}getBatchEndpointPath(a){return"/batch/"}async sendBatch(a,b,c=bk){let d={api_key:this.apiKey,batch:a.map(a=>{if(!a)return a;let b=this.normalizeTimestampForWire(a.timestamp);return b===a.timestamp?a:{...a,timestamp:b}}),sent_at:O()};this.historicalMigration&&(d.historical_migration=!0);let e=l(d),f=`${this.host}${this.getBatchEndpointPath(c)}`,g=this.disableCompression?null:await this.compressPayload(e),h={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==g&&{"Content-Encoding":"gzip"}},body:g||e};await this.fetchWithRetry(f,h,{type:"successful-write"},b)}async _flush(){let a;this.clearFlushTimer(),await this._initPromise;let b=this.getActiveQueueRoutes();if(!b.some(a=>this.getRouteQueue(a).length>0))return;let c=[];for(let d of b)try{await this._flushRoute(d,c)}catch(b){void 0===a&&(a=b)}if(void 0!==a)throw a;this._events.emit("flush",c)}async _flushRoute(a,b){let c=this.persistedQueueKeyForRoute(a),d=this.getPersistedProperty(c)||[];if(!d.length)return;let e=d.length,f=0;for(;d.length>0&&f<e;){let e=d.slice(0,this.maxBatchSize),g=e.map(a=>void 0===a.message?a.message:this.normalizeMessage(a.message)),h=async()=>{let a=this.getPersistedProperty(c)||[],b=[...e],f=a.filter(a=>{let c=a.message?.uuid,d=b.findIndex(b=>b===a||"string"==typeof c&&c.length>0&&b.message?.uuid===c);return -1===d||(b.splice(d,1),!1)});this.setPersistedProperty(c,f),d=f,this._dequeuedMessagesCount+=e.length,await this.flushStorage()},i={retryCheck:a=>!bh(a)&&bi(a)};try{await this.sendBatch(g,i,a)}catch(a){if(bh(a)&&g.length>1){this.maxBatchSize=Math.max(1,Math.floor(g.length/2)),this._logger.warn(`Received 413 when sending batch of size ${g.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof bc||await h(),this._events.emit("error",a),a}await h(),b.push(...g),f+=g.length}}async _sendOtlpBatch({path:a,auth:b,payload:c}){let d;if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};try{d=JSON.stringify(c)}catch(b){return this.logMsgIfDebug(()=>console.warn(`[PostHog] Could not serialize a ${a} batch; reporting it as too large`,b)),{kind:"too-large",measuredLocally:!0}}let e=bg(d);if(e>0xa00000)return this.logMsgIfDebug(()=>console.warn(`[PostHog] Not sending a ${a} batch of ${e} bytes: the endpoint accepts at most 10485760`)),{kind:"too-large",measuredLocally:!0};let f="bearer"===b?`${this.host}/i/v1/${a}`:`${this.host}/i/v1/${a}?token=${encodeURIComponent(this.apiKey)}`,g=this.disableCompression?null:await this.compressPayload(d),h=g||d,i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",..."bearer"===b&&{Authorization:`Bearer ${this.apiKey}`},...null!==g&&{"Content-Encoding":"gzip"}},body:h};try{return await this.fetchWithRetry(f,i,{type:"successful-write"},{retryCheck:a=>!bh(a)&&(!(a instanceof bb)||void 0===a.retryAfterMs)&&bi(a)}),{kind:"ok"}}catch(a){if(bh(a))return{kind:"too-large"};if(bi(a)){let b=a instanceof bb?a.retryAfterMs:void 0;return{kind:"retry-later",error:a,...void 0!==b&&{retryAfterMs:b}}}return{kind:"fatal",error:a}}}async _sendLogsBatch(a){return this._sendOtlpBatch({path:"logs",auth:"query-token",payload:a})}async _sendMetricsBatch(a){return this._sendOtlpBatch({path:"metrics",auth:"query-token",payload:a})}async _sendTracesBatch(a){return this._sendOtlpBatch({path:"traces",auth:"bearer",payload:a})}async fetchWithRetry(a,b,c,d,e){let f=bg(b.body?b.body:""),g={...this._retryOptions,...d},h=0;return await N(async()=>{let d,g,i;h++;let j=new AbortController,k=e??this.requestTimeout,l=Date.now()+k,m=new Promise((a,b)=>{d=P(()=>{let a=L("AbortError",`Request timed out after ${k}ms`);b(a),j.abort(a)},k)}),n=!1,o=()=>i??=(async()=>{try{await g?.body?.cancel()}catch{}})();try{let d;try{d=this.fetch(a,{signal:j.signal,...b})}catch(a){throw new bc(a)}d.then(a=>{j.signal.aborted&&!n&&Promise.resolve(a.body?.cancel()).catch(()=>{})}).catch(()=>{});try{g=await Promise.race([d,m]),n=!0}catch(a){throw new bc(a)}let e="no-cors"===b.mode,h="successful-write"===c.type?300:400;if(!e&&(g.status<200||g.status>=h))throw new bb(g,f,l,j);if("successful-write"===c.type){try{await Promise.race([o(),m])}catch{}return}try{return await Promise.race([c.consume(g),m])}catch(a){if(j.signal.aborted)throw new bc(a);throw a}}finally{clearTimeout(d),j.signal.aborted&&g&&o()}},{...g,retryCheck:a=>{let b=g.retryCheck(a);return b&&h<=g.retryCount&&a instanceof bb&&a.cancelResponseBody(),b}})}async _shutdown(a=3e4){await this._initPromise;let b=!1;if(this.clearFlushTimer(),!this.disabled)return Q((async()=>{try{for(await this.promiseQueue.join();this.getActiveQueueRoutes().some(a=>this.getRouteQueue(a).length>0);){let a=this._dequeuedMessagesCount;if(await this.flush(),b)break;if(this._dequeuedMessagesCount===a){this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");break}}}catch(a){if(!("object"==typeof a&&(a instanceof bb||be(a))))throw a;await bd(a)}})(),a,()=>{this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.",{shutdownTimeoutMs:a}),b=!0})}async shutdown(a=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}let bm="[Circular]",bn="[Truncated]",bo="[Unserializable]";function bp(a){let b="";for(let c=0;c<a.length;c++){let d=a.charCodeAt(c);if(d>=55296&&d<=56319){let d=a.charCodeAt(c+1);d>=56320&&d<=57343?(b+=a[c]+a[c+1],c++):b+="�"}else b+=d>=56320&&d<=57343?"�":a[c]}return b}function bq(a,b){if(!b)return a;let c=[];try{c=Object.keys(b)}catch{c=[]}for(let d of c){let c;try{c=b[d]}catch{c=bo}Object.defineProperty(a,d,{value:c,enumerable:!0,writable:!0,configurable:!0})}return a}Date.prototype.getTime,Date.prototype.toISOString,Object.prototype.propertyIsEnumerable;let br=Object.prototype.propertyIsEnumerable;function bs(a,b){try{return bt(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function bt(a,b,c,d){let e=[];for(let f in a)if(br.call(a,f)){if(!f){b?.debug("Dropping an attribute with an empty key");continue}if(e.length>=1e3||c.remainingNodes<=0){b?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{let g=a[f];if(u(g)||r(g))continue;e.push({key:bp(f),value:function a(b,c,d,e){if(d.remainingNodes<=0)return{stringValue:bn};if(d.remainingNodes--,"[object Boolean]"===o.call(b))return{boolValue:b};if("bigint"==typeof b){let a,d;return a=b.toString(),b>=(d=BigInt("9223372036854775808"))||b<-d?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}if("number"==typeof b){if(!Number.isFinite(b))return{stringValue:String(b)};if(Number.isInteger(b)){if(Number.isSafeInteger(b))return{intValue:String(b)};if("u"<typeof BigInt)return{stringValue:String(b)};let a=BigInt(b).toString();return b>=0x8000000000000000||b<-0x8000000000000000?(c?.debug(`Attribute ${a} is outside the int64 range; encoding it as a string`),{stringValue:a}):{intValue:a}}return{doubleValue:b}}if("string"==typeof b)return{stringValue:bp(b)};if("function"==typeof b)return{stringValue:"[Function]"};if("symbol"==typeof b)return{stringValue:String(b)};if("object"==typeof b&&null!==b){if(d.ancestors.has(b))return{stringValue:bm};if(e>=20)return{stringValue:bn};if(b instanceof Date){let a=Number.isFinite(b.getTime())?b.toISOString():String(b);return{stringValue:"string"==typeof a?bp(a):String(a)}}d.ancestors.add(b);try{try{let f=b.toJSON;if("function"==typeof f)return a(f.call(b),c,d,e+1)}catch{}if(p(b))return{arrayValue:{values:function(b,c,d,e){let f=[],g=Math.min(b.length,1e3),h=0;for(;h<g&&d.remainingNodes>0;h++)try{let g=h in b?b[h]:void 0;if(v(g))continue;f.push(a(g,c,d,e))}catch{f.push({stringValue:bo})}return b.length>h&&f.push({stringValue:bn}),f}(b,c,d,e+1)}};return{kvlistValue:{values:bt(b,c,d,e+1)}}}finally{d.ancestors.delete(b)}}return{stringValue:bp(String(b))}}(g,b,c,d)})}catch{e.push({key:bp(f),value:{stringValue:bo}})}}return e}function bu(a,b,c){return{...bq({},a.resourceAttributes),"service.name":a.serviceName||"unknown_service",...a.environment&&{"deployment.environment":a.environment},...a.serviceVersion&&{"service.version":a.serviceVersion},"telemetry.sdk.name":b,"telemetry.sdk.version":c}}let bv=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function bw(a,b){let c=bq({},a),d={};for(let a of bv)Object.prototype.hasOwnProperty.call(c,a)&&(d[a]=c[a],delete c[a]);return[...bs(c,b),...bs(d,b)]}let bx={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"};class by{constructor(a){this._onFire=a,this._firesAt=0}get pending(){return!!this._timer}arm(a){this.clear(),this._firesAt=Date.now()+a,this._timer=P(()=>{this._timer=void 0,this._onFire()},a)}armNoEarlierThan(a){this._timer&&Date.now()+a<=this._firesAt||this.arm(a)}clear(){this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}function bz(){return .75+.25*Math.random()*2}function bA(a,b,c,d){let e=Math.min(Math.max(0,b-1),6),f=a*2**e;return Math.round((void 0===d?f:Math.min(f,Math.max(d,a)))*c)}let bB=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function bC(a){return String(a)+"000000"}function bD(a,b,c,d){let e="";return d&&(e=Object.keys(d).sort().map(a=>`${JSON.stringify(a)}:${JSON.stringify(d[a])}`).join(",")),`${a}\u0000${b}\u0000${c??""}\u0000${e}`}class bE{constructor(a,b,c){this._instance=a,this._config=b,this._logger=c,this._series=new Map,this._flushTimer=new by(()=>this.flush().catch(a=>{this._logger.error("Metrics flush failed:",a)})),this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._retryAfter=new ba,this._consecutiveFlushFailures=0,this._flushJitter=1,this._generation=0}count(a,b=1,c){this._capture({name:a,type:"count",value:b,unit:c?.unit,attributes:c?.attributes})}gauge(a,b,c){this._capture({name:a,type:"gauge",value:b,unit:c?.unit,attributes:c?.attributes})}histogram(a,b,c){this._capture({name:a,type:"histogram",value:b,unit:c?.unit,attributes:c?.attributes})}flush(){let a=this._flushPromise,b=(async()=>{a&&await a.catch(()=>{}),await this._doFlush()})().finally(()=>{this._flushPromise===b&&(this._flushPromise=null)});return this._flushPromise=b,b}drainWindow(){if(0===this._series.size)return null;let a=this._series;return this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set,this._buildPayload(a)}reset(){this._generation++,this._retryAfter.reset(),this._consecutiveFlushFailures=0,this._flushJitter=1,this._flushTimer.clear(),this._series=new Map,this._flushPromise=null,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set}_capture(a){let b,c;if(this._instance.isDisabled||this._instance.optedOut)return;let d=this._runBeforeSend(a);if(null===d)return;if(!d.name||"string"!=typeof d.name)return void this._logger.warn("Dropping metric with empty name");if("number"!=typeof d.value||!Number.isFinite(d.value))return void this._logger.warn(`Dropping metric '${d.name}': value must be a finite number`);if("count"===d.type&&d.value<0)return void this._logger.warn(`Dropping count '${d.name}': counters are monotonic, value must be >= 0`);try{b=d.attributes?{...d.attributes}:void 0,c=bD(d.type,d.name,d.unit,b)}catch(a){this._logger.warn(`Dropping metric '${d.name}': attributes could not be serialized`,a);return}let e=this._series.get(c);if(!e){if(!this._admitNewSeries())return;e={name:d.name,type:d.type,unit:d.unit,attributes:b,windowStartMs:Date.now()},this._series.set(c,e)}let f=this._typeByName.get(d.name);void 0===f?this._typeByName.set(d.name,d.type):f===d.type||this._typeCollisionWarned.has(d.name)||(this._typeCollisionWarned.add(d.name),this._logger.warn(`Metric name '${d.name}' is already used as a ${f}; recording it as a ${d.type} too will blend both series in charts. Use a distinct name.`)),this._fold(e,d.value),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(a,b){switch(a.type){case"count":a.total=(a.total??0)+b;break;case"gauge":a.last=b;break;case"histogram":{a.hist||(a.hist={count:0,sum:0,min:b,max:b,bucketCounts:Array(bB.length+1).fill(0)});let c=a.hist;c.count+=1,c.sum+=b,c.min=Math.min(c.min,b),c.max=Math.max(c.max,b),c.bucketCounts[function(a,b){for(let c=0;c<b.length;c++)if(a<=b[c])return c;return b.length}(b,bB)]+=1}}}_runBeforeSend(a){let b=this._config.beforeSend;if(!b)return a;let c=p(b)?b:[b],d=a;for(let a of c)try{let b=a(d);if(!b)return this._logger.info("Metric was rejected in beforeSend function"),null;d=b}catch(a){return this._logger.error("Error in beforeSend function for metric:",a),null}return d}_armFlushTimer(){this._flushTimer.pending||this._flushTimer.arm(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bA(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}async _doFlush(){if(this._flushTimer.clear(),0===this._series.size)return;let a=this._series;this._series=new Map,this._seriesCapWarned=!1,this._typeByName=new Map,this._typeCollisionWarned=new Set;let b=this._generation,c=await this._instance._sendMetricsBatch(this._buildPayload(a));if(b===this._generation)switch(this._retryAfter.record(c),"retry-later"===c.kind?(this._consecutiveFlushFailures++,this._flushJitter=bz()):(this._consecutiveFlushFailures=0,this._flushJitter=1),this._flushTimer.pending&&this._flushTimer.arm(this._nextFlushDelay()),c.kind){case"ok":return;case"retry-later":this._mergeWindowBack(a),this._flushTimer.armNoEarlierThan(this._nextFlushDelay());return;case"too-large":this._logger.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":this._logger.error("Failed to send metrics batch:",c.error);return}}_buildPayload(a){var b,c,d,e;return b=this._buildMetrics(a),c=bu(this._config,this._instance.getLibraryId(),this._instance.getLibraryVersion()),d=this._instance.getLibraryId(),e=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:bw(c)},scopeMetrics:[{scope:{name:d,version:e},metrics:b}]}]}}_buildMetrics(a){let b=bC(Date.now()),c=new Map;for(let d of a.values()){let a=bD(d.type,d.name,d.unit,void 0),e=c.get(a);e||(e={name:d.name,...d.unit&&{unit:d.unit}},"count"===d.type?e.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:"gauge"===d.type?e.gauge={dataPoints:[]}:e.histogram={aggregationTemporality:1,dataPoints:[]},c.set(a,e));let f=bs(d.attributes??{},this._logger),g=bC(d.windowStartMs);if("count"===d.type){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,asDouble:d.total??0};e.sum.dataPoints.push(a)}else if("gauge"===d.type){let a={attributes:f,timeUnixNano:b,asDouble:d.last??0};e.gauge.dataPoints.push(a)}else if(d.hist){let a={attributes:f,startTimeUnixNano:g,timeUnixNano:b,count:d.hist.count,sum:d.hist.sum,min:d.hist.min,max:d.hist.max,bucketCounts:d.hist.bucketCounts,explicitBounds:bB};e.histogram.dataPoints.push(a)}}return Array.from(c.values())}_mergeWindowBack(a){for(let[b,c]of a){let a=this._series.get(b);if(!a){this._admitNewSeries()&&this._series.set(b,c);continue}switch(a.windowStartMs=Math.min(a.windowStartMs,c.windowStartMs),a.type){case"count":a.total=(a.total??0)+(c.total??0);break;case"gauge":break;case"histogram":if(c.hist)if(a.hist){a.hist.count+=c.hist.count,a.hist.sum+=c.hist.sum,a.hist.min=Math.min(a.hist.min,c.hist.min),a.hist.max=Math.max(a.hist.max,c.hist.max);for(let b=0;b<a.hist.bucketCounts.length;b++)a.hist.bucketCounts[b]+=c.hist.bucketCounts[b]}else a.hist=c.hist}}}}let bF="0".repeat(32),bG="0".repeat(16),bH=/^[0-9a-f]+$/;function bI(a){let b=function(a){let b="";for(let c=0;c<a.length;c++)b+=a[c].toString(16).padStart(2,"0");return b}(function(a){let b=new Uint8Array(a),c=globalThis.crypto;if(c&&"function"==typeof c.getRandomValues)try{return c.getRandomValues(b),b}catch{}for(let c=0;c<a;c++)b[c]=Math.floor(256*Math.random());return b}(a));return/[^0]/.test(b)?b:b.slice(0,-1)+"1"}function bJ(a,b,c){return"string"==typeof a&&a.length===b&&a!==c&&bH.test(a)}let bK=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})(-.*)?$/;function bL(a){if("string"!=typeof a)return;let b=bK.exec(a.trim());if(!b)return;let[,c,d,e,f,g]=b;if("ff"!==c&&("00"!==c||!g)&&bJ(d,32,bF)&&bJ(e,16,bG))return{version:c,traceId:d,spanId:e,flags:f}}function bM(a){return Array.isArray(a)&&1===a.length?a[0]:a}function bN(a){if("string"!=typeof a)return;let b=a.trim();if(!b||/[^\x20-\x7e\t]/.test(b))return;let c=b.split(",");if(!(c.length>32)){for(let a of c)if(a.trim()&&!a.includes("="))return;return b.length<=512?b:function(a){let b=[...a],c=()=>b.reduce((a,b)=>a+b.length,0)+b.length-1;for(let a=b.length-1;a>=0&&c()>512;a--)b[a].length>128&&b.splice(a,1);for(;b.length&&c()>512;)b.pop();return b.length?b.join(","):void 0}(c)}}let bO="unknown";function bP(a,b,c,d){return"string"==typeof a&&a.trim()?a.length>c?a.slice(0,c):a:(d?.debug(`${b} must be a non-empty string; using "${bO}"`),bO)}function bQ(a){if(null==a)return;let b=a;if(a instanceof Date)try{b=a.getTime()}catch{return}if("number"==typeof b&&Number.isFinite(b)&&!(b<0)&&!(b>0x8637bd05af6))return b}function bR(a,b,c,d){let e=bQ(a);return void 0===e?(void 0!==a&&d?.debug(`Span ${c} is out of range or not a valid time; using the derived time`),b):e}function bS(){let a=globalThis.performance;return"function"==typeof a?.now?a.now():void 0}class bT{constructor(a,b,c){for(const d of(this._onEnd=b,this._logger=c,this._events=[],this._ended=!1,this._userAttributeCount=0,this._userEventCount=0,this._droppedAttributes=0,this._droppedEvents=0,this._traceId=a.traceId,this._spanId=a.spanId,this._parentSpanId=a.parentSpanId,this._traceState=a.traceState,this._traceFlags=a.traceFlags??"01",this._parentIsRemote=a.parentIsRemote??!1,this._name=a.name,this._kind=a.kind,this._autoKeys=new Set(a.autoAttributeKeys),this._maxAttributes=a.maxAttributes,this._maxEvents=a.maxEvents,this._maxAttributesPerEvent=a.maxAttributesPerEvent,this._maxAttributeValueLength=a.maxAttributeValueLength,this._attributes=Object.create(null),Object.keys(a.attributes)))this._writeAttribute(d,a.attributes[d]);this._startMono=a.backdated?void 0:bS(),this._startTime=a.clockAnchor&&void 0!==this._startMono?a.clockAnchor.wall+(this._startMono-a.clockAnchor.mono):a.startTime,void 0!==this._startMono&&(this._clockAnchor=a.clockAnchor??{wall:this._startTime,mono:this._startMono})}_now(){if(void 0!==this._startMono){let a=bS();if(void 0!==a)return this._startTime+Math.max(0,a-this._startMono)}return Date.now()}_mutable(a){return!this._ended||(this._logger?.debug(`Ignoring ${a} on a span that has already ended`),!1)}_writeAttribute(a,b){if(v(b)){a in this._attributes&&!this._autoKeys.has(a)&&this._userAttributeCount--,delete this._attributes[a];return}if(!this._autoKeys.has(a)&&!(a in this._attributes)){if(this._userAttributeCount>=this._maxAttributes)return void this._droppedAttributes++;this._userAttributeCount++}this._attributes[a]=b0(b,this._maxAttributeValueLength)}setAttribute(a,b){return this._mutable("setAttribute")&&this._writeAttribute(a,b),this}setAttributes(a){if(this._mutable("setAttributes")){let b=bq({},a);for(let a of Object.keys(b))this._writeAttribute(a,b[a])}return this}addEvent(a,b,c){if(this._mutable("addEvent")){if(this._userEventCount>=this._maxEvents)return this._droppedEvents++,this;this._userEventCount++;let d=b&&b1(b,this._maxAttributesPerEvent,this._maxAttributeValueLength);this._events.push({name:bP(a,"Span event name",this._maxAttributeValueLength,this._logger),timestamp:bR(c,this._now(),"event timestamp",this._logger),...d&&{attributes:d.attributes,...d.dropped&&{droppedAttributesCount:d.dropped}}})}return this}setStatus(a,b){if(this._mutable("setStatus")){if("ok"!==a&&"error"!==a)return this._logger?.debug(`Ignoring unknown span status "${String(a)}"; expected "ok" or "error"`),this;this._status={code:a,...b&&{message:b_(b,this._maxAttributeValueLength)}}}return this}get statusIsExplicitlyOk(){return this._status?.code==="ok"}recordException(a){if(!this._mutable("recordException"))return this;let{type:b,message:c,stack:d}=b3(a);return this.addEvent(bU,{"exception.type":b,"exception.message":c,...d&&{"exception.stacktrace":d}}),this.setStatus("error",c)}updateName(a){return this._mutable("updateName")&&(this._name=bP(a,"Span name",this._maxAttributeValueLength,this._logger)),this}traceparent(){return function(a,b,c="01"){return`00-${a}-${b}-${c}`}(this._traceId,this._spanId,this._traceFlags)}tracestate(){return this._traceState??null}childContext(){return{traceId:this._traceId,parentSpanId:this._spanId,traceState:this._traceState,traceFlags:this._traceFlags,clockAnchor:this._clockAnchor}}end(a){var b;if(this._ended)return void this._logger?.debug("Ignoring end() on a span that has already ended");this._ended=!0;let c=bR(a,this._now(),"end time",this._logger);this._onEnd({traceId:this._traceId,spanId:this._spanId,...this._parentSpanId&&{parentSpanId:this._parentSpanId},...this._traceState&&{traceState:this._traceState},traceFlags:this._traceFlags,parentIsRemote:this._parentIsRemote,name:this._name,kind:this._kind,...this._status&&{status:this._status},attributes:{...this._attributes},events:this._events,startTime:this._startTime,endTime:c<(b=this._startTime)?b:c,...this._droppedAttributes&&{droppedAttributesCount:this._droppedAttributes},...this._droppedEvents&&{droppedEventsCount:this._droppedEvents}},this._autoKeys)}}let bU="exception";function bV(a){return"number"!=typeof a||!Number.isFinite(a)||a<=0?0:Math.min(Math.floor(a),0xffffffff)}class bW{setAttribute(){return this}setAttributes(){return this}addEvent(){return this}setStatus(){return this}recordException(){return this}updateName(){return this}traceparent(){return null}tracestate(){return null}end(){}}let bX=new bW;class bY extends bW{constructor(a,b){super(),this._traceparent=a,this._tracestate=b}traceparent(){return this._traceparent}tracestate(){return this._tracestate??null}}function bZ(a,b){var c;let d=bM(a?.parent)??b,e=bL(c="string"==typeof d||null==d?d:b$(d,"traceparent"))&&c.trim();return e?new bY(e,bN("string"==typeof d||null==d?a?.tracestate:b$(d,"tracestate"))):bX}function b$(a,b){try{let c=a[b];return"function"==typeof c?c.call(a):void 0}catch{return}}function b_(a,b){return a.length>b?a.slice(0,b):a}function b0(a,b){return function a(b,c,d,e){if(null===b||"object"!=typeof b)return v(b)||d.remainingNodes<=0?b:(d.remainingNodes--,"string"==typeof b?b_(b,c):b);if(d.ancestors.has(b))return bm;if(d.remainingNodes<=0||e>=20)return b;d.remainingNodes--,d.ancestors.add(b);try{if(b instanceof Date)return b;let f=function(a){try{let b=a.toJSON;if("function"==typeof b)return{selfDescribed:!0,value:b.call(a)}}catch{}return{selfDescribed:!1}}(b);if(f.selfDescribed)return v(f.value)?String(f.value):a(f.value,c,d,e+1);if(p(b)){let f=Math.min(b.length,1e3),g=[];for(let h=0;h<f;h++)try{g.push(a(b[h],c,d,e+1))}catch{g.push(bo)}return b.length>f&&(g.length=b.length),g}let g={},h=0;for(let f of Object.keys(b)){let i;if(h>=1e3)break;try{i=a(b[f],c,d,e+1)}catch{i=bo}f&&!v(i)&&h++,Object.defineProperty(g,f,{value:i,enumerable:!0,writable:!0,configurable:!0})}return g}catch{return b}finally{d.ancestors.delete(b)}}(a,b,{ancestors:new WeakSet,remainingNodes:1e4},0)}function b1(a,b,c){let d;try{d=Object.keys(a)}catch{return{attributes:{},dropped:0}}let e={},f=0,g=0;for(let h of d){let d;if(f>=b){g++;continue}try{d=b0(a[h],c)}catch{d=bo}v(d)||(f++,Object.defineProperty(e,h,{value:d,enumerable:!0,writable:!0,configurable:!0}))}return{attributes:e,dropped:g}}function b2(a,b,c){return b===bX?c(b):a.with(b,()=>c(b))}function b3(a){try{let b=function(a){try{let b=a.stack;return"string"==typeof b&&b?{stack:b}:{}}catch{return{}}}(a);if(z(a))return{type:a.name||"Error",message:a.message||"",...b};if("string"==typeof a)return{type:"string",message:a};if(a&&"object"==typeof a&&"string"==typeof a.message)return{type:"string"==typeof a.name?a.name:"Object",message:a.message,...b};return{type:typeof a,message:String(a)}}catch{return{type:typeof a,message:""}}}let b4={internal:1,server:2,client:3,producer:4,consumer:5},b5={ok:1,error:2};function b6(a){if("string"==typeof a)return bp(a);try{return bp(String(a))}catch{return bo}}function b7(a){let b=Math.floor(a),c=Math.round((a-b)*1e6);return c>=1e6&&(b+=1,c=0),String(b)+String(c).padStart(6,"0")}function b8(){return bS()??Date.now()}function b9(a){try{return a instanceof bT}catch{return!1}}function ca(a,b){let c,d=(c=bL(a))&&{traceId:c.traceId,spanId:c.spanId,flags:1&parseInt(c.flags,16)?"01":"00"};if(d)return{traceId:d.traceId,parentSpanId:d.spanId,traceState:bN(b),traceFlags:d.flags,isRemote:!0}}function cb(a,b,c){a[b]!==c&&(a[b]=c)}class cc{constructor(a,b,c,d,e,f){this._instance=a,this._config=b,this._logger=c,this._getContext=d,this._contextManager=e,this._onSpanQueued=f,this._queue=[],this._flushTimer=new by(()=>this._flushInBackground()),this._flushPromise=null,this._droppedSinceWarning=0,this._lastDropWarningAt=0,this._dropReasons=new Set,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter=new ba,this._headBatchFailures=0,this._headBatchSize=0,this._headBatchChargeableAt=0,this._generation=0,this._liveSpans=new Map,this._maxExportBatchSize=b.maxExportBatchSize}startSpan(a,b){var c,d;let e;if(this._instance.isDisabled||this._instance.optedOut)return bZ(b,this._contextManager.active());let f=bM(b?.parent);if(f&&"string"!=typeof f&&!b9(f)){if(function(a){try{return"function"==typeof a.traceparent}catch{return!1}}(f))return this._logger.debug("Span parent is not a span from this SDK; returning an inert span"),bZ(b,this._contextManager.active());this._logger.debug("Ignoring an unusable span parent")}let g=this._resolveParent(f,b);if(this._liveSpans.size>=this._config.maxLiveSpans&&this._evictAgedSpans(),this._liveSpans.size>=this._config.maxLiveSpans)return this._recordDrop(1,`the live-span limit (${this._config.maxLiveSpans}) was reached — spans are being started and never ended`),bZ(b,this._contextManager.active());let h=Date.now(),i=(c=b?.startTime,d=this._logger,void 0===(e=bQ(c))?(void 0!==c&&d?.debug("Span startTime is out of range or not a valid time; using the current time"),h):(h-e>864e5?d?.debug("Span startTime is more than 24 hours in the past; the server will clamp it to receive time and keep the original in $originalTimestamp"):e>h&&d?.debug("Span startTime is in the future; the span may export with a zero duration"),e)),j=bI(8);this._liveSpans.set(j,b8());let k=this._autoContextAttributes();return new bT({traceId:g?.traceId??bI(16),spanId:j,parentSpanId:g?.parentSpanId,traceState:g?.traceState,traceFlags:g?.traceFlags,parentIsRemote:g?.isRemote,name:bP(a,"Span name",this._config.maxAttributeValueLength,this._logger),kind:b?.kind??"internal",attributes:bq({...k},b?.attributes),autoAttributeKeys:Object.keys(k),maxAttributes:this._config.maxAttributesPerSpan,maxEvents:this._config.maxEventsPerSpan,maxAttributesPerEvent:this._config.maxAttributesPerEvent,maxAttributeValueLength:this._config.maxAttributeValueLength,startTime:i,backdated:i!==h,clockAnchor:void 0===bQ(b?.startTime)?g?.clockAnchor:void 0},(a,b)=>this._onSpanEnd(a,b),this._logger)}withSpan(a,b,c){let d=this.startSpan(a,"function"==typeof b?void 0:b);try{let a=b2(this._contextManager,d,"function"==typeof b?b:c);if(a&&"function"==typeof a.then)return a.then(a=>(d.end(),a),a=>{throw this._recordCallbackError(d,a),d.end(),a});return d.end(),a}catch(a){throw this._recordCallbackError(d,a),d.end(),a}}getActiveSpan(){return this._contextManager.active()??null}get throttled(){return this._retryAfter.isOpen()}async flush(){for(;;){if(!this._queue.length)return;let a=this._flushPromise;if(!await (a??this._startFlush()))return}}_startFlush(){this._flushTimer.clear();let a=this._generation,b=Promise.resolve().then(()=>a===this._generation?this._flushInner():0).finally(()=>{this._flushPromise===b&&(this._flushPromise=null),this._armFlushTimerIfQueuedNoEarlierThan()});return this._flushPromise=b,b}reset(){this._flushTimer.clear(),this._queue.length&&this._logger.critical(`Discarding ${this._queue.length} span(s) that were still queued when tracing was shut down. Raise the shutdown timeout or flush earlier if they matter.`),this._queue=[],this._liveSpans.clear(),this._flushPromise=null,this._generation++,this._maxExportBatchSize=this._config.maxExportBatchSize,this._droppedSinceWarning=0,this._dropReasons.clear(),this._lastDropWarningAt=0,this._consecutiveFlushFailures=0,this._flushJitter=1,this._retryAfter.reset(),this._resetHeadBatchBudget()}_resetHeadBatchBudget(){this._headBatchFailures=0,this._headBatchChargeableAt=0}_resolveParent(a,b){if("string"==typeof a){let c=ca(a,b?.tracestate);return c||this._logger.debug("Ignoring malformed traceparent; starting a new trace"),c}if(b9(a))return a.childContext();let c=this._contextManager.active();return b9(c)?c.childContext():c instanceof bY?ca(c.traceparent(),c.tracestate()??void 0):void 0}_autoContextAttributes(){let a;try{a=this._getContext()}catch(a){return this._logger.debug("Failed to read tracing context; span will carry no PostHog attributes",a),{}}let b={};return a.distinctId&&(b.posthogDistinctId=a.distinctId),a.sessionId&&(b.sessionId=a.sessionId),a.currentUrl&&(b["url.full"]=a.currentUrl),a.screenName&&(b["screen.name"]=a.screenName),a.appState&&(b["app.state"]=a.appState),b}_recordCallbackError(a,b){if(!(a instanceof bT))return;let{type:c,message:d,stack:e}=b3(b);a.addEvent("exception",{"exception.type":c,"exception.message":d,...e&&{"exception.stacktrace":e}}),a.statusIsExplicitlyOk||a.setStatus("error",d)}_evictAgedSpans(){let a=b8()-this._config.maxSpanAgeMs,b=0;for(let[c,d]of this._liveSpans){if(d>a)break;this._liveSpans.delete(c),b++}b&&this._recordDrop(b,`they were still live after ${this._config.maxSpanAgeMs}ms`)}_onSpanEnd(a,b){if(!this._liveSpans.delete(a.spanId))return;if(this._instance.isDisabled||this._instance.optedOut)return void this._recordDrop(1,"the user has opted out");let c=this._runBeforeSpanSend(a,b);if(c){if(this._reportLimitDrops(c),this._queue.length>=this._config.maxQueueSize)return void this._recordDrop(1,`the queue is full (${this._config.maxQueueSize}) — raise the flush frequency or reduce span volume`);this._queue.push(c);try{this._onSpanQueued?.()}catch(a){this._logger.debug("Span queue notification failed",a)}!(this._queue.length>=this._maxExportBatchSize)||this._consecutiveFlushFailures||this._retryAfter.isOpen()?this._armFlushTimerIfQueued():this._flushInBackground()}}_reportLimitDrops(a){let b=a.droppedAttributesCount??0,c=a.droppedEventsCount??0,d=0;for(let b of a.events)d+=b.droppedAttributesCount??0;(b||c||d)&&this._logger.debug(`Span limits discarded data from "${a.name}": ${b} attributes, ${c} events, ${d} event attributes`)}_runBeforeSpanSend(a,b){if(!this._config.beforeSpanSend.length)return a;let c={traceId:a.traceId,spanId:a.spanId,parentSpanId:a.parentSpanId,traceState:a.traceState},d={startTime:a.startTime,endTime:a.endTime},e={attributes:a.droppedAttributesCount,events:a.droppedEventsCount},f=Object.keys(a.attributes),g={traceFlags:a.traceFlags,parentIsRemote:a.parentIsRemote},h=a.status&&{...a.status},i=a,j=a;try{var k,l,m;for(let a of this._config.beforeSpanSend){let b=a(i);if(!b)return this._recordDrop(1,"beforeSpanSend dropped it"),null;i=this._keepSpanIdentity(b,c)}if(!((k=j={traceId:c.traceId,spanId:c.spanId,parentSpanId:c.parentSpanId,traceState:c.traceState,name:i.name,kind:i.kind,status:i.status,attributes:i.attributes,events:i.events,startTime:i.startTime,endTime:i.endTime,traceFlags:g.traceFlags,parentIsRemote:g.parentIsRemote,droppedAttributesCount:e.attributes,droppedEventsCount:e.events}).attributes&&"object"==typeof k.attributes&&!Array.isArray(k.attributes)&&Array.isArray(k.events)&&void 0!==k.name&&void 0!==k.kind&&void 0!==k.startTime&&void 0!==k.endTime))return this._logger.debug("beforeSpanSend did not return a span record; dropping the span"),this._recordDrop(1,"beforeSpanSend returned an unusable record"),null;j.name=bP(j.name,"Span name",this._config.maxAttributeValueLength,this._logger),j.status&&"ok"!==j.status.code&&"error"!==j.status.code&&(this._logger.debug("beforeSpanSend set an unknown span status; keeping the original"),j.status=h),j.startTime=bQ(j.startTime)??d.startTime,j.endTime=(l=bQ(j.endTime)??d.endTime,m=j.startTime,l<m?m:l);let a=[];for(let b of j.events)try{a.push({...b,name:bP(b.name,"Span event name",this._config.maxAttributeValueLength,this._logger),timestamp:bR(b.timestamp,j.startTime,"event timestamp",this._logger)})}catch{this._logger.debug("beforeSpanSend left an unreadable span event; dropping it")}return j.events=a,!function(a,b,c,d,e,f,g=[]){let h=0,i=0,j={};for(let d of function(a,b){if(!b.length)return Object.keys(a);let c=b.filter(b=>Object.prototype.propertyIsEnumerable.call(a,b)),d=new Set(c);return[...c,...Object.keys(a).filter(a=>!d.has(a))]}(a.attributes,g)){let e=a.attributes[d];if(!v(e)){if(!b.has(d)){if(h>=c){i++;continue}h++}Object.defineProperty(j,d,{value:b0(e,f),enumerable:!0,writable:!0,configurable:!0})}}a.attributes=j,i&&(a.droppedAttributesCount=bV(a.droppedAttributesCount)+i);let k=0,l=0,m=[];for(let b of a.events){if(k>=d){l++;continue}if(k++,b.attributes){let a=b1(b.attributes,e,f);b.attributes=a.attributes,a.dropped&&(b.droppedAttributesCount=bV(b.droppedAttributesCount)+a.dropped)}m.push(b)}a.events=m,l&&(a.droppedEventsCount=bV(a.droppedEventsCount)+l),a.status?.message&&(a.status={...a.status,message:b_(function(a){try{return"string"==typeof a?a:String(a)}catch{return bo}}(a.status.message),f)})}(j,b,this._config.maxAttributesPerSpan,this._config.maxEventsPerSpan,this._config.maxAttributesPerEvent,this._config.maxAttributeValueLength,f),j}catch(a){return this._logger.debug("beforeSpanSend failed; dropping the span rather than exporting it unscrubbed",a),this._recordDrop(1,"beforeSpanSend failed"),null}}_keepSpanIdentity(a,b){(a.traceId!==b.traceId||a.spanId!==b.spanId||a.parentSpanId!==b.parentSpanId)&&this._logger.debug("beforeSpanSend changed a span identity field; keeping the original ids");try{cb(a,"traceId",b.traceId),cb(a,"spanId",b.spanId),cb(a,"parentSpanId",b.parentSpanId),cb(a,"traceState",b.traceState)}catch{try{let c=Object.getOwnPropertyDescriptors(a);for(let a of["traceId","spanId","parentSpanId","traceState"])c[a]={value:b[a],enumerable:!0,writable:!0,configurable:!0};return Object.create(Object.getPrototypeOf(a),c)}catch{;}}return a}_recordDrop(a,b){this._droppedSinceWarning+=a,this._dropReasons.add(b),Date.now()-this._lastDropWarningAt>=this._config.flushIntervalMs&&this._warnAboutDrops()}_warnAboutDrops(){this._droppedSinceWarning&&(this._lastDropWarningAt=Date.now(),this._logger.warn(`Dropping ${this._droppedSinceWarning} span(s): ${[...this._dropReasons].join("; ")}`),this._droppedSinceWarning=0,this._dropReasons.clear())}_encodeBatch(a){let b=[];for(let c of a)try{b.push(function(a,b){var c;let d,e={traceId:a.traceId,spanId:a.spanId,name:b6(a.name),kind:(c=a.kind)&&Object.prototype.hasOwnProperty.call(b4,c)?b4[c]:b4.internal,startTimeUnixNano:b7(a.startTime),endTimeUnixNano:b7(a.endTime),flags:(d=parseInt(a.traceFlags,16),(Number.isFinite(d)?255&d:1)|256|512*!!a.parentIsRemote)};a.parentSpanId&&(e.parentSpanId=a.parentSpanId),a.traceState&&(e.traceState=b6(a.traceState));let f=bs(a.attributes,b);f.length&&(e.attributes=f),a.events.length&&(e.events=a.events.map(a=>(function(a,b){let c={name:b6(a.name),timeUnixNano:b7(a.timestamp)};if(a.attributes){let d=bs(a.attributes,b);d.length&&(c.attributes=d)}let d=bV(a.droppedAttributesCount);return d&&(c.droppedAttributesCount=d),c})(a,b)));let g=bV(a.droppedAttributesCount);g&&(e.droppedAttributesCount=g);let h=bV(a.droppedEventsCount);return h&&(e.droppedEventsCount=h),a.status&&(e.status={code:b5[a.status.code],...a.status.message&&{message:b6(a.status.message)}}),e}(c,this._logger))}catch(a){this._logger.debug("Failed to encode a span; dropping it",a),this._recordDrop(1,"its attributes could not be encoded")}return b}_discardQueueIfConsentWithdrawn(){if(!this._instance.isDisabled&&!this._instance.optedOut)return 0;let a=this._queue.length;return this._queue=[],this._resetHeadBatchBudget(),this._recordDrop(a,"the user has opted out"),this._warnAboutDrops(),a}async _flushInner(){var a,b;if(!this._queue.length)return 0;let c=this._discardQueueIfConsentWithdrawn();if(c)return c;let d=function(a,b){for(let c of Object.keys(a))a[c]=b0(a[c],b);return a}((a=this._config,bu(a,this._instance.getLibraryId(),this._instance.getLibraryVersion())),this._config.maxAttributeValueLength),e=this._instance.getLibraryId(),f=this._instance.getLibraryVersion(),g=this._queue.length,h=0,i=1/0,j=this._generation;try{for(;g>0&&this._queue.length>0;){let a=this._discardQueueIfConsentWithdrawn();if(a)return h+a;let c=this._headBatchFailures>0?Math.min(this._maxExportBatchSize,this._headBatchSize):this._maxExportBatchSize,k=Math.max(1,Math.min(c,i,g,this._queue.length)),l=this._queue.slice(0,k),m=this._encodeBatch(l);if(!m.length){this._queue.splice(0,k),g-=k,h+=k,this._resetHeadBatchBudget();continue}let n=b8()>=this._headBatchChargeableAt&&!this._retryAfter.isOpen(),o=await this._instance._sendTracesBatch((b=this._logger,{resourceSpans:[{resource:{attributes:bw(d,b)},scopeSpans:[{scope:{name:e,version:f},spans:m}]}]}));if(j!==this._generation)break;if(this._retryAfter.record(o),"ok"===o.kind){this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._queue.splice(0,k),g-=k,h+=k,this._maxExportBatchSize<this._config.maxExportBatchSize&&this._maxExportBatchSize++;continue}if("too-large"===o.kind){if(1===k){this._queue.splice(0,1),g-=1,h+=1,this._recordDrop(1,"it is too large for the ingestion endpoint"),this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget();continue}let a=Math.max(1,Math.floor(k/2));o.measuredLocally?i=a:this._maxExportBatchSize=a,this._resetHeadBatchBudget(),this._logger.debug(`Batch too large; retrying the same spans in batches of ${a}`);continue}if("retry-later"===o.kind){if(this._consecutiveFlushFailures++,this._flushJitter=bz(),this._headBatchSize=k,n&&(this._headBatchFailures++,this._headBatchChargeableAt=b8()+this._nextFlushDelay()),this._headBatchFailures<8)return this._logger.debug("Span export failed; retrying on the next flush",o.error),h;if(this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint failed 8 times in a row"),this._retryAfter.isOpen())return h;continue}this._logger.debug("Dropping a span batch the ingestion endpoint rejected",o.error),this._queue.splice(0,k),g-=k,h+=k,this._consecutiveFlushFailures=0,this._flushJitter=1,this._resetHeadBatchBudget(),this._recordDrop(k,"the ingestion endpoint rejected the batch")}return h}finally{this._warnAboutDrops()}}_flushInBackground(){this._backgroundFlush||(this._backgroundFlush=this.flush().catch(a=>{this._logger.debug("Background span flush failed",a)}).finally(()=>{this._backgroundFlush=void 0,this._armFlushTimerIfQueuedNoEarlierThan()}))}_armFlushTimerIfQueued(){!this._flushTimer.pending&&this._queue.length&&this._flushTimer.arm(this._nextFlushDelay())}_armFlushTimerIfQueuedNoEarlierThan(){this._queue.length&&this._flushTimer.armNoEarlierThan(this._nextFlushDelay())}_nextFlushDelay(){return Math.max(bA(this._config.flushIntervalMs,this._consecutiveFlushFailures,this._flushJitter,3e4),this._retryAfter.remainingMs())}}var cd=aP,ce=a.i(2157),cf=a.i(12714),cg=a.i(50227),ch=a.i(1457);let ci=new cd.ReduceableCache(25),cj=new cd.ReduceableCache(20);async function ck(a,b=cf.open,c){let d,e={};try{d=process.cwd()}catch{}for(let b=a.length-1;b>=0;b--){var f,g;let c=a[b],h=c?.filename;!(!c||"string"!=typeof h||"number"!=typeof c.lineno||(f=h).startsWith("node:")||f.endsWith(".min.js")||f.endsWith(".min.cjs")||f.endsWith(".min.mjs")||f.startsWith("data:")||void 0!==(g=c).lineno&&g.lineno>1e4||void 0!==g.colno&&g.colno>1e3)&&((0,cg.isAbsolute)(h)||void 0!==d)&&(e[h]||(e[h]=[]),e[h].push(c.lineno))}let h=Object.keys(e);if(0==h.length)return a;let i=[];for(let a of h){let f=co(a,d);if(void 0===f||cj.get(f))continue;let g=e[a];if(!g)continue;g.sort((a,b)=>a-b);let h=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=cp(c),e=[];for(;;){if(b===a.length-1){e.push(d);break}let c=a[b+1];if("number"!=typeof c)break;c<=d[1]?d[1]=c+7:(e.push(d),d=cp(c)),b++}return e}(g);if(h.every(a=>(function(a,b){let c=ci.get(a);if(void 0===c)return!1;for(let a=b[0];a<=b[1];a++)if(void 0===c[a])return!1;return!0})(f,a)))continue;let j=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(ci,f,{});i.push(cm(a,h,j,f,b,c))}return await Promise.all(i).catch(()=>{}),a&&a.length>0&&function(a,b,c){for(let d of a)if(d.filename&&void 0===d.context_line&&"number"==typeof d.lineno){let a=co(d.filename,c),e=void 0===a?void 0:b.get(a);if(void 0===e)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=cq(a);d<a;d++){let a=c[d];if(void 0===a)return void cn(b);b.pre_context.push(a)}if(void 0===c[a])return cn(b);b.context_line=c[a];let d=function(a){return a+7}(a);b.post_context=[];for(let e=a+1;e<=d;e++){let a=c[e];if(void 0===a)break;b.post_context.push(a)}}(d.lineno,d,e)}}(a,ci,d),ci.reduce(),a}async function cl(a,b,c){let d,e=!1;try{d=await b(a,ce.constants.O_RDONLY|ce.constants.O_NONBLOCK);let f=await d.stat();if(!f.isFile())return;if(f.size>0xa00000)return void c?.debug(`Skipping source context for oversized file ${a}: ${f.size} bytes exceeds 10485760`);return e=!0,d}catch{return}finally{d&&!e&&await d.close().catch(()=>{})}}async function cm(a,b,c,d,e,f){let g=await cl(a,e,f);return void 0===g?void cj.set(d,1):new Promise(a=>{let e,f,h=!1;function i(b){h||(h=!0,b?.destroy(),g.close().then(a,a))}try{e=g.createReadStream({autoClose:!1,start:0,end:0x9fffff})}catch{cj.set(d,1),i();return}try{f=(0,ch.createInterface)({input:e})}catch{cj.set(d,1),i(e);return}let j=0,k=0,l=b[0];if(void 0===l)return void i(e);let m=l[0],n=l[1];function o(){cj.set(d,1),f.close(),f.removeAllListeners(),i(e)}e.on("error",o),f.on("error",o),f.on("close",()=>i(e)),f.on("line",a=>{if(!(++j<m)&&(c[j]=function(a,b){let c=a,d=c.length;if(d<=150)return c;b>d&&(b=d);let e=Math.max(b-60,0);e<5&&(e=0);let f=Math.min(e+140,d);return f>d-5&&(f=d),f===d&&(e=Math.max(f-140,0)),c=c.slice(e,f),e>0&&(c=`...${c}`),f<d&&(c+="..."),c}(a,0),j>=n)){if(k===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++k];if(void 0===a){f.close(),f.removeAllListeners();return}m=a[0],n=a[1]}})})}function cn(a){delete a.pre_context,delete a.context_line,delete a.post_context}function co(a,b){return(0,cg.isAbsolute)(a)?JSON.stringify([null,a]):void 0===b?void 0:JSON.stringify([b,a])}function cp(a){return[cq(a),a+7]}function cq(a){return Math.max(1,a-7)}class cr{active(){return this._active}with(a,b){let c=this._active;this._active=a;try{return b()}finally{this._active=c}}}let cs=["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"],ct=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return cs.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})};function cu(a,b){return"number"==typeof a&&Number.isInteger(a)&&a>=1?a:b}let cv=["service.name","service.version","deployment.environment"],cw={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,cw],46539);class cx{constructor(a){this._host=a.host,this._distinctId=a.distinctId,this._groups=a.groups,this._disableGeoip=a.disableGeoip,this._flags=a.flags,this._requestId=a.requestId,this._evaluatedAt=a.evaluatedAt,this._flagDefinitionsLoadedAt=a.flagDefinitionsLoadedAt,this._errorsWhileComputing=a.errorsWhileComputing??!1,this._quotaLimited=a.quotaLimited??!1,this._accessed=a.accessed??new Set,this._isSlice=a.isSlice??!1}isEnabled(a,b={}){let c=this._flags[a];return this._recordAccess(a),c?.enabled??b.defaultValue??!1}getFlag(a){let b=this._flags[a];if(this._recordAccess(a),b)return!!b.enabled&&(b.variant??!0)}getFlagPayload(a){return this._flags[a]?.payload}onlyAccessed(){let a={};for(let b of this._accessed){let c=this._flags[b];c&&(a[b]=c)}return this._cloneWith(a)}only(a){let b={},c=[];for(let d of a){let a=this._flags[d];a?b[d]=a:c.push(d)}return c.length>0&&this._host.logWarning(`FeatureFlagEvaluations.only() was called with flag keys that are not in the evaluation set and will be dropped: ${c.join(", ")}`),this._cloneWith(b)}get keys(){return Object.keys(this._flags)}_getEventProperties(){let a={},b=[];for(let[c,d]of Object.entries(this._flags)){let e=!1!==d.enabled&&(d.variant??!0);a[`$feature/${c}`]=e,d.enabled&&b.push(c)}return b.length>0&&(b.sort(),a.$active_feature_flags=b),a}_cloneWith(a){return new cx({host:this._host,distinctId:this._distinctId,groups:this._groups,disableGeoip:this._disableGeoip,flags:a,requestId:this._requestId,evaluatedAt:this._evaluatedAt,flagDefinitionsLoadedAt:this._flagDefinitionsLoadedAt,errorsWhileComputing:this._errorsWhileComputing,quotaLimited:this._quotaLimited,accessed:new Set(this._accessed),isSlice:!0})}_recordAccess(a){if(this._accessed.add(a),""===this._distinctId||this._isSlice&&!(a in this._flags))return;let b=this._flags[a],c=void 0===b?void 0:!1!==b.enabled&&(b.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:b?.id,$feature_flag_version:b?.version,$feature_flag_reason:b?.reason,locally_evaluated:b?.locallyEvaluated??!1,[`$feature/${a}`]:c,$feature_flag_request_id:this._requestId,$feature_flag_evaluated_at:b?.locallyEvaluated?Date.now():this._evaluatedAt};b?.hasExperiment!==void 0&&(d.$feature_flag_has_experiment=b.hasExperiment),b?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(d.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let e=[];this._errorsWhileComputing&&e.push(cw.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(cw.QUOTA_LIMITED),void 0===b&&e.push(cw.FLAG_MISSING),e.length>0&&(d.$feature_flag_error=e.join(",")),this._host.captureFlagCalledEventIfNeeded({distinctId:this._distinctId,key:a,response:c,groups:this._groups,disableGeoip:this._disableGeoip,properties:d})}}let cy=["is_not","is_set"];class cz extends Error{constructor(a){super(a),this.name=this.constructor.name,Object.setPrototypeOf(this,cz.prototype)}}function cA(a){if("boolean"==typeof a)return!0;if("string"==typeof a){let b=a.toLowerCase();return"true"===b||"false"===b}if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cA(b in a?a[b]:null))return!1;return!0}function cB(a){if("boolean"==typeof a)return a;if("string"==typeof a)return"true"===a.toLowerCase();if(!Array.isArray(a))return!1;for(let b=0;b<a.length;b++)if(!cB(b in a?a[b]:null))return!1;return!0}function cC(a){for(let b=0;b<a.length;b++){let c=a.charCodeAt(b);if(c>=55296&&c<=56319){let c=a.charCodeAt(b+1);if(b+1>=a.length||c<56320||c>57343)throw new cz("Cannot stringify an unpaired surrogate like the flags service");b++}else if(c>=56320&&c<=57343)throw new cz("Cannot stringify an unpaired surrogate like the flags service")}}function cD(a,b=new Set){if(null!==a&&"boolean"!=typeof a){if("string"==typeof a)return void cC(a);if("number"==typeof a){if(!Number.isFinite(a))throw new cz(`Cannot represent non-finite number ${a} like the flags service`);return}if(Array.isArray(a)){if(b.has(a))throw new cz("Cannot represent a circular array during local evaluation");b.add(a);try{for(let c=0;c<a.length;c++)c in a&&cD(a[c],b)}finally{b.delete(a)}return}if("object"==typeof a){let c=Object.getPrototypeOf(a);if(c!==Object.prototype&&null!==c)throw new cz("Cannot represent a non-JSON object like the flags service");if(b.has(a))throw new cz("Cannot represent a circular object during local evaluation");b.add(a);try{for(let c of Object.keys(a))cC(c),cD(a[c],b)}finally{b.delete(a)}return}throw new cz(`Cannot represent ${typeof a} like the flags service`)}}function cE(a,b){let c=0,d=0;for(;c<a.length&&d<b.length;){let e=a.charCodeAt(c),f=b.charCodeAt(d),g=e>=55296&&e<=56319,h=f>=55296&&f<=56319,i=g?a.charCodeAt(c+1):0,j=h?b.charCodeAt(d+1):0,k=g?(e-55296)*1024+i-56320+65536:e,l=h?(f-55296)*1024+j-56320+65536:f;if(k!==l)return k-l;c+=g?2:1,d+=h?2:1}return a.length-b.length}function cF(a){return"string"==typeof a?(cC(a),a):function a(b,c=new Set){if(null===b)return"null";if("string"==typeof b)return cC(b),JSON.stringify(b);if("boolean"==typeof b)return b?"true":"false";if("number"==typeof b){if(!Number.isFinite(b))throw new cz(`Cannot stringify non-finite number ${b} like the flags service`);if(Number.isInteger(b))throw new cz(`Cannot distinguish integer ${b} from an integral JSON float during local evaluation`);return String(b)}if(Array.isArray(b)){if(c.has(b))throw new cz("Cannot stringify a circular array during local evaluation");c.add(b);try{let d=[];for(let e=0;e<b.length;e++)d.push(e in b?a(b[e],c):"null");return`[${d.join(",")}]`}finally{c.delete(b)}}if("object"==typeof b){let d=Object.getPrototypeOf(b);if(d!==Object.prototype&&null!==d)throw new cz("Cannot stringify a non-JSON object like the flags service");if(c.has(b))throw new cz("Cannot stringify a circular object during local evaluation");c.add(b);try{let d=Object.keys(b);return d.forEach(cC),`{${d.sort(cE).map(d=>`${JSON.stringify(d)}:${a(b[d],c)}`).join(",")}}`}finally{c.delete(b)}}throw new cz(`Cannot stringify ${typeof b} like the flags service`)}(a)}function cG(a){try{return new RegExp(a),!0}catch{return!1}}function cH(a){return String(a).replace(/[A-Z]/g,a=>a.toLowerCase())}function cI(a,b,c){if(!/^\d+$/.test(a)||"strict"===c&&a.length>1&&"0"===a[0])throw new cz(`Invalid semver: ${b}`);return parseInt(a,10)}function cJ(a,b="strict"){let c=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!c||c.startsWith("."))throw new cz(`Invalid semver: ${a}`);let d=c.split("."),e=c=>void 0===c||""===c?0:cI(c,a,b);return[e(d[0]),e(d[1]),e(d[2])]}function cK(a,b){for(let c=0;c<3;c++){if(a[c]<b[c])return -1;if(a[c]>b[c])return 1}return 0}function cL(a){if(a instanceof Date)return a;if("string"==typeof a||"number"==typeof a){let b=new Date(a);if(!isNaN(b.valueOf()))return b;throw new cz(`${a} is in an invalid date format`)}throw new cz(`The date provided ${a} must be a string, number, or date object`)}async function cM(a){let b=globalThis.crypto?.subtle;if(!b)throw Error("SubtleCrypto API not available");return Array.from(new Uint8Array(await b.digest("SHA-1",new TextEncoder().encode(a)))).map(a=>a.toString(16).padStart(2,"0")).join("")}async function cN(a,b,c="",d="."){return parseInt((await cM(`${a}${d}${b}${c}`)).slice(0,15),16)/0x1000000000000000}async function cO(a,b){if(null==a||null==a.id||null==a.exclusion_percentage)return;let c=Number(a.exclusion_percentage);if(!Number.isFinite(c))return;let d=Math.min(Math.max(c,0),100);if(!(100!==d&&await cN("holdout",b,"","-")>d/100))return`holdout-${a.id}`}function cP(a){let b=[],c=0;for(let d of a){let a=c+d.rollout_percentage/100;b.push({valueMin:c,valueMax:a,key:d.key}),c=a}return b}async function cQ(a,b,c){let d=await cN(a,b,"variant");return cP(c).find(a=>d>=a.valueMin&&d<a.valueMax)?.key}function cR(a){return"client"===a||"server"===a?a:"all"}class cS extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,cS.prototype)}}class cT extends Error{constructor(a){super(a),function(a,b){a.name=b.name,Error.captureStackTrace(a,b),Object.setPrototypeOf(a,b.prototype)}(this,cT)}}class cU{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollerStopped=!1,this.filteredOutFlagKeys=new Set,this.pollingInterval=a,this.personalApiKey=b,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=d,this.projectApiKey=c,this.host=e,this.poller=void 0,this.fetch=g.fetch||fetch,this.onError=g.onError,this.customHeaders=f,this.onLoad=g.onLoad,this.onMinimalFlagCalledEvents=g.onMinimalFlagCalledEvents,this.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,this.evaluationContexts=g.evaluationContexts,this.loadFeatureFlags()}debug(a=!0){this.debugMode=a}logMsgIfDebug(a){this.debugMode&&a()}withEvaluationSnapshot(a){return a.definitions?a:{...a,evaluationCache:{},definitions:{featureFlagsByKey:this.featureFlagsByKey,groupTypeMapping:this.groupTypeMapping,cohorts:this.cohorts,filteredOutFlagKeys:this.filteredOutFlagKeys,propertyMatchingVersion:this.propertyMatchingVersion}}}createEvaluationContext(a,b={},c={},d={},e={}){return{distinctId:a,groups:b,personProperties:c,groupProperties:d,evaluationCache:e}}async getFeatureFlag(a,b,c={},d={},e={}){let f,g;if(await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return f;if(void 0!==(g=this.featureFlagsByKey[a])){let h=this.createEvaluationContext(b,c,d,e);try{f=(await this.computeFlagAndPayloadLocally(g,h)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${a} -> ${f}`))}catch(b){b instanceof cT||b instanceof cz?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a}: ${b}`))}}return f}async getAllFlagsAndPayloads(a,b){await this.loadFeatureFlags();let c={},d={},e=0==this.featureFlags.length,f=b?b.map(a=>this.featureFlagsByKey[a]).filter(Boolean):this.featureFlags,g=this.withEvaluationSnapshot({...a,definitions:void 0});return await Promise.all(f.map(async a=>{try{let{value:b,payload:e}=await this.computeFlagAndPayloadLocally(a,g,{skipLoadCheck:!0});c[a.key]=b,e&&(d[a.key]=e)}catch(b){b instanceof cT||b instanceof cz?this.logMsgIfDebug(()=>console.debug(`${b.name} when computing flag locally: ${a.key}: ${b.message}`)):b instanceof Error&&this.onError?.(Error(`Error computing flag locally: ${a.key}: ${b}`)),e=!0}})),{response:c,payloads:d,fallbackToFlags:e}}async computeFlagAndPayloadLocally(a,b,c={}){let d,{matchValue:e,skipLoadCheck:f=!1}=c;if(this.loadedSuccessfullyOnce&&(b=this.withEvaluationSnapshot(b)),f||await this.loadFeatureFlags(),!this.loadedSuccessfullyOnce)return{value:!1,payload:null};a=(b=this.withEvaluationSnapshot(b)).definitions.featureFlagsByKey[a.key]??a,d=void 0!==e?e:await this.computeFlagValueLocally(a,b);let g=function(a,b){if(!1===b||null==b||!a)return null;let c=a["boolean"==typeof b?b.toString():b]||null;return null==c?null:a1(c)}(a.filters?.payloads,d);return{value:d,payload:g}}async computeFlagValueLocally(a,b){let{distinctId:c,groups:d,personProperties:e,groupProperties:f}=b;if(!a.active)return!1;if(a.ensure_experience_continuity)throw new cz("Flag has experience continuity enabled");let g=(a.filters||{}).aggregation_group_type_index;if(void 0!=g){let c=b.definitions.groupTypeMapping[String(g)];if(!c)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${g} for feature flag ${a.key}`)),new cz("Flag has unknown group type index");if(!(c in d))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${a.key} without group names passed in`)),!1;"device_id"===a.bucketing_identifier&&(e?.$device_id===void 0||e?.$device_id===null||e?.$device_id==="")&&this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${a.key}`));let h=f[c];return await this.matchFeatureFlagProperties(a,d[c],h,b)}{let d=this.getBucketingValueForFlag(a,c,e);if(void 0===d)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${a.key} without $device_id, falling back to server evaluation`)),new cz(`Can't compute feature flag: ${a.key} without $device_id`);return await this.matchFeatureFlagProperties(a,d,e,b)}}getBucketingValueForFlag(a,b,c){if(a.filters?.aggregation_group_type_index!=void 0)return b;if("device_id"===a.bucketing_identifier){let a=c?.$device_id;if(null==a||""===a)return;return a}return b}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!c.definitions.featureFlagsByKey)throw new cz("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new cz(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new cz(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new cz(`Circular dependency detected for flag '${e}' (empty dependency chain)`);for(let a of f){if(!(a in d)){let b=c.definitions.featureFlagsByKey[a];if(b)if(b.active)try{let e=await this.computeFlagValueLocally(b,c);d[a]=e}catch(b){throw new cz(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else if(c.definitions.filteredOutFlagKeys.has(a))d[a]=!1;else throw new cz(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new cz(`Dependency '${a}' could not be evaluated`)}let g=d[e];return this.flagEvaluatesToExpectedValue(a.value,g)}flagEvaluatesToExpectedValue(a,b){return"boolean"==typeof a?a===b||"string"==typeof b&&""!==b&&!0===a:"string"==typeof a&&b===a}async matchFeatureFlagProperties(a,b,c,d){let e;d=this.withEvaluationSnapshot(d);let f=a.filters||{},g=await cO(f.holdout,b);if(void 0!==g)return g;let h=f.groups||[],i=f.aggregation_group_type_index,j=f.early_exit??!1,{groups:k,groupProperties:l}=d,m=!1;for(let g of h)try{let h=void 0!==g.aggregation_group_type_index?g.aggregation_group_type_index:i,n=c,o=b;if(h!==i&&null!=h){let b=d.definitions.groupTypeMapping[String(h)];if(!b||!(b in k)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${h} not available`));continue}if(!(b in l)){m=!0;continue}n=l[b],o=k[b]}let p=await this.isConditionMatch(a,o,g,n,d);if("match"===p){let b=g.variant,c=f.multivariate?.variants||[];e=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,o)||!0;break}if(j&&"out_of_rollout_bound"===p){if(m)break;return!1}}catch(a){if(a instanceof cT)throw a;if(a instanceof cz)m=!0;else throw a}if(void 0!==e)return e;if(m)throw new cz("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(a,b,c,d,e){let f=(e=this.withEvaluationSnapshot(e)).definitions,g=c.rollout_percentage,h=a=>{this.logMsgIfDebug(()=>console.warn(a))};if((c.properties||[]).length>0){for(let a of c.properties){let b=a.type,c=!1;if("cohort"===b){let b=await cW(a,d,f.cohorts,this.debugMode,a=>this.evaluateFlagDependency(a,d,e),f.propertyMatchingVersion);c="not_in"===a.operator?!b:b}else c="flag"===b?await this.evaluateFlagDependency(a,d,e):cV(a,d,h,f.propertyMatchingVersion);if(!c)return"no_match"}if(void 0==g)return"match"}return void 0!=g&&await cN(a.key,b)>g/100?"out_of_rollout_bound":"match"}async getMatchingVariant(a,b){return cQ(a.key,b,a.filters?.multivariate?.variants||[])}variantLookupTable(a){return cP(a.filters?.multivariate?.variants||[])}filterFlagsByEvaluationContexts(a){if(!this.evaluationContexts||0===this.evaluationContexts.length)return a;let b=new Set(this.evaluationContexts);return a.filter(a=>{let c=a.evaluation_contexts??a.evaluation_tags;return!c||0===c.length||c.some(a=>b.has(a))})}getEvaluationRuntimeForFlag(a){let b=this.featureFlagsByKey[a];return b?cR(b.evaluation_runtime):void 0}getFlagKeysByEvaluationRuntime(a){return this.featureFlags.filter(b=>{var c;return(c=cR(b.evaluation_runtime))===a||"all"===c||"all"===a}).map(a=>a.key)}updateFlagState(a){let b=this.filterFlagsByEvaluationContexts(a.flags);this.featureFlags=b,this.featureFlagsByKey=b.reduce((a,b)=>(a[b.key]=b,a),{});let c=new Set(b.map(a=>a.key));this.filteredOutFlagKeys=new Set(a.flags.filter(a=>!c.has(a.key)).map(a=>a.key)),this.groupTypeMapping=a.group_type_mapping??a.groupTypeMapping??{},this.cohorts=a.cohorts,this.propertyMatchingVersion=a.property_matching_version??a.propertyMatchingVersion,this.loadedSuccessfullyOnce=!0,this.onMinimalFlagCalledEvents?.((a.minimal_flag_called_events??a.minimalFlagCalledEvents)===!0)}warnAboutExperienceContinuityFlags(a){if(this.strictLocalEvaluation)return;let b=a.filter(a=>a.ensure_experience_continuity);b.length>0&&console.warn(`[PostHog] You are using local evaluation but ${b.length} flag(s) have experience continuity enabled: ${b.map(a=>a.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(a){if(!this.cacheProvider)return!1;try{let b=await this.cacheProvider.getFlagDefinitions();if(b)return this.updateFlagState(b),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${a} (${b.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags),!0;return!1}catch(a){return this.onError?.(Error(`Failed to load from cache: ${a}`)),!1}}async loadFeatureFlags(a=!1){if(!this.loadedSuccessfullyOnce||a)return!a&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt?void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period")):(this.loadingPromise||(this.loadingPromise=this._loadFeatureFlags().catch(a=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${a}`))).finally(()=>{this.loadingPromise=void 0})),this.loadingPromise)}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){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 a=!0;if(this.cacheProvider)try{a=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(a){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${a}`))}if(!a&&(await this.loadFromCache("Loaded flags from cache (skipped fetch)")||this.loadedSuccessfullyOnce))return;let b=await this._requestFeatureFlagDefinitions();if(!b)return;switch(b.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=b.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new cS(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.filteredOutFlagKeys=new Set,this.groupTypeMapping={},this.cohorts={},this.propertyMatchingVersion=void 0,this.onMinimalFlagCalledEvents?.(!1);return;case 403:throw this.beginBackoff(),new cS(`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 cS(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let c=await b.json()??{};if(!("flags"in c))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(c)}`));this.flagsEtag=b.headers?.get("ETag")??void 0;let d=c.group_type_mapping||{},e=!0===c.minimal_flag_called_events,f={flags:c.flags??[],group_type_mapping:d,cohorts:c.cohorts||{},minimal_flag_called_events:e,property_matching_version:c.property_matching_version,propertyMatchingVersion:c.property_matching_version,groupTypeMapping:d,minimalFlagCalledEvents:e};if(this.updateFlagState(f),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&a)try{await this.cacheProvider.onFlagDefinitionsReceived(f)}catch(a){this.onError?.(Error(`Failed to store in cache: ${a}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(this.featureFlags);break}default:return}}catch(a){a instanceof cS&&this.onError?.(a)}finally{this.pollerStopped||(this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval()))}}getPersonalApiKeyRequestOptions(a="GET",b){let c={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};return b&&(c["If-None-Match"]=b),{method:a,headers:c}}async _requestFeatureFlagDefinitions(){let a=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,b=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),c=null;if(this.timeout&&"number"==typeof this.timeout){let a=new AbortController;c=P(()=>{a.abort()},this.timeout),b.signal=a.signal}try{let d=this.fetch,e=await d(a,b);if(200!==e.status)return clearTimeout(c),e;return{status:e.status,headers:e.headers,body:e.body,text:async()=>{try{return await e.text()}finally{clearTimeout(c)}},json:async()=>{try{return await e.json()}finally{clearTimeout(c)}}}}catch(a){throw clearTimeout(c),a}}async stopPoller(a=3e4){if(this.pollerStopped=!0,clearTimeout(this.poller),this.poller=void 0,this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await Q(b,a,()=>{throw Error(`Cache shutdown timeout after ${a}ms`)})}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}function cV(a,b,c,d){return function(a,b,c={}){let d=a.key,e=a.value,f=a.operator||"exact",g=c.semverParsingPolicy??"strict";if(Object.prototype.hasOwnProperty.call(b,d)){if("is_not_set"===f)return!1;else if("is_set"===f)return!0}else throw new cz(`Property ${d} not found in propertyValues`);let h=b[d];if(void 0===h)return c.warnFunction?.(`Property ${d} cannot have a value of undefined with the ${f} operator`),"is_not"===f;if(null===h&&!cy.includes(f)&&"exact"!==f&&"is_not"!==f)return c.warnFunction?.(`Property ${d} cannot have a value of null with the ${f} operator`),!1;let i=(a,b)=>{if(2!==c.propertyMatchingVersion&&cA(a)||Array.isArray(a)&&0===a.length)return cD(b),cB(a)===cB(b);if(2===c.propertyMatchingVersion&&"number"==typeof b&&cA(a))return cD(b),!1;if(Array.isArray(a)){let c=cF(b).toLowerCase();return a.some(a=>cF(a).toLowerCase()===c)}return cF(a).toLowerCase()===cF(b).toLowerCase()},j=(a,b,c)=>{if("gt"===c)return a>b;if("gte"===c)return a>=b;if("lt"===c)return a<b;if("lte"===c)return a<=b;throw Error(`Invalid operator: ${c}`)};switch(f){case"exact":return i(e,h);case"is_not":return!i(e,h);case"is_set":return!0;case"icontains":return cH(h).includes(cH(e));case"not_icontains":return!cH(h).includes(cH(e));case"starts_with":return cH(h).startsWith(cH(e));case"not_starts_with":return!cH(h).startsWith(cH(e));case"ends_with":return cH(h).endsWith(cH(e));case"not_ends_with":return!cH(h).endsWith(cH(e));case"regex":return cG(String(e))&&null!==String(h).match(String(e));case"not_regex":return cG(String(e))&&null===String(h).match(String(e));case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:parseFloat(String(e)),b="number"==typeof h?h:null!=h?parseFloat(String(h)):0/0;if(Number.isFinite(a)&&Number.isFinite(b))return j(b,a,f);return j(String(h),String(e),f)}case"is_date_after":case"is_date_before":{if("boolean"==typeof e)throw new cz("Date operations cannot be performed on boolean values");let a=function(a){let b=a.match(/^-?(?<number>[0-9]+)(?<interval>[a-z])$/),c=new Date(new Date().toISOString());if(!b||!b.groups)return null;let d=parseInt(b.groups.number);if(d>=1e4)return null;let e=b.groups.interval;if("h"===e)c.setUTCHours(c.getUTCHours()-d);else if("d"===e)c.setUTCDate(c.getUTCDate()-d);else if("w"===e)c.setUTCDate(c.getUTCDate()-7*d);else if("m"===e)c.setUTCMonth(c.getUTCMonth()-d);else{if("y"!==e)return null;c.setUTCFullYear(c.getUTCFullYear()-d)}return c}(String(e));null==a&&(a=cL(e));let b=cL(h);return"is_date_before"===f?b<a:b>a}case"semver_eq":return 0===cK(cJ(String(h),g),cJ(String(e),g));case"semver_neq":return 0!==cK(cJ(String(h),g),cJ(String(e),g));case"semver_gt":return cK(cJ(String(h),g),cJ(String(e),g))>0;case"semver_gte":return cK(cJ(String(h),g),cJ(String(e),g))>=0;case"semver_lt":return 0>cK(cJ(String(h),g),cJ(String(e),g));case"semver_lte":return 0>=cK(cJ(String(h),g),cJ(String(e),g));case"semver_tilde":{let a,b=cJ(String(h),g),{lower:c,upper:d}={lower:[(a=cJ(String(e),g))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return cK(b,c)>=0&&0>cK(b,d)}case"semver_caret":{let a=cJ(String(h),g),{lower:b,upper:c}=function(a,b){let[c,d,e]=cJ(a,b);return{lower:[c,d,e],upper:c>0?[c+1,0,0]:d>0?[0,d+1,0]:[0,0,e+1]}}(String(e),g);return cK(a,b)>=0&&0>cK(a,c)}case"semver_wildcard":{let a=cJ(String(h),g),{lower:b,upper:c}=function(a,b){let c=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!c)throw new cz(`Invalid wildcard semver: ${a}`);let d=c.split("."),e=c=>{if("legacy-permissive"===b){let a=parseInt(c,10);if(!isNaN(a))return a}else try{return cI(c,a,b)}catch{}throw new cz(`Invalid wildcard semver: ${a}`)},f=e(d[0]);if(1===d.length)return{lower:[f,0,0],upper:[f+1,0,0]};let g=e(d[1]);return{lower:[f,g,0],upper:[f,g+1,0]}}(String(e),g);return cK(a,b)>=0&&0>cK(a,c)}default:throw new cz(`Unknown operator: ${f}`)}}(a,b,{warnFunction:c,propertyMatchingVersion:d})}async function cW(a,b,c,d=!1,e,f){let g=String(a.value);if(!(g in c))throw new cT(`cohort ${g} not found in local cohorts - likely a static cohort that requires server evaluation`);return cX(c[g],b,c,d,e,f)}async function cX(a,b,c,d=!1,e,f){if(!a)return!0;let g=a.type,h=a.values;if(!h||0===h.length)return!0;let i=!1;if("values"in h[0]){for(let a of h)try{let h=await cX(a,b,c,d,e,f);if("AND"===g){if(!h)return!1}else if(h)return!0}catch(b){if(b instanceof cT)throw b;if(b instanceof cz)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),i=!0;else throw b}if(i)throw new cz("Can't match cohort without a given cohort property value");return"AND"===g}for(let a of h)try{let h;if("cohort"===a.type)h=await cW(a,b,c,d,e,f);else if("flag"===a.type){if(!e)throw new cz(`Flag dependency '${a.key||"unknown"}' cannot be evaluated without a flag dependency evaluator`);h=await e(a)}else h=cV(a,b,void 0,f);let i=a.negation||!1;if("AND"===g){if(!h&&!i||h&&i)return!1}else if(h&&!i||!h&&i)return!0}catch(b){if(b instanceof cT)throw b;if(b instanceof cz)d&&console.debug(`Failed to compute property ${a} locally: ${b}`),i=!0;else throw b}if(i)throw new cz("can't match cohort without a given cohort property value");return"AND"===g}let cY=["--unhandled-rejections","--unhandled_rejections"],cZ=new Set(["throw","strict","warn","warn-with-error-code","none"]),c$=[...globalThis.process?.execArgv??[]],c_=globalThis.process?.env?.NODE_OPTIONS;function c0(a){let b;for(let c=0;c<a.length;c++){let d=a[c],e=cY.find(a=>d===a||d.startsWith(`${a}=`));if(!e)continue;let f=d===e?a[++c]:d.slice(e.length+1);cZ.has(f)&&(b=f)}return b}let c1=function(a=c$,b=c_){return c0(a)??c0(function(a){let b=[],c="",d=!1;for(let e=0;e<a.length;e++){let f=a[e];"\\"===f&&d&&e+1<a.length?c+=a[++e]:" "!==f||d?'"'===f?d=!d:c+=f:c&&(b.push(c),c="")}return c&&b.push(c),b}(b??""))??"throw"}();function c2(a,b,c){a(b,{mechanism:{type:"unhandledRejection"===c?"onunhandledrejection":"onuncaughtexception",handled:!1}})}function c3(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),w(a))if(a>c)return d.warn(" cannot be greater than max: "+c+". Using max value instead."),c;else return a<b?(d.warn(" cannot be less than min: "+b+". Using min value instead."),b):a;return d.warn(" must be a number. using max or fallback. max: "+c+", fallback: "+e),c3(e??c,b,c,d)}class c4{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=c3(a.bucketSize,0,100,a._logger),this._refillRate=c3(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=c3(a.refillInterval,0,864e5,a._logger)}_applyRefill(a,b){let c=Math.floor((b-a.lastAccess)/this._refillInterval);if(c>0){let b=c*this._refillRate;a.tokens=Math.min(a.tokens+b,this._bucketSize),a.lastAccess=a.lastAccess+c*this._refillInterval}}consumeRateLimit(a){let b=Date.now(),c=String(a),d=this._buckets[c];return d?this._applyRefill(d,b):(d={tokens:this._bucketSize,lastAccess:b},this._buckets[c]=d),0===d.tokens||(d.tokens--,0===d.tokens&&this._onBucketRateLimited?.(a),0===d.tokens)}stop(){this._buckets={}}}var cd=aP;let c5=class b{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new c4({...function(a={}){return{refillRate:a.exceptionRateLimiterRefillRate??a.__exceptionRateLimiterRefillRate??1,bucketSize:a.exceptionRateLimiterBucketSize??a.__exceptionRateLimiterBucketSize??10}}(b),refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return q(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d,e){let f={...e},g=a.buildFromUnknown(b,c);g.$exception_list=await a.modifyFrames(g.$exception_list);let h=cd.getInjectedReleaseId();return h&&(f.$release_id=h),{event:"$exception",distinctId:d,properties:{...g,...f},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){this.isEnabled()&&(!function(b,c,d=c1){let e=globalThis.process;if(e){let f;if("strict"===d)return e.on("uncaughtExceptionMonitor",(a,c)=>c2(b,a,c));e.on("uncaughtException",(f=!1,Object.assign((d,e)=>{let g=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;c2(b,d,e),f||0!==g||(f=!0,c(d))},{_posthogErrorHandler:!0})))}}(this.onException.bind(this),this.onFatalError.bind(this)),function(a,b=c1){let c=globalThis.process;c&&"throw"!==b&&"strict"!==b&&"warn-with-error-code"!==b&&c.on("unhandledRejection",b=>{a(b,{mechanism:{type:"onunhandledrejection",handled:!1}})})}(this.onException.bind(this)))}onException(a,c){this.client.addPendingPromise((async()=>{if(!b.isPreviouslyCapturedError(a)){let d=await b.buildEventMessage(this.client.getErrorPropertiesBuilder(),a,c),e=d.properties,f=e?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(f)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:f}):this.client._capturePreparedEvent(d,!1)}})())}async onFatalError(a){console.error(a),await this.client.shutdown(2e3),globalThis.process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}};class c6{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let c7="analytics";class c8 extends Error{constructor({requestId:a,drops:b,retryExhausted:c,cause:d}){super(c8.buildMessage(a,b,c,d)),this.name="CaptureV1Error",this.requestId=a,this.drops=b,this.retryExhausted=c,this.cause=d}static buildMessage(a,b,c,d){let e=`Capture V1 batch ${a} did not fully deliver: ${b.length} dropped, ${c.length} undelivered`;return d instanceof Error&&(e+=` (${d.message})`),e}}function c9(a){if("boolean"==typeof a)return a;if("number"==typeof a)return 0!==a;if("string"==typeof a){let b=a.trim().toLowerCase();if("true"===b||"1"===b)return!0;if("false"===b||"0"===b)return!1}}let da=[{property:"$cookieless_mode",optionKey:"cookieless_mode",coerce:c9},{property:"$ignore_sent_at",optionKey:"disable_skew_correction",coerce:c9},{property:"$process_person_profile",optionKey:"process_person_profile",coerce:c9},{property:"$product_tour_id",optionKey:"product_tour_id",coerce:function(a){return"string"==typeof a?a:void 0}}],db=[{property:"$session_id",field:"session_id"},{property:"$window_id",field:"window_id"}];function dc(a,b,c){void 0===c||b in a||(a[b]=c)}function dd(a){var b;let c={..."object"==typeof(b=a.properties)&&null!==b&&!Array.isArray(b)?a.properties:{}},d={};for(let{property:a,optionKey:b,coerce:e}of da)if(a in c){let f=e(c[a]);void 0!==f&&(d[b]=f),delete c[a]}let e={};for(let{property:a,field:b}of db)if(a in c){let d=c[a];"string"==typeof d&&(e[b]=d),delete c[a]}return delete c.$lib,delete c.$lib_version,dc(c,"$set",a.$set),dc(c,"$set_once",a.$set_once),{event:String(a.event??""),uuid:String(a.uuid??""),distinct_id:String(a.distinct_id??""),timestamp:function(a){if("string"==typeof a){let b=new Date(a);if(Number.isNaN(b.getTime()))return new Date().toISOString();let c=b.toISOString(),d=a.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];return d&&d.length>3?c.replace(/\.\d{3}Z$/,`.${d}Z`):c}if(a instanceof Date)return Number.isNaN(a.getTime())?new Date().toISOString():a.toISOString();let b=null==a?new Date:new Date(a);return Number.isNaN(b.getTime())?new Date().toISOString():b.toISOString()}(a.timestamp),...e,options:d,properties:c}}let de=new Set([408,500,502,503,504]);class df{constructor(a,b){this.config=a,this.maxBackoffMs=a.maxBackoffMs??3e4,this.fetchFn=b.fetch,this.onError=b.onError,this.now=b.now??Date.now,this.sleep=b.sleep??(a=>new Promise(b=>P(b,a))),this.generateRequestId=b.generateRequestId??aU,this.compress=b.compress??a7}async sendV1Batch(a){if(0===a.length)return;let b=this.generateRequestId(),c=new Date(this.now()).toISOString(),{batch:d}=function(a,{createdAt:b,historicalMigration:c}){let d={created_at:b,batch:a.map(dd)};return c&&(d.historical_migration=!0),d}(a,{createdAt:c,historicalMigration:this.config.historicalMigration}),e=`${this.config.host}/i/v1/analytics/events`,f=[],g=d,h=Math.max(1,this.config.maxAttempts);for(let a=1;a<=h;a++){let d,i,j=a===h,k=l({created_at:c,...this.config.historicalMigration?{historical_migration:!0}:{},batch:g});try{let{response:c,signal:h}=d=await this.sendOnce(e,k,a,b),{status:l}=c;if(l<200||l>=300)if(!j&&de.has(l)){let b=this.parseRetryAfter(c);await d.waitFor(d.cancelBody()).catch(()=>{}),i=this.backoffDelay(a,b)}else{let a=await this.buildHttpError(c,l,d.waitFor);return this.surfaceBatchFailure(b,f,g,a)}else{let e;try{e=await d.waitFor(this.parseResponse(c))}catch(a){if(h.aborted)throw a;return this.surfaceBatchFailure(b,f,g,Error(`Capture V1 returned an unparseable ${l} response body`))}let k=this.classify(g,e,f);if(0===k.length)return this.surfacePartialDrops(b,f);if(j)return void this.onError(new c8({requestId:b,drops:f,retryExhausted:k.map(a=>a.uuid)}));g=k;let m=this.parseRetryAfter(c);i=this.backoffDelay(a,m)}}catch(c){if(d&&!d.signal.aborted)throw c;if(j)return this.surfaceBatchFailure(b,f,g,c);i=this.backoffDelay(a)}finally{d?.cleanup()}void 0!==i&&await this.sleep(i)}}async sendOnce(a,b,c,d){let e,f=this.buildHeaders(c,d),g=b;if(this.config.compressionEnabled){let a=await this.compress(b,this.config.isDebug);null!==a&&(g=a,f["Content-Encoding"]="gzip")}let h=new AbortController,i="waiting for response headers",j=new Promise((a,b)=>{e=P(()=>{let a=Error(`Capture V1 request timed out ${i} after ${this.config.requestTimeoutMs}ms`);a.name="AbortError",b(a),h.abort(a)},this.config.requestTimeoutMs)});try{let b,c=this.fetchFn(a,{method:"POST",headers:f,body:g,signal:h.signal}),d=!1;c.then(a=>{h.signal.aborted&&!d&&this.cancelBody(a)}).catch(()=>{});let k=await Promise.race([c,j]);d=!0,i="while reading the response body";let l=!1,m=()=>b??=this.cancelBody(k);return{response:k,signal:h.signal,waitFor:a=>Promise.race([a,j]),cancelBody:m,cleanup:()=>{!l&&(l=!0,clearTimeout(e),h.signal.aborted&&m())}}}catch(a){throw clearTimeout(e),a}}buildHeaders(a,b){let c=`${this.config.libraryId}/${this.config.libraryVersion}`,d={"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`,"PostHog-Sdk-Info":c,"PostHog-Attempt":String(a),"PostHog-Request-Id":b,"PostHog-Request-Timestamp":new Date(this.now()).toISOString()};return this.config.userAgent&&(d["User-Agent"]=this.config.userAgent),d}classify(a,b,c){let d=b.results??{},e=[];for(let b of a){let a=d[b.uuid];a&&("drop"===a.result?c.push({uuid:b.uuid,details:a.details??void 0}):"retry"===a.result&&e.push(b))}return e}backoffDelay(a,b){let c=Math.min(this.config.initialRetryDelayMs*2**(a-1),this.maxBackoffMs);return void 0===b?c:Math.max(c,Math.min(b,this.maxBackoffMs))}parseRetryAfter(a){let b=a.headers?.get("Retry-After");if(!b)return;let c=b.trim();if(/^\d+$/.test(c)){let a=parseInt(c,10);return Number.isFinite(a)&&a>0?1e3*a:void 0}let d=Date.parse(c);if(Number.isNaN(d))return;let e=d-this.now();return e>0?e:void 0}async parseResponse(a){let b=JSON.parse(await a.text());if("object"!=typeof b||null===b||Array.isArray(b))throw Error("unexpected response shape");let c=b.results;if(void 0!==c&&("object"!=typeof c||null===c||Array.isArray(c)))throw Error("unexpected results shape");return{results:c??{}}}async buildHttpError(a,b,c){let d="";try{d=(await c(a.text())).slice(0,512)}catch{}let e=d?`: ${d}`:"";return Error(`Capture V1 request failed with HTTP ${b}${e}`)}surfaceBatchFailure(a,b,c,d){this.onError(new c8({requestId:a,drops:b,retryExhausted:c.map(a=>a.uuid),cause:d}))}surfacePartialDrops(a,b){b.length>0&&this.onError(new c8({requestId:a,drops:b,retryExhausted:[]}))}async cancelBody(a){try{await a.body?.cancel()}catch{}}}let dg="ai-capture",dh="/i/v0/ai/batch/",di=new TextEncoder;function dj(a){return di.encode(l(a)).length}let dk=new Set;function dl(a,b){dk.has(a)||(dk.add(a),console.warn(`[PostHog] ${b}`))}class dm extends bl{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,maxQueueSize:b.maxQueueSize??1e4,flushInterval:b.flushInterval??5e3,host:function(a){return("string"==typeof a?a.trim():"")||"https://us.i.posthog.com"}(b.host),personalApiKey:function(a){return("string"==typeof a?a.trim():"")||void 0}(b.secretKey??b.personalApiKey)};if(super(c,d),this._memoryStorage=new c6,this._aiCaptureRouteActive=!1,this._minimalFlagCalledEvents=!1,this.options=d,this.captureMode=function(){let a="u">typeof process?process.env?.POSTHOG_CAPTURE_MODE:void 0;return"v0"===a||"v1"===a?a:"v0"}(),this.enableFullAiCapture=!0===d.enableFullAiCapture,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval="number"==typeof d.featureFlagsPollingInterval?Math.max(d.featureFlagsPollingInterval,100):3e4,"number"==typeof d.waitUntilDebounceMs&&(this.options.waitUntilDebounceMs=Math.max(d.waitUntilDebounceMs,0)),"number"==typeof d.waitUntilMaxWaitMs&&(this.options.waitUntilMaxWaitMs=Math.max(d.waitUntilMaxWaitMs,0)),!this.disabled&&d.personalApiKey){if(d.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!==d.enableLocalEvaluation&&(this.featureFlagsPoller=new cU({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:d.personalApiKey,projectApiKey:c,timeout:d.requestTimeout??1e4,host:this.host,fetch:d.fetch,onError:a=>{this._events.emit("error",a)},onLoad:a=>{this._events.emit("localEvaluationFlagsLoaded",a)},onMinimalFlagCalledEvents:a=>{this._minimalFlagCalledEvents=a},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation,evaluationContexts:d.evaluationContexts??d.evaluationEnvironments}))}this.errorTracking=new c5(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c,d){super.enqueue(a,b,c,d),this.scheduleDebouncedFlush()}_flushEventsAndSpans(a=!1){let b=this.flushWithPendingPromises();return!this._traces||a&&this._traces.throttled?b:R([b,this._traces.flush().catch(()=>{})]).then(([a])=>{if("rejected"===a.status)throw a.reason})}flushAutomatic(){return this._flushKeepingRuntimeAlive(!0)}async flush(){return this._flushKeepingRuntimeAlive(!1)}_flushKeepingRuntimeAlive(a){let b=this._flushEventsAndSpans(a),c=this.options.waitUntil;if(c&&!this._waitUntilCycle)try{c(b.catch(()=>{}))}catch{}return b}scheduleDebouncedFlush(){let a=this.options.waitUntil;if(!a||this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let b,c=new Promise(a=>{b=a});try{a(c)}catch{return}this._waitUntilCycle={resolve:b,startedAt:Date.now(),timer:void 0}}let b=Date.now()-this._waitUntilCycle.startedAt,c=this.options.waitUntilMaxWaitMs??500;if(void 0!==this._waitUntilCycle.timer&&clearTimeout(this._waitUntilCycle.timer),b>=c)return void this.resolveWaitUntilFlush();let d=this.options.waitUntilDebounceMs??50;this._waitUntilCycle.timer=P(()=>{this.resolveWaitUntilFlush()},d)}_consumeWaitUntilCycle(){let a=this._waitUntilCycle;return a&&(clearTimeout(a.timer),this._waitUntilCycle=void 0),a?.resolve}async resolveWaitUntilFlush(){let a=this._consumeWaitUntilCycle();try{await this._flushEventsAndSpans()}catch{}finally{a?.()}}getPersistedProperty(a){return this._memoryStorage.getProperty(a)}setPersistedProperty(a,b){return this._memoryStorage.setProperty(a,b)}fetch(a,b){return this.options.fetch?this.options.fetch(a,b):fetch(a,b)}getQueueRouteKey(a){var b;return"v1"===this.captureMode&&"string"==typeof(b=a).event&&b.event.startsWith("$ai_")?"ai":c7}persistedQueueKeyForRoute(a){return a===dg?j.AiCaptureQueue:"ai"===a?j.AiQueue:j.Queue}getActiveQueueRoutes(){let a="v1"===this.captureMode?[c7,"ai"]:[c7];return this._aiCaptureRouteActive&&a.push(dg),a}getBatchEndpointPath(a){return a===dg?dh:super.getBatchEndpointPath(a)}async sendBatch(a,b,c=c7){if(c===dg)return this.sendAiCaptureBatch(a,b);if("v1"!==this.captureMode||"ai"===c)return super.sendBatch(a,b,c);let d=a.filter(a=>void 0!==a);await this.getV1Sender().sendV1Batch(d)}async sendAiCaptureBatch(a,b){let{batches:c,dropped:d}=function(a,b=8388608,c=5242880){let d=[],e=[],f=[],g=0;for(let h of a){if(void 0===h)continue;let a=dj(h);if(a>b){e.push({event:"string"==typeof h.event?h.event:"unknown",bytes:a});continue}f.length>0&&g+a>c&&(d.push(f),f=[],g=0),f.push(h),g+=a}return f.length>0&&d.push(f),{batches:d,dropped:e}}(a);for(let{event:a,bytes:b}of d){let c=`Event ${a} (${b} bytes) exceeds the 8MiB limit for ${dh}, dropping.`;this._logger.error(c),this._events.emit("error",Error(c))}for(let a of c)await this.sendAiSubBatch(a,b)}async sendAiSubBatch(a,b){try{await super.sendBatch(a,b,dg)}catch(d){if(!bh(d))throw d;if(1===a.length){let[b]=a,c="string"==typeof b.event?b.event:"unknown",d=`Event ${c} (${dj(b)} bytes) was rejected with 413 by ${dh} on its own, dropping.`;this._logger.error(d),this._events.emit("error",Error(d));return}let c=Math.ceil(a.length/2);await this.sendAiSubBatch(a.slice(0,c),b),await this.sendAiSubBatch(a.slice(c),b)}}getV1Sender(){return this._v1Sender||(this._v1Sender=new df({host:this.host,apiKey:this.apiKey,libraryId:this.getLibraryId(),libraryVersion:this.getLibraryVersion(),userAgent:this.getCustomUserAgent()||void 0,historicalMigration:this.historicalMigration,compressionEnabled:!this.disableCompression,requestTimeoutMs:this.requestTimeout,maxAttempts:(this.options.fetchRetryCount??3)+1,initialRetryDelayMs:this.options.fetchRetryDelay??3e3,isDebug:this.isDebug},{fetch:(a,b)=>this.fetch(a,b),onError:a=>this._events.emit("error",a),compress:a=>this.compressPayload(a)})),this._v1Sender}getLibraryVersion(){return"5.54.1"}get metrics(){var a;let b;return this._metrics||(this._metrics=new bE(this,(a=this.options.metrics,b=a?.resourceAttributes,{serviceName:b?.["service.name"]??a?.serviceName,serviceVersion:b?.["service.version"]??a?.serviceVersion,environment:b?.["deployment.environment"]??a?.environment,resourceAttributes:b,beforeSend:a?.beforeSend,flushIntervalMs:a?.flushIntervalMs??1e4,maxSeriesPerFlush:a?.maxSeriesPerFlush??1e3}),this._logger)),this._metrics}initializeSpanContextManager(){return new cr}hostResourceAttributes(){return{}}get _spanContextManager(){return this._spanContext||(this._spanContext=this.initializeSpanContextManager()),this._spanContext}get _tracesPipeline(){if(this.options.traces){var a,b,c;let d,e;return this._traces||(this._traces=new cc(this,(a=this.options.traces,b=this.hostResourceAttributes(),c=this._logger,d=bq({...b},function(a){if(!(!a||"object"!=typeof a||Array.isArray(a)))try{if(cv.every(b=>!(b in a)||"string"==typeof a[b]))return a;let b={...a};for(let a of cv)a in b&&"string"!=typeof b[a]&&delete b[a];return b}catch{return}}(a?.resourceAttributes)),e=cu(a?.maxExportBatchSize,512),{serviceName:d?.["service.name"]??a?.serviceName,serviceVersion:d?.["service.version"]??a?.serviceVersion,environment:d?.["deployment.environment"]??a?.environment,resourceAttributes:d,beforeSpanSend:function(a,b){if(!a)return[];let c=[a].flat().filter(a=>!!a),d=c.filter(a=>"function"==typeof a);return d.length!==c.length&&b?.critical(`beforeSpanSend: ignoring ${c.length-d.length} of ${c.length} entries that are not functions. Spans export without them, so whatever they were redacting is not redacted.`),d}(a?.beforeSpanSend,c),maxAttributesPerSpan:cu(a?.maxAttributesPerSpan,128),maxEventsPerSpan:cu(a?.maxEventsPerSpan,128),maxAttributesPerEvent:128,maxAttributeValueLength:cu(a?.maxAttributeValueLength,8192),flushIntervalMs:cu(a?.flushIntervalMs,5e3),maxExportBatchSize:e,maxQueueSize:Math.max(cu(a?.maxQueueSize,2048),e),maxLiveSpans:cu(a?.maxLiveSpans,1e4),maxSpanAgeMs:cu(a?.maxSpanAgeMs,36e5)}),this._logger,()=>this._tracingContext(),this._spanContextManager,()=>this.scheduleDebouncedFlush())),this._traces}}_tracingContext(){let a=this.context?.get();return{distinctId:a?.distinctId,sessionId:a?.sessionId}}startSpan(a,b){return this._tracesPipeline?.startSpan(a,b)??bZ(b,this._spanContextManager.active())}withSpan(a,b,c){let d="function"==typeof b?void 0:b,e="function"==typeof b?b:c,f=this._tracesPipeline;return f?d?f.withSpan(a,d,e):f.withSpan(a,e):b2(this._spanContextManager,bZ(d,this._spanContextManager.active()),e)}getActiveSpan(){return this._spanContextManager.active()??null}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}getEvaluationRuntime(){return"server"}getCommonEventProperties(){let a=super.getCommonEventProperties();return(this.options.isServer??!0)&&(a.$is_server=!0),a}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}_warnIfInvalidCapture(a,b,c){"string"==typeof a&&this._logger.warn(b),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn(c)}_sendPreparedEvent(a,b,c,d,e){return this.addPendingPromise(this._prepareEventMessage(b,d).then(({distinctId:b,event:d,properties:f,options:g})=>{let h={timestamp:g.timestamp,disableGeoip:g.disableGeoip,uuid:g.uuid},i={distinctId:b,event:d,properties:{...f,...this.getCommonEventProperties()}};return c?this.sendImmediate(a,i,h,e):this.enqueue(a,i,h,e)}).catch(a=>{a&&console.error(a)}))}_capturePreparedEvent(a,b){return this._sendPreparedEvent("capture",a,b)}capture(a){this._warnIfInvalidCapture(a,"Called capture() with a string as the first argument when an object was expected.","Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this._capturePreparedEvent(a,!1)}async captureImmediate(a){return this._warnIfInvalidCapture(a,"Called captureImmediate() with a string as the first argument when an object was expected.","Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default."),this._capturePreparedEvent(a,!0)}captureAi(a){if(this.disabled)return;let b=K(a.uuid,aU);return this._sendPreparedAiEvent({...a,uuid:b},!1),b}async captureAiImmediate(a){if(this.disabled)return;let b=K(a.uuid,aU);return await this._sendPreparedAiEvent({...a,uuid:b},!0),b}_sendPreparedAiEvent(a,b){return"string"!=typeof a?.event||a.event.startsWith("$ai_")||this._logger.debug(`captureAi called with non-AI event ${a.event}; routing it to the AI endpoint anyway.`),this._aiCaptureRouteActive=!0,this._sendPreparedEvent("capture",a,b,void 0,dg)}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!1,{includeContextProperties:!1})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;await this._sendPreparedEvent("identify",{distinctId:a,event:"$identify",properties:{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},disableGeoip:c},!0,{includeContextProperties:!1})}setPersonProperties({distinctId:a,properties:b={},propertiesOnce:c={}}){if(0===Object.keys(b).length&&0===Object.keys(c).length)return;let d={};Object.keys(b).length>0&&(d.$set=b),Object.keys(c).length>0&&(d.$set_once=c),this.capture({distinctId:a,event:"$set",properties:d})}unsetPersonProperties({distinctId:a,properties:b}){let c=(Array.isArray(b)?b:[b]).filter(a=>"string"==typeof a&&a.trim().length>0);0!==c.length&&this.capture({distinctId:a,event:"$set",properties:{$unset:c}})}alias(a){this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!1,{includeContextProperties:!1})}async aliasImmediate(a){await this._sendPreparedEvent("alias",{distinctId:a.distinctId,event:"$create_alias",properties:{distinct_id:a.distinctId,alias:a.alias},disableGeoip:a.disableGeoip},!0,{includeContextProperties:!1})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}getFeatureFlagEvaluationRuntime(a){return this.featureFlagsPoller?.getEvaluationRuntimeForFlag(a)}getFeatureFlagKeysByEvaluationRuntime(a){return this.featureFlagsPoller?.getFlagKeysByEvaluationRuntime(a)??[]}async waitForLocalEvaluationReady(a=3e4){return!!this.isLocalEvaluationReady()||void 0!==this.featureFlagsPoller&&new Promise(b=>{let c=setTimeout(()=>{d(),b(!1)},a),d=this._events.on("localEvaluationFlagsLoaded",a=>{clearTimeout(c),d(),b(a>0)})})}_resolveDistinctId(a,b){return"string"==typeof a?{distinctId:a,options:b}:{distinctId:this.context?.get()?.distinctId,options:a}}async _getFeatureFlagResult(a,b,c={},d){let e,f,g,h,i,j,k,l;if(this.disabled)return void this._logger.warn("The client is disabled");let m=c.sendFeatureFlagEvents??!0;if(void 0!==this._flagOverrides&&a in this._flagOverrides){let b=this._flagOverrides[a];if(void 0===b)return;let c=this._payloadOverrides?.[a];return{key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c}}let{groups:n,disableGeoip:o}=c,{onlyEvaluateLocally:p,personProperties:q,groupProperties:r}=c,s=this.addLocalPersonAndGroupProperties(b,n,q,r);q=s.allPersonProperties,r=s.allGroupProperties;let t=this.createFeatureFlagEvaluationContext(b,n,this.personPropertiesForLocalEvaluation(b,q),r);void 0==p&&(p=this.options.strictLocalEvaluation??!1);let u=!1;if(void 0!==this.featureFlagsPoller){await this.featureFlagsPoller?.loadFeatureFlags();let b=this.featureFlagsPoller?.featureFlagsByKey[a];if(b)try{let c=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(b,t,{matchValue:d});if(c){u=!0;let d=c.value;i=b.id,k="Evaluated locally",l=b.has_experiment,e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0,reason:k,reasonCode:!1===b.active?"flag_disabled":void 0}}}catch(b){if(b instanceof cT||b instanceof cz)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!u&&!p){let b=await super.getFeatureFlagDetailsStateless(t.distinctId,t.groups,q,r,o,[a]);if(void 0===b)h=cw.UNKNOWN_ERROR;else{this._minimalFlagCalledEvents=!0===b.minimalFlagCalledEvents,f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(cw.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(cw.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(cw.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,l=d.metadata?.has_experiment,d.metadata?.payload!==void 0)try{b=JSON.parse(d.metadata.payload)}catch{b=d.metadata.payload}e={key:a,enabled:d.enabled,variant:d.variant??void 0,payload:b,reason:k,reasonCode:d.reason?.code}}c.length>0&&(h=c.join(","))}}if(m){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:u,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:u?Date.now():g};if(void 0!==l&&(d.$feature_flag_has_experiment=l),u&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(d.$feature_flag_definitions_loaded_at=a)}h&&(d.$feature_flag_error=h),this._captureFlagCalledEventIfNeeded({distinctId:b,key:a,response:c,groups:n,disableGeoip:o,properties:d})}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){dl("getFeatureFlag","`getFeatureFlag` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlag(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(void 0!==d)return!1!==d.enabled&&(d.variant??!0)}async getFeatureFlagPayload(a,b,c,d){if(dl("getFeatureFlagPayload","`getFeatureFlagPayload` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.getFlagPayload(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request."),void 0!==this._payloadOverrides&&a in this._payloadOverrides)return this._payloadOverrides[a];let e=await this._getFeatureFlagResult(a,b,{...d,sendFeatureFlagEvents:!1},c);if(void 0!==e)return e.payload??null}async getFeatureFlagResult(a,b,c){let{distinctId:d,options:e}=this._resolveDistinctId(b,c);return d?this._getFeatureFlagResult(a,d,{...e,sendFeatureFlagEvents:e?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0}):void this._logger.warn("[PostHog] distinctId is required — pass it explicitly or use withContext()")}async getRemoteConfigPayload(a){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let b=await this._requestRemoteConfigPayload(a);if(!b)return;let c=await b.json();if("string"==typeof c)try{return JSON.parse(c)}catch(a){}return c}async isFeatureEnabled(a,b,c){dl("isFeatureEnabled","`isFeatureEnabled` is deprecated and will be removed in a future major version. Use `posthog.evaluateFlags(distinctId, ...)` and call `flags.isEnabled(key)` instead — this consolidates flag evaluation into a single `/flags` request per incoming request.");let d=await this._getFeatureFlagResult(a,b,{...c,sendFeatureFlagEvents:c?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});return void 0===d?void 0:!1!==d.enabled&&!!(d.variant??!0)}async getAllFlags(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);return c?(await this.getAllFlagsAndPayloads(c,d)).featureFlags||{}:(this._logger.warn("[PostHog] distinctId is required to get feature flags — pass it explicitly or use withContext()"),{})}async getAllFlagsAndPayloads(a,b){let{distinctId:c,options:d}=this._resolveDistinctId(a,b);if(!c)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads — pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};if(this.disabled)return this._logger.warn("The client is disabled"),{featureFlags:{},featureFlagPayloads:{}};let{groups:e,disableGeoip:f,flagKeys:g}=d||{},{onlyEvaluateLocally:h,personProperties:i,groupProperties:j}=d||{},k=this.addLocalPersonAndGroupProperties(c,e,i,j);i=k.allPersonProperties,j=k.allGroupProperties;let l=this.createFeatureFlagEvaluationContext(c,e,this.personPropertiesForLocalEvaluation(c,i),j);void 0==h&&(h=this.options.strictLocalEvaluation??!1);let m=await this.featureFlagsPoller?.getAllFlagsAndPayloads(l,g),n={},o={},p=!0;if(m&&(n=m.response,o=m.payloads,p=m.fallbackToFlags),p&&!h){let a=await super.getFeatureFlagsAndPayloadsStateless(l.distinctId,l.groups,i,j,f,g);n={...n,...a.flags||{}},o={...o,...a.payloads||{}}}return void 0!==this._flagOverrides&&(n={...n,...this._flagOverrides}),void 0!==this._payloadOverrides&&(o={...o,...this._payloadOverrides}),{featureFlags:n,featureFlagPayloads:o}}async evaluateFlags(a,b){let c,d,{distinctId:e,options:f}=this._resolveDistinctId(a,b);if(!e)return this._logger.warn("[PostHog] distinctId is required to evaluate feature flags — pass it explicitly or use withContext()"),new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});if(this.disabled)return this._logger.warn("The client is disabled"),new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,flags:{}});let{groups:g,disableGeoip:h}=f||{},i=f?.flagKeys??void 0;if(i?.length===0)return new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:{}});let{onlyEvaluateLocally:j,personProperties:k,groupProperties:l}=f||{},m=this.addLocalPersonAndGroupProperties(e,g,k,l);k=m.allPersonProperties,l=m.allGroupProperties;let n=this.createFeatureFlagEvaluationContext(e,g,this.personPropertiesForLocalEvaluation(e,k),l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o=i?new Set(i):void 0,p={},q=!1,r=!1,s=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),t=new Set;if(s)for(let[a,b]of Object.entries(s.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:s.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0,hasExperiment:c?.has_experiment},t.add(a)}let u=void 0!==o&&Array.from(o).some(a=>this.featureFlagsPoller?.featureFlagsByKey[a]===void 0);if((!s||s.fallbackToFlags||u)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,k,l,h,i);if(a)for(let[b,e]of(this._minimalFlagCalledEvents=!0===a.minimalFlagCalledEvents,c=a.requestId,d=a.evaluatedAt,q=!!a.errorsWhileComputingFlags,r=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!t.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}p[b]={key:b,enabled:e.enabled,variant:e.variant,payload:a,id:e.metadata?.id,version:e.metadata?.version,reason:e.reason?.description??e.reason?.code,locallyEvaluated:!1,hasExperiment:e.metadata?.has_experiment}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete p[a];continue}let c=p[a];p[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:c?.payload,id:c?.id,version:c?.version,reason:c?.reason,locallyEvaluated:c?.locallyEvaluated??!1,hasExperiment:c?.hasExperiment}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=p[a];c&&(p[a]={...c,payload:b})}if(void 0!==o)for(let a of Object.keys(p))o.has(a)||delete p[a];return new cx({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:p,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:q,quotaLimited:r})}_shouldSendMinimalFlagCalledEvent(a,b){return"$feature_flag_called"===a&&this._minimalFlagCalledEvents&&!1===b.$feature_flag_has_experiment}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=e&&Object.keys(e).length>0?`_${JSON.stringify(Object.entries(e).sort(([a],[b])=>a<b?-1:+(a>b)))}`:"",i=`${c}_${d}${h}`;b in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[b].has(i)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),this.distinctIdHasSentFlagCalls[b]instanceof Set?this.distinctIdHasSentFlagCalls[b].add(i):this.distinctIdHasSentFlagCalls[b]=new Set([i]),this.capture({distinctId:b,event:"$feature_flag_called",properties:g,groups:e,disableGeoip:f}))}_getFeatureFlagEvaluationsHost(){return this._featureFlagEvaluationsHost||(this._featureFlagEvaluationsHost={captureFlagCalledEventIfNeeded:a=>this._captureFlagCalledEventIfNeeded(a),logWarning:a=>{!1!==this.options.featureFlagsLogWarnings&&console.warn(`[PostHog] ${a}`)}}),this._featureFlagEvaluationsHost}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!1,{includeContextProperties:!1})}async groupIdentifyImmediate({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){await this._sendPreparedEvent("capture",{distinctId:d||`$${a}_${b}`,event:"$groupidentify",properties:{$group_type:a,$group_key:b,$group_set:c||{}},disableGeoip:e},!0,{includeContextProperties:!1})}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(a){let b=a=>Object.fromEntries(a.map(a=>[a,!0]));if(!1===a){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(a)){this._flagOverrides=b(a);return}if(this._isFeatureFlagOverrideOptions(a)){"flags"in a&&(!1===a.flags?this._flagOverrides=void 0:Array.isArray(a.flags)?this._flagOverrides=b(a.flags):void 0!==a.flags&&(this._flagOverrides={...a.flags})),"payloads"in a&&(!1===a.payloads?this._payloadOverrides=void 0:void 0!==a.payloads&&(this._payloadOverrides={...a.payloads}));return}this._flagOverrides={...a}}_isFeatureFlagOverrideOptions(a){if("object"!=typeof a||null===a||Array.isArray(a))return!1;if("flags"in a){let b=a.flags;if(!1===b||Array.isArray(b)||"object"==typeof b&&null!==b)return!0}if("payloads"in a){let b=a.payloads;if(!1===b||"object"==typeof b&&null!==b)return!0}return!1}withContext(a,b,c){return this.context?this.context.run(a,b,c):b()}getContext(){return this.context?.get()}enterContext(a,b){this.context?.enter(a,b)}async _shutdown(a){let b=Date.now()+(a??3e4),c=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown(),this._metrics&&(await Q(this._metrics.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._metrics.reset()),this._traces&&(await Q(this._traces.flush().catch(()=>{}),Math.max(0,b-Date.now())),this._traces.reset());try{return await super._shutdown(Math.max(0,b-Date.now()))}finally{this.distinctIdHasSentFlagCalls={},c?.()}}async _requestRemoteConfigPayload(a){if(this.disabled||!this.apiKey||!this.options.personalApiKey)return;let b=`${this.host}/api/projects/@current/feature_flags/${a}/remote_config?token=${encodeURIComponent(this.apiKey)}`,c={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},d=null;if(this.options.requestTimeout&&"number"==typeof this.options.requestTimeout){let a=new AbortController;d=P(()=>{a.abort()},this.options.requestTimeout),c.signal=a.signal}try{return await this.fetch(b,c)}catch(a){this._events.emit("error",a);return}finally{d&&clearTimeout(d)}}extractPropertiesFromEvent(a,b){if(!a)return{personProperties:{},groupProperties:{}};let c={},d={};for(let[e,f]of Object.entries(a))if(y(f,"Object")&&b&&e in b){let a={};for(let[b,c]of Object.entries(f))a[String(b)]=String(c);d[String(e)]=a}else c[String(e)]=String(f);return{personProperties:c,groupProperties:d}}async getFeatureFlagsForEvent(a,b,c,d){if(this.disabled||!this.apiKey)return void this._logger.warn("The client is disabled");let e=d?.personProperties||{},f=d?.groupProperties||{},g=d?.flagKeys;if(d?.onlyEvaluateLocally??this.options.strictLocalEvaluation)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let d={};for(let[a,c]of Object.entries(b||{}))d[a]=String(c);return await this.getAllFlags(a,{groups:d,personProperties:e,groupProperties:f,disableGeoip:c,onlyEvaluateLocally:!0,flagKeys:g})}return(await super.getFeatureFlagsStateless(a,b,e,f,c)).flags}addLocalPersonAndGroupProperties(a,b,c,d){let e={...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}personPropertiesForLocalEvaluation(a,b){return{distinct_id:a,...b||{}}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!c5.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(c5.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:f},b,c).then(a=>this._capturePreparedEvent({...a,uuid:d,flags:e},!1)))}}async captureExceptionImmediate(a,b,c,d){if(!c5.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(c5.buildEventMessage(this.getErrorPropertiesBuilder(),a,{syntheticException:e},b,c).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){return this._prepareEventMessage(a)}async _prepareEventMessage(a,b={}){let{distinctId:c,event:d,properties:e,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k}=a,l=this.context?.get(),m=b.includeContextProperties??!0,n=c||l?.distinctId,o=m?{...this.props,...l?.properties||{},...e||{}}:{...e||{}};n||(n=aU(),o.$process_person_profile=!1),m&&l?.sessionId&&!o.$session_id&&(o.$session_id=l.sessionId);let p=this._shouldSendMinimalFlagCalledEvent(d,o)?a3(o):o,q=this._runBeforeSend({distinctId:n,event:d,properties:p,groups:f,flags:g,sendFeatureFlags:h,timestamp:i,disableGeoip:j,uuid:k});if(!q)return Promise.reject(null);let r=await Promise.resolve().then(async()=>{if(g)return h&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),g._getEventProperties();if(h){dl("sendFeatureFlags","`sendFeatureFlags` is deprecated and will be removed in a future major version. Pass a `flags` snapshot from `posthog.evaluateFlags(...)` instead — it avoids a second `/flags` request per capture and guarantees the event carries the exact flag values your code branched on.");var a=await this.getFeatureFlagsForEvent(q.distinctId,f,j,"object"==typeof h?h:void 0);if(!a)return{};let b={};for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a).filter(b=>!1!==a[b]).sort();return c.length>0&&(b.$active_feature_flags=c),b}return{}}).catch(()=>({})).then(a=>{let b=q.groups||f;return{...a,...q.properties||{},...void 0!==b&&Object.keys(b).length>0?{$groups:b}:{}}});return"$pageview"===q.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof r.$raw_user_agent&&ct(r.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(q.event="$bot_pageview",r.$browser_type="bot"),{distinctId:q.distinctId,event:q.event,properties:r,options:{timestamp:q.timestamp,disableGeoip:q.disableGeoip,uuid:q.uuid}}}_runBeforeSend(a){let b=this.options.before_send;if(!b)return a;let c=Array.isArray(b)?b:[b],d=a;for(let b of c)try{if(!(d=b(d)))return this._logger.info(`Event '${a.event}' was rejected in beforeSend function`),null;if(!d.properties||0===Object.keys(d.properties).length){let a=`Event '${d.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(a)}}catch(b){return this._logger.error(`Error in before_send function for event '${a.event}':`,b),null}return d}}var cd=aP,dn=a.i(78500);class dp{constructor(){this.storage=new dn.AsyncLocalStorage}get(){return this.storage.getStore()}run(a,b,c){return this.storage.run(this.resolve(a,c),b)}enter(a,b){this.storage.enterWith(this.resolve(a,b))}resolve(a,b){if(b?.fresh===!0)return a;let c=this.get()||{};return{distinctId:a.distinctId??c.distinctId,sessionId:a.sessionId??c.sessionId,properties:{...c.properties||{},...a.properties||{}}}}}class dq{active(){return this._storage.getStore()}with(a,b){return this._storage.run(a,b)}constructor(){this._storage=new dn.AsyncLocalStorage}}var dr=a.i(27028);let ds=(0,a.i(12057).promisify)(dr.gzip);async function dt(a,b=!0){try{let b=await ds(a);return new Uint8Array(b)}catch(a){return b&&console.error("Failed to gzip compress data",a),null}}var du=a.i(60526),cd=aP;let dv="posthog-node";function dw(a,{organization:b,projectId:c,prefix:d,severityAllowList:e=["error"],sendExceptionsToPostHog:f=!0}={}){return g=>{if(!("*"===e||e.includes(g.level)))return g;g.tags||(g.tags={});let h=g.tags[dy.POSTHOG_ID_TAG];if(void 0===h)return g;let i=a.options.host??"https://us.i.posthog.com",j=new URL(`/project/${a.apiKey}/person/${h}`,i).toString();g.tags["PostHog Person URL"]=j;let k=g.exception?.values||[],l=k.map(a=>({...a,stacktrace:a.stacktrace?{...a.stacktrace,type:"raw",frames:(a.stacktrace.frames||[]).map(a=>({...a,platform:"node:javascript"}))}:void 0})),m={$exception_message:k[0]?.value||g.message,$exception_type:k[0]?.type,$exception_level:g.level,$exception_list:l,$sentry_event_id:g.event_id,$sentry_exception:g.exception,$sentry_exception_message:k[0]?.value||g.message,$sentry_exception_type:k[0]?.type,$sentry_tags:g.tags},n=cd.getInjectedReleaseId();return n&&(m.$release_id=n),b&&c&&(m.$sentry_url=(d||"https://sentry.io/organizations/")+b+"/issues/?project="+c+"&query="+g.event_id),f&&a.capture({event:"$exception",distinctId:h,properties:m}),g}}function dx(a,b){let c=dw(a,b);return{name:dv,processEvent:a=>c(a)}}class dy{static{this.POSTHOG_ID_TAG="posthog_distinct_id"}constructor(a,b,c,d,e){this.name=dv,this.name=dv,this.setupOnce=function(f,g){f(dw(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,dy,"createEventProcessor",0,dw,"sentryIntegration",0,dx],9318);let dz=/[\x00-\x1f\x7f-\x9f]/g;function dA(a,b,c){null!=c&&""!==c&&(a[b]=c)}function dB(a){return Array.isArray(a)?a[0]:a}function dC(a){if(Array.isArray(a)){for(let b of a){let a=dC(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(dz,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function dD(a,b){var c,d;let e,{sessionId:f,distinctId:g}=function(a){if(!a)return{};let b=dC(a["x-posthog-session-id"]),c=dC(a["x-posthog-distinct-id"]);return{...void 0!==b?{sessionId:b}:{},...void 0!==c?{distinctId:c}:{}}}(b.headers),h={},i=!0===a.options.disable_capture_url_hashes;return dA(h,"$current_url",(c=b.originalUrl||b.url,i?M(c):c)),dA(h,"$request_method",b.method),dA(h,"$request_path",(d=b.path,e=function(a){if(!a)return a;let b=a.indexOf("?"),c=a.indexOf("#");return -1===b||-1!==c&&c<b?a:`${a.slice(0,b)}${-1===c?"":a.slice(c)}`}(d),i?M(e):e)),dA(h,"$user_agent",dB(b.headers["user-agent"])),dA(h,"$ip",function(a){let b=dB(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(b)),{...void 0!==f?{sessionId:f}:{},...void 0!==g?{distinctId:g}:{},properties:h}}function dE(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(dD(c,a),()=>d())}))}function dF(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(c5.isPreviouslyCapturedError(a))return void e(a);let f=dD(c,b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{}};c.addPendingPromise(Promise.all([c5.buildEventMessage(c.getErrorPropertiesBuilder(),a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h),d.headersSent||d.destroyed?Promise.resolve(d.headersSent?d.statusCode:void 0):new Promise(a=>{let b=b=>{clearTimeout(e),d.removeListener("finish",c),d.removeListener("close",c),a(b)},c=()=>b(d.headersSent?d.statusCode:void 0),e=setTimeout(()=>b(void 0),1e3);e.unref(),d.once("finish",c),d.once("close",c)})]).then(([a,b])=>(void 0!==b&&(a.properties={...a.properties,$response_status_code:b}),c._capturePreparedEvent(a,!1)))),e(a)}))}a.s(["setupExpressErrorHandler",0,dF,"setupExpressRequestContext",0,dE],40602),a.s([],51328);class dG extends dm{getLibraryId(){return"posthog-node"}compressPayload(a){return dt(a,this.isDebug)}initializeContext(){return new dp}initializeSpanContextManager(){return new dq}hostResourceAttributes(){return function(){var a,b;let c,d,e;try{c=(0,du.platform)(),d=(0,du.release)()}catch{}return a=c,b=d,{...(e=function(a){if(a)return Object.prototype.hasOwnProperty.call(bx,a)?bx[a]:a}(a))?{"os.name":e}:{},...b?{"os.version":b}:{}}}()}createErrorPropertiesBuilder(){let a;return new cd.ErrorPropertiesBuilder([new cd.EventCoercer,new cd.ErrorCoercer,new cd.ObjectCoercer,new cd.StringCoercer,new cd.PrimitiveCoercer],cd.createStackParser("node:javascript",cd.nodeStackLineParser),[(a=function(a=process.argv[1]?(0,h.dirname)(process.argv[1]):process.cwd(),b="\\"===h.sep){let c=b?i(a):a;return a=>{if(!a)return;let d=b?i(a):a,{dir:e,base:f,ext:g}=h.posix.parse(d);(".js"===g||".mjs"===g||".cjs"===g)&&(f=f.slice(0,-1*g.length));let j=decodeURIComponent(f);e||(e=".");let k=e.lastIndexOf("/node_modules");if(k>-1)return`${e.slice(k+14).replace(/\//g,".")}:${j}`;if(e.startsWith(c)){let a=e.slice(c.length+1).replace(/\//g,".");return a?`${a}:${j}`:j}return j}}(),async b=>{for(let c of b)c.module=a(c.filename);return b}),a=>ck(a,void 0,this._logger),function(a=process.cwd()){h.sep;let b=a=>a,c=b(a);return async a=>{for(let d of a)!(!d.filename||d.filename.startsWith("node:")||d.filename.startsWith("data:"))&&(0,h.isAbsolute)(d.filename)&&(d.filename=b((0,h.relative)(c,b(d.filename))));return a}}()])}}a.s(["PostHog",0,dG],81035),a.i(81035),a.i(51328),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,k,"FeatureFlagEvaluations",0,cx,"PostHogSentryIntegration",0,dy,"cookieStateToProperties",0,a$,"cookieStoreFromHeader",0,aW,"createEventProcessor",0,dw,"getPostHogCookieName",0,aX,"parsePostHogCookie",0,a_,"readPostHogCookie",0,aZ,"sentryIntegration",0,dx,"serializePostHogCookie",0,aY,"setupExpressErrorHandler",0,dF,"setupExpressRequestContext",0,dE,"uuidv7",0,aU],80456),a.i(80456),a.s(["FeatureFlagError",0,k,"FeatureFlagEvaluations",0,cx,"PostHog",0,dG,"PostHogSentryIntegration",0,dy,"cookieStateToProperties",0,a$,"cookieStoreFromHeader",0,aW,"createEventProcessor",0,dw,"getPostHogCookieName",0,aX,"parsePostHogCookie",0,a_,"readPostHogCookie",0,aZ,"sentryIntegration",0,dx,"serializePostHogCookie",0,aY,"setupExpressErrorHandler",0,dF,"setupExpressRequestContext",0,dE,"uuidv7",0,aU],74493)}];
|
|
3
3
|
|
|
4
4
|
//# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_11bnuzn._.js.map
|