failproofai 0.0.10-beta.0 → 0.0.10-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +3 -3
  3. package/.next/standalone/.next/prerender-manifest.json +3 -3
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  6. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.rsc +7 -7
  10. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  11. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +7 -7
  12. package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +3 -3
  13. package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +3 -3
  14. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  15. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.html +2 -2
  19. package/.next/standalone/.next/server/app/_not-found.rsc +17 -17
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +17 -17
  21. package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +4 -4
  22. package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +11 -11
  23. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +2 -2
  24. package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +3 -3
  25. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +2 -2
  26. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/index.html +1 -1
  28. package/.next/standalone/.next/server/app/index.rsc +16 -16
  29. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +2 -2
  30. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +16 -16
  31. package/.next/standalone/.next/server/app/index.segments/_head.segment.rsc +4 -4
  32. package/.next/standalone/.next/server/app/index.segments/_index.segment.rsc +11 -11
  33. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  34. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  35. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  36. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  37. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +8 -8
  38. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  39. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  40. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  41. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  42. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  43. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  44. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  45. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  46. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  47. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  48. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  49. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  50. package/.next/standalone/.next/server/chunks/[root-of-the-server]__0dtn9lr._.js +1 -1
  51. package/.next/standalone/.next/server/chunks/node_modules_posthog-node_dist_entrypoints_index_node_mjs_05pz9._._.js +1 -1
  52. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_0z7w.hh._.js +1 -1
  53. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0-2wr.c._.js +2 -2
  54. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0.~m-w2._.js +2 -2
  55. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0709m8.._.js +2 -2
  56. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bz245.._.js +2 -2
  57. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0dl0kgt._.js +2 -2
  58. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0gmhxyo._.js +2 -2
  59. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__0ymn496._.js → [root-of-the-server]__0ils1oq._.js} +2 -2
  60. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ohb3gc._.js +2 -2
  61. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__10h.ggz._.js → [root-of-the-server]__0tt8-uq._.js} +2 -2
  62. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0ymlddl._.js +28 -4
  63. package/.next/standalone/.next/server/chunks/ssr/_10lm7or._.js +2 -2
  64. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_0xerkr6._.js +1 -1
  65. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_0q-m0y-._.js +1 -1
  66. package/.next/standalone/.next/server/chunks/ssr/node_modules_posthog-node_dist_entrypoints_index_node_mjs_0mebn66._.js +1 -1
  67. package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
  68. package/.next/standalone/.next/server/pages/404.html +2 -2
  69. package/.next/standalone/.next/server/pages/500.html +1 -1
  70. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  71. package/.next/standalone/.next/server/server-reference-manifest.json +9 -9
  72. package/.next/standalone/.next/static/chunks/{0agmlhk5ml7x5.js → 0-dltnti0ew4y.js} +1 -1
  73. package/.next/standalone/.next/static/chunks/{14lmf8boay-zu.js → 02h_cfxpk4x9..js} +1 -1
  74. package/.next/standalone/.next/static/chunks/{0s6nux54y~l~r.js → 0a_w-lcg.0tl7.js} +1 -1
  75. package/.next/standalone/.next/static/chunks/{1400rtd5ywbt..js → 0lscbfo_2_h14.js} +2 -2
  76. package/.next/standalone/.next/static/chunks/0xr8w5io1-kb9.css +1 -0
  77. package/.next/standalone/.next/static/chunks/{0tpse0wu2wwo0.js → 0y8oyen~jnjl3.js} +1 -1
  78. package/.next/standalone/.next/static/chunks/{00ay03h8bq4b~.js → 0yzl~f-qji0...js} +1 -1
  79. package/.next/standalone/.next/static/chunks/{0en4v5k2nnxks.js → 16k5y9ruha2v4.js} +1 -1
  80. package/.next/standalone/.next/static/chunks/{17htukxga7bil.js → 17o7-pn_xzt-t.js} +1 -1
  81. package/.next/standalone/app/components/raw-log-viewer.tsx +25 -5
  82. package/.next/standalone/package.json +2 -2
  83. package/.next/standalone/pi-extension/index.ts +21 -4
  84. package/.next/standalone/server.js +1 -1
  85. package/dist/cli.mjs +203 -16
  86. package/package.json +2 -2
  87. package/pi-extension/index.ts +21 -4
  88. package/scripts/install-diagnosis.mjs +190 -0
  89. package/scripts/launch.ts +32 -0
  90. package/scripts/postinstall.mjs +25 -0
  91. package/src/hooks/handler.ts +24 -11
  92. package/src/hooks/integrations.ts +27 -3
  93. package/src/hooks/types.ts +73 -2
  94. package/.next/standalone/.next/static/chunks/12po2vpc-4_c1.css +0 -1
  95. /package/.next/standalone/.next/static/{68TLSFdjAQYIulNHfP0QY → EBbXdrT2rHib3zGLSuY7Q}/_buildManifest.js +0 -0
  96. /package/.next/standalone/.next/static/{68TLSFdjAQYIulNHfP0QY → EBbXdrT2rHib3zGLSuY7Q}/_clientMiddlewareManifest.js +0 -0
  97. /package/.next/standalone/.next/static/{68TLSFdjAQYIulNHfP0QY → EBbXdrT2rHib3zGLSuY7Q}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- module.exports=[22712,a=>{"use strict";var b=a.i(87924),c=a.i(72131),d=a.i(35112),e=a.i(38246),f=a.i(64831);let g=(0,f.default)("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]),h=(0,f.default)("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),i=(0,f.default)("shield-x",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]),j=(0,f.default)("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);var k=a.i(14258),l=a.i(89027),m=a.i(85650),n=a.i(52562);let o=(0,f.default)("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),p=(0,f.default)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]]);var q=a.i(74215),r=a.i(65967),s=a.i(5050);let t=(0,s.createServerReference)("40b6b77c3d46ce8a0febee33d73a1a20b1bf03a105",s.callServer,void 0,s.findSourceMapURL,"getHookActivityAction"),u=(0,s.createServerReference)("60d150d7b5bcb81ffdc547b9e6237da6230457581d",s.callServer,void 0,s.findSourceMapURL,"searchHookActivityAction"),v=(0,s.createServerReference)("008e1c49d3beb0c15d7aa52742e3e0f6e7c618079d",s.callServer,void 0,s.findSourceMapURL,"getHooksConfigAction"),w=(0,s.createServerReference)("60c9a6cc3c2510a46405e330f7a9d1d6a9ef6db843",s.callServer,void 0,s.findSourceMapURL,"togglePolicyAction"),x=(0,s.createServerReference)("60d1bf56081277520b164ddfc66317962301f9b18b",s.callServer,void 0,s.findSourceMapURL,"installHooksWebAction"),y=(0,s.createServerReference)("60510d06a1277a0e2391d6723e0d0ac41fbfafb09c",s.callServer,void 0,s.findSourceMapURL,"removeHooksWebAction"),z=(0,s.createServerReference)("60f8afd76ad0ef7224d2ccfb28fcb21e8152fab6f2",s.callServer,void 0,s.findSourceMapURL,"updatePolicyParamsAction");var A=a.i(6236),B=a.i(90619),C=a.i(95947),D=a.i(87256),E=a.i(40695);function F({sessionId:a,transcriptPath:c,integration:d,cwd:f}){if(!a)return(0,b.jsx)("span",{className:"text-muted-foreground",children:"\\u2014"});let g=a?a.slice(0,8):"—",h="codex"===d||(c?.includes("/.codex/")??!1),i="copilot"===d||(c?.includes("/.copilot/session-state/")??!1),j="cursor"===d||(c?.includes("/.cursor/")??!1),k="opencode"===d||(c?.includes("/.local/share/opencode/")??!1)||(c?.includes("/.opencode/")??!1),l="pi"===d||(c?.includes("/.pi/")??!1),m="gemini"===d||(c?.includes("/.gemini/")??!1);if(h||i||j||k||l||m){let c,d=f?(c=/^([A-Za-z]):[\\/](.*)$/.exec(f))?c[1]+"--"+c[2].replace(/[\\/]/g,"-"):f.replace(/[\\/]/g,"-"):h?"codex":i?"copilot":j?"cursor":k?"opencode":l?"pi":"gemini";return(0,b.jsx)(e.default,{href:`/project/${encodeURIComponent(d)}/session/${encodeURIComponent(a)}`,className:"text-primary hover:underline font-mono",onClick:a=>a.stopPropagation(),children:g})}let n=c?function(a){let b=a.replace(/\\/g,"/").split("/").filter(Boolean);if(b.length<2)return null;let c=b[b.length-2];return!c||c.startsWith(".")?null:c}(c):null;return n?(0,b.jsx)(e.default,{href:`/project/${encodeURIComponent(n)}/session/${encodeURIComponent(a)}`,className:"text-primary hover:underline font-mono",onClick:a=>a.stopPropagation(),children:g}):(0,b.jsx)("span",{className:"text-muted-foreground font-mono",children:g})}function G({decision:a}){return"deny"===a?(0,b.jsxs)("span",{className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[0.65rem] font-semibold tracking-wide uppercase bg-red-500/10 text-red-400 border border-red-500/20",children:[(0,b.jsx)(i,{className:"h-3 w-3"}),"Deny"]}):"instruct"===a?(0,b.jsxs)("span",{className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[0.65rem] font-semibold tracking-wide uppercase bg-amber-500/10 text-amber-400 border border-amber-500/20",children:[(0,b.jsx)(j,{className:"h-3 w-3"}),"Instruct"]}):(0,b.jsxs)("span",{className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[0.65rem] font-semibold tracking-wide uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",children:[(0,b.jsx)(h,{className:"h-3 w-3"}),"Allow"]})}function H({eventType:a}){return(0,b.jsx)("span",{className:"inline-flex items-center rounded px-1.5 py-0.5 text-[0.6rem] font-medium bg-muted text-muted-foreground border border-border/50",children:a})}function I({integration:a}){if(!a)return null;let c=(0,D.getCliLabel)(a),d=(0,D.getCliBadgeClasses)(a);return(0,b.jsx)("span",{className:`inline-flex items-center rounded px-1.5 py-0.5 text-[0.6rem] font-medium border ${d}`,title:`Agent CLI: ${c}`,children:c})}function J({mode:a}){let c="default"===a;return(0,b.jsx)("span",{className:`inline-flex items-center rounded px-1.5 py-0.5 text-[0.6rem] font-medium border ${c?"bg-sky-500/10 text-sky-400 border-sky-500/20":"bg-amber-500/10 text-amber-400 border-amber-500/20"}`,children:a})}function K({ms:a}){return(0,b.jsx)("span",{className:`font-mono text-[0.7rem] ${a>500?"text-red-400":a>100?"text-amber-400":"text-muted-foreground"}`,children:a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`})}function L({text:a}){let[d,e]=(0,c.useState)(!1),f=async b=>{b.stopPropagation();try{await navigator.clipboard.writeText(a),e(!0),setTimeout(()=>e(!1),1500)}catch{let b=document.createElement("textarea");b.value=a,b.style.position="fixed",b.style.opacity="0",document.body.appendChild(b),b.select(),document.execCommand("copy"),document.body.removeChild(b),e(!0),setTimeout(()=>e(!1),1500)}};return(0,b.jsx)("button",{onClick:f,className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:d?(0,b.jsx)(n.Check,{className:"h-3 w-3 text-emerald-400"}):(0,b.jsx)(m.Copy,{className:"h-3 w-3"})})}function M({value:a,onChange:c}){return(0,b.jsx)("div",{className:"inline-flex items-center rounded-md border border-border bg-muted/30 p-0.5",children:[{label:"All",value:""},{label:"Allow",value:"allow"},{label:"Instruct",value:"instruct"},{label:"Deny",value:"deny"}].map(d=>(0,b.jsx)("button",{onClick:()=>c(d.value),className:`px-2.5 py-1 text-[0.65rem] font-medium rounded transition-all ${a===d.value?"deny"===d.value?"bg-red-500/15 text-red-400 shadow-sm":"allow"===d.value?"bg-emerald-500/15 text-emerald-400 shadow-sm":"instruct"===d.value?"bg-amber-500/15 text-amber-400 shadow-sm":"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:d.label},d.value))})}function N({stats:a}){let c=a.totalEvents>0?(a.denyCount/a.totalEvents*100).toFixed(0):"0";return(0,b.jsxs)("div",{className:"flex items-center gap-6 text-[0.7rem] text-muted-foreground",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-foreground font-mono font-semibold",children:a.totalEvents})," total events"]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:`font-mono font-semibold ${a.denyCount>0?"text-red-400":"text-foreground"}`,children:[c,"%"]})," ","deny rate"]}),(0,b.jsxs)("div",{className:"hidden sm:block",children:["top policy:"," ",(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.topPolicy??"—"})]})]})}function O({item:a}){return(0,b.jsx)("tr",{children:(0,b.jsx)("td",{colSpan:10,className:"px-0 py-0",children:(0,b.jsxs)("div",{className:"px-6 py-3 bg-muted/20 border-t border-border/30 space-y-2 text-xs animate-expand",children:[(0,b.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-1.5",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Session ID: "}),(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.sessionId??"—"}),a.sessionId&&(0,b.jsx)(L,{text:a.sessionId})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"CWD: "}),(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.cwd??"—"}),a.cwd&&(0,b.jsx)(L,{text:a.cwd})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Transcript: "}),(0,b.jsx)("span",{className:"font-mono text-foreground break-all",children:a.transcriptPath??"—"})]})]}),a.policyNames&&a.policyNames.length>1&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Policies: "}),(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.policyNames.join(", ")})]}),a.reason&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Full reason: "}),(0,b.jsx)("span",{className:"text-foreground",children:a.reason})]})]})})})}function P({hooksInstalled:a,onSwitchTab:d}){let{intervalSec:e}=(0,A.useAutoRefresh)(),f=(0,B.useUrlParams)(),g=(0,c.useRef)(!1),[h,i]=(0,c.useState)(()=>(0,C.paramToPage)(f.get("page"))),[j,m]=(0,c.useState)(null),[n,o]=(0,c.useState)(null),[p,q]=(0,c.useState)(()=>{let a=f.get("decision");return"allow"===a||"deny"===a||"instruct"===a?a:""}),[s,v]=(0,c.useState)(()=>f.get("event")??""),[w,x]=(0,c.useState)(()=>f.get("policy")??""),[y,z]=(0,c.useState)(()=>f.get("session")??""),[E,L]=(0,c.useState)(()=>{let a=f.get("cli");return(0,D.isKnownCli)(a)?a:""}),Q=(0,c.useRef)(null),R=(0,c.useRef)({filterDecision:p,filterEventType:s,filterPolicy:w,filterSessionId:y,filterCli:E});R.current={filterDecision:p,filterEventType:s,filterPolicy:w,filterSessionId:y,filterCli:E},(0,c.useEffect)(()=>{if(!g.current){g.current=!0;return}f.setAll({decision:p||void 0,event:s||void 0,policy:w||void 0,session:y||void 0,cli:E||void 0,page:(0,C.pageToParam)(h)})},[p,s,w,y,E,h]);let S=""!==p||""!==s||""!==w||""!==y||""!==E,T=(0,c.useCallback)(async a=>{try{let b,{filterDecision:c,filterEventType:d,filterPolicy:e,filterSessionId:f,filterCli:g}=R.current;b=""!==c||""!==d||""!==e||""!==f||""!==g?await u({decision:c||void 0,eventType:d||void 0,policyName:e||void 0,sessionId:f||void 0,integration:g||void 0},a):await t(a),m(b)}catch{}},[]);(0,c.useEffect)(()=>{T(h);let a=setInterval(()=>T(h),e>0?1e3*e:5e3);return()=>clearInterval(a)},[h,T,e]),(0,c.useEffect)(()=>(Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{i(1),o(null),T(1)},300),()=>{Q.current&&clearTimeout(Q.current)}),[p,s,w,y,E]);let U=j?.entries??[],V=j?.totalPages??1;return(0,b.jsxs)(b.Fragment,{children:[j?.stats&&j.stats.totalEvents>0&&(0,b.jsx)("div",{className:"mb-4",children:(0,b.jsx)(N,{stats:j.stats})}),(0,b.jsxs)("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-4 py-2.5 border-b border-border bg-muted/20",children:[(0,b.jsx)(M,{value:p,onChange:q}),(0,b.jsxs)("select",{value:s,onChange:a=>v(a.target.value),className:"h-7 rounded-md border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow",children:[(0,b.jsx)("option",{value:"",children:"All Events"}),(0,b.jsx)("option",{value:"PreToolUse",children:"PreToolUse"}),(0,b.jsx)("option",{value:"PostToolUse",children:"PostToolUse"}),(0,b.jsx)("option",{value:"SessionStart",children:"SessionStart"}),(0,b.jsx)("option",{value:"SessionEnd",children:"SessionEnd"}),(0,b.jsx)("option",{value:"UserPromptSubmit",children:"UserPromptSubmit"}),(0,b.jsx)("option",{value:"PermissionRequest",children:"PermissionRequest"})]}),(0,b.jsxs)("select",{value:E,onChange:a=>{let b=a.target.value;L(""===b||(0,D.isKnownCli)(b)?b:"")},className:"h-7 rounded-md border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow","aria-label":"Filter by CLI",children:[(0,b.jsx)("option",{value:"",children:"All CLIs"}),D.KNOWN_CLI_IDS.map(a=>(0,b.jsx)("option",{value:a,children:(0,D.getCliLabel)(a)},a))]}),(0,b.jsx)("div",{className:"relative",children:(0,b.jsx)("input",{type:"text",value:w,onChange:a=>x(a.target.value),placeholder:"Filter by policy\\u2026",className:"h-7 rounded-md border border-border bg-background px-2.5 text-xs text-foreground placeholder:text-muted-foreground w-44 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow"})}),(0,b.jsx)("div",{className:"relative",children:(0,b.jsx)("input",{type:"text",value:y,onChange:a=>z(a.target.value),placeholder:"Filter by session…",className:"h-7 rounded-md border border-border bg-background px-2.5 text-xs text-foreground placeholder:text-muted-foreground w-44 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow"})})]}),0===U.length?(0,b.jsxs)("div",{className:"flex flex-col items-center justify-center py-16 px-4 text-center",children:[(0,b.jsx)(k.Shield,{className:"h-12 w-12 text-muted-foreground/30"}),!1===a?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("p",{className:"text-sm text-muted-foreground mt-4 font-medium",children:"Policies are not installed"}),(0,b.jsxs)("p",{className:"text-xs text-muted-foreground mt-1 max-w-sm",children:["Go to the"," ",(0,b.jsx)("button",{className:"underline hover:text-foreground transition-colors",onClick:()=>d?.("policies"),children:"Policies tab"})," ","and click ",(0,b.jsx)("span",{className:"font-mono bg-muted px-1 rounded",children:"Install"})," to enable policy monitoring."]})]}):(0,b.jsx)("p",{className:"text-sm text-muted-foreground mt-4",children:S?"No matching activity.":"Waiting for hook events…"})]}):(0,b.jsx)("div",{className:"overflow-x-auto",children:(0,b.jsxs)("table",{className:"w-full text-xs",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{className:"text-left text-muted-foreground border-b border-border bg-muted/30",children:[(0,b.jsx)("th",{className:"px-4 py-2.5 font-medium w-6"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Decision"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Event"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"CLI"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Tool"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Policy"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Reason"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Duration"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Session"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Mode"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium text-right",children:"Time"})]})}),(0,b.jsx)("tbody",{className:"divide-y divide-border/30",children:U.map((a,d)=>{var e;let f,g="deny"===a.decision,h=n===d,i="instruct"===a.decision;return(0,b.jsxs)(c.default.Fragment,{children:[(0,b.jsxs)("tr",{onClick:()=>{o(a=>a===d?null:d)},className:`cursor-pointer transition-colors ${g?"bg-red-500/[0.03] hover:bg-red-500/[0.07] border-l-2 border-l-red-500/40":i?"bg-amber-500/[0.03] hover:bg-amber-500/[0.07] border-l-2 border-l-amber-500/40":d%2==0?"hover:bg-muted/30":"bg-muted/[0.04] hover:bg-muted/30"} ${h?"bg-muted/20":""}`,children:[(0,b.jsx)("td",{className:"px-4 py-2",children:(0,b.jsx)(l.ChevronDown,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform duration-150 ${h?"rotate-0":"-rotate-90"}`})}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(G,{decision:a.decision})}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(H,{eventType:a.eventType})}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(I,{integration:a.integration})}),(0,b.jsx)("td",{className:"px-3 py-2 font-mono text-foreground",children:a.toolName??"—"}),(0,b.jsx)("td",{className:"px-3 py-2 font-mono text-foreground",children:a.policyNames&&a.policyNames.length>1?(0,b.jsxs)("span",{title:a.policyNames.join(", "),children:[a.policyNames[0],(0,b.jsxs)("span",{className:"text-muted-foreground text-[0.6rem]",children:[" +",a.policyNames.length-1]})]}):a.policyName??"—"}),(0,b.jsx)("td",{className:"px-3 py-2 text-muted-foreground truncate max-w-[240px]",title:a.reason??"",children:a.reason??"—"}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(K,{ms:a.durationMs})}),(0,b.jsx)("td",{className:"px-3 py-2",title:a.sessionId??"",children:(0,b.jsx)(F,{sessionId:a.sessionId,transcriptPath:a.transcriptPath,integration:a.integration,cwd:a.cwd})}),(0,b.jsx)("td",{className:"px-3 py-2",children:a.permissionMode?(0,b.jsx)(J,{mode:a.permissionMode}):"—"}),(0,b.jsx)("td",{className:"px-3 py-2 text-right text-muted-foreground whitespace-nowrap",title:new Date(a.timestamp).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}),children:(e=a.timestamp,(f=Date.now()-e)<6e4?`${Math.max(1,Math.floor(f/1e3))}s ago`:f<36e5?`${Math.floor(f/6e4)}m ago`:f<864e5?`${Math.floor(f/36e5)}h ago`:`${Math.floor(f/864e5)}d ago`)})]}),h&&(0,b.jsx)(O,{item:a})]},`${a.timestamp}-${d}`)})})]})}),(0,b.jsx)(r.default,{currentPage:h,totalPages:V,onPageChange:a=>{i(a),o(null)}})]})]})}function Q({enabled:a,onChange:c,disabled:d}){return(0,b.jsx)("button",{onClick:c,disabled:d,className:`relative inline-flex h-4 w-7 shrink-0 items-center rounded-full transition-colors disabled:opacity-40 ${a?"bg-emerald-500":"bg-muted-foreground/30"}`,"aria-label":a?"Disable policy":"Enable policy",children:(0,b.jsx)("span",{className:`inline-block h-3 w-3 rounded-full bg-white shadow transition-transform ${a?"translate-x-3.5":"translate-x-0.5"}`})})}function R({policy:a,onClose:d,onSave:e}){let f=a.params??{},g=a.currentParams??{},[h,i]=(0,c.useState)(()=>{let a={};for(let[b,c]of Object.entries(f)){let d=b in g?g[b]:c.default;a[b]=d}return a});(0,c.useEffect)(()=>{let a=a=>{"Escape"===a.key&&d()};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[d]);let j=(a,b)=>{i(c=>({...c,[a]:b}))};return(0,b.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:a=>{a.target===a.currentTarget&&d()},children:(0,b.jsxs)("div",{className:"bg-card border border-border rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col",children:[(0,b.jsxs)("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("p",{className:"text-sm font-mono font-semibold text-foreground",children:a.name}),(0,b.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:a.description})]}),(0,b.jsx)("button",{onClick:d,className:"text-muted-foreground hover:text-foreground transition-colors",children:(0,b.jsx)(q.X,{className:"h-4 w-4"})})]}),(0,b.jsx)("div",{className:"overflow-y-auto flex-1 px-4 py-4 space-y-4",children:Object.entries(f).map(([a,c])=>(0,b.jsxs)("div",{children:[(0,b.jsx)("label",{className:"block text-xs font-semibold text-foreground mb-1 font-mono",children:a}),(0,b.jsx)("p",{className:"text-[0.65rem] text-muted-foreground mb-1.5",children:c.description}),((a,c)=>{let d=h[a];if("boolean"===c.type)return(0,b.jsxs)("label",{className:"flex items-center gap-2 cursor-pointer",children:[(0,b.jsx)("input",{type:"checkbox",checked:!!d,onChange:b=>j(a,b.target.checked),className:"rounded border-border"}),(0,b.jsx)("span",{className:"text-xs text-muted-foreground",children:c.description})]});if("number"===c.type)return(0,b.jsx)("input",{type:"number",value:"number"==typeof d?d:"",onChange:b=>j(a,Number(b.target.value)),className:"w-full h-7 rounded border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40"});if("string[]"===c.type){let c=Array.isArray(d)?d.join("\n"):"";return(0,b.jsx)("textarea",{value:c,onChange:b=>j(a,b.target.value.split("\n").filter(a=>""!==a.trim())),rows:4,placeholder:"One entry per line",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground font-mono focus:outline-none focus:ring-2 focus:ring-primary/40 resize-y"})}if("pattern[]"===c.type){let c=Array.isArray(d)?d:[];return(0,b.jsxs)("div",{className:"space-y-1.5",children:[c.map((d,e)=>(0,b.jsxs)("div",{className:"flex gap-1.5 items-center",children:[(0,b.jsx)("input",{type:"text",value:d.regex,onChange:b=>{let d=[...c];d[e]={...d[e],regex:b.target.value},j(a,d)},placeholder:"regex",className:"flex-1 h-6 rounded border border-border bg-background px-2 text-xs font-mono focus:outline-none focus:ring-2 focus:ring-primary/40"}),(0,b.jsx)("input",{type:"text",value:d.label,onChange:b=>{let d=[...c];d[e]={...d[e],label:b.target.value},j(a,d)},placeholder:"label",className:"flex-1 h-6 rounded border border-border bg-background px-2 text-xs focus:outline-none focus:ring-2 focus:ring-primary/40"}),(0,b.jsx)("button",{onClick:()=>j(a,c.filter((a,b)=>b!==e)),className:"text-muted-foreground/50 hover:text-destructive transition-colors",children:(0,b.jsx)(q.X,{className:"h-3.5 w-3.5"})})]},e)),(0,b.jsx)("button",{onClick:()=>j(a,[...c,{regex:"",label:""}]),className:"text-xs text-primary hover:underline",children:"+ Add pattern"})]})}return(0,b.jsx)("input",{type:"text",value:"string"==typeof d?d:"",onChange:b=>j(a,b.target.value),className:"w-full h-7 rounded border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40"})})(a,c)]},a))}),(0,b.jsxs)("div",{className:"flex items-center justify-end gap-2 px-4 py-3 border-t border-border",children:[(0,b.jsx)(E.Button,{variant:"outline",size:"sm",onClick:d,className:"h-7 text-xs",children:"Cancel"}),(0,b.jsx)(E.Button,{size:"sm",onClick:()=>e(h),className:"h-7 text-xs",children:"Save"})]})]})})}function S({message:a,onDismiss:c,onInstall:e,isPending:f}){return(0,d.createPortal)((0,b.jsxs)("div",{className:"fixed top-4 right-4 z-[9999] w-full max-w-sm",style:{animation:"slideInFromRight 0.25s ease-out"},children:[(0,b.jsx)("style",{children:`
1
+ module.exports=[22712,a=>{"use strict";var b=a.i(87924),c=a.i(72131),d=a.i(35112),e=a.i(38246),f=a.i(64831);let g=(0,f.default)("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]),h=(0,f.default)("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),i=(0,f.default)("shield-x",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]),j=(0,f.default)("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);var k=a.i(14258),l=a.i(89027),m=a.i(85650),n=a.i(52562);let o=(0,f.default)("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),p=(0,f.default)("code",[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]]);var q=a.i(74215),r=a.i(65967),s=a.i(5050);let t=(0,s.createServerReference)("403eae75122453abcf4043a6ec0d83422ce1d566d8",s.callServer,void 0,s.findSourceMapURL,"getHookActivityAction"),u=(0,s.createServerReference)("60139a5cfb4041468f75d94ed2d3844ae7e54239ef",s.callServer,void 0,s.findSourceMapURL,"searchHookActivityAction"),v=(0,s.createServerReference)("0022bda48482e2c9352c97c9845e258d56bd830798",s.callServer,void 0,s.findSourceMapURL,"getHooksConfigAction"),w=(0,s.createServerReference)("60ec93dd49cc6d89d397256d8b8334133f48d956f5",s.callServer,void 0,s.findSourceMapURL,"togglePolicyAction"),x=(0,s.createServerReference)("600b7af2458583811412d5e0dca5bbd0bc36f00fe9",s.callServer,void 0,s.findSourceMapURL,"installHooksWebAction"),y=(0,s.createServerReference)("6018f6122b7c280233bc69af539d4f7f2a4810ebfb",s.callServer,void 0,s.findSourceMapURL,"removeHooksWebAction"),z=(0,s.createServerReference)("600436cb402b818ebe8a60d93914ad001794fbd262",s.callServer,void 0,s.findSourceMapURL,"updatePolicyParamsAction");var A=a.i(6236),B=a.i(90619),C=a.i(95947),D=a.i(87256),E=a.i(40695);function F({sessionId:a,transcriptPath:c,integration:d,cwd:f}){if(!a)return(0,b.jsx)("span",{className:"text-muted-foreground",children:"\\u2014"});let g=a?a.slice(0,8):"—",h="codex"===d||(c?.includes("/.codex/")??!1),i="copilot"===d||(c?.includes("/.copilot/session-state/")??!1),j="cursor"===d||(c?.includes("/.cursor/")??!1),k="opencode"===d||(c?.includes("/.local/share/opencode/")??!1)||(c?.includes("/.opencode/")??!1),l="pi"===d||(c?.includes("/.pi/")??!1),m="gemini"===d||(c?.includes("/.gemini/")??!1);if(h||i||j||k||l||m){let c,d=f?(c=/^([A-Za-z]):[\\/](.*)$/.exec(f))?c[1]+"--"+c[2].replace(/[\\/]/g,"-"):f.replace(/[\\/]/g,"-"):h?"codex":i?"copilot":j?"cursor":k?"opencode":l?"pi":"gemini";return(0,b.jsx)(e.default,{href:`/project/${encodeURIComponent(d)}/session/${encodeURIComponent(a)}`,className:"text-primary hover:underline font-mono",onClick:a=>a.stopPropagation(),children:g})}let n=c?function(a){let b=a.replace(/\\/g,"/").split("/").filter(Boolean);if(b.length<2)return null;let c=b[b.length-2];return!c||c.startsWith(".")?null:c}(c):null;return n?(0,b.jsx)(e.default,{href:`/project/${encodeURIComponent(n)}/session/${encodeURIComponent(a)}`,className:"text-primary hover:underline font-mono",onClick:a=>a.stopPropagation(),children:g}):(0,b.jsx)("span",{className:"text-muted-foreground font-mono",children:g})}function G({decision:a}){return"deny"===a?(0,b.jsxs)("span",{className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[0.65rem] font-semibold tracking-wide uppercase bg-red-500/10 text-red-400 border border-red-500/20",children:[(0,b.jsx)(i,{className:"h-3 w-3"}),"Deny"]}):"instruct"===a?(0,b.jsxs)("span",{className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[0.65rem] font-semibold tracking-wide uppercase bg-amber-500/10 text-amber-400 border border-amber-500/20",children:[(0,b.jsx)(j,{className:"h-3 w-3"}),"Instruct"]}):(0,b.jsxs)("span",{className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-[0.65rem] font-semibold tracking-wide uppercase bg-emerald-500/10 text-emerald-400 border border-emerald-500/20",children:[(0,b.jsx)(h,{className:"h-3 w-3"}),"Allow"]})}function H({eventType:a}){return(0,b.jsx)("span",{className:"inline-flex items-center rounded px-1.5 py-0.5 text-[0.6rem] font-medium bg-muted text-muted-foreground border border-border/50",children:a})}function I({integration:a}){if(!a)return null;let c=(0,D.getCliLabel)(a),d=(0,D.getCliBadgeClasses)(a);return(0,b.jsx)("span",{className:`inline-flex items-center rounded px-1.5 py-0.5 text-[0.6rem] font-medium border ${d}`,title:`Agent CLI: ${c}`,children:c})}function J({mode:a}){let c="default"===a;return(0,b.jsx)("span",{className:`inline-flex items-center rounded px-1.5 py-0.5 text-[0.6rem] font-medium border ${c?"bg-sky-500/10 text-sky-400 border-sky-500/20":"bg-amber-500/10 text-amber-400 border-amber-500/20"}`,children:a})}function K({ms:a}){return(0,b.jsx)("span",{className:`font-mono text-[0.7rem] ${a>500?"text-red-400":a>100?"text-amber-400":"text-muted-foreground"}`,children:a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`})}function L({text:a}){let[d,e]=(0,c.useState)(!1),f=async b=>{b.stopPropagation();try{await navigator.clipboard.writeText(a),e(!0),setTimeout(()=>e(!1),1500)}catch{let b=document.createElement("textarea");b.value=a,b.style.position="fixed",b.style.opacity="0",document.body.appendChild(b),b.select(),document.execCommand("copy"),document.body.removeChild(b),e(!0),setTimeout(()=>e(!1),1500)}};return(0,b.jsx)("button",{onClick:f,className:"inline-flex items-center justify-center h-5 w-5 rounded hover:bg-muted/50 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:d?(0,b.jsx)(n.Check,{className:"h-3 w-3 text-emerald-400"}):(0,b.jsx)(m.Copy,{className:"h-3 w-3"})})}function M({value:a,onChange:c}){return(0,b.jsx)("div",{className:"inline-flex items-center rounded-md border border-border bg-muted/30 p-0.5",children:[{label:"All",value:""},{label:"Allow",value:"allow"},{label:"Instruct",value:"instruct"},{label:"Deny",value:"deny"}].map(d=>(0,b.jsx)("button",{onClick:()=>c(d.value),className:`px-2.5 py-1 text-[0.65rem] font-medium rounded transition-all ${a===d.value?"deny"===d.value?"bg-red-500/15 text-red-400 shadow-sm":"allow"===d.value?"bg-emerald-500/15 text-emerald-400 shadow-sm":"instruct"===d.value?"bg-amber-500/15 text-amber-400 shadow-sm":"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:d.label},d.value))})}function N({stats:a}){let c=a.totalEvents>0?(a.denyCount/a.totalEvents*100).toFixed(0):"0";return(0,b.jsxs)("div",{className:"flex items-center gap-6 text-[0.7rem] text-muted-foreground",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-foreground font-mono font-semibold",children:a.totalEvents})," total events"]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:`font-mono font-semibold ${a.denyCount>0?"text-red-400":"text-foreground"}`,children:[c,"%"]})," ","deny rate"]}),(0,b.jsxs)("div",{className:"hidden sm:block",children:["top policy:"," ",(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.topPolicy??"—"})]})]})}function O({item:a}){return(0,b.jsx)("tr",{children:(0,b.jsx)("td",{colSpan:10,className:"px-0 py-0",children:(0,b.jsxs)("div",{className:"px-6 py-3 bg-muted/20 border-t border-border/30 space-y-2 text-xs animate-expand",children:[(0,b.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-1.5",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Session ID: "}),(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.sessionId??"—"}),a.sessionId&&(0,b.jsx)(L,{text:a.sessionId})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"CWD: "}),(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.cwd??"—"}),a.cwd&&(0,b.jsx)(L,{text:a.cwd})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Transcript: "}),(0,b.jsx)("span",{className:"font-mono text-foreground break-all",children:a.transcriptPath??"—"})]})]}),a.policyNames&&a.policyNames.length>1&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Policies: "}),(0,b.jsx)("span",{className:"font-mono text-foreground",children:a.policyNames.join(", ")})]}),a.reason&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"text-muted-foreground",children:"Full reason: "}),(0,b.jsx)("span",{className:"text-foreground",children:a.reason})]})]})})})}function P({hooksInstalled:a,onSwitchTab:d}){let{intervalSec:e}=(0,A.useAutoRefresh)(),f=(0,B.useUrlParams)(),g=(0,c.useRef)(!1),[h,i]=(0,c.useState)(()=>(0,C.paramToPage)(f.get("page"))),[j,m]=(0,c.useState)(null),[n,o]=(0,c.useState)(null),[p,q]=(0,c.useState)(()=>{let a=f.get("decision");return"allow"===a||"deny"===a||"instruct"===a?a:""}),[s,v]=(0,c.useState)(()=>f.get("event")??""),[w,x]=(0,c.useState)(()=>f.get("policy")??""),[y,z]=(0,c.useState)(()=>f.get("session")??""),[E,L]=(0,c.useState)(()=>{let a=f.get("cli");return(0,D.isKnownCli)(a)?a:""}),Q=(0,c.useRef)(null),R=(0,c.useRef)({filterDecision:p,filterEventType:s,filterPolicy:w,filterSessionId:y,filterCli:E});R.current={filterDecision:p,filterEventType:s,filterPolicy:w,filterSessionId:y,filterCli:E},(0,c.useEffect)(()=>{if(!g.current){g.current=!0;return}f.setAll({decision:p||void 0,event:s||void 0,policy:w||void 0,session:y||void 0,cli:E||void 0,page:(0,C.pageToParam)(h)})},[p,s,w,y,E,h]);let S=""!==p||""!==s||""!==w||""!==y||""!==E,T=(0,c.useCallback)(async a=>{try{let b,{filterDecision:c,filterEventType:d,filterPolicy:e,filterSessionId:f,filterCli:g}=R.current;b=""!==c||""!==d||""!==e||""!==f||""!==g?await u({decision:c||void 0,eventType:d||void 0,policyName:e||void 0,sessionId:f||void 0,integration:g||void 0},a):await t(a),m(b)}catch{}},[]);(0,c.useEffect)(()=>{T(h);let a=setInterval(()=>T(h),e>0?1e3*e:5e3);return()=>clearInterval(a)},[h,T,e]),(0,c.useEffect)(()=>(Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{i(1),o(null),T(1)},300),()=>{Q.current&&clearTimeout(Q.current)}),[p,s,w,y,E]);let U=j?.entries??[],V=j?.totalPages??1;return(0,b.jsxs)(b.Fragment,{children:[j?.stats&&j.stats.totalEvents>0&&(0,b.jsx)("div",{className:"mb-4",children:(0,b.jsx)(N,{stats:j.stats})}),(0,b.jsxs)("div",{className:"bg-card border border-border rounded-lg overflow-hidden",children:[(0,b.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-4 py-2.5 border-b border-border bg-muted/20",children:[(0,b.jsx)(M,{value:p,onChange:q}),(0,b.jsxs)("select",{value:s,onChange:a=>v(a.target.value),className:"h-7 rounded-md border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow",children:[(0,b.jsx)("option",{value:"",children:"All Events"}),(0,b.jsx)("option",{value:"PreToolUse",children:"PreToolUse"}),(0,b.jsx)("option",{value:"PostToolUse",children:"PostToolUse"}),(0,b.jsx)("option",{value:"SessionStart",children:"SessionStart"}),(0,b.jsx)("option",{value:"SessionEnd",children:"SessionEnd"}),(0,b.jsx)("option",{value:"UserPromptSubmit",children:"UserPromptSubmit"}),(0,b.jsx)("option",{value:"PermissionRequest",children:"PermissionRequest"})]}),(0,b.jsxs)("select",{value:E,onChange:a=>{let b=a.target.value;L(""===b||(0,D.isKnownCli)(b)?b:"")},className:"h-7 rounded-md border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow","aria-label":"Filter by CLI",children:[(0,b.jsx)("option",{value:"",children:"All CLIs"}),D.KNOWN_CLI_IDS.map(a=>(0,b.jsx)("option",{value:a,children:(0,D.getCliLabel)(a)},a))]}),(0,b.jsx)("div",{className:"relative",children:(0,b.jsx)("input",{type:"text",value:w,onChange:a=>x(a.target.value),placeholder:"Filter by policy\\u2026",className:"h-7 rounded-md border border-border bg-background px-2.5 text-xs text-foreground placeholder:text-muted-foreground w-44 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow"})}),(0,b.jsx)("div",{className:"relative",children:(0,b.jsx)("input",{type:"text",value:y,onChange:a=>z(a.target.value),placeholder:"Filter by session…",className:"h-7 rounded-md border border-border bg-background px-2.5 text-xs text-foreground placeholder:text-muted-foreground w-44 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary/40 transition-shadow"})})]}),0===U.length?(0,b.jsxs)("div",{className:"flex flex-col items-center justify-center py-16 px-4 text-center",children:[(0,b.jsx)(k.Shield,{className:"h-12 w-12 text-muted-foreground/30"}),!1===a?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("p",{className:"text-sm text-muted-foreground mt-4 font-medium",children:"Policies are not installed"}),(0,b.jsxs)("p",{className:"text-xs text-muted-foreground mt-1 max-w-sm",children:["Go to the"," ",(0,b.jsx)("button",{className:"underline hover:text-foreground transition-colors",onClick:()=>d?.("policies"),children:"Policies tab"})," ","and click ",(0,b.jsx)("span",{className:"font-mono bg-muted px-1 rounded",children:"Install"})," to enable policy monitoring."]})]}):(0,b.jsx)("p",{className:"text-sm text-muted-foreground mt-4",children:S?"No matching activity.":"Waiting for hook events…"})]}):(0,b.jsx)("div",{className:"overflow-x-auto",children:(0,b.jsxs)("table",{className:"w-full text-xs",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{className:"text-left text-muted-foreground border-b border-border bg-muted/30",children:[(0,b.jsx)("th",{className:"px-4 py-2.5 font-medium w-6"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Decision"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Event"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"CLI"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Tool"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Policy"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Reason"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Duration"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Session"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium",children:"Mode"}),(0,b.jsx)("th",{className:"px-3 py-2.5 font-medium text-right",children:"Time"})]})}),(0,b.jsx)("tbody",{className:"divide-y divide-border/30",children:U.map((a,d)=>{var e;let f,g="deny"===a.decision,h=n===d,i="instruct"===a.decision;return(0,b.jsxs)(c.default.Fragment,{children:[(0,b.jsxs)("tr",{onClick:()=>{o(a=>a===d?null:d)},className:`cursor-pointer transition-colors ${g?"bg-red-500/[0.03] hover:bg-red-500/[0.07] border-l-2 border-l-red-500/40":i?"bg-amber-500/[0.03] hover:bg-amber-500/[0.07] border-l-2 border-l-amber-500/40":d%2==0?"hover:bg-muted/30":"bg-muted/[0.04] hover:bg-muted/30"} ${h?"bg-muted/20":""}`,children:[(0,b.jsx)("td",{className:"px-4 py-2",children:(0,b.jsx)(l.ChevronDown,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform duration-150 ${h?"rotate-0":"-rotate-90"}`})}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(G,{decision:a.decision})}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(H,{eventType:a.eventType})}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(I,{integration:a.integration})}),(0,b.jsx)("td",{className:"px-3 py-2 font-mono text-foreground",children:a.toolName??"—"}),(0,b.jsx)("td",{className:"px-3 py-2 font-mono text-foreground",children:a.policyNames&&a.policyNames.length>1?(0,b.jsxs)("span",{title:a.policyNames.join(", "),children:[a.policyNames[0],(0,b.jsxs)("span",{className:"text-muted-foreground text-[0.6rem]",children:[" +",a.policyNames.length-1]})]}):a.policyName??"—"}),(0,b.jsx)("td",{className:"px-3 py-2 text-muted-foreground truncate max-w-[240px]",title:a.reason??"",children:a.reason??"—"}),(0,b.jsx)("td",{className:"px-3 py-2",children:(0,b.jsx)(K,{ms:a.durationMs})}),(0,b.jsx)("td",{className:"px-3 py-2",title:a.sessionId??"",children:(0,b.jsx)(F,{sessionId:a.sessionId,transcriptPath:a.transcriptPath,integration:a.integration,cwd:a.cwd})}),(0,b.jsx)("td",{className:"px-3 py-2",children:a.permissionMode?(0,b.jsx)(J,{mode:a.permissionMode}):"—"}),(0,b.jsx)("td",{className:"px-3 py-2 text-right text-muted-foreground whitespace-nowrap",title:new Date(a.timestamp).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}),children:(e=a.timestamp,(f=Date.now()-e)<6e4?`${Math.max(1,Math.floor(f/1e3))}s ago`:f<36e5?`${Math.floor(f/6e4)}m ago`:f<864e5?`${Math.floor(f/36e5)}h ago`:`${Math.floor(f/864e5)}d ago`)})]}),h&&(0,b.jsx)(O,{item:a})]},`${a.timestamp}-${d}`)})})]})}),(0,b.jsx)(r.default,{currentPage:h,totalPages:V,onPageChange:a=>{i(a),o(null)}})]})]})}function Q({enabled:a,onChange:c,disabled:d}){return(0,b.jsx)("button",{onClick:c,disabled:d,className:`relative inline-flex h-4 w-7 shrink-0 items-center rounded-full transition-colors disabled:opacity-40 ${a?"bg-emerald-500":"bg-muted-foreground/30"}`,"aria-label":a?"Disable policy":"Enable policy",children:(0,b.jsx)("span",{className:`inline-block h-3 w-3 rounded-full bg-white shadow transition-transform ${a?"translate-x-3.5":"translate-x-0.5"}`})})}function R({policy:a,onClose:d,onSave:e}){let f=a.params??{},g=a.currentParams??{},[h,i]=(0,c.useState)(()=>{let a={};for(let[b,c]of Object.entries(f)){let d=b in g?g[b]:c.default;a[b]=d}return a});(0,c.useEffect)(()=>{let a=a=>{"Escape"===a.key&&d()};return document.addEventListener("keydown",a),()=>document.removeEventListener("keydown",a)},[d]);let j=(a,b)=>{i(c=>({...c,[a]:b}))};return(0,b.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50",onClick:a=>{a.target===a.currentTarget&&d()},children:(0,b.jsxs)("div",{className:"bg-card border border-border rounded-lg shadow-xl w-full max-w-lg mx-4 max-h-[80vh] flex flex-col",children:[(0,b.jsxs)("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("p",{className:"text-sm font-mono font-semibold text-foreground",children:a.name}),(0,b.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:a.description})]}),(0,b.jsx)("button",{onClick:d,className:"text-muted-foreground hover:text-foreground transition-colors",children:(0,b.jsx)(q.X,{className:"h-4 w-4"})})]}),(0,b.jsx)("div",{className:"overflow-y-auto flex-1 px-4 py-4 space-y-4",children:Object.entries(f).map(([a,c])=>(0,b.jsxs)("div",{children:[(0,b.jsx)("label",{className:"block text-xs font-semibold text-foreground mb-1 font-mono",children:a}),(0,b.jsx)("p",{className:"text-[0.65rem] text-muted-foreground mb-1.5",children:c.description}),((a,c)=>{let d=h[a];if("boolean"===c.type)return(0,b.jsxs)("label",{className:"flex items-center gap-2 cursor-pointer",children:[(0,b.jsx)("input",{type:"checkbox",checked:!!d,onChange:b=>j(a,b.target.checked),className:"rounded border-border"}),(0,b.jsx)("span",{className:"text-xs text-muted-foreground",children:c.description})]});if("number"===c.type)return(0,b.jsx)("input",{type:"number",value:"number"==typeof d?d:"",onChange:b=>j(a,Number(b.target.value)),className:"w-full h-7 rounded border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40"});if("string[]"===c.type){let c=Array.isArray(d)?d.join("\n"):"";return(0,b.jsx)("textarea",{value:c,onChange:b=>j(a,b.target.value.split("\n").filter(a=>""!==a.trim())),rows:4,placeholder:"One entry per line",className:"w-full rounded border border-border bg-background px-2 py-1.5 text-xs text-foreground font-mono focus:outline-none focus:ring-2 focus:ring-primary/40 resize-y"})}if("pattern[]"===c.type){let c=Array.isArray(d)?d:[];return(0,b.jsxs)("div",{className:"space-y-1.5",children:[c.map((d,e)=>(0,b.jsxs)("div",{className:"flex gap-1.5 items-center",children:[(0,b.jsx)("input",{type:"text",value:d.regex,onChange:b=>{let d=[...c];d[e]={...d[e],regex:b.target.value},j(a,d)},placeholder:"regex",className:"flex-1 h-6 rounded border border-border bg-background px-2 text-xs font-mono focus:outline-none focus:ring-2 focus:ring-primary/40"}),(0,b.jsx)("input",{type:"text",value:d.label,onChange:b=>{let d=[...c];d[e]={...d[e],label:b.target.value},j(a,d)},placeholder:"label",className:"flex-1 h-6 rounded border border-border bg-background px-2 text-xs focus:outline-none focus:ring-2 focus:ring-primary/40"}),(0,b.jsx)("button",{onClick:()=>j(a,c.filter((a,b)=>b!==e)),className:"text-muted-foreground/50 hover:text-destructive transition-colors",children:(0,b.jsx)(q.X,{className:"h-3.5 w-3.5"})})]},e)),(0,b.jsx)("button",{onClick:()=>j(a,[...c,{regex:"",label:""}]),className:"text-xs text-primary hover:underline",children:"+ Add pattern"})]})}return(0,b.jsx)("input",{type:"text",value:"string"==typeof d?d:"",onChange:b=>j(a,b.target.value),className:"w-full h-7 rounded border border-border bg-background px-2 text-xs text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40"})})(a,c)]},a))}),(0,b.jsxs)("div",{className:"flex items-center justify-end gap-2 px-4 py-3 border-t border-border",children:[(0,b.jsx)(E.Button,{variant:"outline",size:"sm",onClick:d,className:"h-7 text-xs",children:"Cancel"}),(0,b.jsx)(E.Button,{size:"sm",onClick:()=>e(h),className:"h-7 text-xs",children:"Save"})]})]})})}function S({message:a,onDismiss:c,onInstall:e,isPending:f}){return(0,d.createPortal)((0,b.jsxs)("div",{className:"fixed top-4 right-4 z-[9999] w-full max-w-sm",style:{animation:"slideInFromRight 0.25s ease-out"},children:[(0,b.jsx)("style",{children:`
2
2
  @keyframes slideInFromRight {
3
3
  from { transform: translateX(calc(100% + 1rem)); opacity: 0; }
4
4
  to { transform: translateX(0); opacity: 1; }
@@ -1,3 +1,3 @@
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,"/")}let j=a=>void 0===a?void 0:a.variant??a.enabled,k=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}};async function l(a,b=!0,c){try{let b=new CompressionStream("gzip"),c=b.writable.getWriter(),d=c.write(new TextEncoder().encode(a)).then(()=>c.close()).catch(async a=>{try{await c.abort(a)}catch{}throw a}),e=new Response(b.readable).blob(),[f]=await Promise.all([e,d]);return f}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}var m=((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.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.SurveyLastSeenDate="survey_last_seen_date",g.SurveysSeen="surveys_seen",g.Surveys="surveys",g.RemoteConfig="remote_config",g.FlagsEndpointWasHit="flags_endpoint_was_hit",g.DeviceId="device_id",g);let n={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}`},o=Array.isArray,p=Object.prototype;p.hasOwnProperty;let q=p.toString,r=o||function(a){return"[object Array]"===q.call(a)},s=a=>a===Object(a)&&!r(a),t=a=>"[object String]"==q.call(a),u=a=>"[object Number]"==q.call(a)&&a==a;function v(a){return null===a||"object"!=typeof a}function w(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function x(a){return"u">typeof Event&&function(a,b){try{return a instanceof b}catch{return!1}}(a,Event)}let y="Android",z="BlackBerry",A="Nintendo",B="PlayStation",C="Xbox",D="Windows",E="(\\d+(\\.\\d+)?)";RegExp("Version/"+E),RegExp(C,"i"),RegExp(B+" \\w+","i"),RegExp(A+" \\w+","i"),RegExp(z+"|PlayBook|BB10","i");async function F(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 G(){return new Date().toISOString()}function H(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}RegExp("rv:"+E),RegExp("Edge?\\/"+E),RegExp("(Chrome|CrMo)\\/"+E),RegExp("CriOS\\/"+E),RegExp("(UCBrowser|UCWEB)\\/"+E),RegExp("(Opera|OPR)\\/"+E),RegExp("Firefox\\/"+E),RegExp("FxiOS\\/"+E),RegExp("Konqueror[:/]?"+E,"i"),RegExp(z+" "+E),RegExp("android\\s"+E,"i"),RegExp("SamsungBrowser\\/"+E),RegExp("(rv:|MSIE )"+E),RegExp("rv:"+E),RegExp(C+"; "+C+" (.*?)[);]","i"),RegExp(A,"i"),RegExp(B,"i"),RegExp(D,"i"),RegExp("("+y+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+y+")","i");let I=a=>a instanceof Error;function J(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let K="0123456789abcdef";class L{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new L(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 L(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 L(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=K.charAt(this.bytes[b]>>>4),a+=K.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+=K.charAt(this.bytes[b]>>>4),a+=K.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 L(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 M{constructor(a){this.timestamp=0,this.counter=0,this.random=a??N()}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 L.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,L.ofInner(a)}}let N=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),O=()=>(b||(b=new M)).generate();class P{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)}}class Q{add(a){let b=O().toString();return this.promiseByIds[b]=a,a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds)).length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}let R=(a,b,c)=>{function d(e,...f){b(()=>{(0,c[e])(a,...f)})}return{info:(...a)=>{d("log",...a)},warn:(...a)=>{d("warn",...a)},error:(...a)=>{d("error",...a)},critical:(...b)=>{c.error(a,...b)},createLogger:d=>R(`${a} ${d}`,b,c)}};class S extends Error{constructor(a,b){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class T extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function U(a){if(a instanceof S){let b="";try{b=await a.text}catch{}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 V(a){return"object"==typeof a&&(a instanceof S||a instanceof T)}function W(a){return"object"==typeof a&&a instanceof S&&413===a.status}class X{constructor(a,b={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new Q,this._events=new P,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 R(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:V},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,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(m.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(m.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(m.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){return{distinct_id:a.distinct_id,event:a.event,properties:{...a.properties||{},...this.getCommonEventProperties()}}}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 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,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(a=>a.json()).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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,i,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(a=>a.json()).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,j(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?k(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,k(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 S)return{type:"api_error",statusCode:a.status};if(a instanceof T){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=j(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={};(e??this.disableGeoip)&&(g.geoip_disable=!0),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,!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).then(a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);this._logger.error(c),this._events.emit("error",Error(b));return}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(m.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(m.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(m.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}enqueue(a,b,c){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let d=this.prepareMessage(a,b,c);if(null===(d=this.processBeforeEnqueue(d)))return;let e=this.getPersistedProperty(m.Queue)||[];e.length>=this.maxQueueSize&&(e.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),e.push({message:d}),this.setPersistedProperty(m.Queue,e),this._events.emit(a,d),e.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=H(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c){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 d=this.prepareMessage(a,b,c);if(null===(d=this.processBeforeEnqueue(d)))return;let e={api_key:this.apiKey,batch:[d],sent_at:G()};this.historicalMigration&&(e.historical_migration=!0);let f=JSON.stringify(e),g=`${this.host}/batch/`,h=this.disableCompression?null:await l(f,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==h&&{"Content-Encoding":"gzip"}},body:h||f};try{await this.fetchWithRetry(g,i)}catch(a){this._events.emit("error",a)}}prepareMessage(a,b,c){let d={...b,type:a,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:c?.timestamp?c?.timestamp:G(),uuid:c?.uuid?c.uuid:O().toString()};return(c?.disableGeoip??this.disableGeoip)&&(d.properties||(d.properties={}),d.properties.$geoip_disable=!0),d.distinctId&&(d.distinct_id=d.distinctId,delete d.distinctId),d}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async a=>{await U(a)})}async flush(){let a=J([this.flushPromise]).then(()=>this._flush());return this.flushPromise=a,this.addPendingPromise(a),J([a]).then(()=>{this.flushPromise===a&&(this.flushPromise=null)}),a}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}async _flush(){this.clearFlushTimer(),await this._initPromise;let a=this.getPersistedProperty(m.Queue)||[];if(!a.length)return;let b=[],c=a.length;for(;a.length>0&&b.length<c;){let c=a.slice(0,this.maxBatchSize),d=c.map(a=>a.message),e=async()=>{let b=(this.getPersistedProperty(m.Queue)||[]).slice(c.length);this.setPersistedProperty(m.Queue,b),a=b,await this.flushStorage()},f={api_key:this.apiKey,batch:d,sent_at:G()};this.historicalMigration&&(f.historical_migration=!0);let g=JSON.stringify(f),h=`${this.host}/batch/`,i=this.disableCompression?null:await l(g,this.isDebug),j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==i&&{"Content-Encoding":"gzip"}},body:i||g},k={retryCheck:a=>!W(a)&&V(a)};try{await this.fetchWithRetry(h,j,k)}catch(a){if(W(a)&&d.length>1){this.maxBatchSize=Math.max(1,Math.floor(d.length/2)),this._logger.warn(`Received 413 when sending batch of size ${d.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof T||await e(),this._events.emit("error",a),a}await e(),b.push(...d)}this._events.emit("flush",b)}async fetchWithRetry(a,b,c,d){let e=b.body?b.body:"",f=-1;try{f=e instanceof Blob?e.size:Buffer.byteLength(e,"utf8")}catch{f=e instanceof Blob?e.size:new TextEncoder().encode(e).length}return await F(async()=>{let c=new AbortController,e=H(()=>c.abort(),d??this.requestTimeout),g=null;try{g=await this.fetch(a,{signal:c.signal,...b})}catch(a){throw new T(a)}finally{clearTimeout(e)}if("no-cors"!==b.mode&&(g.status<200||g.status>=400))throw new S(g,f);return g},{...this._retryOptions,...c})}async _shutdown(a=3e4){let b;await this._initPromise;let c=!1;this.clearFlushTimer();let d=async()=>{try{for(await this.promiseQueue.join();;){let a=this.getPersistedProperty(m.Queue)||[];if(0===a.length||(await this.flush(),c))break}}catch(a){if(!V(a))throw a;await U(a)}};try{return await Promise.race([new Promise((d,e)=>{b=H(()=>{this._logger.error("Timed out while shutting down PostHog"),c=!0,e("Timeout while shutting down PostHog. Some events may not have been sent.")},a)}),d()])}finally{clearTimeout(b)}}async shutdown(a=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class Y{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&r(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;return null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack&&(d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)),{...a,cause:c,stack:d}}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={type:a.type,value:a.value,mechanism:{type:b.type??"generic",handled:b.handled??!0,synthetic:a.synthetic??!1}};a.stack&&(c.stacktrace={type:"raw",frames:a.stack});let d=[c];return null!=a.cause&&d.push(...this.convertToExceptionList(a.cause,{...b,handled:!0})),d}buildParsingContext(a){return{chunkIdMap:function(a){let b=globalThis._posthogChunkIds;if(!b)return;let f=Object.keys(b);return e&&f.length===d?e:(d=f.length,e=f.reduce((d,e)=>{c||(c={});let f=c[e];if(f)d[f[0]]=f[1];else{let f=a(e);for(let a=f.length-1;a>=0;a--){let g=f[a],h=g?.filename,i=b[e];if(h&&i){d[h]=i,c[e]=[h,i];break}}}return d},{}))}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}buildCoercingContext(a,b,c=0){let d=(c,d)=>{if(d<=4){let e=this.buildCoercingContext(a,b,d);return this.applyCoercers(c,e)}};return{...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:a,apply:a=>d(a,c),next:a=>d(a,c+1)}}}function Z(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:!0};return void 0!==d&&(f.lineno=d),void 0!==e&&(f.colno=e),f}a.s(["ErrorPropertiesBuilder",0,Y],6762);let $=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},_=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,aa=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ab=/\((\S*)(?::(\d+))(?::(\d+))\)/,ac=(a,b)=>{let c=_.exec(a);if(c){let[,a,d,e]=c;return Z(b,a,"?",+d,+e)}let d=aa.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=ab.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=$(d[1]||"?",d[2]);return Z(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},ad=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ae=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,af=(a,b)=>{let c=ad.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=ae.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]=$(d,a),Z(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},ag=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ah=(a,b)=>{let c=ag.exec(a);return c?Z(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ai=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,aj=(a,b)=>{let c=ai.exec(a);return c?Z(b,c[2],c[3]||"?",+c[1]):void 0},ak=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,al=(a,b)=>{let c=ak.exec(a);return c?Z(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},am=/^\s*[-]{4,}$/,an=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ao=(a,b)=>{let c=a.match(an);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]),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:ap(c[3]),colno:ap(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(am))return{filename:a,platform:b}};function ap(a){return parseInt(a||"",10)||void 0}let aq=/\(error: (.*)\)/;function ar(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 as(){return at("web:javascript",ac,af)}function at(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n");for(let c=d;c<f.length;c++){let d=f[c];if(d.length>1024)continue;let g=aq.test(d)?d.replace(aq,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);break}}if(e.length>=50)break}}return ar(e)}}a.s(["createDefaultStackParser",0,as,"createStackParser",0,at,"reverseAndStripFrames",0,ar],67970);class au{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=t(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 w(a,"DOMException")}isDOMError(a){return w(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,au],51671);class av{match(a){return a instanceof Error}coerce(a,b){return{type:this.getType(a),value:this.getMessage(a,b),stack:this.getStack(a),cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}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){return a.stacktrace||a.stack||void 0}}a.s(["ErrorCoercer",0,av],10692);class aw{match(a){return w(a,"ErrorEvent")&&void 0!=a.error}coerce(a,b){let c=b.apply(a.error);return c||{type:"ErrorEvent",value:a.message,stack:b.syntheticException?.stack,synthetic:!0}}}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:b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){return x(a)?a.constructor.name:"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 t(a)&&!(t(a)&&0===a.trim().length)&&ax.indexOf(a)>=0}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(I(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 x(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 v(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 w(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!x(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 v(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(!u(a)||a===1/0||a===-1/0)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=function(a){let b=new WeakSet;try{return JSON.stringify(a,(a,c)=>{if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Date)return c.toISOString();if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){if(b.has(c))return"[Circular]";b.add(c)}return c}})}catch{return}}(a);if(b)try{let a=JSON.parse(b);if(!s(a))return;let c=a[aD.MESSAGE],d=a[aD.TIMESTAMP];if(!t(c)||0===c.trim().length||!t(d)&&!u(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,ac,"createDefaultStackParser",0,as,"createStackParser",0,at,"geckoStackLineParser",0,af,"nodeStackLineParser",0,ao,"opera10StackLineParser",0,aj,"opera11StackLineParser",0,al,"reverseAndStripFrames",0,ar,"winjsStackLineParser",0,ah],64583),a.i(64583),a.i(7610),a.i(51671),a.i(10692),a.i(75368);let aK=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aL{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(aK);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aL],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,au,"ErrorCoercer",0,av,"ErrorEventCoercer",0,aw,"EventCoercer",0,aA,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"StringCoercer",0,aL],54253),a.i(54253);class aM{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,aM],98966),a.i(98966),a.i(97383),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aF,"DOMExceptionCoercer",0,au,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aD,"ErrorCoercer",0,av,"ErrorEventCoercer",0,aw,"ErrorPropertiesBuilder",0,Y,"EventCoercer",0,aA,"ExceptionStepsBuffer",0,aI,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"ReduceableCache",0,aM,"StringCoercer",0,aL,"chromeStackLineParser",0,ac,"createDefaultStackParser",0,as,"createStackParser",0,at,"geckoStackLineParser",0,af,"getUtf8ByteLength",0,aJ,"nodeStackLineParser",0,ao,"opera10StackLineParser",0,aj,"opera11StackLineParser",0,al,"resolveExceptionStepsConfig",0,aG,"reverseAndStripFrames",0,ar,"stripReservedExceptionStepFields",0,aH,"winjsStackLineParser",0,ah],60485);var aN=a.i(60485),aO=aN,aP=a.i(2157),aQ=a.i(1457);let aR=new aO.ReduceableCache(25),aS=new aO.ReduceableCache(20);async function aT(a){let b={};for(let e=a.length-1;e>=0;e--){var c,d;let f=a[e],g=f?.filename;!(!f||"string"!=typeof g||"number"!=typeof f.lineno||(c=g).startsWith("node:")||c.endsWith(".min.js")||c.endsWith(".min.cjs")||c.endsWith(".min.mjs")||c.startsWith("data:")||void 0!==(d=f).lineno&&d.lineno>1e4||void 0!==d.colno&&d.colno>1e3)&&(b[g]||(b[g]=[]),b[g].push(f.lineno))}let e=Object.keys(b);if(0==e.length)return a;let f=[];for(let a of e){if(aS.get(a))continue;let c=b[a];if(!c)continue;c.sort((a,b)=>a-b);let d=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=aV(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=aV(c)),b++}return e}(c);if(d.every(b=>(function(a,b){let c=aR.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})(a,b)))continue;let e=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(aR,a,{});f.push(function(a,b,c){return new Promise(d=>{let e=(0,aP.createReadStream)(a),f=(0,aQ.createInterface)({input:e});function g(){e.destroy(),d()}let h=0,i=0,j=b[0];if(void 0===j)return void g();let k=j[0],l=j[1];function m(){aS.set(a,1),f.close(),f.removeAllListeners(),g()}e.on("error",m),f.on("error",m),f.on("close",g),f.on("line",a=>{if(!(++h<k)&&(c[h]=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),h>=l)){if(i===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++i];if(void 0===a){f.close(),f.removeAllListeners();return}k=a[0],l=a[1]}})})}(a,d,e))}return await Promise.all(f).catch(()=>{}),a&&a.length>0&&function(a,b){for(let c of a)if(c.filename&&void 0===c.context_line&&"number"==typeof c.lineno){let a=b.get(c.filename);if(void 0===a)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=aW(a);d<a;d++){let a=c[d];if(void 0===a)return void aU(b);b.pre_context.push(a)}if(void 0===c[a])return aU(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)}}(c.lineno,c,a)}}(a,aR),aR.reduce(),a}function aU(a){delete a.pre_context,delete a.context_line,delete a.post_context}function aV(a){return[aW(a),a+7]}function aW(a){return Math.max(1,a-7)}function aX(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),u(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),aX(e||c,b,c,d)}class aY{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=aX(a.bucketSize,0,100,a._logger),this._refillRate=aX(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=aX(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={}}}class aZ{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new aY({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return s(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d){let e={...d},f=this.errorPropertiesBuilder.buildFromUnknown(a,b);return f.$exception_list=await this.errorPropertiesBuilder.modifyFrames(f.$exception_list),{event:"$exception",distinctId:c,properties:{...f,...e},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var b,c,d;let e;b=this.onException.bind(this),c=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(e=!1,Object.assign(d=>{let f=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;b(d,{mechanism:{type:"onuncaughtexception",handled:!1}}),e||0!==f||(e=!0,c(d))},{_posthogErrorHandler:!0}))),d=this.onException.bind(this),globalThis.process?.on("unhandledRejection",a=>d(a,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(a,b){this.client.addPendingPromise((async()=>{if(!aZ.isPreviouslyCapturedError(a)){let c=await aZ.buildEventMessage(a,b),d=c.properties,e=d?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(e)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:e}):this.client.capture(c)}})())}async onFatalError(a){console.error(a),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}let a$=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],a_=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return a$.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})},a0={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};async function a1(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("")}a.s(["FeatureFlagError",0,a0],46539);let a2=["is_not"];class a3 extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,a3.prototype)}}class a4 extends Error{constructor(a){super(a),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,a4.prototype)}}class a5 extends Error{constructor(a){super(a),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,a5.prototype)}}class a6{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,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 a5||b instanceof a4?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 a5||b instanceof a4?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.ensure_experience_continuity)throw new a4("Flag has experience continuity enabled");if(!a.active)return!1;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 a4("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 a4(`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){let c=null;if(!1!==b&&null!=b&&("boolean"==typeof b?c=this.featureFlagsByKey?.[a]?.filters?.payloads?.[b.toString()]||null:"string"==typeof b&&(c=this.featureFlagsByKey?.[a]?.filters?.payloads?.[b]||null),null!=c)){if("object"==typeof c)return c;if("string"==typeof c)try{return JSON.parse(c)}catch{}return c}return null}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!this.featureFlagsByKey)throw new a4("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new a4(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new a4(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new a4(`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 a4(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else throw new a4(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new a4(`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=!1;for(let i of g)try{if(await this.isConditionMatch(a,b,i,c,d)){let c=i.variant,d=f.multivariate?.variants||[];e=c&&d.some(a=>a.key===c)?c:await this.getMatchingVariant(a,b)||!0;break}}catch(a){if(a instanceof a5)throw a;if(a instanceof a4)h=!0;else throw a}if(void 0!==e)return e;if(h)throw new a4("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;if(!("cohort"===b?function a(b,c,d,e=!1){let f=String(b.value);if(!(f in d))throw new a5(`cohort ${f} not found in local cohorts - likely a static cohort that requires server evaluation`);return function b(c,d,e,f=!1){if(!c)return!0;let g=c.type,h=c.values;if(!h||0===h.length)return!0;let i=!1;if("values"in h[0]){for(let a of h)try{let c=b(a,d,e,f);if("AND"===g){if(!c)return!1}else if(c)return!0}catch(b){if(b instanceof a5)throw b;if(b instanceof a4)f&&console.debug(`Failed to compute property ${a} locally: ${b}`),i=!0;else throw b}if(i)throw new a4("Can't match cohort without a given cohort property value");return"AND"===g}for(let b of h)try{let c;if("cohort"===b.type)c=a(b,d,e,f);else if("flag"===b.type){f&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${b.key||"unknown"}'`);continue}else c=a8(b,d);let h=b.negation||!1;if("AND"===g){if(!c&&!h||c&&h)return!1}else if(c&&!h||!c&&h)return!0}catch(a){if(a instanceof a5)throw a;if(a instanceof a4)f&&console.debug(`Failed to compute property ${b} locally: ${a}`),i=!0;else throw a}if(i)throw new a4("can't match cohort without a given cohort property value");return"AND"===g}(d[f],c,d,e)}(a,d,this.cohorts,this.debugMode):"flag"===b?await this.evaluateFlagDependency(a,d,e):a8(a,d,g)))return!1}if(void 0==f)return!0}return!(void 0!=f&&await a7(a.key,b)>f/100)}async getMatchingVariant(a,b){let c=await a7(a.key,b,"variant"),d=this.variantLookupTable(a).find(a=>c>=a.valueMin&&c<a.valueMax);if(d)return d.key}variantLookupTable(a){let b=[],c=0,d=0,e=a.filters||{};return(e.multivariate?.variants||[]).forEach(a=>{d=c+a.rollout_percentage/100,b.push({valueMin:c,valueMax:d,key:a.key}),c=d}),b}updateFlagState(a){this.featureFlags=a.flags,this.featureFlagsByKey=a.flags.reduce((a,b)=>(a[b.key]=b,a),{}),this.groupTypeMapping=a.groupTypeMapping,this.cohorts=a.cohorts,this.loadedSuccessfullyOnce=!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(b.flags),!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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 a3(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new a3(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new a3(`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||{}};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(d.flags);break}default:return}}catch(a){a instanceof a3&&this.onError?.(a)}}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}}_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=H(()=>{a.abort()},this.timeout),b.signal=a.signal}try{return(0,this.fetch)(a,b)}finally{clearTimeout(c)}}async stopPoller(a=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await Promise.race([b,new Promise((b,c)=>setTimeout(()=>c(Error(`Cache shutdown timeout after ${a}ms`)),a))])}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}async function a7(a,b,c=""){return parseInt((await a1(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function a8(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact";if(d in b){if("is_not_set"===f)throw new a4("Operator is_not_set is not supported")}else throw new a4(`Property ${d} not found in propertyValues`);let g=b[d];if(null==g&&!a2.includes(f))return c&&c(`Property ${d} cannot have a value of null/undefined with the ${f} operator`),!1;function h(a,b){return Array.isArray(a)?a.map(a=>String(a).toLowerCase()).includes(String(b).toLowerCase()):String(a).toLowerCase()===String(b).toLowerCase()}function i(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 h(e,g);case"is_not":return!h(e,g);case"is_set":return d in b;case"icontains":return String(g).toLowerCase().includes(String(e).toLowerCase());case"not_icontains":return!String(g).toLowerCase().includes(String(e).toLowerCase());case"regex":return a9(String(e))&&null!==String(g).match(String(e));case"not_regex":return a9(String(e))&&null===String(g).match(String(e));case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:null;if("string"==typeof e)try{a=parseFloat(e)}catch(a){}if(null==a||null==g)return i(String(g),String(e),f);if("string"==typeof g)return i(g,String(e),f);return i(g,a,f)}case"is_date_after":case"is_date_before":{if("boolean"==typeof e)throw new a4("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)return null;{if(!b.groups)return null;let a=parseInt(b.groups.number);if(a>=1e4)return null;let d=b.groups.interval;if("h"==d)c.setUTCHours(c.getUTCHours()-a);else if("d"==d)c.setUTCDate(c.getUTCDate()-a);else if("w"==d)c.setUTCDate(c.getUTCDate()-7*a);else if("m"==d)c.setUTCMonth(c.getUTCMonth()-a);else{if("y"!=d)return null;c.setUTCFullYear(c.getUTCFullYear()-a)}return c}}(String(e));if(null==a&&(a=bc(e)),null==a)throw new a4(`Invalid date: ${e}`);let b=bc(g);if(["is_date_before"].includes(f))return b<a;return b>a}case"semver_eq":return 0===bb(ba(String(g)),ba(String(e)));case"semver_neq":return 0!==bb(ba(String(g)),ba(String(e)));case"semver_gt":return bb(ba(String(g)),ba(String(e)))>0;case"semver_gte":return bb(ba(String(g)),ba(String(e)))>=0;case"semver_lt":return 0>bb(ba(String(g)),ba(String(e)));case"semver_lte":return 0>=bb(ba(String(g)),ba(String(e)));case"semver_tilde":{let a,b=ba(String(g)),{lower:c,upper:d}={lower:[(a=ba(String(e)))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return bb(b,c)>=0&&0>bb(b,d)}case"semver_caret":{let a=ba(String(g)),{lower:b,upper:c}=function(a){let[b,c,d]=ba(a);return{lower:[b,c,d],upper:b>0?[b+1,0,0]:c>0?[0,c+1,0]:[0,0,d+1]}}(String(e));return bb(a,b)>=0&&0>bb(a,c)}case"semver_wildcard":{let a=ba(String(g)),{lower:b,upper:c}=function(a){let b,c,d=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!d)throw new a4(`Invalid wildcard semver: ${a}`);let e=d.split("."),f=parseInt(e[0],10);if(isNaN(f))throw new a4(`Invalid wildcard semver: ${a}`);if(1===e.length)b=[f,0,0],c=[f+1,0,0];else{let d=parseInt(e[1],10);if(isNaN(d))throw new a4(`Invalid wildcard semver: ${a}`);b=[f,d,0],c=[f,d+1,0]}return{lower:b,upper:c}}(String(e));return bb(a,b)>=0&&0>bb(a,c)}default:throw new a4(`Unknown operator: ${f}`)}}function a9(a){try{return new RegExp(a),!0}catch(a){return!1}}function ba(a){let b=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!b||b.startsWith("."))throw new a4(`Invalid semver: ${a}`);let c=b.split("."),d=b=>{if(void 0===b||""===b)return 0;if(!/^\d+$/.test(b))throw new a4(`Invalid semver: ${a}`);return parseInt(b,10)};return[d(c[0]),d(c[1]),d(c[2])]}function bb(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 bc(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 a4(`${a} is in an invalid date format`)}throw new a4(`The date provided ${a} must be a string, number, or date object`)}class bd{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}class be extends X{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,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.personalApiKey)};if(super(c,d),this._memoryStorage=new bd,this.options=d,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)),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 a6({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)},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation}))}this.errorTracking=new aZ(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c){super.enqueue(a,b,c),this.scheduleDebouncedFlush()}async flush(){let a=super.flush(),b=this.options.waitUntil;if(b&&!this._waitUntilCycle)try{b(a.catch(()=>{}))}catch{}return a}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=H(()=>{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 super.flush()}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)}getLibraryVersion(){return"5.30.6"}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}capture(a){"string"==typeof a&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(a).then(({distinctId:a,event:b,properties:c,options:d})=>super.captureStateless(a,b,c,{timestamp:d.timestamp,disableGeoip:d.disableGeoip,uuid:d.uuid})).catch(a=>{a&&console.error(a)}))}async captureImmediate(a){return"string"==typeof a&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn("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.addPendingPromise(this.prepareEventMessage(a).then(({distinctId:a,event:b,properties:c,options:d})=>super.captureStatelessImmediate(a,b,c,{timestamp:d.timestamp,disableGeoip:d.disableGeoip,uuid:d.uuid})).catch(a=>{a&&console.error(a)}))}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;super.identifyStateless(a,{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},{disableGeoip:c})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;super.identifyStatelessImmediate(a,{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},{disableGeoip:c})}alias(a){super.aliasStateless(a.alias,a.distinctId,void 0,{disableGeoip:a.disableGeoip})}async aliasImmediate(a){await super.aliasStatelessImmediate(a.alias,a.distinctId,void 0,{disableGeoip:a.disableGeoip})}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=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:m,disableGeoip:n}=c,{onlyEvaluateLocally:o,personProperties:p,groupProperties:q}=c,r=this.addLocalPersonAndGroupProperties(b,m,p,q);p=r.allPersonProperties,q=r.allGroupProperties;let s=this.createFeatureFlagEvaluationContext(b,m,p,q);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let t=!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,s,{matchValue:d});if(c){t=!0;let d=c.value;i=b.id,k="Evaluated locally",e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0}}}catch(b){if(b instanceof a5||b instanceof a4)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!t&&!o){let b=await super.getFeatureFlagDetailsStateless(s.distinctId,s.groups,s.personProperties,s.groupProperties,n,[a]);if(void 0===b)h=a0.UNKNOWN_ERROR;else{f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(a0.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(a0.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(a0.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,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,payload:b}}c.length>0&&(h=c.join(","))}}if(l){let c=void 0===e?void 0:!1!==e.enabled&&(e.variant??!0),d=`${a}_${c}`;if(!(b in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[b].includes(d)){Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[b])?this.distinctIdHasSentFlagCalls[b].push(d):this.distinctIdHasSentFlagCalls[b]=[d];let e={$feature_flag:a,$feature_flag_response:c,$feature_flag_id:i,$feature_flag_version:j,$feature_flag_reason:k,locally_evaluated:t,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:t?Date.now():g};if(t&&this.featureFlagsPoller){let a=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();void 0!==a&&(e.$feature_flag_definitions_loaded_at=a)}h&&(e.$feature_flag_error=h),this.capture({distinctId:b,event:"$feature_flag_called",properties:e,groups:m,disableGeoip:n})}}return void 0!==e&&void 0!==this._payloadOverrides&&a in this._payloadOverrides&&(e={...e,payload:this._payloadOverrides[a]}),e}async getFeatureFlag(a,b,c){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(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.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){let d=await this.getFeatureFlag(a,b,c);if(void 0!==d)return!!d}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:{}};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,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,l.personProperties,l.groupProperties,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}}groupIdentify({groupType:a,groupKey:b,properties:c,distinctId:d,disableGeoip:e}){super.groupIdentifyStateless(a,b,c,{disableGeoip:e},d)}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=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown();try{return await super._shutdown(a)}finally{b?.()}}async _requestRemoteConfigPayload(a){if(!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=H(()=>{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(w(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){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={distinct_id:a,...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d){if(!aZ.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");this.addPendingPromise(aZ.buildEventMessage(a,{syntheticException:e},b,c).then(a=>this.capture({...a,uuid:d})))}}async captureExceptionImmediate(a,b,c){if(!aZ.isPreviouslyCapturedError(a)){let d=Error("PostHog syntheticException");return this.addPendingPromise(aZ.buildEventMessage(a,{syntheticException:d},b,c).then(a=>this.captureImmediate(a)))}}async prepareEventMessage(a){let{distinctId:b,event:c,properties:d,groups:e,sendFeatureFlags:f,timestamp:g,disableGeoip:h,uuid:i}=a,j=this.context?.get(),k=b||j?.distinctId,l={...this.props,...j?.properties||{},...d||{}};k||(k=O().toString(),l.$process_person_profile=!1),j?.sessionId&&!l.$session_id&&(l.$session_id=j.sessionId);let m=this._runBeforeSend({distinctId:k,event:c,properties:l,groups:e,sendFeatureFlags:f,timestamp:g,disableGeoip:h,uuid:i});if(!m)return Promise.reject(null);let n=await Promise.resolve().then(async()=>f?await this.getFeatureFlagsForEvent(m.distinctId,e,h,"object"==typeof f?f:void 0):(m.event,{})).then(a=>{let b={};if(a)for(let[c,d]of Object.entries(a))b[`$feature/${c}`]=d;let c=Object.keys(a||{}).filter(b=>a?.[b]!==!1).sort();return c.length>0&&(b.$active_feature_flags=c),b}).catch(()=>({})).then(a=>({...a,...m.properties||{},$groups:m.groups||e}));return"$pageview"===m.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof n.$raw_user_agent&&a_(n.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(m.event="$bot_pageview",n.$browser_type="bot"),{distinctId:m.distinctId,event:m.event,properties:n,options:{timestamp:m.timestamp,disableGeoip:m.disableGeoip,uuid:m.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){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)}}return d}}var aO=aN,bf=a.i(78500);class bg{constructor(){this.storage=new bf.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||{}}}}}function bh(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(aZ.isPreviouslyCapturedError(a))return void e(a);let f=b.headers["x-posthog-session-id"],g=b.headers["x-posthog-distinct-id"],h=Error("Synthetic exception");c.addPendingPromise(aZ.buildEventMessage(a,{mechanism:{type:"middleware",handled:!1},syntheticException:h},g,{$session_id:f,$current_url:b.url,$request_method:b.method,$request_path:b.path,$user_agent:b.headers["user-agent"],$response_status_code:d.statusCode,$ip:b.headers["x-forwarded-for"]||b?.socket?.remoteAddress}).then(a=>{c.capture(a)})),e(a)}))}a.s(["setupExpressErrorHandler",0,bh],40602),a.s([],51328),aZ.errorPropertiesBuilder=new aO.ErrorPropertiesBuilder([new aO.EventCoercer,new aO.ErrorCoercer,new aO.ObjectCoercer,new aO.StringCoercer,new aO.PrimitiveCoercer],aO.createStackParser("node:javascript",aO.nodeStackLineParser),[(f=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 a=>{for(let b of a)b.module=f(b.filename);return a}),aT,function(a=process.cwd()){let b="\\"===h.sep,c=a=>b?a.replace(/\\/g,"/"):a,d=c(a);return async a=>{for(let b of a)!(!b.filename||b.filename.startsWith("node:")||b.filename.startsWith("data:"))&&(0,h.isAbsolute)(b.filename)&&(b.filename=c((0,h.relative)(d,c(b.filename))));return a}}()]);class bi extends be{getLibraryId(){return"posthog-node"}initializeContext(){return new bg}}a.s(["PostHog",0,bi],81035),a.i(81035),a.i(51328);let bj="posthog-node";function bk(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[bm.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};return 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 bl(a,b){let c=bk(a,b);return{name:bj,processEvent:a=>c(a)}}class bm{static #a=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(a,b,c,d,e){this.name=bj,this.name=bj,this.setupOnce=function(f,g){f(bk(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,bm,"createEventProcessor",0,bk,"sentryIntegration",0,bl],9318),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,n,"PostHogSentryIntegration",0,bm,"createEventProcessor",0,bk,"sentryIntegration",0,bl,"setupExpressErrorHandler",0,bh],80456),a.i(80456),a.s(["FeatureFlagError",0,n,"PostHog",0,bi,"PostHogSentryIntegration",0,bm,"createEventProcessor",0,bk,"sentryIntegration",0,bl,"setupExpressErrorHandler",0,bh],74493)}];
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,"/")}let j=a=>void 0===a?void 0:a.variant??a.enabled,k=a=>{if("string"!=typeof a)return a;try{return JSON.parse(a)}catch{return a}};async function l(a,b=!0,c){try{let b=new CompressionStream("gzip"),c=b.writable.getWriter(),d=c.write(new TextEncoder().encode(a)).then(()=>c.close()).catch(async a=>{try{await c.abort(a)}catch{}throw a}),e=new Response(b.readable).blob(),[f]=await Promise.all([e,d]);return f}catch(a){if(c?.rethrow)throw a;return b&&console.error("Failed to gzip compress data",a),null}}var m=((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.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.SurveyLastSeenDate="survey_last_seen_date",g.SurveysSeen="surveys_seen",g.Surveys="surveys",g.RemoteConfig="remote_config",g.FlagsEndpointWasHit="flags_endpoint_was_hit",g.DeviceId="device_id",g);let n={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}`},o=Array.isArray,p=Object.prototype;p.hasOwnProperty;let q=p.toString,r=o||function(a){return"[object Array]"===q.call(a)},s=a=>a===Object(a)&&!r(a),t=a=>"[object String]"==q.call(a),u=a=>"[object Number]"==q.call(a)&&a==a;function v(a){return null===a||"object"!=typeof a}function w(a,b){return Object.prototype.toString.call(a)===`[object ${b}]`}function x(a){return"u">typeof Event&&function(a,b){try{return a instanceof b}catch{return!1}}(a,Event)}let y="Android",z="BlackBerry",A="Nintendo",B="PlayStation",C="Xbox",D="Windows",E="(\\d+(\\.\\d+)?)";RegExp("Version/"+E),RegExp(C,"i"),RegExp(B+" \\w+","i"),RegExp(A+" \\w+","i"),RegExp(z+"|PlayBook|BB10","i");async function F(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 G(){return new Date().toISOString()}function H(a,b){let c=setTimeout(a,b);return c?.unref&&c?.unref(),c}RegExp("rv:"+E),RegExp("Edge?\\/"+E),RegExp("(Chrome|CrMo)\\/"+E),RegExp("CriOS\\/"+E),RegExp("(UCBrowser|UCWEB)\\/"+E),RegExp("(Opera|OPR)\\/"+E),RegExp("Firefox\\/"+E),RegExp("FxiOS\\/"+E),RegExp("Konqueror[:/]?"+E,"i"),RegExp(z+" "+E),RegExp("android\\s"+E,"i"),RegExp("SamsungBrowser\\/"+E),RegExp("(rv:|MSIE )"+E),RegExp("rv:"+E),RegExp(C+"; "+C+" (.*?)[);]","i"),RegExp(A,"i"),RegExp(B,"i"),RegExp(D,"i"),RegExp("("+y+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+y+")","i");let I=a=>a instanceof Error;function J(a){return Promise.all(a.map(a=>(a??Promise.resolve()).then(a=>({status:"fulfilled",value:a}),a=>({status:"rejected",reason:a}))))}let K="0123456789abcdef";class L{constructor(a){this.bytes=a}static ofInner(a){if(16===a.length)return new L(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 L(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 L(a)}throw SyntaxError("could not parse UUID string")}toString(){let a="";for(let b=0;b<this.bytes.length;b++)a+=K.charAt(this.bytes[b]>>>4),a+=K.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+=K.charAt(this.bytes[b]>>>4),a+=K.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 L(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 M{constructor(a){this.timestamp=0,this.counter=0,this.random=a??N()}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 L.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,L.ofInner(a)}}let N=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),O=()=>(b||(b=new M)).generate();class P{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)}}class Q{add(a){let b=O().toString();return this.promiseByIds[b]=a,a.catch(()=>{}).finally(()=>{delete this.promiseByIds[b]}),a}async join(){let a=Object.values(this.promiseByIds),b=a.length;for(;b>0;)await Promise.all(a),b=(a=Object.values(this.promiseByIds)).length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}let R=(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=>R(`${a} ${d}`,b,c)}};class S extends Error{constructor(a,b){super("HTTP error while fetching PostHog: status="+a.status+", reqByteLength="+b),this.response=a,this.reqByteLength=b,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}}class T extends Error{constructor(a){super("Network error while fetching PostHog",a instanceof Error?{cause:a}:{}),this.error=a,this.name="PostHogFetchNetworkError"}}async function U(a){if(a instanceof S){let b="";try{b=await a.text}catch{}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 V(a){return"object"==typeof a&&(a instanceof S||a instanceof T)}function W(a){return"object"==typeof a&&a instanceof S&&413===a.status}class X{constructor(a,b={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new Q,this._events=new P,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 R(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:V},this.requestTimeout=b.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=b.featureFlagsRequestTimeoutMs??3e3,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(m.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(m.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(m.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){return{distinct_id:a.distinct_id,event:a.event,properties:{...a.properties||{},...this.getCommonEventProperties()}}}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 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,{retryCount:0},this.remoteConfigRequestTimeoutMs).then(a=>a.json()).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={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(h)};return this._logger.info("Flags URL",g),this.fetchWithRetry(g,i,{retryCount:0},this.featureFlagsRequestTimeoutMs).then(a=>a.json()).then(a=>({success:!0,response:(a=>{if("flags"in a){let b,c=Object.fromEntries(Object.entries(a.flags??{}).map(([a,b])=>[a,j(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?k(c):void 0]}));return{...a,featureFlags:c,featureFlagPayloads:d}}{let b=a.featureFlags??{},c=Object.fromEntries(Object.entries(a.featureFlagPayloads||{}).map(([a,b])=>[a,k(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 S)return{type:"api_error",statusCode:a.status};if(a instanceof T){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=j(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={};(e??this.disableGeoip)&&(g.geoip_disable=!0),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).then(a=>{if(200!==a.status||!a.json){let b=`Surveys API could not be loaded: ${a.status}`,c=Error(b);this._logger.error(c),this._events.emit("error",Error(b));return}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(m.Props)),this._props||{}}set props(a){this._props=a}async register(a){this.wrap(()=>{this.props={...this.props,...a},this.setPersistedProperty(m.Props,this.props)})}async unregister(a){this.wrap(()=>{delete this.props[a],this.setPersistedProperty(m.Props,this.props)})}processBeforeEnqueue(a){return a}async flushStorage(){}enqueue(a,b,c){this.wrap(()=>{if(this.optedOut)return void this._events.emit(a,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let d=this.prepareMessage(a,b,c);if(null===(d=this.processBeforeEnqueue(d)))return;let e=this.getPersistedProperty(m.Queue)||[];e.length>=this.maxQueueSize&&(e.shift(),this._logger.info("Queue is full, the oldest event is dropped.")),e.push({message:d}),this.setPersistedProperty(m.Queue,e),this._events.emit(a,d),e.length>=this.flushAt&&this.flushBackground(),this.flushInterval&&!this._flushTimer&&(this._flushTimer=H(()=>this.flushBackground(),this.flushInterval))})}async sendImmediate(a,b,c){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 d=this.prepareMessage(a,b,c);if(null===(d=this.processBeforeEnqueue(d)))return;let e={api_key:this.apiKey,batch:[d],sent_at:G()};this.historicalMigration&&(e.historical_migration=!0);let f=JSON.stringify(e),g=`${this.host}/batch/`,h=this.disableCompression?null:await l(f,this.isDebug),i={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==h&&{"Content-Encoding":"gzip"}},body:h||f};try{let a=await this.fetchWithRetry(g,i);await a.body?.cancel()?.catch(()=>{})}catch(a){this._events.emit("error",a)}}prepareMessage(a,b,c){let d={...b,type:a,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:c?.timestamp?c?.timestamp:G(),uuid:c?.uuid?c.uuid:O().toString()};return(c?.disableGeoip??this.disableGeoip)&&(d.properties||(d.properties={}),d.properties.$geoip_disable=!0),d.distinctId&&(d.distinct_id=d.distinctId,delete d.distinctId),d}clearFlushTimer(){this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=void 0)}flushBackground(){this.flush().catch(async a=>{await U(a)})}async flush(){if(this.disabled)return;let a=J([this.flushPromise]).then(()=>this._flush());return this.flushPromise=a,this.addPendingPromise(a),J([a]).then(()=>{this.flushPromise===a&&(this.flushPromise=null)}),a}getCustomHeaders(){let a=this.getCustomUserAgent(),b={};return a&&""!==a&&(b["User-Agent"]=a),b}async _flush(){this.clearFlushTimer(),await this._initPromise;let a=this.getPersistedProperty(m.Queue)||[];if(!a.length)return;let b=[],c=a.length;for(;a.length>0&&b.length<c;){let c=a.slice(0,this.maxBatchSize),d=c.map(a=>a.message),e=async()=>{let b=(this.getPersistedProperty(m.Queue)||[]).slice(c.length);this.setPersistedProperty(m.Queue,b),a=b,await this.flushStorage()},f={api_key:this.apiKey,batch:d,sent_at:G()};this.historicalMigration&&(f.historical_migration=!0);let g=JSON.stringify(f),h=`${this.host}/batch/`,i=this.disableCompression?null:await l(g,this.isDebug),j={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==i&&{"Content-Encoding":"gzip"}},body:i||g},k={retryCheck:a=>!W(a)&&V(a)};try{let a=await this.fetchWithRetry(h,j,k);await a.body?.cancel()?.catch(()=>{})}catch(a){if(W(a)&&d.length>1){this.maxBatchSize=Math.max(1,Math.floor(d.length/2)),this._logger.warn(`Received 413 when sending batch of size ${d.length}, reducing batch size to ${this.maxBatchSize}`);continue}throw a instanceof T||await e(),this._events.emit("error",a),a}await e(),b.push(...d)}this._events.emit("flush",b)}async _sendLogsBatch(a){if(this.disabled)return{kind:"fatal",error:Error("The client is disabled")};let b=JSON.stringify(a),c=`${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`,d=this.disableCompression?null:await l(b,this.isDebug),e={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...null!==d&&{"Content-Encoding":"gzip"}},body:d||b};try{return await this.fetchWithRetry(c,e,{retryCheck:a=>!W(a)&&V(a)}),{kind:"ok"}}catch(a){if(W(a))return{kind:"too-large"};if(a instanceof T)return{kind:"retry-later",error:a};return{kind:"fatal",error:a}}}async fetchWithRetry(a,b,c,d){let e=b.body?b.body:"",f=-1;try{f=e instanceof Blob?e.size:Buffer.byteLength(e,"utf8")}catch{f=e instanceof Blob?e.size:new TextEncoder().encode(e).length}return await F(async()=>{let c=new AbortController,e=H(()=>c.abort(),d??this.requestTimeout),g=null;try{g=await this.fetch(a,{signal:c.signal,...b})}catch(a){throw new T(a)}finally{clearTimeout(e)}if("no-cors"!==b.mode&&(g.status<200||g.status>=400))throw new S(g,f);return g},{...this._retryOptions,...c})}async _shutdown(a=3e4){let b;await this._initPromise;let c=!1;if(this.clearFlushTimer(),this.disabled)return;let d=async()=>{try{for(await this.promiseQueue.join();;){let a=this.getPersistedProperty(m.Queue)||[];if(0===a.length||(await this.flush(),c))break}}catch(a){if(!V(a))throw a;await U(a)}};try{return await Promise.race([new Promise((d,e)=>{b=H(()=>{this._logger.error("Timed out while shutting down PostHog"),c=!0,e("Timeout while shutting down PostHog. Some events may not have been sent.")},a)}),d()])}finally{clearTimeout(b)}}async shutdown(a=3e4){return this.shutdownPromise?this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup"):this.shutdownPromise=this._shutdown(a).finally(()=>{this.shutdownPromise=null}),this.shutdownPromise}}class Y{constructor(a,b,c=[]){this.coercers=a,this.stackParser=b,this.modifiers=c}buildFromUnknown(a,b={}){let c=b&&b.mechanism||{handled:!0,type:"generic"},d=this.buildCoercingContext(c,b,0).apply(a),e=this.buildParsingContext(b),f=this.parseStacktrace(d,e);return{$exception_list:this.convertToExceptionList(f,c),$exception_level:"error"}}async modifyFrames(a){for(let b of a)b.stacktrace&&b.stacktrace.frames&&r(b.stacktrace.frames)&&(b.stacktrace.frames=await this.applyModifiers(b.stacktrace.frames));return a}coerceFallback(a){return{type:"Error",value:"Unknown error",stack:a.syntheticException?.stack,synthetic:!0}}parseStacktrace(a,b){let c,d;return null!=a.cause&&(c=this.parseStacktrace(a.cause,b)),""!=a.stack&&null!=a.stack&&(d=this.applyChunkIds(this.stackParser(a.stack,a.synthetic?b.skipFirstLines:0),b.chunkIdMap)),{...a,cause:c,stack:d}}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={type:a.type,value:a.value,mechanism:{type:b.type??"generic",handled:b.handled??!0,synthetic:a.synthetic??!1}};a.stack&&(c.stacktrace={type:"raw",frames:a.stack});let d=[c];return null!=a.cause&&d.push(...this.convertToExceptionList(a.cause,{...b,handled:!0})),d}buildParsingContext(a){return{chunkIdMap:function(a){let b=globalThis._posthogChunkIds;if(!b)return;let f=Object.keys(b);return e&&f.length===d?e:(d=f.length,e=f.reduce((d,e)=>{c||(c={});let f=c[e];if(f)d[f[0]]=f[1];else{let f=a(e);for(let a=f.length-1;a>=0;a--){let g=f[a],h=g?.filename,i=b[e];if(h&&i){d[h]=i,c[e]=[h,i];break}}}return d},{}))}(this.stackParser),skipFirstLines:a.skipFirstLines??1}}buildCoercingContext(a,b,c=0){let d=(c,d)=>{if(d<=4){let e=this.buildCoercingContext(a,b,d);return this.applyCoercers(c,e)}};return{...b,syntheticException:0==c?b.syntheticException:void 0,mechanism:a,apply:a=>d(a,c),next:a=>d(a,c+1)}}}function Z(a,b,c,d,e){let f={platform:a,filename:b,function:"<anonymous>"===c?"?":c,in_app:!0};return void 0!==d&&(f.lineno=d),void 0!==e&&(f.colno=e),f}a.s(["ErrorPropertiesBuilder",0,Y],6762);let $=(a,b)=>{let c=-1!==a.indexOf("safari-extension"),d=-1!==a.indexOf("safari-web-extension");return c||d?[-1!==a.indexOf("@")?a.split("@")[0]:"?",c?`safari-extension:${b}`:`safari-web-extension:${b}`]:[a,b]},_=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,aa=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,ab=/\((\S*)(?::(\d+))(?::(\d+))\)/,ac=(a,b)=>{let c=_.exec(a);if(c){let[,a,d,e]=c;return Z(b,a,"?",+d,+e)}let d=aa.exec(a);if(d){if(d[2]&&0===d[2].indexOf("eval")){let a=ab.exec(d[2]);a&&(d[2]=a[1],d[3]=a[2],d[4]=a[3])}let[a,c]=$(d[1]||"?",d[2]);return Z(b,c,a,d[3]?+d[3]:void 0,d[4]?+d[4]:void 0)}},ad=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ae=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,af=(a,b)=>{let c=ad.exec(a);if(c){if(c[3]&&c[3].indexOf(" > eval")>-1){let a=ae.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]=$(d,a),Z(b,a,d,c[4]?+c[4]:void 0,c[5]?+c[5]:void 0)}},ag=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i,ah=(a,b)=>{let c=ag.exec(a);return c?Z(b,c[2],c[1]||"?",+c[3],c[4]?+c[4]:void 0):void 0},ai=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,aj=(a,b)=>{let c=ai.exec(a);return c?Z(b,c[2],c[3]||"?",+c[1]):void 0},ak=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i,al=(a,b)=>{let c=ak.exec(a);return c?Z(b,c[5],c[3]||c[4]||"?",+c[1],+c[2]):void 0},am=/^\s*[-]{4,}$/,an=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/,ao=(a,b)=>{let c=a.match(an);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]),{filename:h?decodeURI(h):void 0,module:void 0,function:e,lineno:ap(c[3]),colno:ap(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(am))return{filename:a,platform:b}};function ap(a){return parseInt(a||"",10)||void 0}let aq=/\(error: (.*)\)/;function ar(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 as(){return at("web:javascript",ac,af)}function at(a,...b){return(c,d=0)=>{let e=[],f=c.split("\n");for(let c=d;c<f.length;c++){let d=f[c];if(d.length>1024)continue;let g=aq.test(d)?d.replace(aq,"$1"):d;if(!g.match(/\S*Error: /)){for(let c of b){let b=c(g,a);if(b){e.push(b);break}}if(e.length>=50)break}}return ar(e)}}a.s(["createDefaultStackParser",0,as,"createStackParser",0,at,"reverseAndStripFrames",0,ar],67970);class au{match(a){return this.isDOMException(a)||this.isDOMError(a)}coerce(a,b){let c=t(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 w(a,"DOMException")}isDOMError(a){return w(a,"DOMError")}}a.s(["DOMExceptionCoercer",0,au],51671);class av{match(a){return a instanceof Error}coerce(a,b){return{type:this.getType(a),value:this.getMessage(a,b),stack:this.getStack(a),cause:a.cause?b.next(a.cause):void 0,synthetic:!1}}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){return a.stacktrace||a.stack||void 0}}a.s(["ErrorCoercer",0,av],10692);class aw{match(a){return w(a,"ErrorEvent")&&void 0!=a.error}coerce(a,b){let c=b.apply(a.error);return c||{type:"ErrorEvent",value:a.message,stack:b.syntheticException?.stack,synthetic:!0}}}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:b.syntheticException?.stack,level:this.isSeverityLevel(a.level)?a.level:"error",synthetic:!0}}getType(a){return x(a)?a.constructor.name:"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 t(a)&&!(t(a)&&0===a.trim().length)&&ax.indexOf(a)>=0}getErrorPropertyFromObject(a){for(let b in a)if(Object.prototype.hasOwnProperty.call(a,b)){let c=a[b];if(I(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 x(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 v(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 w(a,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(a)}isCustomEventWrappingRejection(a){if(!x(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 v(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(!u(a)||a===1/0||a===-1/0)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=function(a){let b=new WeakSet;try{return JSON.stringify(a,(a,c)=>{if("bigint"==typeof c)return c.toString();if("function"!=typeof c&&"symbol"!=typeof c){if(c instanceof Date)return c.toISOString();if(c instanceof Error)return{name:c.name,message:c.message,stack:c.stack};if(c&&"object"==typeof c){if(b.has(c))return"[Circular]";b.add(c)}return c}})}catch{return}}(a);if(b)try{let a=JSON.parse(b);if(!s(a))return;let c=a[aD.MESSAGE],d=a[aD.TIMESTAMP];if(!t(c)||0===c.trim().length||!t(d)&&!u(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,ac,"createDefaultStackParser",0,as,"createStackParser",0,at,"geckoStackLineParser",0,af,"nodeStackLineParser",0,ao,"opera10StackLineParser",0,aj,"opera11StackLineParser",0,al,"reverseAndStripFrames",0,ar,"winjsStackLineParser",0,ah],64583),a.i(64583),a.i(7610),a.i(51671),a.i(10692),a.i(75368);let aK=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class aL{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(aK);return d&&(b=d[1],c=d[2]),[b,c]}}a.s(["StringCoercer",0,aL],57802),a.i(57802),a.i(93874),a.i(46980),a.i(28150),a.i(98140),a.s(["DOMExceptionCoercer",0,au,"ErrorCoercer",0,av,"ErrorEventCoercer",0,aw,"EventCoercer",0,aA,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"StringCoercer",0,aL],54253),a.i(54253);class aM{constructor(a){this._maxSize=a,this._cache=new Map}get(a){let b=this._cache.get(a);if(void 0!==b)return this._cache.delete(a),this._cache.set(a,b),b}set(a,b){this._cache.set(a,b)}reduce(){for(;this._cache.size>=this._maxSize;){let a=this._cache.keys().next().value;a&&this._cache.delete(a)}}}a.s(["ReduceableCache",0,aM],98966),a.i(98966),a.i(97383),a.s(["DEFAULT_EXCEPTION_STEPS_CONFIG",0,aF,"DOMExceptionCoercer",0,au,"EXCEPTION_STEP_INTERNAL_FIELDS",0,aD,"ErrorCoercer",0,av,"ErrorEventCoercer",0,aw,"ErrorPropertiesBuilder",0,Y,"EventCoercer",0,aA,"ExceptionStepsBuffer",0,aI,"ObjectCoercer",0,az,"PrimitiveCoercer",0,aB,"PromiseRejectionEventCoercer",0,aC,"ReduceableCache",0,aM,"StringCoercer",0,aL,"chromeStackLineParser",0,ac,"createDefaultStackParser",0,as,"createStackParser",0,at,"geckoStackLineParser",0,af,"getUtf8ByteLength",0,aJ,"nodeStackLineParser",0,ao,"opera10StackLineParser",0,aj,"opera11StackLineParser",0,al,"resolveExceptionStepsConfig",0,aG,"reverseAndStripFrames",0,ar,"stripReservedExceptionStepFields",0,aH,"winjsStackLineParser",0,ah],60485);var aN=a.i(60485),aO=aN,aP=a.i(2157),aQ=a.i(1457);let aR=new aO.ReduceableCache(25),aS=new aO.ReduceableCache(20);async function aT(a){let b={};for(let e=a.length-1;e>=0;e--){var c,d;let f=a[e],g=f?.filename;!(!f||"string"!=typeof g||"number"!=typeof f.lineno||(c=g).startsWith("node:")||c.endsWith(".min.js")||c.endsWith(".min.cjs")||c.endsWith(".min.mjs")||c.startsWith("data:")||void 0!==(d=f).lineno&&d.lineno>1e4||void 0!==d.colno&&d.colno>1e3)&&(b[g]||(b[g]=[]),b[g].push(f.lineno))}let e=Object.keys(b);if(0==e.length)return a;let f=[];for(let a of e){if(aS.get(a))continue;let c=b[a];if(!c)continue;c.sort((a,b)=>a-b);let d=function(a){if(!a.length)return[];let b=0,c=a[0];if("number"!=typeof c)return[];let d=aV(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=aV(c)),b++}return e}(c);if(d.every(b=>(function(a,b){let c=aR.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})(a,b)))continue;let e=function(a,b,c){let d=a.get(b);return void 0===d?(a.set(b,c),c):d}(aR,a,{});f.push(function(a,b,c){return new Promise(d=>{let e=(0,aP.createReadStream)(a),f=(0,aQ.createInterface)({input:e});function g(){e.destroy(),d()}let h=0,i=0,j=b[0];if(void 0===j)return void g();let k=j[0],l=j[1];function m(){aS.set(a,1),f.close(),f.removeAllListeners(),g()}e.on("error",m),f.on("error",m),f.on("close",g),f.on("line",a=>{if(!(++h<k)&&(c[h]=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),h>=l)){if(i===b.length-1){f.close(),f.removeAllListeners();return}let a=b[++i];if(void 0===a){f.close(),f.removeAllListeners();return}k=a[0],l=a[1]}})})}(a,d,e))}return await Promise.all(f).catch(()=>{}),a&&a.length>0&&function(a,b){for(let c of a)if(c.filename&&void 0===c.context_line&&"number"==typeof c.lineno){let a=b.get(c.filename);if(void 0===a)continue;!function(a,b,c){if(void 0===b.lineno||void 0===c)return;b.pre_context=[];for(let d=aW(a);d<a;d++){let a=c[d];if(void 0===a)return void aU(b);b.pre_context.push(a)}if(void 0===c[a])return aU(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)}}(c.lineno,c,a)}}(a,aR),aR.reduce(),a}function aU(a){delete a.pre_context,delete a.context_line,delete a.post_context}function aV(a){return[aW(a),a+7]}function aW(a){return Math.max(1,a-7)}function aX(a,b,c,d,e){if(b>c&&(d.warn("min cannot be greater than max."),b=c),u(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),aX(e||c,b,c,d)}class aY{constructor(a){this._buckets={},this._onBucketRateLimited=a._onBucketRateLimited,this._bucketSize=aX(a.bucketSize,0,100,a._logger),this._refillRate=aX(a.refillRate,0,this._bucketSize,a._logger),this._refillInterval=aX(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={}}}class aZ{constructor(a,b,c){this.client=a,this._exceptionAutocaptureEnabled=b.enableExceptionAutocapture||!1,this._logger=c,this._rateLimiter=new aY({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(a){return s(a)&&"__posthog_previously_captured_error"in a&&!0===a.__posthog_previously_captured_error}static async buildEventMessage(a,b,c,d){let e={...d},f=this.errorPropertiesBuilder.buildFromUnknown(a,b);return f.$exception_list=await this.errorPropertiesBuilder.modifyFrames(f.$exception_list),{event:"$exception",distinctId:c,properties:{...f,...e},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled()){var b,c,d;let e;b=this.onException.bind(this),c=this.onFatalError.bind(this),globalThis.process?.on("uncaughtException",(e=!1,Object.assign(d=>{let f=a.g.process.listeners("uncaughtException").filter(a=>"domainUncaughtExceptionClear"!==a.name&&!0!==a._posthogErrorHandler).length;b(d,{mechanism:{type:"onuncaughtexception",handled:!1}}),e||0!==f||(e=!0,c(d))},{_posthogErrorHandler:!0}))),d=this.onException.bind(this),globalThis.process?.on("unhandledRejection",a=>d(a,{mechanism:{type:"onunhandledrejection",handled:!1}}))}}onException(a,b){this.client.addPendingPromise((async()=>{if(!aZ.isPreviouslyCapturedError(a)){let c=await aZ.buildEventMessage(a,b),d=c.properties,e=d?.$exception_list[0]?.type??"Exception";return this._rateLimiter.consumeRateLimit(e)?void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:e}):this.client.capture(c)}})())}async onFatalError(a){console.error(a),await this.client.shutdown(2e3),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}let a$=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],a_=function(a,b=[]){if(!a)return!1;let c=a.toLowerCase();return a$.concat(b).some(a=>{let b=a.toLowerCase();return -1!==c.indexOf(b)})},a0={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"};a.s(["FeatureFlagError",0,a0],46539);class a1{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){let b=this._flags[a];return this._recordAccess(a),b?.enabled??!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 a1({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?.locallyEvaluated&&void 0!==this._flagDefinitionsLoadedAt&&(d.$feature_flag_definitions_loaded_at=this._flagDefinitionsLoadedAt);let e=[];this._errorsWhileComputing&&e.push(a0.ERRORS_WHILE_COMPUTING),this._quotaLimited&&e.push(a0.QUOTA_LIMITED),void 0===b&&e.push(a0.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})}}async function a2(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("")}let a3=["is_not"];class a4 extends Error{constructor(a){super(),Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=a,Object.setPrototypeOf(this,a4.prototype)}}class a5 extends Error{constructor(a){super(a),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,a5.prototype)}}class a6 extends Error{constructor(a){super(a),this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,a6.prototype)}}class a7{constructor({pollingInterval:a,personalApiKey:b,projectApiKey:c,timeout:d,host:e,customHeaders:f,...g}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,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.cacheProvider=g.cacheProvider,this.strictLocalEvaluation=g.strictLocalEvaluation??!1,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 a6||b instanceof a5?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 a6||b instanceof a5?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.ensure_experience_continuity)throw new a5("Flag has experience continuity enabled");if(!a.active)return!1;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 a5("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 a5(`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){let c=null;if(!1!==b&&null!=b&&("boolean"==typeof b?c=this.featureFlagsByKey?.[a]?.filters?.payloads?.[b.toString()]||null:"string"==typeof b&&(c=this.featureFlagsByKey?.[a]?.filters?.payloads?.[b]||null),null!=c)){if("object"==typeof c)return c;if("string"==typeof c)try{return JSON.parse(c)}catch{}return c}return null}async evaluateFlagDependency(a,b,c){let{evaluationCache:d}=c,e=a.key;if(!this.featureFlagsByKey)throw new a5("Feature flags not available for dependency evaluation");if(!("dependency_chain"in a))throw new a5(`Flag dependency property for '${e}' is missing required 'dependency_chain' field`);let f=a.dependency_chain;if(!Array.isArray(f))throw new a5(`Flag dependency property for '${e}' has an invalid 'dependency_chain' (expected array, got ${typeof f})`);if(0===f.length)throw new a5(`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 a5(`Error evaluating flag dependency '${a}' for flag '${e}': ${b}`)}else d[a]=!1;else throw new a5(`Missing flag dependency '${a}' for flag '${e}'`)}if(null==d[a])throw new a5(`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,{groups:i,groupProperties:j}=d,k=!1;for(let l of g)try{let g=void 0!==l.aggregation_group_type_index?l.aggregation_group_type_index:h,m=c,n=b;if(g!==h&&null!=g){let b=this.groupTypeMapping[String(g)];if(!b||!(b in i)){this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Skipping group condition for flag '${a.key}': group type index ${g} not available`));continue}if(!(b in j)){k=!0;continue}m=j[b],n=i[b]}if(await this.isConditionMatch(a,n,l,m,d)){let b=l.variant,c=f.multivariate?.variants||[];e=b&&c.some(a=>a.key===b)?b:await this.getMatchingVariant(a,n)||!0;break}}catch(a){if(a instanceof a6)throw a;if(a instanceof a5)k=!0;else throw a}if(void 0!==e)return e;if(k)throw new a5("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;if(!("cohort"===b?function a(b,c,d,e=!1){let f=String(b.value);if(!(f in d))throw new a6(`cohort ${f} not found in local cohorts - likely a static cohort that requires server evaluation`);return function b(c,d,e,f=!1){if(!c)return!0;let g=c.type,h=c.values;if(!h||0===h.length)return!0;let i=!1;if("values"in h[0]){for(let a of h)try{let c=b(a,d,e,f);if("AND"===g){if(!c)return!1}else if(c)return!0}catch(b){if(b instanceof a6)throw b;if(b instanceof a5)f&&console.debug(`Failed to compute property ${a} locally: ${b}`),i=!0;else throw b}if(i)throw new a5("Can't match cohort without a given cohort property value");return"AND"===g}for(let b of h)try{let c;if("cohort"===b.type)c=a(b,d,e,f);else if("flag"===b.type){f&&console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${b.key||"unknown"}'`);continue}else c=a9(b,d);let h=b.negation||!1;if("AND"===g){if(!c&&!h||c&&h)return!1}else if(c&&!h||!c&&h)return!0}catch(a){if(a instanceof a6)throw a;if(a instanceof a5)f&&console.debug(`Failed to compute property ${b} locally: ${a}`),i=!0;else throw a}if(i)throw new a5("can't match cohort without a given cohort property value");return"AND"===g}(d[f],c,d,e)}(a,d,this.cohorts,this.debugMode):"flag"===b?await this.evaluateFlagDependency(a,d,e):a9(a,d,g)))return!1}if(void 0==f)return!0}return!(void 0!=f&&await a8(a.key,b)>f/100)}async getMatchingVariant(a,b){let c=await a8(a.key,b,"variant"),d=this.variantLookupTable(a).find(a=>c>=a.valueMin&&c<a.valueMax);if(d)return d.key}variantLookupTable(a){let b=[],c=0,d=0,e=a.filters||{};return(e.multivariate?.variants||[]).forEach(a=>{d=c+a.rollout_percentage/100,b.push({valueMin:c,valueMax:d,key:a.key}),c=d}),b}updateFlagState(a){this.featureFlags=a.flags,this.featureFlagsByKey=a.flags.reduce((a,b)=>(a[b.key]=b,a),{}),this.groupTypeMapping=a.groupTypeMapping,this.cohorts=a.cohorts,this.loadedSuccessfullyOnce=!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(b.flags),!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),this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());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 a4(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new a4(`Your personal API 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 personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new a4(`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||{}};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(d.flags);break}default:return}}catch(a){a instanceof a4&&this.onError?.(a)}}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}}_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=H(()=>{a.abort()},this.timeout),b.signal=a.signal}try{return(0,this.fetch)(a,b)}finally{clearTimeout(c)}}async stopPoller(a=3e4){if(clearTimeout(this.poller),this.cacheProvider)try{let b=this.cacheProvider.shutdown();b instanceof Promise&&await Promise.race([b,new Promise((b,c)=>setTimeout(()=>c(Error(`Cache shutdown timeout after ${a}ms`)),a))])}catch(a){this.onError?.(Error(`Error during cache shutdown: ${a}`))}}}async function a8(a,b,c=""){return parseInt((await a2(`${a}.${b}${c}`)).slice(0,15),16)/0x1000000000000000}function a9(a,b,c){let d=a.key,e=a.value,f=a.operator||"exact";if(d in b){if("is_not_set"===f)throw new a5("Operator is_not_set is not supported")}else throw new a5(`Property ${d} not found in propertyValues`);let g=b[d];if(null==g&&!a3.includes(f))return c&&c(`Property ${d} cannot have a value of null/undefined with the ${f} operator`),!1;function h(a,b){return Array.isArray(a)?a.map(a=>String(a).toLowerCase()).includes(String(b).toLowerCase()):String(a).toLowerCase()===String(b).toLowerCase()}function i(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 h(e,g);case"is_not":return!h(e,g);case"is_set":return d in b;case"icontains":return String(g).toLowerCase().includes(String(e).toLowerCase());case"not_icontains":return!String(g).toLowerCase().includes(String(e).toLowerCase());case"regex":return ba(String(e))&&null!==String(g).match(String(e));case"not_regex":return ba(String(e))&&null===String(g).match(String(e));case"gt":case"gte":case"lt":case"lte":{let a="number"==typeof e?e:null;if("string"==typeof e)try{a=parseFloat(e)}catch(a){}if(null==a||null==g)return i(String(g),String(e),f);if("string"==typeof g)return i(g,String(e),f);return i(g,a,f)}case"is_date_after":case"is_date_before":{if("boolean"==typeof e)throw new a5("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)return null;{if(!b.groups)return null;let a=parseInt(b.groups.number);if(a>=1e4)return null;let d=b.groups.interval;if("h"==d)c.setUTCHours(c.getUTCHours()-a);else if("d"==d)c.setUTCDate(c.getUTCDate()-a);else if("w"==d)c.setUTCDate(c.getUTCDate()-7*a);else if("m"==d)c.setUTCMonth(c.getUTCMonth()-a);else{if("y"!=d)return null;c.setUTCFullYear(c.getUTCFullYear()-a)}return c}}(String(e));if(null==a&&(a=bd(e)),null==a)throw new a5(`Invalid date: ${e}`);let b=bd(g);if(["is_date_before"].includes(f))return b<a;return b>a}case"semver_eq":return 0===bc(bb(String(g)),bb(String(e)));case"semver_neq":return 0!==bc(bb(String(g)),bb(String(e)));case"semver_gt":return bc(bb(String(g)),bb(String(e)))>0;case"semver_gte":return bc(bb(String(g)),bb(String(e)))>=0;case"semver_lt":return 0>bc(bb(String(g)),bb(String(e)));case"semver_lte":return 0>=bc(bb(String(g)),bb(String(e)));case"semver_tilde":{let a,b=bb(String(g)),{lower:c,upper:d}={lower:[(a=bb(String(e)))[0],a[1],a[2]],upper:[a[0],a[1]+1,0]};return bc(b,c)>=0&&0>bc(b,d)}case"semver_caret":{let a=bb(String(g)),{lower:b,upper:c}=function(a){let[b,c,d]=bb(a);return{lower:[b,c,d],upper:b>0?[b+1,0,0]:c>0?[0,c+1,0]:[0,0,d+1]}}(String(e));return bc(a,b)>=0&&0>bc(a,c)}case"semver_wildcard":{let a=bb(String(g)),{lower:b,upper:c}=function(a){let b,c,d=String(a).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!d)throw new a5(`Invalid wildcard semver: ${a}`);let e=d.split("."),f=parseInt(e[0],10);if(isNaN(f))throw new a5(`Invalid wildcard semver: ${a}`);if(1===e.length)b=[f,0,0],c=[f+1,0,0];else{let d=parseInt(e[1],10);if(isNaN(d))throw new a5(`Invalid wildcard semver: ${a}`);b=[f,d,0],c=[f,d+1,0]}return{lower:b,upper:c}}(String(e));return bc(a,b)>=0&&0>bc(a,c)}default:throw new a5(`Unknown operator: ${f}`)}}function ba(a){try{return new RegExp(a),!0}catch(a){return!1}}function bb(a){let b=String(a).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!b||b.startsWith("."))throw new a5(`Invalid semver: ${a}`);let c=b.split("."),d=b=>{if(void 0===b||""===b)return 0;if(!/^\d+$/.test(b))throw new a5(`Invalid semver: ${a}`);return parseInt(b,10)};return[d(c[0]),d(c[1]),d(c[2])]}function bc(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 bd(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 a5(`${a} is in an invalid date format`)}throw new a5(`The date provided ${a} must be a string, number, or date object`)}class be{getProperty(a){return this._memoryStorage[a]}setProperty(a,b){this._memoryStorage[a]=null!==b?b:void 0}constructor(){this._memoryStorage={}}}let bf=new Set;function bg(a,b){bf.has(a)||(bf.add(a),console.warn(`[PostHog] ${b}`))}class bh extends X{constructor(a,b={}){const c=function(a){return"string"==typeof a?a.trim():""}(a),d={...b,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.personalApiKey)};if(super(c,d),this._memoryStorage=new be,this.options=d,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)),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 a7({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)},customHeaders:this.getCustomHeaders(),cacheProvider:d.flagDefinitionCacheProvider,strictLocalEvaluation:d.strictLocalEvaluation}))}this.errorTracking=new aZ(this,d,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=d.maxCacheSize||5e4}enqueue(a,b,c){super.enqueue(a,b,c),this.scheduleDebouncedFlush()}async flush(){let a=super.flush(),b=this.options.waitUntil;if(b&&!this._waitUntilCycle)try{b(a.catch(()=>{}))}catch{}return a}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=H(()=>{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 super.flush()}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)}getLibraryVersion(){return"5.33.2"}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(a=!0){super.debug(a),this.featureFlagsPoller?.debug(a)}capture(a){"string"==typeof a&&this._logger.warn("Called capture() with a string as the first argument when an object was expected."),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.addPendingPromise(this.prepareEventMessage(a).then(({distinctId:a,event:b,properties:c,options:d})=>super.captureStateless(a,b,c,{timestamp:d.timestamp,disableGeoip:d.disableGeoip,uuid:d.uuid})).catch(a=>{a&&console.error(a)}))}async captureImmediate(a){return"string"==typeof a&&this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected."),"$exception"!==a.event||a._originatedFromCaptureException||this._logger.warn("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.addPendingPromise(this.prepareEventMessage(a).then(({distinctId:a,event:b,properties:c,options:d})=>super.captureStatelessImmediate(a,b,c,{timestamp:d.timestamp,disableGeoip:d.disableGeoip,uuid:d.uuid})).catch(a=>{a&&console.error(a)}))}identify({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;super.identifyStateless(a,{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},{disableGeoip:c})}async identifyImmediate({distinctId:a,properties:b={},disableGeoip:c}){let{$set:d,$set_once:e,$anon_distinct_id:f,...g}=b;super.identifyStatelessImmediate(a,{$set:d||g,$set_once:e||{},$anon_distinct_id:f??void 0},{disableGeoip:c})}alias(a){super.aliasStateless(a.alias,a.distinctId,void 0,{disableGeoip:a.disableGeoip})}async aliasImmediate(a){await super.aliasStatelessImmediate(a.alias,a.distinctId,void 0,{disableGeoip:a.disableGeoip})}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=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:m,disableGeoip:n}=c,{onlyEvaluateLocally:o,personProperties:p,groupProperties:q}=c,r=this.addLocalPersonAndGroupProperties(b,m,p,q);p=r.allPersonProperties,q=r.allGroupProperties;let s=this.createFeatureFlagEvaluationContext(b,m,p,q);void 0==o&&(o=this.options.strictLocalEvaluation??!1);let t=!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,s,{matchValue:d});if(c){t=!0;let d=c.value;i=b.id,k="Evaluated locally",e={key:a,enabled:!1!==d,variant:"string"==typeof d?d:void 0,payload:c.payload??void 0}}}catch(b){if(b instanceof a6||b instanceof a5)this._logger?.info(`${b.name} when computing flag locally: ${a}: ${b.message}`);else throw b}}if(!t&&!o){let b=await super.getFeatureFlagDetailsStateless(s.distinctId,s.groups,s.personProperties,s.groupProperties,n,[a]);if(void 0===b)h=a0.UNKNOWN_ERROR;else{f=b.requestId,g=b.evaluatedAt;let c=[];b.errorsWhileComputingFlags&&c.push(a0.ERRORS_WHILE_COMPUTING),b.quotaLimited?.includes("feature_flags")&&c.push(a0.QUOTA_LIMITED);let d=b.flags[a];if(void 0===d)c.push(a0.FLAG_MISSING);else{let b;if(i=d.metadata?.id,j=d.metadata?.version,k=d.reason?.description??d.reason?.code,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,payload:b}}c.length>0&&(h=c.join(","))}}if(l){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:t,[`$feature/${a}`]:c,$feature_flag_request_id:f,$feature_flag_evaluated_at:t?Date.now():g};if(t&&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:m,disableGeoip:n,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){bg("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(bg("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.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){bg("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:{}};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,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,l.personProperties,l.groupProperties,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 a1({host:this._getFeatureFlagEvaluationsHost(),distinctId:"",flags:{}});let{groups:g,disableGeoip:h,flagKeys:i}=f||{},{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,k,l);void 0==j&&(j=this.options.strictLocalEvaluation??!1);let o={},p=!1,q=!1,r=await this.featureFlagsPoller?.getAllFlagsAndPayloads(n,i),s=new Set;if(r)for(let[a,b]of Object.entries(r.response)){let c=this.featureFlagsPoller?.featureFlagsByKey[a];o[a]={key:a,enabled:!1!==b,variant:"string"==typeof b?b:void 0,payload:r.payloads[a],id:c?.id,version:void 0,reason:"Evaluated locally",locallyEvaluated:!0},s.add(a)}if((!r||r.fallbackToFlags)&&!j){let a=await super.getFeatureFlagDetailsStateless(n.distinctId,n.groups,n.personProperties,n.groupProperties,h,i);if(a)for(let[b,e]of(c=a.requestId,d=a.evaluatedAt,p=!!a.errorsWhileComputingFlags,q=Array.isArray(a.quotaLimited)&&a.quotaLimited.includes("feature_flags"),Object.entries(a.flags))){let a;if(!s.has(b)){if(e.metadata?.payload!==void 0)try{a=JSON.parse(e.metadata.payload)}catch{a=e.metadata.payload}o[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}}}}if(void 0!==this._flagOverrides)for(let[a,b]of Object.entries(this._flagOverrides)){if(void 0===b){delete o[a];continue}let c=o[a];o[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}}if(void 0!==this._payloadOverrides)for(let[a,b]of Object.entries(this._payloadOverrides)){let c=o[a];c&&(o[a]={...c,payload:b})}return new a1({host:this._getFeatureFlagEvaluationsHost(),distinctId:e,groups:g,disableGeoip:h,flags:o,requestId:c,evaluatedAt:d,flagDefinitionsLoadedAt:this.featureFlagsPoller?.getFlagDefinitionsLoadedAt(),errorsWhileComputing:p,quotaLimited:q})}_captureFlagCalledEventIfNeeded(a){let{distinctId:b,key:c,response:d,groups:e,disableGeoip:f,properties:g}=a,h=`${c}_${d}`;b in this.distinctIdHasSentFlagCalls&&this.distinctIdHasSentFlagCalls[b].includes(h)||(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize&&(this.distinctIdHasSentFlagCalls={}),Array.isArray(this.distinctIdHasSentFlagCalls[b])?this.distinctIdHasSentFlagCalls[b].push(h):this.distinctIdHasSentFlagCalls[b]=[h],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}){super.groupIdentifyStateless(a,b,c,{disableGeoip:e},d)}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=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(a),this.errorTracking.shutdown();try{return await super._shutdown(a)}finally{b?.()}}async _requestRemoteConfigPayload(a){if(!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=H(()=>{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(w(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){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={distinct_id:a,...c||{}},f={};if(b)for(let a of Object.keys(b))f[a]={$group_key:b[a],...d?.[a]||{}};return{allPersonProperties:e,allGroupProperties:f}}createFeatureFlagEvaluationContext(a,b,c,d){return{distinctId:a,groups:b||{},personProperties:c||{},groupProperties:d||{},evaluationCache:{}}}captureException(a,b,c,d,e){if(!aZ.isPreviouslyCapturedError(a)){let f=Error("PostHog syntheticException");this.addPendingPromise(aZ.buildEventMessage(a,{syntheticException:f},b,c).then(a=>this.capture({...a,uuid:d,flags:e})))}}async captureExceptionImmediate(a,b,c,d){if(!aZ.isPreviouslyCapturedError(a)){let e=Error("PostHog syntheticException");return this.addPendingPromise(aZ.buildEventMessage(a,{syntheticException:e},b,c).then(a=>this.captureImmediate({...a,flags:d})))}}async prepareEventMessage(a){let{distinctId:b,event:c,properties:d,groups:e,flags:f,sendFeatureFlags:g,timestamp:h,disableGeoip:i,uuid:j}=a,k=this.context?.get(),l=b||k?.distinctId,m={...this.props,...k?.properties||{},...d||{}};l||(l=O().toString(),m.$process_person_profile=!1),k?.sessionId&&!m.$session_id&&(m.$session_id=k.sessionId);let n=this._runBeforeSend({distinctId:l,event:c,properties:m,groups:e,flags:f,sendFeatureFlags:g,timestamp:h,disableGeoip:i,uuid:j});if(!n)return Promise.reject(null);let o=await Promise.resolve().then(async()=>{if(f)return g&&console.warn("[PostHog] Both `flags` and `sendFeatureFlags` were passed to capture(); using `flags` and ignoring `sendFeatureFlags`."),f._getEventProperties();if(g){bg("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(n.distinctId,e,i,"object"==typeof g?g: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=>({...a,...n.properties||{},$groups:n.groups||e}));return"$pageview"===n.event&&this.options.__preview_capture_bot_pageviews&&"string"==typeof o.$raw_user_agent&&a_(o.$raw_user_agent,this.options.custom_blocked_useragents||[])&&(n.event="$bot_pageview",o.$browser_type="bot"),{distinctId:n.distinctId,event:n.event,properties:o,options:{timestamp:n.timestamp,disableGeoip:n.disableGeoip,uuid:n.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){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)}}return d}}var aO=aN,bi=a.i(78500);class bj{constructor(){this.storage=new bi.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||{}}}}}let bk=/[\x00-\x1f\x7f-\x9f]/g;function bl(a,b,c){null!=c&&""!==c&&(a[b]=c)}function bm(a){return Array.isArray(a)?a[0]:a}function bn(a){if(Array.isArray(a)){for(let b of a){let a=bn(b);if(void 0!==a)return a}return}if("string"!=typeof a)return;let b=a.replace(bk,"").trim();if(b)return b.length>1e3?b.slice(0,1e3):b}function bo(a){let{sessionId:b,distinctId:c}=function(a){if(!a)return{};let b=bn(a["x-posthog-session-id"]),c=bn(a["x-posthog-distinct-id"]);return{...void 0!==b?{sessionId:b}:{},...void 0!==c?{distinctId:c}:{}}}(a.headers),d={};return bl(d,"$current_url",a.originalUrl||a.url),bl(d,"$request_method",a.method),bl(d,"$request_path",a.path),bl(d,"$user_agent",bm(a.headers["user-agent"])),bl(d,"$ip",function(a){let b=bm(a.headers["x-forwarded-for"]);if(b){let a=b.split(",")[0].trim();if(a)return a}return a.socket?.remoteAddress}(a)),{...void 0!==b?{sessionId:b}:{},...void 0!==c?{distinctId:c}:{},properties:d}}function bp(a,b){var c;b.use((c=a,(a,b,d)=>{c.withContext(bo(a),()=>d())}))}function bq(a,b){var c;b.use((c=a,(a,b,d,e)=>{if(aZ.isPreviouslyCapturedError(a))return void e(a);let f=bo(b),g=Error("Synthetic exception"),h={...void 0!==f.sessionId?{$session_id:f.sessionId}:{},...f.properties||{},$response_status_code:d.statusCode};c.addPendingPromise(aZ.buildEventMessage(a,{mechanism:{type:"middleware",handled:!1},syntheticException:g},f.distinctId,h).then(a=>{c.capture(a)})),e(a)}))}a.s(["setupExpressErrorHandler",0,bq,"setupExpressRequestContext",0,bp],40602),a.s([],51328),aZ.errorPropertiesBuilder=new aO.ErrorPropertiesBuilder([new aO.EventCoercer,new aO.ErrorCoercer,new aO.ObjectCoercer,new aO.StringCoercer,new aO.PrimitiveCoercer],aO.createStackParser("node:javascript",aO.nodeStackLineParser),[(f=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 a=>{for(let b of a)b.module=f(b.filename);return a}),aT,function(a=process.cwd()){let b="\\"===h.sep,c=a=>b?a.replace(/\\/g,"/"):a,d=c(a);return async a=>{for(let b of a)!(!b.filename||b.filename.startsWith("node:")||b.filename.startsWith("data:"))&&(0,h.isAbsolute)(b.filename)&&(b.filename=c((0,h.relative)(d,c(b.filename))));return a}}()]);class br extends bh{getLibraryId(){return"posthog-node"}initializeContext(){return new bj}}a.s(["PostHog",0,br],81035),a.i(81035),a.i(51328);let bs="posthog-node";function bt(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[bv.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};return 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 bu(a,b){let c=bt(a,b);return{name:bs,processEvent:a=>c(a)}}class bv{static #a=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(a,b,c,d,e){this.name=bs,this.name=bs,this.setupOnce=function(f,g){f(bt(a,{organization:b,projectId:g()?.getClient()?.getDsn()?.projectId,prefix:c,severityAllowList:d,sendExceptionsToPostHog:e??!0}))}}}a.s(["PostHogSentryIntegration",0,bv,"createEventProcessor",0,bt,"sentryIntegration",0,bu],9318),a.i(9318),a.i(40602),a.i(46539),a.s(["FeatureFlagError",0,n,"FeatureFlagEvaluations",0,a1,"PostHogSentryIntegration",0,bv,"createEventProcessor",0,bt,"sentryIntegration",0,bu,"setupExpressErrorHandler",0,bq,"setupExpressRequestContext",0,bp],80456),a.i(80456),a.s(["FeatureFlagError",0,n,"FeatureFlagEvaluations",0,a1,"PostHog",0,br,"PostHogSentryIntegration",0,bv,"createEventProcessor",0,bt,"sentryIntegration",0,bu,"setupExpressErrorHandler",0,bq,"setupExpressRequestContext",0,bp],74493)}];
2
2
 
3
3
  //# sourceMappingURL=node_modules_posthog-node_dist_entrypoints_index_node_mjs_0mebn66._.js.map