oh-my-opencode 5.0.0-beta.2 → 5.0.0-beta.21

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 (460) hide show
  1. package/.agents/command/publish.md +44 -16
  2. package/.agents/skills/publish/SKILL.md +44 -16
  3. package/.agents/skills/senpi-qa/SKILL.md +80 -0
  4. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.mjs +65 -0
  5. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs +171 -0
  6. package/.agents/skills/work-with-pr/SKILL.md +37 -23
  7. package/.opencode/command/publish.md +44 -16
  8. package/.opencode/skills/work-with-pr/SKILL.md +37 -23
  9. package/README.ja.md +25 -21
  10. package/README.ko.md +25 -21
  11. package/README.md +38 -23
  12. package/README.ru.md +24 -20
  13. package/README.zh-cn.md +25 -21
  14. package/dist/agents/atlas/agent.d.ts +0 -1
  15. package/dist/agents/sisyphus/grok-4.d.ts +20 -0
  16. package/dist/agents/sisyphus/index.d.ts +2 -0
  17. package/dist/agents/sisyphus-agent-config.d.ts +6 -0
  18. package/dist/agents/sisyphus-agent-factory.d.ts +1 -1
  19. package/dist/agents/sisyphus-runtime-prompt-reconciler.d.ts +15 -4
  20. package/dist/agents/types.d.ts +2 -2
  21. package/dist/cli/fallback-lane-policy.d.ts +1 -0
  22. package/dist/cli/index.js +23057 -20893
  23. package/dist/cli/install-codex/install-codex-test-fixtures.d.ts +1 -1
  24. package/dist/cli/run/on-complete-hook.d.ts +2 -0
  25. package/dist/cli/runtime-commands.d.ts +1 -1
  26. package/dist/cli/worktree-sweep/classify.d.ts +16 -0
  27. package/dist/cli/worktree-sweep/format.d.ts +8 -0
  28. package/dist/cli/worktree-sweep/git.d.ts +19 -0
  29. package/dist/cli/worktree-sweep/index.d.ts +7 -0
  30. package/dist/cli/worktree-sweep/options.d.ts +2 -0
  31. package/dist/cli/worktree-sweep/parse-worktree-list.d.ts +8 -0
  32. package/dist/cli/worktree-sweep/sweep.d.ts +2 -0
  33. package/dist/cli/worktree-sweep/types.d.ts +65 -0
  34. package/dist/cli/worktree-sweep/worktree-sweep.d.ts +2 -0
  35. package/dist/cli-node/index.js +23093 -20929
  36. package/dist/config/schema/commands.d.ts +1 -1
  37. package/dist/config/schema/hooks.d.ts +1 -1
  38. package/dist/config/schema/oh-my-opencode-config.d.ts +4 -1
  39. package/dist/config/schema/ulw-execute.d.ts +5 -0
  40. package/dist/config/validate.d.ts +2 -0
  41. package/dist/create-hooks.d.ts +3 -1
  42. package/dist/features/btw-side/btw-command-draft.d.ts +7 -0
  43. package/dist/features/btw-side/context-injector.d.ts +15 -0
  44. package/dist/features/btw-side/index.d.ts +8 -0
  45. package/dist/features/btw-side/metadata.d.ts +15 -0
  46. package/dist/features/btw-side/parent-context-budget.d.ts +9 -0
  47. package/dist/features/btw-side/server-session-registry.d.ts +8 -0
  48. package/dist/features/btw-side/tui-adoption-cache.d.ts +13 -0
  49. package/dist/features/btw-side/tui-adoption-guard.d.ts +5 -0
  50. package/dist/features/btw-side/tui-controller-types.d.ts +68 -0
  51. package/dist/features/btw-side/tui-controller.d.ts +19 -0
  52. package/dist/features/btw-side/tui-escape-return.d.ts +12 -0
  53. package/dist/features/btw-side/tui-keymap.d.ts +17 -0
  54. package/dist/features/btw-side/tui-parent-validator.d.ts +6 -0
  55. package/dist/features/btw-side/tui-picker-options.d.ts +20 -0
  56. package/dist/features/btw-side/tui-picker.d.ts +9 -0
  57. package/dist/features/btw-side/tui-prompt-queue.d.ts +8 -0
  58. package/dist/features/btw-side/tui-session-bridge.d.ts +11 -0
  59. package/dist/features/btw-side/tui-session-catalog.d.ts +35 -0
  60. package/dist/features/btw-side/tui-side-removal.d.ts +11 -0
  61. package/dist/features/btw-side/tui-side-start.d.ts +9 -0
  62. package/dist/features/btw-side/tui-wiring.d.ts +8 -0
  63. package/dist/features/builtin-commands/templates/ulw-execute.d.ts +1 -0
  64. package/dist/features/builtin-commands/types.d.ts +1 -1
  65. package/dist/features/opengateway-provider/index.d.ts +13 -0
  66. package/dist/hooks/atlas/atlas-hook.d.ts +1 -0
  67. package/dist/hooks/atlas/atlas-lifecycle-store.d.ts +50 -0
  68. package/dist/hooks/atlas/event-handler.d.ts +1 -0
  69. package/dist/hooks/atlas/final-wave-approval-gate.test-support.d.ts +50 -0
  70. package/dist/hooks/atlas/system-reminder-templates.d.ts +0 -1
  71. package/dist/hooks/atlas/tool-execute-before.d.ts +3 -0
  72. package/dist/hooks/atlas/types.d.ts +1 -0
  73. package/dist/hooks/index.d.ts +1 -1
  74. package/dist/hooks/prometheus-md-only/agent-resolution.d.ts +2 -2
  75. package/dist/hooks/runtime-fallback/chat-message-handler.d.ts +2 -0
  76. package/dist/hooks/runtime-fallback/retry-model-payload.d.ts +1 -0
  77. package/dist/hooks/runtime-fallback/runtime-model-settings.d.ts +6 -0
  78. package/dist/hooks/runtime-fallback/session-status-handler.d.ts +1 -1
  79. package/dist/hooks/runtime-fallback/types.d.ts +3 -1
  80. package/dist/hooks/sisyphus-junior-notepad/constants.d.ts +1 -1
  81. package/dist/hooks/{start-work → ulw-execute}/context-info-builder.d.ts +1 -1
  82. package/dist/hooks/{start-work → ulw-execute}/index.d.ts +1 -1
  83. package/dist/hooks/ulw-execute/ulw-execute-hook.d.ts +23 -0
  84. package/dist/index.js +11724 -6355
  85. package/dist/oh-my-opencode.schema.json +15 -2
  86. package/dist/plugin/chat-message/types.d.ts +3 -3
  87. package/dist/plugin/chat-message/ulw-execute-message.d.ts +5 -0
  88. package/dist/plugin/event-session-lifecycle.d.ts +1 -0
  89. package/dist/plugin/hooks/create-core-hooks.d.ts +2 -1
  90. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -2
  91. package/dist/plugin/hooks/create-transform-hooks.d.ts +2 -0
  92. package/dist/plugin/messages-transform.d.ts +1 -0
  93. package/dist/shared/index.d.ts +1 -0
  94. package/dist/shared/normalize-sdk-response.d.ts +1 -0
  95. package/dist/shared/runtime-fallback-retry-marker.d.ts +16 -0
  96. package/dist/shared/shell-env.d.ts +1 -1
  97. package/dist/skills/ast-grep/AGENTS.md +51 -0
  98. package/dist/skills/coding-agent-sessions/AGENTS.md +62 -0
  99. package/dist/skills/coding-agent-sessions/SKILL.md +3 -2
  100. package/dist/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  101. package/dist/skills/coding-agent-sessions/references/senpi.md +4 -4
  102. package/dist/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  103. package/dist/skills/frontend/SKILL.md +11 -7
  104. package/dist/skills/frontend/references/design/_INDEX.md +1 -0
  105. package/dist/skills/frontend/references/design/print-paged-media.md +76 -0
  106. package/dist/skills/frontend/references/design/stylegallery.md +80 -0
  107. package/dist/skills/frontend/references/designpowers/README.md +1 -1
  108. package/dist/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  109. package/dist/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  110. package/dist/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  111. package/dist/skills/frontend/references/designpowers/orchestration.md +1 -1
  112. package/dist/skills/frontend/references/designpowers/routing.md +5 -5
  113. package/dist/skills/review-work/SKILL.md +3 -3
  114. package/dist/skills/ultimate-browsing/ATTRIBUTION.md +37 -10
  115. package/dist/skills/ultimate-browsing/SKILL.md +2 -0
  116. package/dist/skills/ultimate-browsing/engine/AGENTS.md +179 -0
  117. package/dist/skills/ultimate-browsing/engine/templates/package.json +1 -1
  118. package/dist/skills/ultimate-browsing/references/chrome-stealth.md +13 -11
  119. package/dist/skills/{start-work → ulw-execute}/SKILL.md +9 -8
  120. package/dist/skills/ulw-plan/SKILL.md +6 -6
  121. package/dist/skills/ulw-plan/references/full-workflow.md +31 -7
  122. package/dist/skills/ulw-plan/references/intent-clear.md +2 -1
  123. package/dist/skills/ulw-plan/references/intent-unclear.md +5 -5
  124. package/dist/skills/ulw-research/SKILL.md +1 -1
  125. package/dist/skills/visual-qa/AGENTS.md +58 -0
  126. package/dist/skills/visual-qa/SKILL.md +3 -2
  127. package/dist/tools/delegate-task/builtin-categories.d.ts +1 -0
  128. package/dist/tools/delegate-task/builtin-category-definition.d.ts +1 -0
  129. package/dist/tools/delegate-task/tool-description.d.ts +3 -1
  130. package/dist/tui.js +8824 -8906
  131. package/package.json +38 -35
  132. package/packages/git-bash-mcp/dist/cli.js +5 -1
  133. package/packages/git-bash-mcp/package.json +1 -1
  134. package/packages/lsp-core/src/lsp/client-diagnostics-concurrency.integration.test.ts +44 -0
  135. package/packages/lsp-core/src/lsp/client-diagnostics-freshness.integration.test.ts +0 -28
  136. package/packages/lsp-core/src/lsp/client-wrapper-outside-cwd.test.ts +78 -0
  137. package/packages/lsp-core/src/lsp/client-wrapper.test.ts +66 -13
  138. package/packages/lsp-core/src/lsp/client-wrapper.ts +70 -18
  139. package/packages/lsp-core/src/lsp/outside-context-workspace.ts +33 -0
  140. package/packages/lsp-core/src/lsp/workspace-edit-adversarial.test.ts +20 -1
  141. package/packages/lsp-core/src/lsp/workspace-markers.ts +1 -0
  142. package/packages/lsp-core/src/tools/diagnostics.ts +3 -3
  143. package/packages/lsp-core/src/tools/navigation.ts +4 -2
  144. package/packages/lsp-core/src/tools/rename.ts +4 -2
  145. package/packages/lsp-core/src/tools/symbols.ts +1 -1
  146. package/packages/lsp-daemon/dist/cli.js +246 -185
  147. package/packages/lsp-daemon/dist/client.js +222 -164
  148. package/packages/lsp-daemon/dist/ensure-daemon.js +1 -0
  149. package/packages/lsp-daemon/dist/index.js +236 -177
  150. package/packages/lsp-daemon/dist/version-reap.js +1 -1
  151. package/packages/lsp-tools-mcp/dist/cli.js +198 -136
  152. package/packages/lsp-tools-mcp/dist/lsp/manager.js +62 -92
  153. package/packages/lsp-tools-mcp/dist/mcp.js +200 -138
  154. package/packages/lsp-tools-mcp/dist/request-context.js +11 -12
  155. package/packages/lsp-tools-mcp/dist/tools.js +204 -146
  156. package/packages/omo-codex/THIRD-PARTY-NOTICES.md +4 -4
  157. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +4 -4
  158. package/packages/omo-codex/plugin/AGENTS.md +47 -0
  159. package/packages/omo-codex/plugin/README.md +1 -1
  160. package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +32 -31
  161. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  162. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  163. package/packages/omo-codex/plugin/components/bootstrap/src/hook.ts +1 -0
  164. package/packages/omo-codex/plugin/components/codegraph/dist/cli.js +224 -81
  165. package/packages/omo-codex/plugin/components/codegraph/dist/serve.js +224 -82
  166. package/packages/omo-codex/plugin/components/codegraph/package.json +4 -4
  167. package/packages/omo-codex/plugin/components/codegraph/src/mcp-bridge.ts +1 -0
  168. package/packages/omo-codex/plugin/components/codegraph/src/session-start-hook-runtime.ts +1 -0
  169. package/packages/omo-codex/plugin/components/comment-checker/AGENTS.md +9 -0
  170. package/packages/omo-codex/plugin/components/comment-checker/biome.json +2 -2
  171. package/packages/omo-codex/plugin/components/comment-checker/dist/cli.js +2 -1
  172. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  173. package/packages/omo-codex/plugin/components/comment-checker/package.json +5 -5
  174. package/packages/omo-codex/plugin/components/comment-checker/src/apply-patch.ts +2 -8
  175. package/packages/omo-codex/plugin/components/comment-checker/src/core.ts +1 -2
  176. package/packages/omo-codex/plugin/components/comment-checker/src/request-extractor.ts +1 -1
  177. package/packages/omo-codex/plugin/components/comment-checker/src/runner.ts +1 -0
  178. package/packages/omo-codex/plugin/components/git-bash/AGENTS.md +1 -1
  179. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  180. package/packages/omo-codex/plugin/components/git-bash/package.json +3 -4
  181. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/biome.json +2 -2
  182. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/cli.js +1 -5
  183. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/codex-hook.js +1 -5
  184. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  185. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +5 -5
  186. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/src/codex-hook.ts +1 -5
  187. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/test/codex-hook.test.ts +4 -21
  188. package/packages/omo-codex/plugin/components/lsp/AGENTS.md +30 -15
  189. package/packages/omo-codex/plugin/components/lsp/biome.json +2 -2
  190. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +4 -4
  191. package/packages/omo-codex/plugin/components/lsp/dist/cli.js +217 -171
  192. package/packages/omo-codex/plugin/components/lsp/dist/daemon-cli-path.js +1 -1
  193. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  194. package/packages/omo-codex/plugin/components/lsp/package.json +5 -5
  195. package/packages/omo-codex/plugin/components/lsp/src/cli.ts +1 -1
  196. package/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts +1 -1
  197. package/packages/omo-codex/plugin/components/lsp/src/daemon-cli-path.ts +1 -5
  198. package/packages/omo-codex/plugin/components/lsp/test/codex-hook-unavailable.test.ts +6 -7
  199. package/packages/omo-codex/plugin/components/lsp/test/codex-hook.test.ts +1 -2
  200. package/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts +11 -1
  201. package/packages/omo-codex/plugin/components/rules/AGENTS.md +12 -0
  202. package/packages/omo-codex/plugin/components/rules/biome.json +2 -2
  203. package/packages/omo-codex/plugin/components/rules/dist/cli.js +57 -42
  204. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  205. package/packages/omo-codex/plugin/components/rules/package.json +7 -7
  206. package/packages/omo-codex/plugin/components/rules/src/config.ts +1 -2
  207. package/packages/omo-codex/plugin/components/rules/src/persistent-cache.ts +1 -2
  208. package/packages/omo-codex/plugin/components/rules/src/post-compact-budget.ts +6 -2
  209. package/packages/omo-codex/plugin/components/rules/src/rules-engine-factory.ts +1 -4
  210. package/packages/omo-codex/plugin/components/rules/src/static-injection.ts +4 -9
  211. package/packages/omo-codex/plugin/components/rules/test/bundled-rules-priority.test.ts +11 -16
  212. package/packages/omo-codex/plugin/components/rules/test/bundled-rules.test.ts +17 -25
  213. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-budget.test.ts +9 -7
  214. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-context.test.ts +0 -6
  215. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-dedup.test.ts +6 -4
  216. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-directive.test.ts +12 -9
  217. package/packages/omo-codex/plugin/components/rules/test/codex-hook.test.ts +28 -37
  218. package/packages/omo-codex/plugin/components/rules/test/dynamic-target-fingerprints.test.ts +1 -2
  219. package/packages/omo-codex/plugin/components/rules/test/engine.test.ts +7 -4
  220. package/packages/omo-codex/plugin/components/rules/test/finder.test.ts +2 -3
  221. package/packages/omo-codex/plugin/components/rules/test/formatter.test.ts +39 -72
  222. package/packages/omo-codex/plugin/components/rules/test/hephaestus-model-variant.test.ts +1 -2
  223. package/packages/omo-codex/plugin/components/rules/test/hook-output.test.ts +2 -3
  224. package/packages/omo-codex/plugin/components/rules/test/matcher.test.ts +2 -3
  225. package/packages/omo-codex/plugin/components/rules/test/package-smoke.test.ts +1 -1
  226. package/packages/omo-codex/plugin/components/rules/test/parser.test.ts +1 -2
  227. package/packages/omo-codex/plugin/components/rules/test/post-compact-budget.test.ts +1 -2
  228. package/packages/omo-codex/plugin/components/rules/test/rules-engine-consumption.test.ts +3 -6
  229. package/packages/omo-codex/plugin/components/rules/test/scanner.test.ts +1 -2
  230. package/packages/omo-codex/plugin/components/rules/test/sources.test.ts +2 -5
  231. package/packages/omo-codex/plugin/components/rules/test/windows-git-bash-bundled-rule.test.ts +2 -17
  232. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  233. package/packages/omo-codex/plugin/components/teammode/package.json +5 -5
  234. package/packages/omo-codex/plugin/components/teammode/test/thread-title-hook.test.ts +3 -9
  235. package/packages/omo-codex/plugin/components/telemetry/AGENTS.md +8 -0
  236. package/packages/omo-codex/plugin/components/telemetry/biome.json +2 -2
  237. package/packages/omo-codex/plugin/components/telemetry/dist/cli.js +2433 -422
  238. package/packages/omo-codex/plugin/components/telemetry/dist/posthog.js +2437 -426
  239. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  240. package/packages/omo-codex/plugin/components/telemetry/package.json +5 -5
  241. package/packages/omo-codex/plugin/components/telemetry/src/codex-hook.ts +1 -4
  242. package/packages/omo-codex/plugin/components/telemetry/src/posthog.ts +4 -14
  243. package/packages/omo-codex/plugin/components/telemetry/src/product-identity.ts +1 -1
  244. package/packages/omo-codex/plugin/components/telemetry/test/diagnostics.test.ts +2 -5
  245. package/packages/omo-codex/plugin/components/ultrawork/AGENTS.md +5 -0
  246. package/packages/omo-codex/plugin/components/ultrawork/biome.json +2 -2
  247. package/packages/omo-codex/plugin/components/ultrawork/directive.md +13 -1
  248. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  249. package/packages/omo-codex/plugin/components/ultrawork/package.json +5 -5
  250. package/packages/omo-codex/plugin/components/ultrawork/skills/ultrawork/SKILL.md +13 -1
  251. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/SKILL.md +6 -6
  252. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/full-workflow.md +31 -7
  253. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-clear.md +2 -1
  254. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-unclear.md +5 -5
  255. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook-trigger-policy.test.ts +9 -1
  256. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook.test.ts +0 -136
  257. package/packages/omo-codex/plugin/components/ultrawork/test/skill-pointer.test.ts +0 -2
  258. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/AGENTS.md +5 -4
  259. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/NOTICE +1 -1
  260. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/README.md +5 -5
  261. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/biome.json +2 -2
  262. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/directive.md +6 -6
  263. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/dist/cli.js +12 -12
  264. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +28 -0
  265. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/package.json +12 -12
  266. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/boulder-reader.ts +1 -1
  267. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/cli.ts +1 -1
  268. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/codex-hook.ts +3 -3
  269. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/directive.ts +1 -1
  270. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/index.ts +1 -1
  271. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/boulder-reader.test.ts +3 -3
  272. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/cli.test.ts +1 -4
  273. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/codex-hook.test.ts +8 -22
  274. package/packages/omo-codex/plugin/components/ulw-loop/AGENTS.md +16 -0
  275. package/packages/omo-codex/plugin/components/ulw-loop/CHANGELOG.md +1 -1
  276. package/packages/omo-codex/plugin/components/ulw-loop/biome.json +2 -2
  277. package/packages/omo-codex/plugin/components/ulw-loop/directive.md +13 -1
  278. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli.js +2 -4
  279. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-snapshot.js +1 -1
  280. package/packages/omo-codex/plugin/components/ulw-loop/dist/paths.js +1 -1
  281. package/packages/omo-codex/plugin/components/ulw-loop/dist/stop-resume-hook.js +3 -3
  282. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +4 -4
  283. package/packages/omo-codex/plugin/components/ulw-loop/package.json +5 -5
  284. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/SKILL.md +3 -2
  285. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/define-goal.md +108 -0
  286. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/full-workflow.md +1 -0
  287. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-goal-snapshot.ts +3 -1
  288. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-hook.ts +3 -1
  289. package/packages/omo-codex/plugin/components/ulw-loop/src/paths.ts +1 -1
  290. package/packages/omo-codex/plugin/components/ulw-loop/src/stop-resume-hook.ts +3 -3
  291. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-continuation.test.ts +0 -1
  292. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-create-goals.test.ts +25 -0
  293. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-instruction.test.ts +2 -2
  294. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-snapshot.test.ts +18 -0
  295. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-hook.test.ts +0 -3
  296. package/packages/omo-codex/plugin/components/ulw-loop/test/package-smoke.test.ts +5 -37
  297. package/packages/omo-codex/plugin/components/ulw-loop/test/paths.test.ts +9 -0
  298. package/packages/omo-codex/plugin/components/ulw-loop/test/steering.test.ts +8 -5
  299. package/packages/omo-codex/plugin/components/ulw-loop/test/stop-resume-hook.test.ts +1 -1
  300. package/packages/omo-codex/plugin/components/ulw-loop/test/ultrawork-directive.test.ts +4 -5
  301. package/packages/omo-codex/plugin/components/ulw-loop/vitest.config.ts +1 -0
  302. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  303. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  304. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  305. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-codegraph-init-guidance.json +1 -1
  306. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  307. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  308. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  309. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  310. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  311. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  312. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  313. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  314. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  315. package/packages/omo-codex/plugin/hooks/session-start-checking-codegraph-bootstrap.json +1 -1
  316. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  317. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  318. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +17 -0
  319. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  320. package/packages/omo-codex/plugin/hooks/subagent-stop-checking-ulw-execute-continuation.json +17 -0
  321. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  322. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  323. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  324. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  325. package/packages/omo-codex/plugin/package-lock.json +681 -395
  326. package/packages/omo-codex/plugin/package.json +2 -2
  327. package/packages/omo-codex/plugin/scripts/AGENTS.md +40 -0
  328. package/packages/omo-codex/plugin/scripts/auto-update-plan.mjs +1 -1
  329. package/packages/omo-codex/plugin/scripts/sync-skills.mjs +11 -11
  330. package/packages/omo-codex/plugin/shared/package.json +3 -4
  331. package/packages/omo-codex/plugin/skills/ast-grep/AGENTS.md +51 -0
  332. package/packages/omo-codex/plugin/skills/coding-agent-sessions/AGENTS.md +62 -0
  333. package/packages/omo-codex/plugin/skills/coding-agent-sessions/SKILL.md +3 -2
  334. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  335. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/senpi.md +4 -4
  336. package/packages/omo-codex/plugin/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  337. package/packages/omo-codex/plugin/skills/frontend/SKILL.md +11 -7
  338. package/packages/omo-codex/plugin/skills/frontend/references/design/_INDEX.md +1 -0
  339. package/packages/omo-codex/plugin/skills/frontend/references/design/print-paged-media.md +76 -0
  340. package/packages/omo-codex/plugin/skills/frontend/references/design/stylegallery.md +80 -0
  341. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/README.md +1 -1
  342. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  343. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  344. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  345. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/orchestration.md +1 -1
  346. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/routing.md +5 -5
  347. package/packages/omo-codex/plugin/skills/review-work/SKILL.md +4 -4
  348. package/packages/omo-codex/plugin/skills/ultimate-browsing/ATTRIBUTION.md +37 -10
  349. package/packages/omo-codex/plugin/skills/ultimate-browsing/SKILL.md +2 -0
  350. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/AGENTS.md +179 -0
  351. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/templates/package.json +1 -1
  352. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/chrome-stealth.md +13 -11
  353. package/packages/omo-codex/plugin/skills/ultrawork/SKILL.md +13 -1
  354. package/packages/omo-codex/plugin/skills/{start-work → ulw-execute}/SKILL.md +12 -11
  355. package/packages/omo-codex/plugin/skills/ulw-execute/agents/openai.yaml +2 -0
  356. package/packages/omo-codex/plugin/skills/ulw-loop/SKILL.md +3 -2
  357. package/packages/omo-codex/plugin/skills/ulw-loop/references/define-goal.md +108 -0
  358. package/packages/omo-codex/plugin/skills/ulw-loop/references/full-workflow.md +1 -0
  359. package/packages/omo-codex/plugin/skills/ulw-plan/SKILL.md +6 -6
  360. package/packages/omo-codex/plugin/skills/ulw-plan/references/full-workflow.md +31 -7
  361. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-clear.md +2 -1
  362. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-unclear.md +5 -5
  363. package/packages/omo-codex/plugin/skills/ulw-research/SKILL.md +1 -1
  364. package/packages/omo-codex/plugin/skills/visual-qa/AGENTS.md +58 -0
  365. package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +3 -2
  366. package/packages/omo-codex/plugin/test/AGENTS.md +47 -0
  367. package/packages/omo-codex/plugin/test/aggregate-agents.test.mjs +19 -173
  368. package/packages/omo-codex/plugin/test/aggregate-hooks.test.mjs +8 -28
  369. package/packages/omo-codex/plugin/test/aggregate-manifest.test.mjs +1 -1
  370. package/packages/omo-codex/plugin/test/aggregate-plugin-fixture.mjs +175 -13
  371. package/packages/omo-codex/plugin/test/aggregate.test.mjs +78 -2
  372. package/packages/omo-codex/plugin/test/auto-update-release-notes.test.mjs +19 -33
  373. package/packages/omo-codex/plugin/test/component-bin-names.test.mjs +2 -2
  374. package/packages/omo-codex/plugin/test/component-bundled-cli.test.mjs +1 -1
  375. package/packages/omo-codex/plugin/test/component-hook-contract-cases.mjs +2 -2
  376. package/packages/omo-codex/plugin/test/hook-status-message.test.mjs +4 -4
  377. package/packages/omo-codex/plugin/test/lcx-contribute-bug-fix-template.test.mjs +21 -27
  378. package/packages/omo-codex/plugin/test/scaffold-plan.test.mjs +0 -36
  379. package/packages/omo-codex/plugin/test/sync-skills-codex-compatibility.test.mjs +101 -0
  380. package/packages/omo-codex/plugin/test/sync-skills-test-support.mjs +12 -12
  381. package/packages/omo-codex/plugin/test/sync-skills.test.mjs +1 -119
  382. package/packages/omo-codex/plugin/test/teammode-archive-ambiguity.test.mjs +0 -40
  383. package/packages/omo-codex/plugin/test/teammode-communication.test.mjs +6 -62
  384. package/packages/omo-codex/plugin/test/teammode-thread-links.test.mjs +3 -36
  385. package/packages/omo-codex/plugin/test/teammode-transport.test.mjs +0 -44
  386. package/packages/omo-codex/plugin/test/teammode-worktree.test.mjs +2 -6
  387. package/packages/omo-codex/plugin/test/ultrawork-skill-pointer.test.mjs +0 -3
  388. package/packages/omo-codex/plugin/test/ulw-plan-review-state-contract.test.mjs +0 -3
  389. package/packages/omo-codex/scripts/AGENTS.md +36 -0
  390. package/packages/omo-codex/scripts/install-dist/install-local.mjs +2601 -528
  391. package/packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs +7 -2
  392. package/packages/shared-skills/skills/ast-grep/AGENTS.md +51 -0
  393. package/packages/shared-skills/skills/coding-agent-sessions/AGENTS.md +62 -0
  394. package/packages/shared-skills/skills/coding-agent-sessions/SKILL.md +3 -2
  395. package/packages/shared-skills/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  396. package/packages/shared-skills/skills/coding-agent-sessions/references/senpi.md +4 -4
  397. package/packages/shared-skills/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  398. package/packages/shared-skills/skills/frontend/SKILL.md +11 -7
  399. package/packages/shared-skills/skills/frontend/references/design/_INDEX.md +1 -0
  400. package/packages/shared-skills/skills/frontend/references/design/print-paged-media.md +76 -0
  401. package/packages/shared-skills/skills/frontend/references/design/stylegallery.md +80 -0
  402. package/packages/shared-skills/skills/frontend/references/designpowers/README.md +1 -1
  403. package/packages/shared-skills/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  404. package/packages/shared-skills/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  405. package/packages/shared-skills/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  406. package/packages/shared-skills/skills/frontend/references/designpowers/orchestration.md +1 -1
  407. package/packages/shared-skills/skills/frontend/references/designpowers/routing.md +5 -5
  408. package/packages/shared-skills/skills/review-work/SKILL.md +3 -3
  409. package/packages/shared-skills/skills/ultimate-browsing/ATTRIBUTION.md +37 -10
  410. package/packages/shared-skills/skills/ultimate-browsing/SKILL.md +2 -0
  411. package/packages/shared-skills/skills/ultimate-browsing/engine/AGENTS.md +179 -0
  412. package/packages/shared-skills/skills/ultimate-browsing/engine/templates/package.json +1 -1
  413. package/packages/shared-skills/skills/ultimate-browsing/references/chrome-stealth.md +13 -11
  414. package/packages/shared-skills/skills/{start-work → ulw-execute}/SKILL.md +9 -8
  415. package/packages/shared-skills/skills/ulw-plan/SKILL.md +6 -6
  416. package/packages/shared-skills/skills/ulw-plan/references/full-workflow.md +31 -7
  417. package/packages/shared-skills/skills/ulw-plan/references/intent-clear.md +2 -1
  418. package/packages/shared-skills/skills/ulw-plan/references/intent-unclear.md +5 -5
  419. package/packages/shared-skills/skills/ulw-research/SKILL.md +1 -1
  420. package/packages/shared-skills/skills/visual-qa/AGENTS.md +58 -0
  421. package/packages/shared-skills/skills/visual-qa/SKILL.md +3 -2
  422. package/script/qa/web-terminal-visual-qa.mjs +2 -0
  423. package/script/qa/xterm-live-terminal.mjs +18 -2
  424. package/dist/config/schema/start-work.d.ts +0 -5
  425. package/dist/features/builtin-commands/templates/start-work.d.ts +0 -1
  426. package/dist/hooks/start-work/start-work-hook.d.ts +0 -23
  427. package/dist/plugin/chat-message/start-work-message.d.ts +0 -5
  428. package/dist/tools/call-omo-agent/background-agent-executor.d.ts +0 -5
  429. package/packages/omo-codex/plugin/components/start-work-continuation/hooks/hooks.json +0 -28
  430. package/packages/omo-codex/plugin/hooks/stop-checking-start-work-continuation.json +0 -17
  431. package/packages/omo-codex/plugin/hooks/subagent-stop-checking-start-work-continuation.json +0 -17
  432. package/packages/omo-codex/plugin/skills/start-work/agents/openai.yaml +0 -2
  433. package/packages/omo-codex/plugin/test/aggregate-skills.test.mjs +0 -92
  434. package/packages/omo-codex/plugin/test/sync-skills-orchestration.test.mjs +0 -314
  435. package/packages/omo-codex/plugin/test/ulw-plan-scope-contract.test.mjs +0 -24
  436. /package/dist/hooks/{start-work → ulw-execute}/context-info-formatters.d.ts +0 -0
  437. /package/dist/hooks/{start-work → ulw-execute}/explicit-plan-context.d.ts +0 -0
  438. /package/dist/hooks/{start-work → ulw-execute}/notepad-scaffold.d.ts +0 -0
  439. /package/dist/hooks/{start-work → ulw-execute}/parse-user-request.d.ts +0 -0
  440. /package/dist/hooks/{start-work → ulw-execute}/plan-discovery-context.d.ts +0 -0
  441. /package/dist/hooks/{start-work → ulw-execute}/plan-selection.d.ts +0 -0
  442. /package/dist/hooks/{start-work → ulw-execute}/session-plan-affinity.d.ts +0 -0
  443. /package/dist/hooks/{start-work → ulw-execute}/work-initializer.d.ts +0 -0
  444. /package/dist/hooks/{start-work → ulw-execute}/worktree-block.d.ts +0 -0
  445. /package/dist/hooks/{start-work → ulw-execute}/worktree-detector.d.ts +0 -0
  446. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/.gitattributes +0 -0
  447. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/CHANGELOG.md +0 -0
  448. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/LICENSE +0 -0
  449. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/plan-checklist.ts +0 -0
  450. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/types.ts +0 -0
  451. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-completed.json +0 -0
  452. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-mixed-platforms.json +0 -0
  453. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-single-codex-work.json +0 -0
  454. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-all-done.md +0 -0
  455. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-scaffold.md +0 -0
  456. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-nested-checkboxes.md +0 -0
  457. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-unchecked.md +0 -0
  458. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.build.json +0 -0
  459. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.json +0 -0
  460. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/vitest.config.ts +0 -0
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // omo-codex-install:7bc4b0f020f0a1b4448cc75385a7e3c60042e3b270e304d4c1a43a859e81a4c2:4c93b95fbe888175c5755a1acb72a046e2ca6abc572d7a53842a6d756711634c
2
+ // omo-codex-install:475155d5e39ca774e5cf86194fee97439fd9c4f3624a85e946a994d5493e4629:a81031b3fe18e3977f1f0ad2b0683290efaaaa1a0a05202aecf0b69725c05678
3
3
  var __defProp = Object.defineProperty;
4
4
  var __returnValue = (v) => v;
5
5
  function __exportSetter(name, newValue) {
@@ -177,7 +177,7 @@ var init_activity_state = __esm(() => {
177
177
  });
178
178
 
179
179
  // packages/telemetry-core/src/constants.ts
180
- var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74";
180
+ var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74", UNCONFIGURED_POSTHOG_API_KEY = "phc_REPLACE_ME_OMO_NATIVE";
181
181
 
182
182
  // packages/telemetry-core/src/diagnostics.ts
183
183
  import { appendFileSync, existsSync as existsSync6, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
@@ -315,6 +315,9 @@ function shouldDisableTelemetry(input) {
315
315
  const env = input.env ?? process.env;
316
316
  const globalPrefix = input.globalEnvPrefix ?? "OMO";
317
317
  const prefixes = Array.from(new Set([globalPrefix, input.productEnvPrefix]));
318
+ if (isDisableFlag(env["DO_NOT_TRACK"])) {
319
+ return true;
320
+ }
318
321
  for (const prefix of prefixes) {
319
322
  if (isDisableFlag(env[`${prefix}_DISABLE_POSTHOG`])) {
320
323
  return true;
@@ -328,6 +331,13 @@ function shouldDisableTelemetry(input) {
328
331
  function getTelemetryApiKey(env = process.env, defaultApiKey = DEFAULT_POSTHOG_API_KEY) {
329
332
  return env["POSTHOG_API_KEY"]?.trim() ?? defaultApiKey;
330
333
  }
334
+ function isConfiguredTelemetryApiKey(apiKey) {
335
+ const normalized = apiKey.trim();
336
+ return normalized.length > 0 && normalized !== UNCONFIGURED_POSTHOG_API_KEY;
337
+ }
338
+ function hasTelemetryApiKey(env, defaultApiKey) {
339
+ return isConfiguredTelemetryApiKey(getTelemetryApiKey(env, defaultApiKey));
340
+ }
331
341
  function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST) {
332
342
  return env["POSTHOG_HOST"]?.trim() || defaultHost;
333
343
  }
@@ -337,18 +347,7 @@ var init_env = __esm(() => {
337
347
  SEND_OPT_OUT_VALUES = ["0", "false", "no", "yes"];
338
348
  });
339
349
 
340
- // packages/telemetry-core/src/machine-id.ts
341
- import { createHash as createHash3 } from "node:crypto";
342
- import os2 from "node:os";
343
- function getDefaultTelemetryOsProvider() {
344
- return os2;
345
- }
346
- function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
347
- return createHash3("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
348
- }
349
- var init_machine_id = () => {};
350
-
351
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
350
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
352
351
  import { dirname as dirname10, posix as posix2, sep as sep7 } from "node:path";
353
352
  function createModulerModifier() {
354
353
  const getModuleFromFileName = createGetModuleFromFilename();
@@ -385,7 +384,7 @@ function normalizeWindowsPath(path2) {
385
384
  }
386
385
  var init_module_node = () => {};
387
386
 
388
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/featureFlagUtils.mjs
387
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/featureFlagUtils.mjs
389
388
  function getFlagDetailFromFlagAndPayload(key, value, payload) {
390
389
  return {
391
390
  key,
@@ -450,10 +449,71 @@ var normalizeFlagsResponse = (flagsResponse) => {
450
449
  } catch {
451
450
  return response;
452
451
  }
452
+ }, MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES, MINIMAL_FLAG_CALLED_EVENT_PROPERTIES, minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
453
+ const minimal = {};
454
+ const copyKey = (key) => {
455
+ if (properties[key] !== undefined)
456
+ minimal[key] = properties[key];
457
+ };
458
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
459
+ transportKeys.forEach(copyKey);
460
+ return minimal;
453
461
  };
454
- var init_featureFlagUtils = () => {};
462
+ var init_featureFlagUtils = __esm(() => {
463
+ MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
464
+ "utm_source",
465
+ "utm_medium",
466
+ "utm_campaign",
467
+ "utm_content",
468
+ "utm_term",
469
+ "gad_source",
470
+ "mc_cid",
471
+ "gclid",
472
+ "gclsrc",
473
+ "dclid",
474
+ "gbraid",
475
+ "wbraid",
476
+ "fbclid",
477
+ "msclkid",
478
+ "twclid",
479
+ "li_fat_id",
480
+ "igshid",
481
+ "ttclid",
482
+ "rdt_cid",
483
+ "epik",
484
+ "qclid",
485
+ "sccid",
486
+ "irclid",
487
+ "_kx"
488
+ ];
489
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
490
+ "$feature_flag",
491
+ "$feature_flag_response",
492
+ "$feature_flag_has_experiment",
493
+ "$feature_flag_id",
494
+ "$feature_flag_version",
495
+ "$feature_flag_reason",
496
+ "$feature_flag_request_id",
497
+ "$feature_flag_evaluated_at",
498
+ "$feature_flag_error",
499
+ "locally_evaluated",
500
+ "$groups",
501
+ "$process_person_profile",
502
+ "$geoip_disable",
503
+ "$current_url",
504
+ "$pathname",
505
+ "$referring_domain",
506
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
507
+ "$session_id",
508
+ "$window_id",
509
+ "$lib",
510
+ "$lib_version",
511
+ "$device_id",
512
+ "$is_server"
513
+ ];
514
+ });
455
515
 
456
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/types.mjs
516
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/types.mjs
457
517
  var types_PostHogPersistedProperty;
458
518
  var init_types = __esm(() => {
459
519
  types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
@@ -470,6 +530,8 @@ var init_types = __esm(() => {
470
530
  PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
471
531
  PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
472
532
  PostHogPersistedProperty["Queue"] = "queue";
533
+ PostHogPersistedProperty["AiQueue"] = "ai_queue";
534
+ PostHogPersistedProperty["AiCaptureQueue"] = "ai_capture_queue";
473
535
  PostHogPersistedProperty["LogsQueue"] = "logs_queue";
474
536
  PostHogPersistedProperty["OptedOut"] = "opted_out";
475
537
  PostHogPersistedProperty["SessionId"] = "session_id";
@@ -480,6 +542,8 @@ var init_types = __esm(() => {
480
542
  PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
481
543
  PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
482
544
  PostHogPersistedProperty["SessionReplay"] = "session_replay";
545
+ PostHogPersistedProperty["PushRegistered"] = "push_registered";
546
+ PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
483
547
  PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
484
548
  PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
485
549
  PostHogPersistedProperty["Surveys"] = "surveys";
@@ -490,14 +554,14 @@ var init_types = __esm(() => {
490
554
  }({});
491
555
  });
492
556
 
493
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/gzip.mjs
557
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/gzip.mjs
494
558
  function isGzipSupported() {
495
559
  return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
496
560
  }
497
561
  async function gzipCompress(input, isDebug = true, options) {
498
562
  try {
499
563
  const inputBytes = new TextEncoder().encode(input);
500
- const compressedStream = new CompressionStream("gzip");
564
+ const compressedStream = new globalThis.CompressionStream("gzip");
501
565
  const writer = compressedStream.writable.getWriter();
502
566
  const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
503
567
  try {
@@ -558,7 +622,30 @@ var init_gzip = __esm(() => {
558
622
  init_types();
559
623
  });
560
624
 
561
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bot-detection.mjs
625
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/json-utils.mjs
626
+ function sanitizeString(value) {
627
+ let output = "";
628
+ for (let index = 0;index < value.length; index++) {
629
+ const codeUnit = value.charCodeAt(index);
630
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
631
+ const nextCodeUnit = value.charCodeAt(index + 1);
632
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
633
+ output += value[index] + value[index + 1];
634
+ index++;
635
+ } else
636
+ output += "�";
637
+ } else
638
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
639
+ }
640
+ return output;
641
+ }
642
+ var MAX_JSON_SAFE_VALUE_DEPTH = 20, MAX_JSON_SAFE_VALUE_ITEMS = 1000, MAX_JSON_SAFE_VALUE_NODES = 1e4, CIRCULAR_VALUE = "[Circular]", TRUNCATED_VALUE = "[Truncated]", UNSERIALIZABLE_VALUE = "[Unserializable]", FUNCTION_VALUE = "[Function]", dateGetTime, dateToISOString;
643
+ var init_json_utils = __esm(() => {
644
+ dateGetTime = Date.prototype.getTime;
645
+ dateToISOString = Date.prototype.toISOString;
646
+ });
647
+
648
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bot-detection.mjs
562
649
  var DEFAULT_BLOCKED_UA_STRS, isBlockedUA = function(ua, customBlockedUserAgents = []) {
563
650
  if (!ua)
564
651
  return false;
@@ -650,16 +737,56 @@ var init_bot_detection = __esm(() => {
650
737
  ];
651
738
  });
652
739
 
653
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/string-utils.mjs
740
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/string-utils.mjs
741
+ function safeJsonStringify(value) {
742
+ const ancestors = [];
743
+ return JSON.stringify(value, function(_key, replacementValue) {
744
+ if (typeof replacementValue == "bigint")
745
+ return replacementValue.toString();
746
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
747
+ return;
748
+ if (replacementValue instanceof Error)
749
+ return {
750
+ name: replacementValue.name,
751
+ message: replacementValue.message,
752
+ stack: replacementValue.stack
753
+ };
754
+ if (replacementValue && typeof replacementValue == "object") {
755
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
756
+ ancestors.pop();
757
+ if (ancestors.includes(replacementValue))
758
+ return "[Circular]";
759
+ ancestors.push(replacementValue);
760
+ }
761
+ return replacementValue;
762
+ }) ?? "null";
763
+ }
654
764
  var init_string_utils = () => {};
655
765
 
656
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/type-utils.mjs
766
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/browser-utils.mjs
767
+ var init_browser_utils = __esm(() => {
768
+ init_string_utils();
769
+ });
770
+
771
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/type-utils.mjs
657
772
  function isPrimitive(value) {
658
773
  return value === null || typeof value != "object";
659
774
  }
660
775
  function isBuiltin(candidate, className) {
661
776
  return Object.prototype.toString.call(candidate) === `[object ${className}]`;
662
777
  }
778
+ function isError(candidate) {
779
+ switch (Object.prototype.toString.call(candidate)) {
780
+ case "[object Error]":
781
+ case "[object Exception]":
782
+ case "[object DOMException]":
783
+ case "[object DOMError]":
784
+ case "[object WebAssembly.Exception]":
785
+ return true;
786
+ default:
787
+ return isInstanceOf(candidate, Error);
788
+ }
789
+ }
663
790
  function isErrorEvent(event) {
664
791
  return isBuiltin(event, "ErrorEvent");
665
792
  }
@@ -676,7 +803,7 @@ function isInstanceOf(candidate, base) {
676
803
  return false;
677
804
  }
678
805
  }
679
- var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isPlainError = (x) => x instanceof Error;
806
+ var nativeIsArray, ObjProto, type_utils_hasOwnProperty, type_utils_toString, isArray, isObject = (x) => x === Object(x) && !isArray(x), isUndefined = (x) => x === undefined, isString = (x) => type_utils_toString.call(x) == "[object String]", isEmptyString = (x) => isString(x) && x.trim().length === 0, isNull = (x) => x === null, isNullish = (x) => isUndefined(x) || isNull(x), isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x, isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
680
807
  var init_type_utils = __esm(() => {
681
808
  init_types();
682
809
  init_string_utils();
@@ -689,7 +816,7 @@ var init_type_utils = __esm(() => {
689
816
  };
690
817
  });
691
818
 
692
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/number-utils.mjs
819
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/number-utils.mjs
693
820
  function clampToRange(value, min, max, logger, fallbackValue) {
694
821
  if (min > max) {
695
822
  logger.warn("min cannot be greater than max.");
@@ -712,7 +839,14 @@ var init_number_utils = __esm(() => {
712
839
  init_type_utils();
713
840
  });
714
841
 
715
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
842
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
843
+ function resolveExceptionRateLimiterConfig(config = {}) {
844
+ return {
845
+ refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,
846
+ bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE
847
+ };
848
+ }
849
+
716
850
  class BucketedRateLimiter {
717
851
  constructor(options) {
718
852
  this._buckets = {};
@@ -754,12 +888,12 @@ class BucketedRateLimiter {
754
888
  this._buckets = {};
755
889
  }
756
890
  }
757
- var ONE_DAY_IN_MS = 86400000;
891
+ var ONE_DAY_IN_MS = 86400000, DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1, DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;
758
892
  var init_bucketed_rate_limiter = __esm(() => {
759
893
  init_number_utils();
760
894
  });
761
895
 
762
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
896
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
763
897
  class UUID {
764
898
  constructor(bytes) {
765
899
  this.bytes = bytes;
@@ -934,37 +1068,49 @@ var init_uuidv7 = __esm(() => {
934
1068
  /*! For license information please see uuidv7.mjs.LICENSE.txt */
935
1069
  });
936
1070
 
937
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/promise-queue.mjs
1071
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/promise-queue.mjs
938
1072
  class PromiseQueue {
939
1073
  add(promise) {
940
1074
  const promiseUUID = uuidv7();
941
- this.promiseByIds[promiseUUID] = promise;
1075
+ const id = ++this.nextId;
1076
+ this.promiseByIds[promiseUUID] = {
1077
+ id,
1078
+ promise
1079
+ };
942
1080
  promise.catch(() => {}).finally(() => {
943
1081
  delete this.promiseByIds[promiseUUID];
944
1082
  });
945
1083
  return promise;
946
1084
  }
947
1085
  async join() {
948
- let promises = Object.values(this.promiseByIds);
1086
+ let promises = Object.values(this.promiseByIds).map((item) => item.promise);
949
1087
  let length = promises.length;
950
1088
  while (length > 0) {
951
1089
  await Promise.all(promises);
952
- promises = Object.values(this.promiseByIds);
1090
+ promises = Object.values(this.promiseByIds).map((item) => item.promise);
953
1091
  length = promises.length;
954
1092
  }
955
1093
  }
1094
+ getPromises(ignoredPromises = [], maxId = this.nextId) {
1095
+ const ignoredPromiseSet = new Set(ignoredPromises);
1096
+ return Object.values(this.promiseByIds).filter((item) => item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item) => item.promise);
1097
+ }
1098
+ get maxId() {
1099
+ return this.nextId;
1100
+ }
956
1101
  get length() {
957
1102
  return Object.keys(this.promiseByIds).length;
958
1103
  }
959
1104
  constructor() {
960
1105
  this.promiseByIds = {};
1106
+ this.nextId = 0;
961
1107
  }
962
1108
  }
963
1109
  var init_promise_queue = __esm(() => {
964
1110
  init_uuidv7();
965
1111
  });
966
1112
 
967
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/logger.mjs
1113
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/logger.mjs
968
1114
  function createConsole(consoleLike = console) {
969
1115
  const lockedMethods = {
970
1116
  log: consoleLike.log.bind(consoleLike),
@@ -1006,8 +1152,8 @@ var _createLogger = (prefix, maybeCall, consoleLike) => {
1006
1152
  }, passThrough = (fn) => fn();
1007
1153
  var init_logger = () => {};
1008
1154
 
1009
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1010
- var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
1155
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1156
+ var MOBILE = "Mobile", IOS = "iOS", ANDROID = "Android", TABLET = "Tablet", ANDROID_TABLET, APPLE = "Apple", APPLE_WATCH, SAFARI = "Safari", BLACKBERRY = "BlackBerry", SAMSUNG = "Samsung", SAMSUNG_BROWSER, SAMSUNG_INTERNET, CHROME = "Chrome", CHROME_OS, CHROME_IOS, INTERNET_EXPLORER = "Internet Explorer", INTERNET_EXPLORER_MOBILE, OPERA = "Opera", OPERA_MINI, EDGE = "Edge", MICROSOFT_EDGE, FIREFOX = "Firefox", FIREFOX_IOS, NINTENDO = "Nintendo", PLAYSTATION = "PlayStation", XBOX = "Xbox", ANDROID_MOBILE, MOBILE_SAFARI, WINDOWS = "Windows", WINDOWS_PHONE, GENERIC = "Generic", GENERIC_MOBILE, GENERIC_TABLET, KONQUEROR = "Konqueror", OCULUS_BROWSER = "Oculus Browser", VIVALDI = "Vivaldi", YANDEX = "Yandex", WHALE = "Whale", DUCKDUCKGO = "DuckDuckGo", PALE_MOON = "Pale Moon", WATERFOX = "Waterfox", BRAVE = "Brave", GOOGLE_SEARCH_APP = "Google Search App", BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)", DEFAULT_BROWSER_VERSION_REGEX, XBOX_REGEX, PLAYSTATION_REGEX, NINTENDO_REGEX, BLACKBERRY_REGEX, windowsVersionMap, versionRegexes, osMatchers;
1011
1157
  var init_user_agent_utils = __esm(() => {
1012
1158
  init_string_utils();
1013
1159
  init_type_utils();
@@ -1112,6 +1258,9 @@ var init_user_agent_utils = __esm(() => {
1112
1258
  [WATERFOX]: [
1113
1259
  new RegExp(WATERFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1114
1260
  ],
1261
+ [GOOGLE_SEARCH_APP]: [
1262
+ new RegExp("GSA\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1263
+ ],
1115
1264
  [INTERNET_EXPLORER]: [
1116
1265
  new RegExp("(rv:|MSIE )" + BROWSER_VERSION_REGEX_SUFFIX)
1117
1266
  ],
@@ -1272,7 +1421,13 @@ var init_user_agent_utils = __esm(() => {
1272
1421
  ];
1273
1422
  });
1274
1423
 
1275
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/index.mjs
1424
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/index.mjs
1425
+ function isValidUUID(value) {
1426
+ return typeof value == "string" && UUID_REGEX.test(value);
1427
+ }
1428
+ function getEventUuid(uuid, generateUuid) {
1429
+ return isValidUUID(uuid) ? uuid : generateUuid();
1430
+ }
1276
1431
  function removeTrailingSlash(url) {
1277
1432
  return url?.replace(/\/+$/, "");
1278
1433
  }
@@ -1300,6 +1455,26 @@ function safeSetTimeout(fn, timeout) {
1300
1455
  t?.unref && t?.unref();
1301
1456
  return t;
1302
1457
  }
1458
+ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
1459
+ let timeoutHandle;
1460
+ try {
1461
+ return await Promise.race([
1462
+ promise,
1463
+ new Promise((resolve9, reject) => {
1464
+ timeoutHandle = safeSetTimeout(() => {
1465
+ try {
1466
+ onTimeout?.();
1467
+ resolve9();
1468
+ } catch (error) {
1469
+ reject(error);
1470
+ }
1471
+ }, timeoutMs);
1472
+ })
1473
+ ]);
1474
+ } finally {
1475
+ clearTimeout(timeoutHandle);
1476
+ }
1477
+ }
1303
1478
  function allSettled(promises) {
1304
1479
  return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
1305
1480
  status: "fulfilled",
@@ -1309,9 +1484,11 @@ function allSettled(promises) {
1309
1484
  reason
1310
1485
  }))));
1311
1486
  }
1312
- var STRING_FORMAT = "utf8", isError = (x) => x instanceof Error;
1487
+ var STRING_FORMAT = "utf8", UUID_REGEX;
1313
1488
  var init_utils = __esm(() => {
1489
+ init_json_utils();
1314
1490
  init_bot_detection();
1491
+ init_browser_utils();
1315
1492
  init_bucketed_rate_limiter();
1316
1493
  init_number_utils();
1317
1494
  init_string_utils();
@@ -1319,12 +1496,168 @@ var init_utils = __esm(() => {
1319
1496
  init_promise_queue();
1320
1497
  init_logger();
1321
1498
  init_user_agent_utils();
1499
+ UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1322
1500
  });
1323
1501
 
1324
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1325
- var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY;
1502
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1503
+ function newState() {
1504
+ return {
1505
+ ancestors: new WeakSet,
1506
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
1507
+ };
1508
+ }
1509
+ function toOtlpKeyValueList(attrs, logger2) {
1510
+ try {
1511
+ return encodeKeyValueList(attrs, logger2, newState(), 0);
1512
+ } catch {
1513
+ return [];
1514
+ }
1515
+ }
1516
+ function encodeAnyValue(value, logger2, state, depth) {
1517
+ if (state.remainingNodes <= 0)
1518
+ return {
1519
+ stringValue: TRUNCATED_VALUE
1520
+ };
1521
+ state.remainingNodes--;
1522
+ if (isBoolean(value))
1523
+ return {
1524
+ boolValue: value
1525
+ };
1526
+ if (typeof value == "number") {
1527
+ if (!Number.isFinite(value))
1528
+ return {
1529
+ stringValue: String(value)
1530
+ };
1531
+ if (Number.isInteger(value)) {
1532
+ if (Number.isSafeInteger(value))
1533
+ return {
1534
+ intValue: String(value)
1535
+ };
1536
+ if (typeof BigInt == "undefined")
1537
+ return {
1538
+ stringValue: String(value)
1539
+ };
1540
+ const decimal = BigInt(value).toString();
1541
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
1542
+ logger2?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
1543
+ return {
1544
+ stringValue: decimal
1545
+ };
1546
+ }
1547
+ return {
1548
+ intValue: decimal
1549
+ };
1550
+ }
1551
+ return {
1552
+ doubleValue: value
1553
+ };
1554
+ }
1555
+ if (typeof value == "string")
1556
+ return {
1557
+ stringValue: sanitizeString(value)
1558
+ };
1559
+ if (typeof value == "function")
1560
+ return {
1561
+ stringValue: FUNCTION_VALUE
1562
+ };
1563
+ if (typeof value == "symbol")
1564
+ return {
1565
+ stringValue: String(value)
1566
+ };
1567
+ if (typeof value == "object" && value !== null) {
1568
+ if (state.ancestors.has(value))
1569
+ return {
1570
+ stringValue: CIRCULAR_VALUE
1571
+ };
1572
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
1573
+ return {
1574
+ stringValue: TRUNCATED_VALUE
1575
+ };
1576
+ if (value instanceof Date) {
1577
+ const time = value.getTime();
1578
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
1579
+ return {
1580
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
1581
+ };
1582
+ }
1583
+ state.ancestors.add(value);
1584
+ try {
1585
+ try {
1586
+ const toJSON = value.toJSON;
1587
+ if (typeof toJSON == "function")
1588
+ return encodeAnyValue(toJSON.call(value), logger2, state, depth + 1);
1589
+ } catch {}
1590
+ if (isArray(value))
1591
+ return {
1592
+ arrayValue: {
1593
+ values: encodeArrayValues(value, logger2, state, depth + 1)
1594
+ }
1595
+ };
1596
+ return {
1597
+ kvlistValue: {
1598
+ values: encodeKeyValueList(value, logger2, state, depth + 1)
1599
+ }
1600
+ };
1601
+ } finally {
1602
+ state.ancestors.delete(value);
1603
+ }
1604
+ }
1605
+ return {
1606
+ stringValue: sanitizeString(String(value))
1607
+ };
1608
+ }
1609
+ function encodeArrayValues(values, logger2, state, depth) {
1610
+ const result = [];
1611
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
1612
+ let index = 0;
1613
+ for (;index < itemCount && state.remainingNodes > 0; index++)
1614
+ try {
1615
+ const element = index in values ? values[index] : undefined;
1616
+ if (isNullish(element))
1617
+ continue;
1618
+ result.push(encodeAnyValue(element, logger2, state, depth));
1619
+ } catch {
1620
+ result.push({
1621
+ stringValue: UNSERIALIZABLE_VALUE
1622
+ });
1623
+ }
1624
+ if (values.length > index)
1625
+ result.push({
1626
+ stringValue: TRUNCATED_VALUE
1627
+ });
1628
+ return result;
1629
+ }
1630
+ function encodeKeyValueList(attrs, logger2, state, depth) {
1631
+ const result = [];
1632
+ for (const key in attrs)
1633
+ if (propertyIsEnumerable.call(attrs, key)) {
1634
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
1635
+ logger2?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
1636
+ break;
1637
+ }
1638
+ try {
1639
+ const value = attrs[key];
1640
+ if (isNull(value) || isUndefined(value))
1641
+ continue;
1642
+ result.push({
1643
+ key: sanitizeString(key),
1644
+ value: encodeAnyValue(value, logger2, state, depth)
1645
+ });
1646
+ } catch {
1647
+ result.push({
1648
+ key: sanitizeString(key),
1649
+ value: {
1650
+ stringValue: UNSERIALIZABLE_VALUE
1651
+ }
1652
+ });
1653
+ }
1654
+ }
1655
+ return result;
1656
+ }
1657
+ var OTLP_SEVERITY_MAP, DEFAULT_OTLP_SEVERITY, INT64_RANGE_LIMIT = 9223372036854776000, propertyIsEnumerable;
1326
1658
  var init_logs_utils = __esm(() => {
1327
1659
  init_utils();
1660
+ init_json_utils();
1328
1661
  OTLP_SEVERITY_MAP = {
1329
1662
  trace: {
1330
1663
  text: "TRACE",
@@ -1352,27 +1685,444 @@ var init_logs_utils = __esm(() => {
1352
1685
  }
1353
1686
  };
1354
1687
  DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
1688
+ propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
1355
1689
  });
1356
1690
 
1357
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/logs/index.mjs
1691
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/logs/index.mjs
1358
1692
  var init_logs = __esm(() => {
1359
1693
  init_logs_utils();
1360
1694
  init_types();
1361
1695
  init_utils();
1362
1696
  });
1363
1697
 
1364
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/surveys/validation.mjs
1698
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
1699
+ function msToUnixNano(ms) {
1700
+ return String(ms) + "000000";
1701
+ }
1702
+ function seriesKey(type, name, unit, attributes) {
1703
+ let attrsKey = "";
1704
+ if (attributes) {
1705
+ const keys = Object.keys(attributes).sort();
1706
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
1707
+ }
1708
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
1709
+ }
1710
+ function bucketIndexFor(value, bounds) {
1711
+ for (let i = 0;i < bounds.length; i++)
1712
+ if (value <= bounds[i])
1713
+ return i;
1714
+ return bounds.length;
1715
+ }
1716
+ function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
1717
+ return {
1718
+ ...config.resourceAttributes,
1719
+ "service.name": config.serviceName || "unknown_service",
1720
+ ...config.environment && {
1721
+ "deployment.environment": config.environment
1722
+ },
1723
+ ...config.serviceVersion && {
1724
+ "service.version": config.serviceVersion
1725
+ },
1726
+ "telemetry.sdk.name": scopeName,
1727
+ "telemetry.sdk.version": scopeVersion
1728
+ };
1729
+ }
1730
+ function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
1731
+ return {
1732
+ resourceMetrics: [
1733
+ {
1734
+ resource: {
1735
+ attributes: toOtlpKeyValueList(resourceAttributes)
1736
+ },
1737
+ scopeMetrics: [
1738
+ {
1739
+ scope: {
1740
+ name: scopeName,
1741
+ version: scopeVersion
1742
+ },
1743
+ metrics
1744
+ }
1745
+ ]
1746
+ }
1747
+ ]
1748
+ };
1749
+ }
1750
+ var DEFAULT_HISTOGRAM_BOUNDS;
1751
+ var init_metrics_utils = __esm(() => {
1752
+ init_logs_utils();
1753
+ DEFAULT_HISTOGRAM_BOUNDS = [
1754
+ 0,
1755
+ 5,
1756
+ 10,
1757
+ 25,
1758
+ 50,
1759
+ 75,
1760
+ 100,
1761
+ 250,
1762
+ 500,
1763
+ 750,
1764
+ 1000,
1765
+ 2500,
1766
+ 5000,
1767
+ 7500,
1768
+ 1e4
1769
+ ];
1770
+ });
1771
+
1772
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/config.mjs
1773
+ function resolveMetricsConfig(config) {
1774
+ const resourceAttributes = config?.resourceAttributes;
1775
+ return {
1776
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
1777
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
1778
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
1779
+ resourceAttributes,
1780
+ beforeSend: config?.beforeSend,
1781
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
1782
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
1783
+ };
1784
+ }
1785
+ var DEFAULT_FLUSH_INTERVAL_MS = 1e4, DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
1786
+ var init_config = () => {};
1787
+
1788
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/index.mjs
1789
+ class PostHogMetrics {
1790
+ constructor(_instance, _config, _logger) {
1791
+ this._instance = _instance;
1792
+ this._config = _config;
1793
+ this._logger = _logger;
1794
+ this._series = new Map;
1795
+ this._flushPromise = null;
1796
+ this._seriesCapWarned = false;
1797
+ this._typeByName = new Map;
1798
+ this._typeCollisionWarned = new Set;
1799
+ this._generation = 0;
1800
+ }
1801
+ count(name, value = 1, options) {
1802
+ this._capture({
1803
+ name,
1804
+ type: "count",
1805
+ value,
1806
+ unit: options?.unit,
1807
+ attributes: options?.attributes
1808
+ });
1809
+ }
1810
+ gauge(name, value, options) {
1811
+ this._capture({
1812
+ name,
1813
+ type: "gauge",
1814
+ value,
1815
+ unit: options?.unit,
1816
+ attributes: options?.attributes
1817
+ });
1818
+ }
1819
+ histogram(name, value, options) {
1820
+ this._capture({
1821
+ name,
1822
+ type: "histogram",
1823
+ value,
1824
+ unit: options?.unit,
1825
+ attributes: options?.attributes
1826
+ });
1827
+ }
1828
+ flush() {
1829
+ const prev = this._flushPromise;
1830
+ const run = async () => {
1831
+ if (prev)
1832
+ await prev.catch(() => {});
1833
+ await this._doFlush();
1834
+ };
1835
+ const p = run().finally(() => {
1836
+ if (this._flushPromise === p)
1837
+ this._flushPromise = null;
1838
+ });
1839
+ this._flushPromise = p;
1840
+ return p;
1841
+ }
1842
+ drainWindow() {
1843
+ if (this._series.size === 0)
1844
+ return null;
1845
+ const window = this._series;
1846
+ this._series = new Map;
1847
+ this._seriesCapWarned = false;
1848
+ this._typeByName = new Map;
1849
+ this._typeCollisionWarned = new Set;
1850
+ return this._buildPayload(window);
1851
+ }
1852
+ reset() {
1853
+ this._generation++;
1854
+ this._clearFlushTimer();
1855
+ this._series = new Map;
1856
+ this._flushPromise = null;
1857
+ this._seriesCapWarned = false;
1858
+ this._typeByName = new Map;
1859
+ this._typeCollisionWarned = new Set;
1860
+ }
1861
+ _capture(sample) {
1862
+ if (this._instance.isDisabled || this._instance.optedOut)
1863
+ return;
1864
+ const filtered = this._runBeforeSend(sample);
1865
+ if (filtered === null)
1866
+ return;
1867
+ if (!filtered.name || typeof filtered.name != "string")
1868
+ return void this._logger.warn("Dropping metric with empty name");
1869
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
1870
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
1871
+ if (filtered.type === "count" && filtered.value < 0)
1872
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
1873
+ let attributes;
1874
+ let key;
1875
+ try {
1876
+ attributes = filtered.attributes ? {
1877
+ ...filtered.attributes
1878
+ } : undefined;
1879
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
1880
+ } catch (e) {
1881
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
1882
+ return;
1883
+ }
1884
+ let state = this._series.get(key);
1885
+ if (!state) {
1886
+ if (!this._admitNewSeries())
1887
+ return;
1888
+ state = {
1889
+ name: filtered.name,
1890
+ type: filtered.type,
1891
+ unit: filtered.unit,
1892
+ attributes,
1893
+ windowStartMs: Date.now()
1894
+ };
1895
+ this._series.set(key, state);
1896
+ }
1897
+ const seenType = this._typeByName.get(filtered.name);
1898
+ if (seenType === undefined)
1899
+ this._typeByName.set(filtered.name, filtered.type);
1900
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
1901
+ this._typeCollisionWarned.add(filtered.name);
1902
+ this._logger.warn(`Metric name '${filtered.name}' is already used as a ${seenType}; recording it as a ${filtered.type} too will blend both series in charts. Use a distinct name.`);
1903
+ }
1904
+ this._fold(state, filtered.value);
1905
+ this._armFlushTimer();
1906
+ }
1907
+ _admitNewSeries() {
1908
+ if (this._series.size < this._config.maxSeriesPerFlush)
1909
+ return true;
1910
+ if (!this._seriesCapWarned) {
1911
+ this._seriesCapWarned = true;
1912
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
1913
+ }
1914
+ return false;
1915
+ }
1916
+ _fold(state, value) {
1917
+ switch (state.type) {
1918
+ case "count":
1919
+ state.total = (state.total ?? 0) + value;
1920
+ break;
1921
+ case "gauge":
1922
+ state.last = value;
1923
+ break;
1924
+ case "histogram": {
1925
+ if (!state.hist)
1926
+ state.hist = {
1927
+ count: 0,
1928
+ sum: 0,
1929
+ min: value,
1930
+ max: value,
1931
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
1932
+ };
1933
+ const hist = state.hist;
1934
+ hist.count += 1;
1935
+ hist.sum += value;
1936
+ hist.min = Math.min(hist.min, value);
1937
+ hist.max = Math.max(hist.max, value);
1938
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
1939
+ break;
1940
+ }
1941
+ }
1942
+ }
1943
+ _runBeforeSend(sample) {
1944
+ const beforeSend = this._config.beforeSend;
1945
+ if (!beforeSend)
1946
+ return sample;
1947
+ const fns = isArray(beforeSend) ? beforeSend : [
1948
+ beforeSend
1949
+ ];
1950
+ let result = sample;
1951
+ for (const fn of fns)
1952
+ try {
1953
+ const next = fn(result);
1954
+ if (!next) {
1955
+ this._logger.info("Metric was rejected in beforeSend function");
1956
+ return null;
1957
+ }
1958
+ result = next;
1959
+ } catch (e) {
1960
+ this._logger.error("Error in beforeSend function for metric:", e);
1961
+ return null;
1962
+ }
1963
+ return result;
1964
+ }
1965
+ _armFlushTimer() {
1966
+ if (this._flushTimer)
1967
+ return;
1968
+ this._flushTimer = safeSetTimeout(() => {
1969
+ this._flushTimer = undefined;
1970
+ this.flush().catch((e) => {
1971
+ this._logger.error("Metrics flush failed:", e);
1972
+ });
1973
+ }, this._config.flushIntervalMs);
1974
+ }
1975
+ _clearFlushTimer() {
1976
+ if (this._flushTimer) {
1977
+ clearTimeout(this._flushTimer);
1978
+ this._flushTimer = undefined;
1979
+ }
1980
+ }
1981
+ async _doFlush() {
1982
+ if (this._series.size === 0)
1983
+ return;
1984
+ const window = this._series;
1985
+ this._series = new Map;
1986
+ this._seriesCapWarned = false;
1987
+ this._typeByName = new Map;
1988
+ this._typeCollisionWarned = new Set;
1989
+ const generation = this._generation;
1990
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
1991
+ if (generation !== this._generation)
1992
+ return;
1993
+ switch (outcome.kind) {
1994
+ case "ok":
1995
+ return;
1996
+ case "retry-later":
1997
+ this._mergeWindowBack(window);
1998
+ this._armFlushTimer();
1999
+ return;
2000
+ case "too-large":
2001
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
2002
+ return;
2003
+ case "fatal":
2004
+ this._logger.error("Failed to send metrics batch:", outcome.error);
2005
+ return;
2006
+ }
2007
+ }
2008
+ _buildPayload(window) {
2009
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
2010
+ }
2011
+ _buildMetrics(window) {
2012
+ const nowNano = msToUnixNano(Date.now());
2013
+ const byMetric = new Map;
2014
+ for (const state of window.values()) {
2015
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
2016
+ let metric = byMetric.get(metricKey);
2017
+ if (!metric) {
2018
+ metric = {
2019
+ name: state.name,
2020
+ ...state.unit && {
2021
+ unit: state.unit
2022
+ }
2023
+ };
2024
+ if (state.type === "count")
2025
+ metric.sum = {
2026
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2027
+ isMonotonic: true,
2028
+ dataPoints: []
2029
+ };
2030
+ else if (state.type === "gauge")
2031
+ metric.gauge = {
2032
+ dataPoints: []
2033
+ };
2034
+ else
2035
+ metric.histogram = {
2036
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2037
+ dataPoints: []
2038
+ };
2039
+ byMetric.set(metricKey, metric);
2040
+ }
2041
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
2042
+ const startNano = msToUnixNano(state.windowStartMs);
2043
+ if (state.type === "count") {
2044
+ const dp = {
2045
+ attributes,
2046
+ startTimeUnixNano: startNano,
2047
+ timeUnixNano: nowNano,
2048
+ asDouble: state.total ?? 0
2049
+ };
2050
+ metric.sum.dataPoints.push(dp);
2051
+ } else if (state.type === "gauge") {
2052
+ const dp = {
2053
+ attributes,
2054
+ timeUnixNano: nowNano,
2055
+ asDouble: state.last ?? 0
2056
+ };
2057
+ metric.gauge.dataPoints.push(dp);
2058
+ } else if (state.hist) {
2059
+ const dp = {
2060
+ attributes,
2061
+ startTimeUnixNano: startNano,
2062
+ timeUnixNano: nowNano,
2063
+ count: state.hist.count,
2064
+ sum: state.hist.sum,
2065
+ min: state.hist.min,
2066
+ max: state.hist.max,
2067
+ bucketCounts: state.hist.bucketCounts,
2068
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
2069
+ };
2070
+ metric.histogram.dataPoints.push(dp);
2071
+ }
2072
+ }
2073
+ return Array.from(byMetric.values());
2074
+ }
2075
+ _mergeWindowBack(window) {
2076
+ for (const [key, old] of window) {
2077
+ const current = this._series.get(key);
2078
+ if (!current) {
2079
+ if (this._admitNewSeries())
2080
+ this._series.set(key, old);
2081
+ continue;
2082
+ }
2083
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
2084
+ switch (current.type) {
2085
+ case "count":
2086
+ current.total = (current.total ?? 0) + (old.total ?? 0);
2087
+ break;
2088
+ case "gauge":
2089
+ break;
2090
+ case "histogram":
2091
+ if (old.hist)
2092
+ if (current.hist) {
2093
+ current.hist.count += old.hist.count;
2094
+ current.hist.sum += old.hist.sum;
2095
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
2096
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
2097
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
2098
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
2099
+ } else
2100
+ current.hist = old.hist;
2101
+ break;
2102
+ }
2103
+ }
2104
+ }
2105
+ }
2106
+ var OTLP_TEMPORALITY_DELTA = 1;
2107
+ var init_metrics = __esm(() => {
2108
+ init_utils();
2109
+ init_logs_utils();
2110
+ init_metrics_utils();
2111
+ init_config();
2112
+ });
2113
+
2114
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/surveys/validation.mjs
1365
2115
  var init_validation = __esm(() => {
1366
2116
  init_types();
1367
2117
  });
1368
2118
 
1369
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/cookie.mjs
2119
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/cookie.mjs
1370
2120
  var init_cookie = __esm(() => {
1371
2121
  init_utils();
1372
2122
  init_uuidv7();
1373
2123
  });
1374
2124
 
1375
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/eventemitter.mjs
2125
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/eventemitter.mjs
1376
2126
  class SimpleEventEmitter {
1377
2127
  constructor() {
1378
2128
  this.events = {};
@@ -1395,7 +2145,7 @@ class SimpleEventEmitter {
1395
2145
  }
1396
2146
  var init_eventemitter = () => {};
1397
2147
 
1398
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
2148
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
1399
2149
  function getFilenameToChunkIdMap(stackParser) {
1400
2150
  const chunkIdMap = globalThis._posthogChunkIds;
1401
2151
  if (!chunkIdMap)
@@ -1433,7 +2183,7 @@ function getFilenameToChunkIdMap(stackParser) {
1433
2183
  var parsedStackResults, lastKeysCount, cachedFilenameChunkIds;
1434
2184
  var init_chunk_ids = () => {};
1435
2185
 
1436
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
2186
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
1437
2187
  class ErrorPropertiesBuilder {
1438
2188
  constructor(coercers, stackParser, modifiers = []) {
1439
2189
  this.coercers = coercers;
@@ -1559,13 +2309,13 @@ var init_error_properties_builder = __esm(() => {
1559
2309
  init_chunk_ids();
1560
2310
  });
1561
2311
 
1562
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
2312
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
1563
2313
  function createFrame(platform, filename, func, lineno, colno) {
1564
2314
  const frame = {
1565
2315
  platform,
1566
2316
  filename,
1567
2317
  function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
1568
- in_app: true
2318
+ in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
1569
2319
  };
1570
2320
  if (!isUndefined(lineno))
1571
2321
  frame.lineno = lineno;
@@ -1573,12 +2323,12 @@ function createFrame(platform, filename, func, lineno, colno) {
1573
2323
  frame.colno = colno;
1574
2324
  return frame;
1575
2325
  }
1576
- var UNKNOWN_FUNCTION = "?";
2326
+ var UNKNOWN_FUNCTION = "?", MASKED_URL_PREFIX = "webkit-masked-url://", ANONYMOUS_FILENAME = "<anonymous>";
1577
2327
  var init_base = __esm(() => {
1578
2328
  init_utils();
1579
2329
  });
1580
2330
 
1581
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
2331
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
1582
2332
  var extractSafariExtensionDetails = (func, filename) => {
1583
2333
  const isSafariExtension = func.indexOf("safari-extension") !== -1;
1584
2334
  const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
@@ -1594,7 +2344,7 @@ var init_safari = __esm(() => {
1594
2344
  init_base();
1595
2345
  });
1596
2346
 
1597
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
2347
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
1598
2348
  var chromeRegexNoFnName, chromeRegex, chromeEvalRegex, chromeStackLineParser = (line, platform) => {
1599
2349
  const noFnParts = chromeRegexNoFnName.exec(line);
1600
2350
  if (noFnParts) {
@@ -1624,7 +2374,7 @@ var init_chrome = __esm(() => {
1624
2374
  chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1625
2375
  });
1626
2376
 
1627
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
2377
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
1628
2378
  var geckoREgex, geckoEvalRegex, geckoStackLineParser = (line, platform) => {
1629
2379
  const parts = geckoREgex.exec(line);
1630
2380
  if (parts) {
@@ -1651,7 +2401,7 @@ var init_gecko = __esm(() => {
1651
2401
  geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1652
2402
  });
1653
2403
 
1654
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
2404
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
1655
2405
  var winjsRegex, winjsStackLineParser = (line, platform) => {
1656
2406
  const parts = winjsRegex.exec(line);
1657
2407
  return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined) : undefined;
@@ -1661,7 +2411,7 @@ var init_winjs = __esm(() => {
1661
2411
  winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1662
2412
  });
1663
2413
 
1664
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
2414
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
1665
2415
  var opera10Regex, opera10StackLineParser = (line, platform) => {
1666
2416
  const parts = opera10Regex.exec(line);
1667
2417
  return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;
@@ -1675,7 +2425,7 @@ var init_opera = __esm(() => {
1675
2425
  opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
1676
2426
  });
1677
2427
 
1678
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
2428
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
1679
2429
  function filenameIsInApp(filename, isNative = false) {
1680
2430
  const isInternal = isNative || filename && !filename.startsWith("/") && !filename.match(/^[A-Z]:/) && !filename.startsWith(".") && !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
1681
2431
  return !isInternal && filename !== undefined && !filename.includes("node_modules/");
@@ -1683,7 +2433,7 @@ function filenameIsInApp(filename, isNative = false) {
1683
2433
  function _parseIntOrUndefined(input) {
1684
2434
  return parseInt(input || "", 10) || undefined;
1685
2435
  }
1686
- var FILENAME_MATCH, FULL_MATCH, nodeStackLineParser = (line, platform) => {
2436
+ var FILENAME_MATCH, FULL_MATCH, PROMISE_COMBINATOR, PROMISE_INDEX, PROMISE_FRAME_FILENAME = "node:internal/promise", nodeStackLineParser = (line, platform) => {
1687
2437
  const lineMatch = line.match(FULL_MATCH);
1688
2438
  if (lineMatch) {
1689
2439
  let object;
@@ -1725,6 +2475,8 @@ var FILENAME_MATCH, FULL_MATCH, nodeStackLineParser = (line, platform) => {
1725
2475
  filename = filename.slice(1);
1726
2476
  if (!filename && lineMatch[5] && !isNative)
1727
2477
  filename = lineMatch[5];
2478
+ if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
2479
+ filename = PROMISE_FRAME_FILENAME;
1728
2480
  return {
1729
2481
  filename: filename ? decodeURI(filename) : undefined,
1730
2482
  module: undefined,
@@ -1745,9 +2497,11 @@ var init_node = __esm(() => {
1745
2497
  init_base();
1746
2498
  FILENAME_MATCH = /^\s*[-]{4,}$/;
1747
2499
  FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
2500
+ PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
2501
+ PROMISE_INDEX = /^index \d+$/;
1748
2502
  });
1749
2503
 
1750
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
2504
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
1751
2505
  function reverseAndStripFrames(stack) {
1752
2506
  if (!stack.length)
1753
2507
  return [];
@@ -1801,7 +2555,7 @@ var init_parsers = __esm(() => {
1801
2555
  WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1802
2556
  });
1803
2557
 
1804
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
2558
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
1805
2559
  class DOMExceptionCoercer {
1806
2560
  match(err) {
1807
2561
  return this.isDOMException(err) || this.isDOMError(err);
@@ -1835,18 +2589,20 @@ var init_dom_exception_coercer = __esm(() => {
1835
2589
  init_utils();
1836
2590
  });
1837
2591
 
1838
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
2592
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
1839
2593
  class ErrorCoercer {
1840
2594
  match(err) {
1841
- return isPlainError(err);
2595
+ return isError(err);
1842
2596
  }
1843
2597
  coerce(err, ctx) {
2598
+ const stack = this.getStack(err);
2599
+ const synthetic = stack === undefined;
1844
2600
  return {
1845
2601
  type: this.getType(err),
1846
2602
  value: this.getMessage(err, ctx),
1847
- stack: this.getStack(err),
2603
+ stack: stack ?? ctx.syntheticException?.stack,
1848
2604
  cause: err.cause ? ctx.next(err.cause) : undefined,
1849
- synthetic: false
2605
+ synthetic
1850
2606
  };
1851
2607
  }
1852
2608
  getType(err) {
@@ -1863,32 +2619,48 @@ class ErrorCoercer {
1863
2619
  }
1864
2620
  }
1865
2621
  var init_error_coercer = __esm(() => {
1866
- init_utils();
2622
+ init_type_utils();
1867
2623
  });
1868
2624
 
1869
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
2625
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
1870
2626
  class ErrorEventCoercer {
1871
2627
  constructor() {}
1872
2628
  match(err) {
1873
- return isErrorEvent(err) && err.error != null;
2629
+ if (!isErrorEvent(err))
2630
+ return false;
2631
+ const errorEvent = err;
2632
+ return errorEvent.error != null || this._hasUsableMessage(errorEvent);
1874
2633
  }
1875
2634
  coerce(err, ctx) {
1876
- const exceptionLike = ctx.apply(err.error);
1877
- if (!exceptionLike)
1878
- return {
1879
- type: "ErrorEvent",
1880
- value: err.message,
1881
- stack: ctx.syntheticException?.stack,
1882
- synthetic: true
1883
- };
1884
- return exceptionLike;
2635
+ if (err.error != null)
2636
+ return ctx.apply(err.error);
2637
+ const exceptionLike = ctx.apply(err.message);
2638
+ return {
2639
+ ...exceptionLike,
2640
+ stack: this._buildLocationStack(err) ?? exceptionLike.stack,
2641
+ synthetic: true
2642
+ };
1885
2643
  }
1886
- }
1887
- var init_error_event_coercer = __esm(() => {
1888
- init_utils();
2644
+ _hasUsableMessage(err) {
2645
+ return isString(err.message) && err.message.length > 0;
2646
+ }
2647
+ _buildLocationStack(err) {
2648
+ const location = err;
2649
+ const lineno = location.lineno ?? 0;
2650
+ const colno = location.colno ?? 0;
2651
+ if (!isString(location.filename) || location.filename.length === 0)
2652
+ return;
2653
+ if (lineno === 0)
2654
+ return;
2655
+ return `Error
2656
+ at ${location.filename}:${lineno}:${colno}`;
2657
+ }
2658
+ }
2659
+ var init_error_event_coercer = __esm(() => {
2660
+ init_utils();
1889
2661
  });
1890
2662
 
1891
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
2663
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
1892
2664
  class StringCoercer {
1893
2665
  match(input) {
1894
2666
  return typeof input == "string";
@@ -1921,7 +2693,7 @@ var init_string_coercer = __esm(() => {
1921
2693
  ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
1922
2694
  });
1923
2695
 
1924
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/types.mjs
2696
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/types.mjs
1925
2697
  var severityLevels;
1926
2698
  var init_types2 = __esm(() => {
1927
2699
  severityLevels = [
@@ -1934,7 +2706,7 @@ var init_types2 = __esm(() => {
1934
2706
  ];
1935
2707
  });
1936
2708
 
1937
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
2709
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
1938
2710
  function extractExceptionKeysForMessage(err, maxLength = 40) {
1939
2711
  const keys = Object.keys(err);
1940
2712
  keys.sort();
@@ -1952,7 +2724,7 @@ function extractExceptionKeysForMessage(err, maxLength = 40) {
1952
2724
  }
1953
2725
  var init_utils2 = () => {};
1954
2726
 
1955
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
2727
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
1956
2728
  class ObjectCoercer {
1957
2729
  match(candidate) {
1958
2730
  return typeof candidate == "object" && candidate !== null;
@@ -1964,13 +2736,16 @@ class ObjectCoercer {
1964
2736
  return {
1965
2737
  type: this.getType(candidate),
1966
2738
  value: this.getValue(candidate),
1967
- stack: ctx.syntheticException?.stack,
2739
+ stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
1968
2740
  level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
1969
2741
  synthetic: true
1970
2742
  };
1971
2743
  }
1972
2744
  getType(err) {
1973
- return isEvent(err) ? err.constructor.name : "Error";
2745
+ if (isEvent(err))
2746
+ return err.constructor.name;
2747
+ const name = "name" in err ? err.name : undefined;
2748
+ return isString(name) && !isEmptyString(name) ? name : "Error";
1974
2749
  }
1975
2750
  getValue(err) {
1976
2751
  if ("name" in err && typeof err.name == "string") {
@@ -1988,6 +2763,15 @@ class ObjectCoercer {
1988
2763
  isSeverityLevel(x) {
1989
2764
  return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
1990
2765
  }
2766
+ getStack(candidate) {
2767
+ try {
2768
+ if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
2769
+ return candidate.stacktrace;
2770
+ return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
2771
+ } catch {
2772
+ return;
2773
+ }
2774
+ }
1991
2775
  getErrorPropertyFromObject(obj) {
1992
2776
  for (const prop in obj)
1993
2777
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
@@ -2011,7 +2795,7 @@ var init_object_coercer = __esm(() => {
2011
2795
  init_utils2();
2012
2796
  });
2013
2797
 
2014
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2798
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2015
2799
  class EventCoercer {
2016
2800
  match(err) {
2017
2801
  return isEvent(err);
@@ -2031,7 +2815,7 @@ var init_event_coercer = __esm(() => {
2031
2815
  init_utils2();
2032
2816
  });
2033
2817
 
2034
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2818
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2035
2819
  class PrimitiveCoercer {
2036
2820
  match(candidate) {
2037
2821
  return isPrimitive(candidate);
@@ -2049,7 +2833,7 @@ var init_primitive_coercer = __esm(() => {
2049
2833
  init_utils();
2050
2834
  });
2051
2835
 
2052
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2836
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
2053
2837
  class PromiseRejectionEventCoercer {
2054
2838
  match(err) {
2055
2839
  return isBuiltin(err, "PromiseRejectionEvent") || this.isCustomEventWrappingRejection(err);
@@ -2089,7 +2873,7 @@ var init_promise_rejection_event = __esm(() => {
2089
2873
  init_utils();
2090
2874
  });
2091
2875
 
2092
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
2876
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/index.mjs
2093
2877
  var init_coercers = __esm(() => {
2094
2878
  init_dom_exception_coercer();
2095
2879
  init_error_coercer();
@@ -2101,7 +2885,7 @@ var init_coercers = __esm(() => {
2101
2885
  init_promise_rejection_event();
2102
2886
  });
2103
2887
 
2104
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2888
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2105
2889
  class ReduceableCache {
2106
2890
  constructor(_maxSize) {
2107
2891
  this._maxSize = _maxSize;
@@ -2128,7 +2912,7 @@ class ReduceableCache {
2128
2912
  }
2129
2913
  var init_utils3 = () => {};
2130
2914
 
2131
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2915
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2132
2916
  function resolveExceptionStepsConfig(config) {
2133
2917
  if (!config)
2134
2918
  return {
@@ -2211,9 +2995,12 @@ function normalizePositiveInteger(input, fallback) {
2211
2995
  return normalized;
2212
2996
  }
2213
2997
  function normalizeAndSerializeStep(step) {
2214
- const json = safeStringify(step);
2215
- if (!json)
2998
+ let json;
2999
+ try {
3000
+ json = safeJsonStringify(step);
3001
+ } catch {
2216
3002
  return;
3003
+ }
2217
3004
  try {
2218
3005
  const parsed = JSON.parse(json);
2219
3006
  if (!isObject(parsed))
@@ -2233,33 +3020,6 @@ function normalizeAndSerializeStep(step) {
2233
3020
  return;
2234
3021
  }
2235
3022
  }
2236
- function safeStringify(value) {
2237
- const seen = new WeakSet;
2238
- try {
2239
- return JSON.stringify(value, (_key, replacementValue) => {
2240
- if (typeof replacementValue == "bigint")
2241
- return replacementValue.toString();
2242
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
2243
- return;
2244
- if (replacementValue instanceof Date)
2245
- return replacementValue.toISOString();
2246
- if (replacementValue instanceof Error)
2247
- return {
2248
- name: replacementValue.name,
2249
- message: replacementValue.message,
2250
- stack: replacementValue.stack
2251
- };
2252
- if (replacementValue && typeof replacementValue == "object") {
2253
- if (seen.has(replacementValue))
2254
- return "[Circular]";
2255
- seen.add(replacementValue);
2256
- }
2257
- return replacementValue;
2258
- });
2259
- } catch {
2260
- return;
2261
- }
2262
- }
2263
3023
  function getUtf8ByteLength(value) {
2264
3024
  if (typeof TextEncoder != "undefined")
2265
3025
  return new TextEncoder().encode(value).length;
@@ -2290,34 +3050,42 @@ var init_exception_steps = __esm(() => {
2290
3050
  };
2291
3051
  });
2292
3052
 
2293
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/index.mjs
3053
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/release.mjs
3054
+ function getInjectedReleaseId() {
3055
+ const injected = globalThis._posthogReleaseId;
3056
+ return typeof injected == "string" && injected.length > 0 ? injected : undefined;
3057
+ }
3058
+ var init_release = () => {};
3059
+
3060
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/index.mjs
2294
3061
  var exports_error_tracking = {};
2295
3062
  __export(exports_error_tracking, {
2296
- winjsStackLineParser: () => winjsStackLineParser,
2297
- stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
2298
- reverseAndStripFrames: () => reverseAndStripFrames,
2299
- resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
2300
- opera11StackLineParser: () => opera11StackLineParser,
2301
- opera10StackLineParser: () => opera10StackLineParser,
2302
- nodeStackLineParser: () => nodeStackLineParser,
2303
- getUtf8ByteLength: () => getUtf8ByteLength,
2304
- geckoStackLineParser: () => geckoStackLineParser,
2305
- createStackParser: () => createStackParser,
2306
- createDefaultStackParser: () => createDefaultStackParser,
2307
- chromeStackLineParser: () => chromeStackLineParser,
2308
- StringCoercer: () => StringCoercer,
2309
- ReduceableCache: () => ReduceableCache,
2310
- PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
2311
- PrimitiveCoercer: () => PrimitiveCoercer,
2312
- ObjectCoercer: () => ObjectCoercer,
2313
- ExceptionStepsBuffer: () => ExceptionStepsBuffer,
2314
- EventCoercer: () => EventCoercer,
2315
- ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
2316
- ErrorEventCoercer: () => ErrorEventCoercer,
2317
- ErrorCoercer: () => ErrorCoercer,
2318
- EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
3063
+ DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG,
2319
3064
  DOMExceptionCoercer: () => DOMExceptionCoercer,
2320
- DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG
3065
+ EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
3066
+ ErrorCoercer: () => ErrorCoercer,
3067
+ ErrorEventCoercer: () => ErrorEventCoercer,
3068
+ ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
3069
+ EventCoercer: () => EventCoercer,
3070
+ ExceptionStepsBuffer: () => ExceptionStepsBuffer,
3071
+ ObjectCoercer: () => ObjectCoercer,
3072
+ PrimitiveCoercer: () => PrimitiveCoercer,
3073
+ PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
3074
+ ReduceableCache: () => ReduceableCache,
3075
+ StringCoercer: () => StringCoercer,
3076
+ chromeStackLineParser: () => chromeStackLineParser,
3077
+ createDefaultStackParser: () => createDefaultStackParser,
3078
+ createStackParser: () => createStackParser,
3079
+ geckoStackLineParser: () => geckoStackLineParser,
3080
+ getInjectedReleaseId: () => getInjectedReleaseId,
3081
+ getUtf8ByteLength: () => getUtf8ByteLength,
3082
+ nodeStackLineParser: () => nodeStackLineParser,
3083
+ opera10StackLineParser: () => opera10StackLineParser,
3084
+ opera11StackLineParser: () => opera11StackLineParser,
3085
+ resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
3086
+ reverseAndStripFrames: () => reverseAndStripFrames,
3087
+ stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
3088
+ winjsStackLineParser: () => winjsStackLineParser
2321
3089
  });
2322
3090
  var init_error_tracking = __esm(() => {
2323
3091
  init_error_properties_builder();
@@ -2325,15 +3093,19 @@ var init_error_tracking = __esm(() => {
2325
3093
  init_coercers();
2326
3094
  init_utils3();
2327
3095
  init_exception_steps();
3096
+ init_release();
2328
3097
  });
2329
3098
 
2330
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
3099
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
2331
3100
  async function logFlushError(err) {
2332
3101
  if (err instanceof PostHogFetchHttpError) {
2333
3102
  let text = "";
2334
3103
  try {
2335
3104
  text = await err.text;
2336
- } catch {}
3105
+ } catch {
3106
+ if (err.bodyReadTimedOut)
3107
+ text = "<response body read timed out>";
3108
+ }
2337
3109
  console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
2338
3110
  } else
2339
3111
  console.error("Error while flushing PostHog", err);
@@ -2345,9 +3117,26 @@ function isPostHogFetchError(err) {
2345
3117
  function isPostHogFetchNetworkError(err) {
2346
3118
  return err instanceof PostHogFetchNetworkError;
2347
3119
  }
3120
+ function isRetryableFlagsFetchError(err) {
3121
+ if (err instanceof PostHogFetchHttpError)
3122
+ return err.status === 502 || err.status === 504;
3123
+ if (!(err instanceof PostHogFetchNetworkError))
3124
+ return false;
3125
+ const cause = err.error;
3126
+ const code = cause?.code ?? cause?.cause?.code;
3127
+ return code !== "ECONNREFUSED";
3128
+ }
2348
3129
  function isPostHogFetchContentTooLargeError(err) {
2349
3130
  return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
2350
3131
  }
3132
+ function isPostHogFetchRetryableError(err) {
3133
+ if (err instanceof PostHogFetchHttpError)
3134
+ return err.status === 408 || err.status === 429 || err.status >= 500;
3135
+ return isPostHogFetchNetworkError(err);
3136
+ }
3137
+ function isPostHogEventProperties(value) {
3138
+ return value !== null && typeof value == "object" && !Array.isArray(value);
3139
+ }
2351
3140
 
2352
3141
  class PostHogCoreStateless {
2353
3142
  getErrorPropertiesBuilder() {
@@ -2365,6 +3154,9 @@ class PostHogCoreStateless {
2365
3154
  }
2366
3155
  constructor(apiKey, options = {}) {
2367
3156
  this.flushPromise = null;
3157
+ this.pendingFlushPromise = null;
3158
+ this.flushPromises = new Set;
3159
+ this._dequeuedMessagesCount = 0;
2368
3160
  this.shutdownPromise = null;
2369
3161
  this.promiseQueue = new PromiseQueue;
2370
3162
  this._events = new SimpleEventEmitter;
@@ -2387,10 +3179,11 @@ class PostHogCoreStateless {
2387
3179
  this._retryOptions = {
2388
3180
  retryCount: options.fetchRetryCount ?? 3,
2389
3181
  retryDelay: options.fetchRetryDelay ?? 3000,
2390
- retryCheck: isPostHogFetchError
3182
+ retryCheck: isPostHogFetchRetryableError
2391
3183
  };
2392
3184
  this.requestTimeout = options.requestTimeout ?? 1e4;
2393
3185
  this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
3186
+ this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
2394
3187
  this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
2395
3188
  this.disableGeoip = options.disableGeoip ?? true;
2396
3189
  this.disabled = (options.disabled ?? false) || missingApiKey;
@@ -2452,15 +3245,23 @@ class PostHogCoreStateless {
2452
3245
  return this.disabled;
2453
3246
  }
2454
3247
  buildPayload(payload) {
3248
+ const userProperties = payload.properties || {};
3249
+ let properties = {
3250
+ ...userProperties,
3251
+ ...this.getCommonEventProperties()
3252
+ };
3253
+ applyCallerFeatureFlagOverrides(properties, userProperties);
3254
+ if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
3255
+ properties = minimizeFlagCalledEventProperties(properties);
2455
3256
  return {
2456
3257
  distinct_id: payload.distinct_id,
2457
3258
  event: payload.event,
2458
- properties: {
2459
- ...payload.properties || {},
2460
- ...this.getCommonEventProperties()
2461
- }
3259
+ properties
2462
3260
  };
2463
3261
  }
3262
+ isMinimalFlagCalledEventsEnabled() {
3263
+ return false;
3264
+ }
2464
3265
  addPendingPromise(promise) {
2465
3266
  return this.promiseQueue.add(promise);
2466
3267
  }
@@ -2545,6 +3346,19 @@ class PostHogCoreStateless {
2545
3346
  this.enqueue("capture", payload, options);
2546
3347
  });
2547
3348
  }
3349
+ async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
3350
+ const payload = this.buildPayload({
3351
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
3352
+ event: "$groupidentify",
3353
+ properties: {
3354
+ $group_type: groupType,
3355
+ $group_key: groupKey,
3356
+ $group_set: groupProperties || {},
3357
+ ...eventProperties || {}
3358
+ }
3359
+ });
3360
+ await this.sendImmediate("capture", payload, options);
3361
+ }
2548
3362
  async getRemoteConfig() {
2549
3363
  await this._initPromise;
2550
3364
  let host = this.host;
@@ -2561,8 +3375,11 @@ class PostHogCoreStateless {
2561
3375
  }
2562
3376
  };
2563
3377
  return this.fetchWithRetry(url, fetchOptions, {
3378
+ type: "required",
3379
+ consume: (response) => response.json()
3380
+ }, {
2564
3381
  retryCount: 0
2565
- }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
3382
+ }, this.remoteConfigRequestTimeoutMs).catch((error) => {
2566
3383
  this._logger.error("Remote config could not be loaded", error);
2567
3384
  this._events.emit("error", error);
2568
3385
  });
@@ -2593,8 +3410,12 @@ class PostHogCoreStateless {
2593
3410
  };
2594
3411
  this._logger.info("Flags URL", url);
2595
3412
  return this.fetchWithRetry(url, fetchOptions, {
2596
- retryCount: 0
2597
- }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => ({
3413
+ type: "required",
3414
+ consume: (response) => response.json()
3415
+ }, {
3416
+ retryCount: this.featureFlagsRequestMaxRetries,
3417
+ retryCheck: isRetryableFlagsFetchError
3418
+ }, this.featureFlagsRequestTimeoutMs).then((response) => ({
2598
3419
  success: true,
2599
3420
  response: normalizeFlagsResponse(response)
2600
3421
  })).catch((error) => {
@@ -2694,9 +3515,9 @@ class PostHogCoreStateless {
2694
3515
  }
2695
3516
  async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2696
3517
  await this._initPromise;
2697
- const extraPayload = {};
2698
- if (disableGeoip ?? this.disableGeoip)
2699
- extraPayload["geoip_disable"] = true;
3518
+ const extraPayload = {
3519
+ geoip_disable: disableGeoip ?? this.disableGeoip
3520
+ };
2700
3521
  if (flagKeysToEvaluate)
2701
3522
  extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
2702
3523
  const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
@@ -2733,15 +3554,18 @@ class PostHogCoreStateless {
2733
3554
  "Content-Type": "application/json"
2734
3555
  }
2735
3556
  };
2736
- const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
2737
- if (response2.status !== 200 || !response2.json) {
2738
- const msg = `Surveys API could not be loaded: ${response2.status}`;
2739
- const error = new Error(msg);
2740
- this._logger.error(error);
2741
- this._events.emit("error", new Error(msg));
2742
- return;
3557
+ const response = await this.fetchWithRetry(url, fetchOptions, {
3558
+ type: "required",
3559
+ consume: (response2) => {
3560
+ if (response2.status !== 200 || !response2.json) {
3561
+ const msg = `Surveys API could not be loaded: ${response2.status}`;
3562
+ const error = new Error(msg);
3563
+ this._logger.error(error);
3564
+ this._events.emit("error", new Error(msg));
3565
+ return Promise.resolve(undefined);
3566
+ }
3567
+ return response2.json();
2743
3568
  }
2744
- return response2.json();
2745
3569
  }).catch((error) => {
2746
3570
  this._logger.error("Surveys API could not be loaded", error);
2747
3571
  this._events.emit("error", error);
@@ -2778,23 +3602,39 @@ class PostHogCoreStateless {
2778
3602
  return message;
2779
3603
  }
2780
3604
  async flushStorage() {}
2781
- enqueue(type, _message, options) {
3605
+ getQueueRouteKey(_message) {
3606
+ return DEFAULT_QUEUE_ROUTE;
3607
+ }
3608
+ persistedQueueKeyForRoute(_route) {
3609
+ return types_PostHogPersistedProperty.Queue;
3610
+ }
3611
+ getActiveQueueRoutes() {
3612
+ return [
3613
+ DEFAULT_QUEUE_ROUTE
3614
+ ];
3615
+ }
3616
+ getRouteQueue(route) {
3617
+ return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
3618
+ }
3619
+ enqueue(type, _message, options, explicitRoute) {
2782
3620
  this.wrap(() => {
2783
3621
  if (this.optedOut)
2784
3622
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2785
- let message = this.prepareMessage(type, _message, options);
3623
+ let message = this.prepareMessage(_message, options);
2786
3624
  message = this.processBeforeEnqueue(message);
2787
3625
  if (message === null)
2788
3626
  return;
2789
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
3627
+ message = this.normalizeMessage(message);
3628
+ const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
3629
+ const queue = this.getPersistedProperty(queueKey) || [];
2790
3630
  if (queue.length >= this.maxQueueSize) {
2791
3631
  queue.shift();
2792
- this._logger.info("Queue is full, the oldest event is dropped.");
3632
+ this._logger.warn("Queue is full, the oldest event is dropped.");
2793
3633
  }
2794
3634
  queue.push({
2795
3635
  message
2796
3636
  });
2797
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
3637
+ this.setPersistedProperty(queueKey, queue);
2798
3638
  this._events.emit(type, message);
2799
3639
  if (queue.length >= this.flushAt)
2800
3640
  this.flushBackground();
@@ -2802,61 +3642,63 @@ class PostHogCoreStateless {
2802
3642
  this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
2803
3643
  });
2804
3644
  }
2805
- async sendImmediate(type, _message, options) {
3645
+ async sendImmediate(type, _message, options, explicitRoute) {
2806
3646
  if (this.disabled)
2807
3647
  return void this._logger.warn("The client is disabled");
2808
3648
  if (!this._isInitialized)
2809
3649
  await this._initPromise;
2810
3650
  if (this.optedOut)
2811
3651
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2812
- let message = this.prepareMessage(type, _message, options);
3652
+ let message = this.prepareMessage(_message, options);
2813
3653
  message = this.processBeforeEnqueue(message);
2814
3654
  if (message === null)
2815
3655
  return;
2816
- const data = {
2817
- api_key: this.apiKey,
2818
- batch: [
2819
- message
2820
- ],
2821
- sent_at: currentISOTime()
2822
- };
2823
- if (this.historicalMigration)
2824
- data.historical_migration = true;
2825
- const payload = JSON.stringify(data);
2826
- const url = `${this.host}/batch/`;
2827
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2828
- const fetchOptions = {
2829
- method: "POST",
2830
- headers: {
2831
- ...this.getCustomHeaders(),
2832
- "Content-Type": "application/json",
2833
- ...gzippedPayload !== null && {
2834
- "Content-Encoding": "gzip"
2835
- }
2836
- },
2837
- body: gzippedPayload || payload
2838
- };
3656
+ message = this.normalizeMessage(message);
2839
3657
  try {
2840
- const response = await this.fetchWithRetry(url, fetchOptions);
2841
- await response.body?.cancel()?.catch(() => {});
3658
+ await this.sendBatch([
3659
+ message
3660
+ ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
2842
3661
  } catch (err) {
2843
3662
  this._events.emit("error", err);
2844
3663
  }
2845
3664
  }
2846
- prepareMessage(type, _message, options) {
3665
+ normalizeMessage(message) {
3666
+ const { type: _type, library, library_version, ...sanitizedMessage } = message;
3667
+ let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
3668
+ if (library !== undefined && properties?.$lib === undefined)
3669
+ properties = {
3670
+ ...properties || {},
3671
+ $lib: library
3672
+ };
3673
+ if (library_version !== undefined && properties?.$lib_version === undefined)
3674
+ properties = {
3675
+ ...properties || {},
3676
+ $lib_version: library_version
3677
+ };
3678
+ if (properties)
3679
+ sanitizedMessage.properties = properties;
3680
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
3681
+ return sanitizedMessage;
3682
+ }
3683
+ normalizeTimestampForWire(timestamp) {
3684
+ const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
3685
+ if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
3686
+ return timestamp;
3687
+ const normalized = parsedTimestamp.toISOString();
3688
+ const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
3689
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
3690
+ }
3691
+ prepareMessage(_message, options) {
2847
3692
  const message = {
2848
3693
  ..._message,
2849
- type,
2850
- library: this.getLibraryId(),
2851
- library_version: this.getLibraryVersion(),
2852
3694
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
2853
- uuid: options?.uuid ? options.uuid : uuidv7()
3695
+ uuid: getEventUuid(options?.uuid, uuidv7)
2854
3696
  };
2855
3697
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
2856
3698
  if (addGeoipDisableProperty) {
2857
- if (!message.properties)
3699
+ if (!isPostHogEventProperties(message.properties))
2858
3700
  message.properties = {};
2859
- message["properties"]["$geoip_disable"] = true;
3701
+ message.properties["$geoip_disable"] = true;
2860
3702
  }
2861
3703
  if (message.distinctId) {
2862
3704
  message.distinct_id = message.distinctId;
@@ -2871,21 +3713,64 @@ class PostHogCoreStateless {
2871
3713
  }
2872
3714
  }
2873
3715
  flushBackground() {
3716
+ if (this.pendingFlushPromise)
3717
+ return;
2874
3718
  this.flush().catch(async (err) => {
2875
3719
  await logFlushError(err);
2876
3720
  });
2877
3721
  }
2878
- async flush() {
3722
+ async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
3723
+ const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
3724
+ let iteration = 0;
3725
+ while (true) {
3726
+ const promises = this.promiseQueue.getPromises([
3727
+ ...ignoredPendingPromises,
3728
+ ...this.flushPromises
3729
+ ], maxPromiseId);
3730
+ if (promises.length === 0)
3731
+ return;
3732
+ if (iteration > 0)
3733
+ this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
3734
+ await Promise.all(promises.map((promise) => promise.catch(() => {})));
3735
+ iteration++;
3736
+ }
3737
+ }
3738
+ flushWithPendingPromises() {
3739
+ return this.flushInternal(true);
3740
+ }
3741
+ flush() {
3742
+ return this.flushInternal(false);
3743
+ }
3744
+ flushInternal(waitForPendingPromises) {
2879
3745
  if (this.disabled)
2880
- return;
2881
- const nextFlushPromise = allSettled([
2882
- this.flushPromise
2883
- ]).then(() => this._flush());
3746
+ return Promise.resolve();
3747
+ if (!waitForPendingPromises && this.pendingFlushPromise)
3748
+ return this.pendingFlushPromise;
3749
+ const previousFlushPromise = this.flushPromise;
3750
+ const maxPromiseId = this.promiseQueue.maxId;
3751
+ const nextFlushPromise = Promise.resolve().then(() => {
3752
+ if (waitForPendingPromises)
3753
+ return this.waitForPendingPromises(maxPromiseId, [
3754
+ previousFlushPromise,
3755
+ nextFlushPromise
3756
+ ]);
3757
+ }).then(() => allSettled([
3758
+ previousFlushPromise
3759
+ ])).then(() => {
3760
+ if (this.pendingFlushPromise === nextFlushPromise)
3761
+ this.pendingFlushPromise = null;
3762
+ return this._flush();
3763
+ });
3764
+ this.pendingFlushPromise = nextFlushPromise;
2884
3765
  this.flushPromise = nextFlushPromise;
3766
+ this.flushPromises.add(nextFlushPromise);
2885
3767
  this.addPendingPromise(nextFlushPromise);
2886
3768
  allSettled([
2887
3769
  nextFlushPromise
2888
3770
  ]).then(() => {
3771
+ this.flushPromises.delete(nextFlushPromise);
3772
+ if (this.pendingFlushPromise === nextFlushPromise)
3773
+ this.pendingFlushPromise = null;
2889
3774
  if (this.flushPromise === nextFlushPromise)
2890
3775
  this.flushPromise = null;
2891
3776
  });
@@ -2898,55 +3783,102 @@ class PostHogCoreStateless {
2898
3783
  headers["User-Agent"] = customUserAgent;
2899
3784
  return headers;
2900
3785
  }
3786
+ compressPayload(payload) {
3787
+ return gzipCompress(payload, this.isDebug);
3788
+ }
3789
+ getBatchEndpointPath(_route) {
3790
+ return "/batch/";
3791
+ }
3792
+ async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
3793
+ const data = {
3794
+ api_key: this.apiKey,
3795
+ batch: batchMessages.map((message) => {
3796
+ if (!message)
3797
+ return message;
3798
+ const timestamp = this.normalizeTimestampForWire(message.timestamp);
3799
+ return timestamp === message.timestamp ? message : {
3800
+ ...message,
3801
+ timestamp
3802
+ };
3803
+ }),
3804
+ sent_at: currentISOTime()
3805
+ };
3806
+ if (this.historicalMigration)
3807
+ data.historical_migration = true;
3808
+ const payload = safeJsonStringify(data);
3809
+ const url = `${this.host}${this.getBatchEndpointPath(route)}`;
3810
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
3811
+ const fetchOptions = {
3812
+ method: "POST",
3813
+ headers: {
3814
+ ...this.getCustomHeaders(),
3815
+ "Content-Type": "application/json",
3816
+ ...gzippedPayload !== null && {
3817
+ "Content-Encoding": "gzip"
3818
+ }
3819
+ },
3820
+ body: gzippedPayload || payload
3821
+ };
3822
+ await this.fetchWithRetry(url, fetchOptions, {
3823
+ type: "successful-write"
3824
+ }, retryOptions);
3825
+ }
2901
3826
  async _flush() {
2902
3827
  this.clearFlushTimer();
2903
3828
  await this._initPromise;
2904
- let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2905
- if (!queue.length)
3829
+ const routes = this.getActiveQueueRoutes();
3830
+ if (!routes.some((route) => this.getRouteQueue(route).length > 0))
2906
3831
  return;
2907
3832
  const sentMessages = [];
3833
+ let firstError;
3834
+ for (const route of routes)
3835
+ try {
3836
+ await this._flushRoute(route, sentMessages);
3837
+ } catch (err) {
3838
+ if (firstError === undefined)
3839
+ firstError = err;
3840
+ }
3841
+ if (firstError !== undefined)
3842
+ throw firstError;
3843
+ this._events.emit("flush", sentMessages);
3844
+ }
3845
+ async _flushRoute(route, sentMessages) {
3846
+ const queueKey = this.persistedQueueKeyForRoute(route);
3847
+ let queue = this.getPersistedProperty(queueKey) || [];
3848
+ if (!queue.length)
3849
+ return;
2908
3850
  const originalQueueLength = queue.length;
2909
- while (queue.length > 0 && sentMessages.length < originalQueueLength) {
3851
+ let sentFromRoute = 0;
3852
+ while (queue.length > 0 && sentFromRoute < originalQueueLength) {
2910
3853
  const batchItems = queue.slice(0, this.maxBatchSize);
2911
- const batchMessages = batchItems.map((item) => item.message);
3854
+ const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
2912
3855
  const persistQueueChange = async () => {
2913
- const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2914
- const newQueue = refreshedQueue.slice(batchItems.length);
2915
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
3856
+ const refreshedQueue = this.getPersistedProperty(queueKey) || [];
3857
+ const remainingBatchItems = [
3858
+ ...batchItems
3859
+ ];
3860
+ const newQueue = refreshedQueue.filter((item) => {
3861
+ const itemUuid = item.message?.uuid;
3862
+ const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
3863
+ if (batchItemIndex === -1)
3864
+ return true;
3865
+ remainingBatchItems.splice(batchItemIndex, 1);
3866
+ return false;
3867
+ });
3868
+ this.setPersistedProperty(queueKey, newQueue);
2916
3869
  queue = newQueue;
3870
+ this._dequeuedMessagesCount += batchItems.length;
2917
3871
  await this.flushStorage();
2918
3872
  };
2919
- const data = {
2920
- api_key: this.apiKey,
2921
- batch: batchMessages,
2922
- sent_at: currentISOTime()
2923
- };
2924
- if (this.historicalMigration)
2925
- data.historical_migration = true;
2926
- const payload = JSON.stringify(data);
2927
- const url = `${this.host}/batch/`;
2928
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2929
- const fetchOptions = {
2930
- method: "POST",
2931
- headers: {
2932
- ...this.getCustomHeaders(),
2933
- "Content-Type": "application/json",
2934
- ...gzippedPayload !== null && {
2935
- "Content-Encoding": "gzip"
2936
- }
2937
- },
2938
- body: gzippedPayload || payload
2939
- };
2940
3873
  const retryOptions = {
2941
3874
  retryCheck: (err) => {
2942
3875
  if (isPostHogFetchContentTooLargeError(err))
2943
3876
  return false;
2944
- return isPostHogFetchError(err);
3877
+ return isPostHogFetchRetryableError(err);
2945
3878
  }
2946
3879
  };
2947
3880
  try {
2948
- const response = await this.fetchWithRetry(url, fetchOptions, retryOptions);
2949
- await response.body?.cancel()?.catch(() => {});
3881
+ await this.sendBatch(batchMessages, retryOptions, route);
2950
3882
  } catch (err) {
2951
3883
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
2952
3884
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
@@ -2960,8 +3892,8 @@ class PostHogCoreStateless {
2960
3892
  }
2961
3893
  await persistQueueChange();
2962
3894
  sentMessages.push(...batchMessages);
3895
+ sentFromRoute += batchMessages.length;
2963
3896
  }
2964
- this._events.emit("flush", sentMessages);
2965
3897
  }
2966
3898
  async _sendLogsBatch(payload) {
2967
3899
  if (this.disabled)
@@ -2971,7 +3903,7 @@ class PostHogCoreStateless {
2971
3903
  };
2972
3904
  const serialized = JSON.stringify(payload);
2973
3905
  const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
2974
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);
3906
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
2975
3907
  const fetchOptions = {
2976
3908
  method: "POST",
2977
3909
  headers: {
@@ -2985,10 +3917,12 @@ class PostHogCoreStateless {
2985
3917
  };
2986
3918
  try {
2987
3919
  await this.fetchWithRetry(url, fetchOptions, {
3920
+ type: "successful-write"
3921
+ }, {
2988
3922
  retryCheck: (err) => {
2989
3923
  if (isPostHogFetchContentTooLargeError(err))
2990
3924
  return false;
2991
- return isPostHogFetchError(err);
3925
+ return isPostHogFetchRetryableError(err);
2992
3926
  }
2993
3927
  });
2994
3928
  return {
@@ -3010,41 +3944,155 @@ class PostHogCoreStateless {
3010
3944
  };
3011
3945
  }
3012
3946
  }
3013
- async fetchWithRetry(url, options, retryOptions, requestTimeout) {
3947
+ async _sendMetricsBatch(payload) {
3948
+ if (this.disabled)
3949
+ return {
3950
+ kind: "fatal",
3951
+ error: new Error("The client is disabled")
3952
+ };
3953
+ const serialized = JSON.stringify(payload);
3954
+ const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
3955
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
3956
+ const fetchOptions = {
3957
+ method: "POST",
3958
+ headers: {
3959
+ ...this.getCustomHeaders(),
3960
+ "Content-Type": "application/json",
3961
+ ...gzippedPayload !== null && {
3962
+ "Content-Encoding": "gzip"
3963
+ }
3964
+ },
3965
+ body: gzippedPayload || serialized
3966
+ };
3967
+ try {
3968
+ await this.fetchWithRetry(url, fetchOptions, {
3969
+ type: "successful-write"
3970
+ }, {
3971
+ retryCheck: (err) => {
3972
+ if (isPostHogFetchContentTooLargeError(err))
3973
+ return false;
3974
+ return isPostHogFetchRetryableError(err);
3975
+ }
3976
+ });
3977
+ return {
3978
+ kind: "ok"
3979
+ };
3980
+ } catch (err) {
3981
+ if (isPostHogFetchContentTooLargeError(err))
3982
+ return {
3983
+ kind: "too-large"
3984
+ };
3985
+ if (isPostHogFetchRetryableError(err))
3986
+ return {
3987
+ kind: "retry-later",
3988
+ error: err
3989
+ };
3990
+ return {
3991
+ kind: "fatal",
3992
+ error: err
3993
+ };
3994
+ }
3995
+ }
3996
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
3014
3997
  const body = options.body ? options.body : "";
3015
3998
  let reqByteLength = -1;
3016
3999
  try {
3017
- reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
4000
+ reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
3018
4001
  } catch {
3019
4002
  if (body instanceof Blob)
3020
4003
  reqByteLength = body.size;
4004
+ else if (body instanceof Uint8Array)
4005
+ reqByteLength = body.byteLength;
3021
4006
  else {
3022
4007
  const encoded = new TextEncoder().encode(body);
3023
4008
  reqByteLength = encoded.length;
3024
4009
  }
3025
4010
  }
4011
+ const retriableOptions = {
4012
+ ...this._retryOptions,
4013
+ ...retryOptions
4014
+ };
4015
+ let attempt = 0;
3026
4016
  return await retriable(async () => {
4017
+ attempt++;
3027
4018
  const ctrl = new AbortController;
3028
4019
  const timeoutMs = requestTimeout ?? this.requestTimeout;
3029
- const timer = safeSetTimeout(() => ctrl.abort(), timeoutMs);
3030
- let res = null;
4020
+ const requestDeadline = Date.now() + timeoutMs;
4021
+ let timer;
4022
+ const deadline = new Promise((_resolve, reject) => {
4023
+ timer = safeSetTimeout(() => {
4024
+ const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
4025
+ timeoutError.name = "AbortError";
4026
+ reject(timeoutError);
4027
+ ctrl.abort(timeoutError);
4028
+ }, timeoutMs);
4029
+ });
4030
+ let res;
4031
+ let responseAccepted = false;
4032
+ let cancellation;
4033
+ const cancelBody = () => cancellation ??= (async () => {
4034
+ try {
4035
+ await res?.body?.cancel();
4036
+ } catch {}
4037
+ })();
3031
4038
  try {
3032
- res = await this.fetch(url, {
3033
- signal: ctrl.signal,
3034
- ...options
3035
- });
3036
- } catch (e) {
3037
- throw new PostHogFetchNetworkError(e);
4039
+ let fetchPromise;
4040
+ try {
4041
+ fetchPromise = this.fetch(url, {
4042
+ signal: ctrl.signal,
4043
+ ...options
4044
+ });
4045
+ } catch (e) {
4046
+ throw new PostHogFetchNetworkError(e);
4047
+ }
4048
+ fetchPromise.then((lateResponse) => {
4049
+ if (ctrl.signal.aborted && !responseAccepted)
4050
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
4051
+ }).catch(() => {});
4052
+ try {
4053
+ res = await Promise.race([
4054
+ fetchPromise,
4055
+ deadline
4056
+ ]);
4057
+ responseAccepted = true;
4058
+ } catch (e) {
4059
+ throw new PostHogFetchNetworkError(e);
4060
+ }
4061
+ const isNoCors = options.mode === "no-cors";
4062
+ if (!isNoCors && (res.status < 200 || res.status >= 400))
4063
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
4064
+ if (responseHandling.type === "successful-write") {
4065
+ try {
4066
+ await Promise.race([
4067
+ cancelBody(),
4068
+ deadline
4069
+ ]);
4070
+ } catch {}
4071
+ return;
4072
+ }
4073
+ try {
4074
+ return await Promise.race([
4075
+ responseHandling.consume(res),
4076
+ deadline
4077
+ ]);
4078
+ } catch (e) {
4079
+ if (ctrl.signal.aborted)
4080
+ throw new PostHogFetchNetworkError(e);
4081
+ throw e;
4082
+ }
3038
4083
  } finally {
3039
4084
  clearTimeout(timer);
4085
+ if (ctrl.signal.aborted && res)
4086
+ cancelBody();
3040
4087
  }
3041
- const isNoCors = options.mode === "no-cors";
3042
- if (!isNoCors && (res.status < 200 || res.status >= 400))
3043
- throw new PostHogFetchHttpError(res, reqByteLength);
3044
- return res;
3045
4088
  }, {
3046
- ...this._retryOptions,
3047
- ...retryOptions
4089
+ ...retriableOptions,
4090
+ retryCheck: (error) => {
4091
+ const shouldRetry = retriableOptions.retryCheck(error);
4092
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
4093
+ error.cancelResponseBody();
4094
+ return shouldRetry;
4095
+ }
3048
4096
  });
3049
4097
  }
3050
4098
  async _shutdown(shutdownTimeoutMs = 30000) {
@@ -3057,12 +4105,17 @@ class PostHogCoreStateless {
3057
4105
  try {
3058
4106
  await this.promiseQueue.join();
3059
4107
  while (true) {
3060
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
3061
- if (queue.length === 0)
4108
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
4109
+ if (!hasQueuedEvents)
3062
4110
  break;
4111
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
3063
4112
  await this.flush();
3064
4113
  if (hasTimedOut)
3065
4114
  break;
4115
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
4116
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
4117
+ break;
4118
+ }
3066
4119
  }
3067
4120
  } catch (e) {
3068
4121
  if (!isPostHogFetchError(e))
@@ -3070,21 +4123,12 @@ class PostHogCoreStateless {
3070
4123
  await logFlushError(e);
3071
4124
  }
3072
4125
  };
3073
- let timeoutHandle;
3074
- try {
3075
- return await Promise.race([
3076
- new Promise((_, reject) => {
3077
- timeoutHandle = safeSetTimeout(() => {
3078
- this._logger.error("Timed out while shutting down PostHog");
3079
- hasTimedOut = true;
3080
- reject("Timeout while shutting down PostHog. Some events may not have been sent.");
3081
- }, shutdownTimeoutMs);
3082
- }),
3083
- doShutdown()
3084
- ]);
3085
- } finally {
3086
- clearTimeout(timeoutHandle);
3087
- }
4126
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
4127
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
4128
+ shutdownTimeoutMs
4129
+ });
4130
+ hasTimedOut = true;
4131
+ });
3088
4132
  }
3089
4133
  async shutdown(shutdownTimeoutMs = 30000) {
3090
4134
  if (this.shutdownPromise)
@@ -3096,7 +4140,11 @@ class PostHogCoreStateless {
3096
4140
  return this.shutdownPromise;
3097
4141
  }
3098
4142
  }
3099
- var PostHogFetchHttpError, PostHogFetchNetworkError;
4143
+ var PostHogFetchHttpError, PostHogFetchNetworkError, applyCallerFeatureFlagOverrides = (target, callerProperties) => {
4144
+ for (const key of Object.keys(callerProperties))
4145
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
4146
+ target[key] = callerProperties[key];
4147
+ }, DEFAULT_QUEUE_ROUTE = "default";
3100
4148
  var init_posthog_core_stateless = __esm(() => {
3101
4149
  init_eventemitter();
3102
4150
  init_featureFlagUtils();
@@ -3106,17 +4154,58 @@ var init_posthog_core_stateless = __esm(() => {
3106
4154
  init_uuidv7();
3107
4155
  init_error_tracking();
3108
4156
  PostHogFetchHttpError = class PostHogFetchHttpError extends Error {
3109
- constructor(response, reqByteLength) {
3110
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
4157
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
4158
+ super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.responseBodyDeadline = responseBodyDeadline, this.abortController = abortController, this.name = "PostHogFetchHttpError", this._bodyReadTimedOut = false;
3111
4159
  }
3112
4160
  get status() {
3113
4161
  return this.response.status;
3114
4162
  }
4163
+ get bodyReadTimedOut() {
4164
+ return this._bodyReadTimedOut;
4165
+ }
3115
4166
  get text() {
3116
- return this.response.text();
4167
+ if (!this.responseBodyTextPromise)
4168
+ if (Date.now() >= this.responseBodyDeadline) {
4169
+ this._bodyReadTimedOut = true;
4170
+ const timeoutError = new Error("Response body read timed out");
4171
+ timeoutError.name = "AbortError";
4172
+ this.cancelResponseBody(timeoutError);
4173
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
4174
+ } else {
4175
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
4176
+ this.responseBodyTimer = safeSetTimeout(() => {
4177
+ this._bodyReadTimedOut = true;
4178
+ const timeoutError = new Error("Response body read timed out");
4179
+ timeoutError.name = "AbortError";
4180
+ reject(timeoutError);
4181
+ this.cancelResponseBody(timeoutError);
4182
+ }, this.responseBodyDeadline - Date.now());
4183
+ });
4184
+ let responseBodyText;
4185
+ try {
4186
+ responseBodyText = Promise.resolve(this.response.text());
4187
+ } catch (error) {
4188
+ responseBodyText = Promise.reject(error);
4189
+ }
4190
+ this.responseBodyTextPromise = Promise.race([
4191
+ responseBodyText,
4192
+ responseBodyTimeout
4193
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
4194
+ }
4195
+ return this.responseBodyTextPromise;
3117
4196
  }
3118
4197
  get json() {
3119
- return this.response.json();
4198
+ return this.text.then((text) => JSON.parse(text));
4199
+ }
4200
+ cancelResponseBody(reason) {
4201
+ clearTimeout(this.responseBodyTimer);
4202
+ if (!this.abortController.signal.aborted)
4203
+ this.abortController.abort(reason);
4204
+ (async () => {
4205
+ try {
4206
+ await this.response.body?.cancel();
4207
+ } catch {}
4208
+ })();
3120
4209
  }
3121
4210
  };
3122
4211
  PostHogFetchNetworkError = class PostHogFetchNetworkError extends Error {
@@ -3128,7 +4217,7 @@ var init_posthog_core_stateless = __esm(() => {
3128
4217
  };
3129
4218
  });
3130
4219
 
3131
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/posthog-core.mjs
4220
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/posthog-core.mjs
3132
4221
  var init_posthog_core = __esm(() => {
3133
4222
  init_featureFlagUtils();
3134
4223
  init_types();
@@ -3137,17 +4226,18 @@ var init_posthog_core = __esm(() => {
3137
4226
  init_utils();
3138
4227
  });
3139
4228
 
3140
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/tracing-headers.mjs
4229
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/tracing-headers.mjs
3141
4230
  var init_tracing_headers = __esm(() => {
3142
4231
  init_type_utils();
3143
4232
  });
3144
4233
 
3145
- // node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/index.mjs
4234
+ // node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/index.mjs
3146
4235
  var init_dist = __esm(() => {
3147
4236
  init_featureFlagUtils();
3148
4237
  init_gzip();
3149
4238
  init_logs_utils();
3150
4239
  init_logs();
4240
+ init_metrics();
3151
4241
  init_uuidv7();
3152
4242
  init_validation();
3153
4243
  init_error_tracking();
@@ -3159,16 +4249,24 @@ var init_dist = __esm(() => {
3159
4249
  init_types();
3160
4250
  });
3161
4251
 
3162
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
3163
- import { createReadStream } from "node:fs";
4252
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
4253
+ import { constants as constants3 } from "node:fs";
4254
+ import { open as promises_open } from "node:fs/promises";
4255
+ import { isAbsolute as isAbsolute7 } from "node:path";
3164
4256
  import { createInterface } from "node:readline";
3165
- async function addSourceContext(frames) {
4257
+ async function addSourceContext(frames, openSourceFile = promises_open, logger2) {
3166
4258
  const filesToLines = {};
4259
+ let basePath;
4260
+ try {
4261
+ basePath = process.cwd();
4262
+ } catch {}
3167
4263
  for (let i = frames.length - 1;i >= 0; i--) {
3168
4264
  const frame = frames[i];
3169
4265
  const filename = frame?.filename;
3170
4266
  if (!frame || typeof filename != "string" || typeof frame.lineno != "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame))
3171
4267
  continue;
4268
+ if (!isAbsolute7(filename) && basePath === undefined)
4269
+ continue;
3172
4270
  const filesToLinesOutput = filesToLines[filename];
3173
4271
  if (!filesToLinesOutput)
3174
4272
  filesToLines[filename] = [];
@@ -3179,50 +4277,98 @@ async function addSourceContext(frames) {
3179
4277
  return frames;
3180
4278
  const readlinePromises = [];
3181
4279
  for (const file of files) {
3182
- if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file))
4280
+ const cacheKey = makeSourceCacheKey(file, basePath);
4281
+ if (cacheKey === undefined)
4282
+ continue;
4283
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(cacheKey))
3183
4284
  continue;
3184
4285
  const filesToLineRanges = filesToLines[file];
3185
4286
  if (!filesToLineRanges)
3186
4287
  continue;
3187
4288
  filesToLineRanges.sort((a, b) => a - b);
3188
4289
  const ranges = makeLineReaderRanges(filesToLineRanges);
3189
- if (ranges.every((r) => rangeExistsInContentCache(file, r)))
4290
+ if (ranges.every((r) => rangeExistsInContentCache(cacheKey, r)))
3190
4291
  continue;
3191
- const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
3192
- readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
4292
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, cacheKey, {});
4293
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache, cacheKey, openSourceFile, logger2));
3193
4294
  }
3194
4295
  await Promise.all(readlinePromises).catch(() => {});
3195
4296
  if (frames && frames.length > 0)
3196
- addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
4297
+ addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE, basePath);
3197
4298
  LRU_FILE_CONTENTS_CACHE.reduce();
3198
4299
  return frames;
3199
4300
  }
3200
- function getContextLinesFromFile(path2, ranges, output) {
4301
+ async function openRegularSourceFile(path2, openSourceFile, logger2) {
4302
+ let fileHandle;
4303
+ let isValid = false;
4304
+ try {
4305
+ fileHandle = await openSourceFile(path2, constants3.O_RDONLY | constants3.O_NONBLOCK);
4306
+ const fileStat = await fileHandle.stat();
4307
+ if (!fileStat.isFile())
4308
+ return;
4309
+ if (fileStat.size > MAX_CONTEXTLINES_FILE_SIZE)
4310
+ return void logger2?.debug(`Skipping source context for oversized file ${path2}: ${fileStat.size} bytes exceeds ${MAX_CONTEXTLINES_FILE_SIZE}`);
4311
+ isValid = true;
4312
+ return fileHandle;
4313
+ } catch {
4314
+ return;
4315
+ } finally {
4316
+ if (fileHandle && !isValid)
4317
+ await fileHandle.close().catch(() => {});
4318
+ }
4319
+ }
4320
+ async function getContextLinesFromFile(path2, ranges, output, cacheKey, openSourceFile, logger2) {
4321
+ const fileHandle = await openRegularSourceFile(path2, openSourceFile, logger2);
4322
+ if (fileHandle === undefined)
4323
+ return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
4324
+ const openedFileHandle = fileHandle;
3201
4325
  return new Promise((resolve9) => {
3202
- const stream = createReadStream(path2);
3203
- const lineReaded = createInterface({
3204
- input: stream
3205
- });
3206
- function destroyStreamAndResolve() {
3207
- stream.destroy();
3208
- resolve9();
4326
+ let finished = false;
4327
+ function destroyStreamAndResolve(stream2) {
4328
+ if (finished)
4329
+ return;
4330
+ finished = true;
4331
+ stream2?.destroy();
4332
+ openedFileHandle.close().then(resolve9, resolve9);
4333
+ }
4334
+ let stream;
4335
+ try {
4336
+ stream = openedFileHandle.createReadStream({
4337
+ autoClose: false,
4338
+ start: 0,
4339
+ end: MAX_CONTEXTLINES_FILE_SIZE - 1
4340
+ });
4341
+ } catch {
4342
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
4343
+ destroyStreamAndResolve();
4344
+ return;
4345
+ }
4346
+ let lineReaded;
4347
+ try {
4348
+ lineReaded = createInterface({
4349
+ input: stream
4350
+ });
4351
+ } catch {
4352
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
4353
+ destroyStreamAndResolve(stream);
4354
+ return;
3209
4355
  }
3210
4356
  let lineNumber = 0;
3211
4357
  let currentRangeIndex = 0;
3212
4358
  const range = ranges[currentRangeIndex];
3213
4359
  if (range === undefined)
3214
- return void destroyStreamAndResolve();
4360
+ return void destroyStreamAndResolve(stream);
3215
4361
  let rangeStart = range[0];
3216
4362
  let rangeEnd = range[1];
3217
4363
  function onStreamError() {
3218
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path2, 1);
4364
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3219
4365
  lineReaded.close();
3220
4366
  lineReaded.removeAllListeners();
3221
- destroyStreamAndResolve();
4367
+ destroyStreamAndResolve(stream);
3222
4368
  }
3223
4369
  stream.on("error", onStreamError);
3224
4370
  lineReaded.on("error", onStreamError);
3225
- lineReaded.on("close", destroyStreamAndResolve);
4371
+ lineReaded.on("close", () => destroyStreamAndResolve(stream));
3226
4372
  lineReaded.on("line", (line) => {
3227
4373
  lineNumber++;
3228
4374
  if (lineNumber < rangeStart)
@@ -3247,10 +4393,11 @@ function getContextLinesFromFile(path2, ranges, output) {
3247
4393
  });
3248
4394
  });
3249
4395
  }
3250
- function addSourceContextToFrames(frames, cache) {
4396
+ function addSourceContextToFrames(frames, cache, basePath) {
3251
4397
  for (const frame of frames)
3252
4398
  if (frame.filename && frame.context_line === undefined && typeof frame.lineno == "number") {
3253
- const contents = cache.get(frame.filename);
4399
+ const cacheKey = makeSourceCacheKey(frame.filename, basePath);
4400
+ const contents = cacheKey === undefined ? undefined : cache.get(cacheKey);
3254
4401
  if (contents === undefined)
3255
4402
  continue;
3256
4403
  addContextToFrame(frame.lineno, frame, contents);
@@ -3293,8 +4440,19 @@ function shouldSkipContextLinesForFrame(frame) {
3293
4440
  return true;
3294
4441
  return false;
3295
4442
  }
3296
- function rangeExistsInContentCache(file, range) {
3297
- const contents = LRU_FILE_CONTENTS_CACHE.get(file);
4443
+ function makeSourceCacheKey(path2, basePath) {
4444
+ if (isAbsolute7(path2))
4445
+ return JSON.stringify([
4446
+ null,
4447
+ path2
4448
+ ]);
4449
+ return basePath === undefined ? undefined : JSON.stringify([
4450
+ basePath,
4451
+ path2
4452
+ ]);
4453
+ }
4454
+ function rangeExistsInContentCache(cacheKey, range) {
4455
+ const contents = LRU_FILE_CONTENTS_CACHE.get(cacheKey);
3298
4456
  if (contents === undefined)
3299
4457
  return false;
3300
4458
  for (let i = range[0];i <= range[1]; i++)
@@ -3371,15 +4529,15 @@ function snipLine(line, colno) {
3371
4529
  newLine += "...";
3372
4530
  return newLine;
3373
4531
  }
3374
- var LRU_FILE_CONTENTS_CACHE, LRU_FILE_CONTENTS_FS_READ_FAILED, DEFAULT_LINES_OF_CONTEXT = 7, MAX_CONTEXTLINES_COLNO = 1000, MAX_CONTEXTLINES_LINENO = 1e4;
4532
+ var LRU_FILE_CONTENTS_CACHE, LRU_FILE_CONTENTS_FS_READ_FAILED, DEFAULT_LINES_OF_CONTEXT = 7, MAX_CONTEXTLINES_COLNO = 1000, MAX_CONTEXTLINES_LINENO = 1e4, MAX_CONTEXTLINES_FILE_SIZE = 10485760;
3375
4533
  var init_context_lines_node = __esm(() => {
3376
4534
  init_dist();
3377
4535
  LRU_FILE_CONTENTS_CACHE = new exports_error_tracking.ReduceableCache(25);
3378
4536
  LRU_FILE_CONTENTS_FS_READ_FAILED = new exports_error_tracking.ReduceableCache(20);
3379
4537
  });
3380
4538
 
3381
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
3382
- import { isAbsolute as isAbsolute7, relative as relative4, sep as sep8 } from "node:path";
4539
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
4540
+ import { isAbsolute as isAbsolute8, relative as relative4, sep as sep8 } from "node:path";
3383
4541
  function createRelativePathModifier(basePath = process.cwd()) {
3384
4542
  const isWindows = sep8 === "\\";
3385
4543
  const toUnix = (p) => isWindows ? p.replace(/\\/g, "/") : p;
@@ -3387,7 +4545,7 @@ function createRelativePathModifier(basePath = process.cwd()) {
3387
4545
  return async (frames) => {
3388
4546
  for (const frame of frames)
3389
4547
  if (!(!frame.filename || frame.filename.startsWith("node:") || frame.filename.startsWith("data:"))) {
3390
- if (isAbsolute7(frame.filename))
4548
+ if (isAbsolute8(frame.filename))
3391
4549
  frame.filename = toUnix(relative4(normalizedBase, toUnix(frame.filename)));
3392
4550
  }
3393
4551
  return frames;
@@ -3395,11 +4553,11 @@ function createRelativePathModifier(basePath = process.cwd()) {
3395
4553
  }
3396
4554
  var init_relative_path_node = () => {};
3397
4555
 
3398
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/version.mjs
3399
- var version = "5.35.12";
4556
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/version.mjs
4557
+ var version = "5.51.1";
3400
4558
  var init_version = () => {};
3401
4559
 
3402
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/types.mjs
4560
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/types.mjs
3403
4561
  var FeatureFlagError2;
3404
4562
  var init_types3 = __esm(() => {
3405
4563
  FeatureFlagError2 = {
@@ -3410,7 +4568,7 @@ var init_types3 = __esm(() => {
3410
4568
  };
3411
4569
  });
3412
4570
 
3413
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
4571
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
3414
4572
  class FeatureFlagEvaluations {
3415
4573
  constructor(init) {
3416
4574
  this._host = init.host;
@@ -3426,10 +4584,10 @@ class FeatureFlagEvaluations {
3426
4584
  this._accessed = init.accessed ?? new Set;
3427
4585
  this._isSlice = init.isSlice ?? false;
3428
4586
  }
3429
- isEnabled(key) {
4587
+ isEnabled(key, options = {}) {
3430
4588
  const flag = this._flags[key];
3431
4589
  this._recordAccess(key);
3432
- return flag?.enabled ?? false;
4590
+ return flag?.enabled ?? options.defaultValue ?? false;
3433
4591
  }
3434
4592
  getFlag(key) {
3435
4593
  const flag = this._flags[key];
@@ -3519,6 +4677,8 @@ class FeatureFlagEvaluations {
3519
4677
  $feature_flag_request_id: this._requestId,
3520
4678
  $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt
3521
4679
  };
4680
+ if (flag?.hasExperiment !== undefined)
4681
+ properties.$feature_flag_has_experiment = flag.hasExperiment;
3522
4682
  if (flag?.locallyEvaluated && this._flagDefinitionsLoadedAt !== undefined)
3523
4683
  properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;
3524
4684
  const errors = [];
@@ -3544,7 +4704,7 @@ var init_feature_flag_evaluations = __esm(() => {
3544
4704
  init_types3();
3545
4705
  });
3546
4706
 
3547
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
4707
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
3548
4708
  async function hashSHA1(text) {
3549
4709
  const subtle = globalThis.crypto?.subtle;
3550
4710
  if (!subtle)
@@ -3555,12 +4715,19 @@ async function hashSHA1(text) {
3555
4715
  }
3556
4716
  var init_crypto = () => {};
3557
4717
 
3558
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
4718
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
4719
+ function setCustomErrorPrototype(error, constructor) {
4720
+ error.name = constructor.name;
4721
+ Error.captureStackTrace(error, constructor);
4722
+ Object.setPrototypeOf(error, constructor.prototype);
4723
+ }
4724
+
3559
4725
  class FeatureFlagsPoller {
3560
4726
  constructor({ pollingInterval, personalApiKey, projectApiKey, timeout, host, customHeaders, ...options }) {
3561
4727
  this.debugMode = false;
3562
4728
  this.shouldBeginExponentialBackoff = false;
3563
4729
  this.backOffCount = 0;
4730
+ this.pollerStopped = false;
3564
4731
  this.pollingInterval = pollingInterval;
3565
4732
  this.personalApiKey = personalApiKey;
3566
4733
  this.featureFlags = [];
@@ -3576,6 +4743,7 @@ class FeatureFlagsPoller {
3576
4743
  this.onError = options.onError;
3577
4744
  this.customHeaders = customHeaders;
3578
4745
  this.onLoad = options.onLoad;
4746
+ this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
3579
4747
  this.cacheProvider = options.cacheProvider;
3580
4748
  this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
3581
4749
  this.loadFeatureFlags();
@@ -3773,6 +4941,7 @@ class FeatureFlagsPoller {
3773
4941
  const flagFilters = flag.filters || {};
3774
4942
  const flagConditions = flagFilters.groups || [];
3775
4943
  const flagAggregation = flagFilters.aggregation_group_type_index;
4944
+ const earlyExitEnabled = flagFilters.early_exit ?? false;
3776
4945
  const { groups, groupProperties } = evaluationContext;
3777
4946
  let isInconclusive = false;
3778
4947
  let result;
@@ -3796,12 +4965,15 @@ class FeatureFlagsPoller {
3796
4965
  effectiveBucketingValue = groups[groupName];
3797
4966
  }
3798
4967
  }
3799
- if (await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext)) {
4968
+ const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);
4969
+ if (matchResult === "match") {
3800
4970
  const variantOverride = condition.variant;
3801
4971
  const flagVariants = flagFilters.multivariate?.variants || [];
3802
4972
  result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
3803
4973
  break;
3804
4974
  }
4975
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
4976
+ return false;
3805
4977
  } catch (e) {
3806
4978
  if (e instanceof RequiresServerEvaluation)
3807
4979
  throw e;
@@ -3825,16 +4997,20 @@ class FeatureFlagsPoller {
3825
4997
  for (const prop of condition.properties) {
3826
4998
  const propertyType = prop.type;
3827
4999
  let matches = false;
3828
- matches = propertyType === "cohort" ? await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext)) : propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
5000
+ if (propertyType === "cohort") {
5001
+ const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext));
5002
+ matches = prop.operator === "not_in" ? !inCohort : inCohort;
5003
+ } else
5004
+ matches = propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
3829
5005
  if (!matches)
3830
- return false;
5006
+ return "no_match";
3831
5007
  }
3832
5008
  if (rolloutPercentage == undefined)
3833
- return true;
5009
+ return "match";
3834
5010
  }
3835
5011
  if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
3836
- return false;
3837
- return true;
5012
+ return "out_of_rollout_bound";
5013
+ return "match";
3838
5014
  }
3839
5015
  async getMatchingVariant(flag, bucketingValue) {
3840
5016
  const hashValue = await _hash(flag.key, bucketingValue, "variant");
@@ -3865,6 +5041,7 @@ class FeatureFlagsPoller {
3865
5041
  this.groupTypeMapping = flagData.groupTypeMapping;
3866
5042
  this.cohorts = flagData.cohorts;
3867
5043
  this.loadedSuccessfullyOnce = true;
5044
+ this.onMinimalFlagCalledEvents?.(flagData.minimalFlagCalledEvents === true);
3868
5045
  }
3869
5046
  warnAboutExperienceContinuityFlags(flags) {
3870
5047
  if (this.strictLocalEvaluation)
@@ -3928,7 +5105,6 @@ class FeatureFlagsPoller {
3928
5105
  clearTimeout(this.poller);
3929
5106
  this.poller = undefined;
3930
5107
  }
3931
- this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3932
5108
  try {
3933
5109
  let shouldFetch = true;
3934
5110
  if (this.cacheProvider)
@@ -3956,17 +5132,18 @@ class FeatureFlagsPoller {
3956
5132
  return;
3957
5133
  case 401:
3958
5134
  this.beginBackoff();
3959
- throw new ClientError(`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`);
5135
+ throw new ClientError(`Your project key or secret key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
3960
5136
  case 402:
3961
5137
  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");
3962
5138
  this.featureFlags = [];
3963
5139
  this.featureFlagsByKey = {};
3964
5140
  this.groupTypeMapping = {};
3965
5141
  this.cohorts = {};
5142
+ this.onMinimalFlagCalledEvents?.(false);
3966
5143
  return;
3967
5144
  case 403:
3968
5145
  this.beginBackoff();
3969
- throw new ClientError(`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`);
5146
+ throw new ClientError(`Your secret key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct secret and Project API key pair? More information: https://posthog.com/docs/api/overview`);
3970
5147
  case 429:
3971
5148
  this.beginBackoff();
3972
5149
  throw new ClientError(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);
@@ -3978,7 +5155,8 @@ class FeatureFlagsPoller {
3978
5155
  const flagData = {
3979
5156
  flags: responseJson.flags ?? [],
3980
5157
  groupTypeMapping: responseJson.group_type_mapping || {},
3981
- cohorts: responseJson.cohorts || {}
5158
+ cohorts: responseJson.cohorts || {},
5159
+ minimalFlagCalledEvents: responseJson.minimal_flag_called_events === true
3982
5160
  };
3983
5161
  this.updateFlagState(flagData);
3984
5162
  this.flagDefinitionsLoadedAt = Date.now();
@@ -3999,6 +5177,9 @@ class FeatureFlagsPoller {
3999
5177
  } catch (err) {
4000
5178
  if (err instanceof ClientError)
4001
5179
  this.onError?.(err);
5180
+ } finally {
5181
+ if (!this.pollerStopped)
5182
+ this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
4002
5183
  }
4003
5184
  }
4004
5185
  getPersonalApiKeyRequestOptions(method = "GET", etag) {
@@ -4014,7 +5195,7 @@ class FeatureFlagsPoller {
4014
5195
  headers
4015
5196
  };
4016
5197
  }
4017
- _requestFeatureFlagDefinitions() {
5198
+ async _requestFeatureFlagDefinitions() {
4018
5199
  const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;
4019
5200
  const options = this.getPersonalApiKeyRequestOptions("GET", this.flagsEtag);
4020
5201
  let abortTimeout = null;
@@ -4025,23 +5206,49 @@ class FeatureFlagsPoller {
4025
5206
  }, this.timeout);
4026
5207
  options.signal = controller.signal;
4027
5208
  }
5209
+ const clearAbortTimeout = () => clearTimeout(abortTimeout);
4028
5210
  try {
4029
5211
  const fetch1 = this.fetch;
4030
- return fetch1(url, options);
4031
- } finally {
4032
- clearTimeout(abortTimeout);
5212
+ const res = await fetch1(url, options);
5213
+ if (res.status !== 200) {
5214
+ clearAbortTimeout();
5215
+ return res;
5216
+ }
5217
+ return {
5218
+ status: res.status,
5219
+ headers: res.headers,
5220
+ body: res.body,
5221
+ text: async () => {
5222
+ try {
5223
+ return await res.text();
5224
+ } finally {
5225
+ clearAbortTimeout();
5226
+ }
5227
+ },
5228
+ json: async () => {
5229
+ try {
5230
+ return await res.json();
5231
+ } finally {
5232
+ clearAbortTimeout();
5233
+ }
5234
+ }
5235
+ };
5236
+ } catch (err) {
5237
+ clearAbortTimeout();
5238
+ throw err;
4033
5239
  }
4034
5240
  }
4035
5241
  async stopPoller(timeoutMs = 30000) {
5242
+ this.pollerStopped = true;
4036
5243
  clearTimeout(this.poller);
5244
+ this.poller = undefined;
4037
5245
  if (this.cacheProvider)
4038
5246
  try {
4039
5247
  const shutdownResult = this.cacheProvider.shutdown();
4040
5248
  if (shutdownResult instanceof Promise)
4041
- await Promise.race([
4042
- shutdownResult,
4043
- new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
4044
- ]);
5249
+ await raceWithTimeout(shutdownResult, timeoutMs, () => {
5250
+ throw new Error(`Cache shutdown timeout after ${timeoutMs}ms`);
5251
+ });
4045
5252
  } catch (err) {
4046
5253
  this.onError?.(new Error(`Error during cache shutdown: ${err}`));
4047
5254
  }
@@ -4096,6 +5303,14 @@ function matchProperty(property, propertyValues, warnFunction) {
4096
5303
  return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
4097
5304
  case "not_icontains":
4098
5305
  return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
5306
+ case "starts_with":
5307
+ return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
5308
+ case "not_starts_with":
5309
+ return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
5310
+ case "ends_with":
5311
+ return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
5312
+ case "not_ends_with":
5313
+ return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
4099
5314
  case "regex":
4100
5315
  return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
4101
5316
  case "not_regex":
@@ -4441,34 +5656,70 @@ var init_feature_flags = __esm(() => {
4441
5656
  InconclusiveMatchError = class InconclusiveMatchError extends Error {
4442
5657
  constructor(message) {
4443
5658
  super(message);
4444
- this.name = this.constructor.name;
4445
- Error.captureStackTrace(this, this.constructor);
4446
- Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
5659
+ setCustomErrorPrototype(this, InconclusiveMatchError);
4447
5660
  }
4448
5661
  };
4449
5662
  RequiresServerEvaluation = class RequiresServerEvaluation extends Error {
4450
5663
  constructor(message) {
4451
5664
  super(message);
4452
- this.name = this.constructor.name;
4453
- Error.captureStackTrace(this, this.constructor);
4454
- Object.setPrototypeOf(this, RequiresServerEvaluation.prototype);
5665
+ setCustomErrorPrototype(this, RequiresServerEvaluation);
4455
5666
  }
4456
5667
  };
4457
5668
  });
4458
5669
 
4459
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5670
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5671
+ function splitNodeOptions(nodeOptions) {
5672
+ const args = [];
5673
+ let current = "";
5674
+ let isInString = false;
5675
+ for (let index = 0;index < nodeOptions.length; index++) {
5676
+ const character = nodeOptions[index];
5677
+ if (character === "\\" && isInString && index + 1 < nodeOptions.length)
5678
+ current += nodeOptions[++index];
5679
+ else if (character !== " " || isInString)
5680
+ if (character === '"')
5681
+ isInString = !isInString;
5682
+ else
5683
+ current += character;
5684
+ else if (current) {
5685
+ args.push(current);
5686
+ current = "";
5687
+ }
5688
+ }
5689
+ if (current)
5690
+ args.push(current);
5691
+ return args;
5692
+ }
5693
+ function findUnhandledRejectionMode(args) {
5694
+ let mode;
5695
+ for (let index = 0;index < args.length; index++) {
5696
+ const argument = args[index];
5697
+ const optionName = UNHANDLED_REJECTION_OPTION_NAMES.find((name) => argument === name || argument.startsWith(`${name}=`));
5698
+ if (!optionName)
5699
+ continue;
5700
+ const value = argument === optionName ? args[++index] : argument.slice(optionName.length + 1);
5701
+ if (UNHANDLED_REJECTION_MODES.has(value))
5702
+ mode = value;
5703
+ }
5704
+ return mode;
5705
+ }
5706
+ function getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = STARTUP_NODE_OPTIONS) {
5707
+ return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? "")) ?? "throw";
5708
+ }
5709
+ function captureUncaughtException(captureFn, error, origin) {
5710
+ captureFn(error, {
5711
+ mechanism: {
5712
+ type: origin === "unhandledRejection" ? "onunhandledrejection" : "onuncaughtexception",
5713
+ handled: false
5714
+ }
5715
+ });
5716
+ }
4460
5717
  function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4461
5718
  let calledFatalError = false;
4462
- return Object.assign((error) => {
5719
+ return Object.assign((error, origin) => {
4463
5720
  const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => listener.name !== "domainUncaughtExceptionClear" && listener._posthogErrorHandler !== true).length;
4464
- const processWouldExit = userProvidedListenersCount === 0;
4465
- captureFn(error, {
4466
- mechanism: {
4467
- type: "onuncaughtexception",
4468
- handled: false
4469
- }
4470
- });
4471
- if (!calledFatalError && processWouldExit) {
5721
+ captureUncaughtException(captureFn, error, origin);
5722
+ if (!calledFatalError && userProvidedListenersCount === 0) {
4472
5723
  calledFatalError = true;
4473
5724
  onFatalFn(error);
4474
5725
  }
@@ -4476,28 +5727,55 @@ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4476
5727
  _posthogErrorHandler: true
4477
5728
  });
4478
5729
  }
4479
- function addUncaughtExceptionListener(captureFn, onFatalFn) {
4480
- globalThis.process?.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
5730
+ function addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5731
+ const process2 = globalThis.process;
5732
+ if (!process2)
5733
+ return;
5734
+ if (mode === "strict")
5735
+ return void process2.on("uncaughtExceptionMonitor", (error, origin) => captureUncaughtException(captureFn, error, origin));
5736
+ process2.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
4481
5737
  }
4482
- function addUnhandledRejectionListener(captureFn) {
4483
- globalThis.process?.on("unhandledRejection", (reason) => captureFn(reason, {
4484
- mechanism: {
4485
- type: "onunhandledrejection",
4486
- handled: false
4487
- }
4488
- }));
5738
+ function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5739
+ const process2 = globalThis.process;
5740
+ if (!process2 || mode === "throw" || mode === "strict" || mode === "warn-with-error-code")
5741
+ return;
5742
+ process2.on("unhandledRejection", (reason) => {
5743
+ captureFn(reason, {
5744
+ mechanism: {
5745
+ type: "onunhandledrejection",
5746
+ handled: false
5747
+ }
5748
+ });
5749
+ });
4489
5750
  }
4490
- var init_autocapture = () => {};
5751
+ var UNHANDLED_REJECTION_OPTION_NAMES, UNHANDLED_REJECTION_MODES, STARTUP_EXEC_ARGV, STARTUP_NODE_OPTIONS, STARTUP_UNHANDLED_REJECTION_MODE;
5752
+ var init_autocapture = __esm(() => {
5753
+ UNHANDLED_REJECTION_OPTION_NAMES = [
5754
+ "--unhandled-rejections",
5755
+ "--unhandled_rejections"
5756
+ ];
5757
+ UNHANDLED_REJECTION_MODES = new Set([
5758
+ "throw",
5759
+ "strict",
5760
+ "warn",
5761
+ "warn-with-error-code",
5762
+ "none"
5763
+ ]);
5764
+ STARTUP_EXEC_ARGV = [
5765
+ ...globalThis.process?.execArgv ?? []
5766
+ ];
5767
+ STARTUP_NODE_OPTIONS = globalThis.process?.env?.NODE_OPTIONS;
5768
+ STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
5769
+ });
4491
5770
 
4492
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
4493
- class ErrorTracking {
5771
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
5772
+ class error_tracking_ErrorTracking {
4494
5773
  constructor(client, options, _logger) {
4495
5774
  this.client = client;
4496
5775
  this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
4497
5776
  this._logger = _logger;
4498
5777
  this._rateLimiter = new BucketedRateLimiter({
4499
- refillRate: 1,
4500
- bucketSize: 10,
5778
+ ...resolveExceptionRateLimiterConfig(options),
4501
5779
  refillInterval: 1e4,
4502
5780
  _logger: this._logger
4503
5781
  });
@@ -4506,76 +5784,536 @@ class ErrorTracking {
4506
5784
  static isPreviouslyCapturedError(x) {
4507
5785
  return isObject(x) && "__posthog_previously_captured_error" in x && x.__posthog_previously_captured_error === true;
4508
5786
  }
4509
- static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {
4510
- const properties = {
4511
- ...additionalProperties
4512
- };
4513
- const exceptionProperties = builder.buildFromUnknown(error, hint);
4514
- exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);
4515
- return {
4516
- event: "$exception",
4517
- distinctId,
4518
- properties: {
4519
- ...exceptionProperties,
4520
- ...properties
4521
- },
4522
- _originatedFromCaptureException: true
5787
+ static async buildEventMessage(builder, error, hint, distinctId, additionalProperties) {
5788
+ const properties = {
5789
+ ...additionalProperties
5790
+ };
5791
+ const exceptionProperties = builder.buildFromUnknown(error, hint);
5792
+ exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);
5793
+ const injectedReleaseId = exports_error_tracking.getInjectedReleaseId();
5794
+ if (injectedReleaseId)
5795
+ properties.$release_id = injectedReleaseId;
5796
+ return {
5797
+ event: "$exception",
5798
+ distinctId,
5799
+ properties: {
5800
+ ...exceptionProperties,
5801
+ ...properties
5802
+ },
5803
+ _originatedFromCaptureException: true
5804
+ };
5805
+ }
5806
+ startAutocaptureIfEnabled() {
5807
+ if (this.isEnabled()) {
5808
+ addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
5809
+ addUnhandledRejectionListener(this.onException.bind(this));
5810
+ }
5811
+ }
5812
+ onException(exception, hint) {
5813
+ this.client.addPendingPromise((async () => {
5814
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {
5815
+ const eventMessage = await error_tracking_ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
5816
+ const exceptionProperties = eventMessage.properties;
5817
+ const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
5818
+ const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
5819
+ if (isRateLimited)
5820
+ return void this._logger.info("Skipping exception capture because of client rate limiting.", {
5821
+ exception: exceptionType
5822
+ });
5823
+ return this.client._capturePreparedEvent(eventMessage, false);
5824
+ }
5825
+ })());
5826
+ }
5827
+ async onFatalError(exception) {
5828
+ console.error(exception);
5829
+ await this.client.shutdown(SHUTDOWN_TIMEOUT);
5830
+ globalThis.process.exit(1);
5831
+ }
5832
+ isEnabled() {
5833
+ return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
5834
+ }
5835
+ shutdown() {
5836
+ this._rateLimiter.stop();
5837
+ }
5838
+ }
5839
+ var SHUTDOWN_TIMEOUT = 2000;
5840
+ var init_error_tracking2 = __esm(() => {
5841
+ init_autocapture();
5842
+ init_dist();
5843
+ });
5844
+
5845
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/storage-memory.mjs
5846
+ class PostHogMemoryStorage {
5847
+ getProperty(key) {
5848
+ return this._memoryStorage[key];
5849
+ }
5850
+ setProperty(key, value) {
5851
+ this._memoryStorage[key] = value !== null ? value : undefined;
5852
+ }
5853
+ constructor() {
5854
+ this._memoryStorage = {};
5855
+ }
5856
+ }
5857
+ var init_storage_memory = () => {};
5858
+
5859
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/config.mjs
5860
+ function isCaptureMode(value) {
5861
+ return value === "v0" || value === "v1";
5862
+ }
5863
+ function resolveCaptureMode() {
5864
+ const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
5865
+ return isCaptureMode(envMode) ? envMode : "v0";
5866
+ }
5867
+ var init_config2 = () => {};
5868
+
5869
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/routing.mjs
5870
+ function isLegacyOnlyEvent(message) {
5871
+ return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
5872
+ }
5873
+ var AI_EVENT_PREFIX = "$ai_", ANALYTICS_ROUTE = "analytics", AI_ROUTE = "ai";
5874
+ var init_routing = () => {};
5875
+
5876
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/errors.mjs
5877
+ var CaptureV1Error;
5878
+ var init_errors = __esm(() => {
5879
+ CaptureV1Error = class CaptureV1Error extends Error {
5880
+ constructor({ requestId, drops, retryExhausted, cause }) {
5881
+ super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = "CaptureV1Error";
5882
+ this.requestId = requestId;
5883
+ this.drops = drops;
5884
+ this.retryExhausted = retryExhausted;
5885
+ this.cause = cause;
5886
+ }
5887
+ static buildMessage(requestId, drops, retryExhausted, cause) {
5888
+ let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;
5889
+ if (cause instanceof Error)
5890
+ message += ` (${cause.message})`;
5891
+ return message;
5892
+ }
5893
+ };
5894
+ });
5895
+
5896
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/transform.mjs
5897
+ function coerceBool(value) {
5898
+ if (typeof value == "boolean")
5899
+ return value;
5900
+ if (typeof value == "number")
5901
+ return value !== 0;
5902
+ if (typeof value == "string") {
5903
+ const normalized = value.trim().toLowerCase();
5904
+ if (normalized === "true" || normalized === "1")
5905
+ return true;
5906
+ if (normalized === "false" || normalized === "0")
5907
+ return false;
5908
+ }
5909
+ }
5910
+ function coerceString(value) {
5911
+ return typeof value == "string" ? value : undefined;
5912
+ }
5913
+ function isRecord3(value) {
5914
+ return typeof value == "object" && value !== null && !Array.isArray(value);
5915
+ }
5916
+ function toRfc3339(timestamp) {
5917
+ if (typeof timestamp == "string") {
5918
+ const asDate2 = new Date(timestamp);
5919
+ if (Number.isNaN(asDate2.getTime()))
5920
+ return new Date().toISOString();
5921
+ const normalized = asDate2.toISOString();
5922
+ const fractionalSeconds = timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];
5923
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
5924
+ }
5925
+ if (timestamp instanceof Date)
5926
+ return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();
5927
+ const asDate = timestamp == null ? new Date : new Date(timestamp);
5928
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();
5929
+ }
5930
+ function relocateInto(properties, key, value) {
5931
+ if (value !== undefined && !(key in properties))
5932
+ properties[key] = value;
5933
+ }
5934
+ function buildV1Event(message) {
5935
+ const sourceProperties = isRecord3(message.properties) ? message.properties : {};
5936
+ const properties = {
5937
+ ...sourceProperties
5938
+ };
5939
+ const options = {};
5940
+ for (const { property, optionKey, coerce } of OPTION_SENTINELS)
5941
+ if (property in properties) {
5942
+ const coerced = coerce(properties[property]);
5943
+ if (coerced !== undefined)
5944
+ options[optionKey] = coerced;
5945
+ delete properties[property];
5946
+ }
5947
+ const topLevel = {};
5948
+ for (const { property, field } of TOPLEVEL_SENTINELS)
5949
+ if (property in properties) {
5950
+ const value = properties[property];
5951
+ if (typeof value == "string")
5952
+ topLevel[field] = value;
5953
+ delete properties[property];
5954
+ }
5955
+ delete properties.$lib;
5956
+ delete properties.$lib_version;
5957
+ relocateInto(properties, "$set", message.$set);
5958
+ relocateInto(properties, "$set_once", message.$set_once);
5959
+ return {
5960
+ event: String(message.event ?? ""),
5961
+ uuid: String(message.uuid ?? ""),
5962
+ distinct_id: String(message.distinct_id ?? ""),
5963
+ timestamp: toRfc3339(message.timestamp),
5964
+ ...topLevel,
5965
+ options,
5966
+ properties
5967
+ };
5968
+ }
5969
+ function buildV1Batch(messages, { createdAt, historicalMigration }) {
5970
+ const batch = {
5971
+ created_at: createdAt,
5972
+ batch: messages.map(buildV1Event)
5973
+ };
5974
+ if (historicalMigration)
5975
+ batch.historical_migration = true;
5976
+ return batch;
5977
+ }
5978
+ var OPTION_SENTINELS, TOPLEVEL_SENTINELS;
5979
+ var init_transform = __esm(() => {
5980
+ OPTION_SENTINELS = [
5981
+ {
5982
+ property: "$cookieless_mode",
5983
+ optionKey: "cookieless_mode",
5984
+ coerce: coerceBool
5985
+ },
5986
+ {
5987
+ property: "$ignore_sent_at",
5988
+ optionKey: "disable_skew_correction",
5989
+ coerce: coerceBool
5990
+ },
5991
+ {
5992
+ property: "$process_person_profile",
5993
+ optionKey: "process_person_profile",
5994
+ coerce: coerceBool
5995
+ },
5996
+ {
5997
+ property: "$product_tour_id",
5998
+ optionKey: "product_tour_id",
5999
+ coerce: coerceString
6000
+ }
6001
+ ];
6002
+ TOPLEVEL_SENTINELS = [
6003
+ {
6004
+ property: "$session_id",
6005
+ field: "session_id"
6006
+ },
6007
+ {
6008
+ property: "$window_id",
6009
+ field: "window_id"
6010
+ }
6011
+ ];
6012
+ });
6013
+
6014
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/sender.mjs
6015
+ class V1CaptureSender {
6016
+ constructor(config, hooks) {
6017
+ this.config = config;
6018
+ this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
6019
+ this.fetchFn = hooks.fetch;
6020
+ this.onError = hooks.onError;
6021
+ this.now = hooks.now ?? Date.now;
6022
+ this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve9) => safeSetTimeout(resolve9, ms)));
6023
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7;
6024
+ this.compress = hooks.compress ?? gzipCompress;
6025
+ }
6026
+ async sendV1Batch(messages) {
6027
+ if (messages.length === 0)
6028
+ return;
6029
+ const requestId = this.generateRequestId();
6030
+ const createdAt = new Date(this.now()).toISOString();
6031
+ const { batch } = buildV1Batch(messages, {
6032
+ createdAt,
6033
+ historicalMigration: this.config.historicalMigration
6034
+ });
6035
+ const url = `${this.config.host}${V1_ANALYTICS_PATH}`;
6036
+ const drops = [];
6037
+ let pending = batch;
6038
+ const maxAttempts = Math.max(1, this.config.maxAttempts);
6039
+ for (let attempt = 1;attempt <= maxAttempts; attempt++) {
6040
+ const isLastAttempt = attempt === maxAttempts;
6041
+ const payload = safeJsonStringify({
6042
+ created_at: createdAt,
6043
+ ...this.config.historicalMigration ? {
6044
+ historical_migration: true
6045
+ } : {},
6046
+ batch: pending
6047
+ });
6048
+ let captureAttempt;
6049
+ let retryDelayMs;
6050
+ try {
6051
+ captureAttempt = await this.sendOnce(url, payload, attempt, requestId);
6052
+ const { response, signal } = captureAttempt;
6053
+ const { status } = response;
6054
+ if (status < 200 || status >= 300)
6055
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
6056
+ const retryAfterMs = this.parseRetryAfter(response);
6057
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {});
6058
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
6059
+ } else {
6060
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
6061
+ return this.surfaceBatchFailure(requestId, drops, pending, httpError);
6062
+ }
6063
+ else {
6064
+ let parsed;
6065
+ try {
6066
+ parsed = await captureAttempt.waitFor(this.parseResponse(response));
6067
+ } catch (error) {
6068
+ if (signal.aborted)
6069
+ throw error;
6070
+ return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));
6071
+ }
6072
+ const retryable = this.classify(pending, parsed, drops);
6073
+ if (retryable.length === 0)
6074
+ return this.surfacePartialDrops(requestId, drops);
6075
+ if (isLastAttempt)
6076
+ return void this.onError(new CaptureV1Error({
6077
+ requestId,
6078
+ drops,
6079
+ retryExhausted: retryable.map((event) => event.uuid)
6080
+ }));
6081
+ pending = retryable;
6082
+ const retryAfterMs = this.parseRetryAfter(response);
6083
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
6084
+ }
6085
+ } catch (transportError) {
6086
+ if (captureAttempt && !captureAttempt.signal.aborted)
6087
+ throw transportError;
6088
+ if (isLastAttempt)
6089
+ return this.surfaceBatchFailure(requestId, drops, pending, transportError);
6090
+ retryDelayMs = this.backoffDelay(attempt);
6091
+ } finally {
6092
+ captureAttempt?.cleanup();
6093
+ }
6094
+ if (retryDelayMs !== undefined)
6095
+ await this.sleep(retryDelayMs);
6096
+ }
6097
+ }
6098
+ async sendOnce(url, payload, attempt, requestId) {
6099
+ const headers = this.buildHeaders(attempt, requestId);
6100
+ let body = payload;
6101
+ if (this.config.compressionEnabled) {
6102
+ const compressed = await this.compress(payload, this.config.isDebug);
6103
+ if (compressed !== null) {
6104
+ body = compressed;
6105
+ headers["Content-Encoding"] = "gzip";
6106
+ }
6107
+ }
6108
+ const controller = new AbortController;
6109
+ let timeoutPhase = "waiting for response headers";
6110
+ let timer;
6111
+ const deadline = new Promise((_resolve, reject) => {
6112
+ timer = safeSetTimeout(() => {
6113
+ const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
6114
+ timeoutError.name = "AbortError";
6115
+ reject(timeoutError);
6116
+ controller.abort(timeoutError);
6117
+ }, this.config.requestTimeoutMs);
6118
+ });
6119
+ try {
6120
+ const fetchPromise = this.fetchFn(url, {
6121
+ method: "POST",
6122
+ headers,
6123
+ body,
6124
+ signal: controller.signal
6125
+ });
6126
+ let responseAccepted = false;
6127
+ fetchPromise.then((lateResponse) => {
6128
+ if (controller.signal.aborted && !responseAccepted)
6129
+ this.cancelBody(lateResponse);
6130
+ }).catch(() => {});
6131
+ const response = await Promise.race([
6132
+ fetchPromise,
6133
+ deadline
6134
+ ]);
6135
+ responseAccepted = true;
6136
+ timeoutPhase = "while reading the response body";
6137
+ let cleanedUp = false;
6138
+ let cancellation;
6139
+ const cancelBody = () => cancellation ??= this.cancelBody(response);
6140
+ return {
6141
+ response,
6142
+ signal: controller.signal,
6143
+ waitFor: (operation) => Promise.race([
6144
+ operation,
6145
+ deadline
6146
+ ]),
6147
+ cancelBody,
6148
+ cleanup: () => {
6149
+ if (cleanedUp)
6150
+ return;
6151
+ cleanedUp = true;
6152
+ clearTimeout(timer);
6153
+ if (controller.signal.aborted)
6154
+ cancelBody();
6155
+ }
6156
+ };
6157
+ } catch (error) {
6158
+ clearTimeout(timer);
6159
+ throw error;
6160
+ }
6161
+ }
6162
+ buildHeaders(attempt, requestId) {
6163
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
6164
+ const headers = {
6165
+ "Content-Type": "application/json",
6166
+ Authorization: `Bearer ${this.config.apiKey}`,
6167
+ "PostHog-Sdk-Info": sdkInfo,
6168
+ "PostHog-Attempt": String(attempt),
6169
+ "PostHog-Request-Id": requestId,
6170
+ "PostHog-Request-Timestamp": new Date(this.now()).toISOString()
4523
6171
  };
6172
+ if (this.config.userAgent)
6173
+ headers["User-Agent"] = this.config.userAgent;
6174
+ return headers;
4524
6175
  }
4525
- startAutocaptureIfEnabled() {
4526
- if (this.isEnabled()) {
4527
- addUncaughtExceptionListener(this.onException.bind(this), this.onFatalError.bind(this));
4528
- addUnhandledRejectionListener(this.onException.bind(this));
4529
- }
4530
- }
4531
- onException(exception, hint) {
4532
- this.client.addPendingPromise((async () => {
4533
- if (!ErrorTracking.isPreviouslyCapturedError(exception)) {
4534
- const eventMessage = await ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
4535
- const exceptionProperties = eventMessage.properties;
4536
- const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
4537
- const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
4538
- if (isRateLimited)
4539
- return void this._logger.info("Skipping exception capture because of client rate limiting.", {
4540
- exception: exceptionType
6176
+ classify(pending, parsed, drops) {
6177
+ const results = parsed.results ?? {};
6178
+ const retryable = [];
6179
+ for (const event of pending) {
6180
+ const result = results[event.uuid];
6181
+ if (result) {
6182
+ if (result.result === "drop")
6183
+ drops.push({
6184
+ uuid: event.uuid,
6185
+ details: result.details ?? undefined
4541
6186
  });
4542
- return this.client.capture(eventMessage);
6187
+ else if (result.result === "retry")
6188
+ retryable.push(event);
4543
6189
  }
4544
- })());
6190
+ }
6191
+ return retryable;
4545
6192
  }
4546
- async onFatalError(exception) {
4547
- console.error(exception);
4548
- await this.client.shutdown(SHUTDOWN_TIMEOUT);
4549
- process.exit(1);
6193
+ backoffDelay(attempt, retryAfterMs) {
6194
+ const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);
6195
+ if (retryAfterMs === undefined)
6196
+ return exponential;
6197
+ return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));
4550
6198
  }
4551
- isEnabled() {
4552
- return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
6199
+ parseRetryAfter(response) {
6200
+ const raw = response.headers?.get("Retry-After");
6201
+ if (!raw)
6202
+ return;
6203
+ const trimmed = raw.trim();
6204
+ if (/^\d+$/.test(trimmed)) {
6205
+ const seconds = parseInt(trimmed, 10);
6206
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : undefined;
6207
+ }
6208
+ const dateMs = Date.parse(trimmed);
6209
+ if (Number.isNaN(dateMs))
6210
+ return;
6211
+ const delta = dateMs - this.now();
6212
+ return delta > 0 ? delta : undefined;
6213
+ }
6214
+ async parseResponse(response) {
6215
+ const text = await response.text();
6216
+ const parsed = JSON.parse(text);
6217
+ if (typeof parsed != "object" || parsed === null || Array.isArray(parsed))
6218
+ throw new Error("unexpected response shape");
6219
+ const results = parsed.results;
6220
+ if (results !== undefined && (typeof results != "object" || results === null || Array.isArray(results)))
6221
+ throw new Error("unexpected results shape");
6222
+ return {
6223
+ results: results ?? {}
6224
+ };
4553
6225
  }
4554
- shutdown() {
4555
- this._rateLimiter.stop();
6226
+ async buildHttpError(response, status, waitFor) {
6227
+ let bodyText = "";
6228
+ try {
6229
+ bodyText = (await waitFor(response.text())).slice(0, 512);
6230
+ } catch {}
6231
+ const suffix = bodyText ? `: ${bodyText}` : "";
6232
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
6233
+ }
6234
+ surfaceBatchFailure(requestId, drops, pending, cause) {
6235
+ this.onError(new CaptureV1Error({
6236
+ requestId,
6237
+ drops,
6238
+ retryExhausted: pending.map((event) => event.uuid),
6239
+ cause
6240
+ }));
6241
+ }
6242
+ surfacePartialDrops(requestId, drops) {
6243
+ if (drops.length > 0)
6244
+ this.onError(new CaptureV1Error({
6245
+ requestId,
6246
+ drops,
6247
+ retryExhausted: []
6248
+ }));
6249
+ }
6250
+ async cancelBody(response) {
6251
+ try {
6252
+ await response.body?.cancel();
6253
+ } catch {}
4556
6254
  }
4557
6255
  }
4558
- var SHUTDOWN_TIMEOUT = 2000;
4559
- var init_error_tracking2 = __esm(() => {
4560
- init_autocapture();
6256
+ var V1_ANALYTICS_PATH = "/i/v1/analytics/events", DEFAULT_MAX_BACKOFF_MS = 30000, RETRYABLE_STATUSES;
6257
+ var init_sender = __esm(() => {
4561
6258
  init_dist();
6259
+ init_errors();
6260
+ init_transform();
6261
+ RETRYABLE_STATUSES = new Set([
6262
+ 408,
6263
+ 500,
6264
+ 502,
6265
+ 503,
6266
+ 504
6267
+ ]);
4562
6268
  });
4563
6269
 
4564
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/storage-memory.mjs
4565
- class PostHogMemoryStorage {
4566
- getProperty(key) {
4567
- return this._memoryStorage[key];
4568
- }
4569
- setProperty(key, value) {
4570
- this._memoryStorage[key] = value !== null ? value : undefined;
4571
- }
4572
- constructor() {
4573
- this._memoryStorage = {};
6270
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/routing.mjs
6271
+ var AI_CAPTURE_ROUTE = "ai-capture", AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/", AI_MAX_EVENT_BYTES = 8388608, AI_BATCH_TARGET_BYTES = 5242880;
6272
+ var init_routing2 = () => {};
6273
+
6274
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/batching.mjs
6275
+ function eventByteSize(message) {
6276
+ return encoder.encode(safeJsonStringify(message)).length;
6277
+ }
6278
+ function partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBatchBytes = AI_BATCH_TARGET_BYTES) {
6279
+ const batches = [];
6280
+ const dropped = [];
6281
+ let current = [];
6282
+ let currentBytes = 0;
6283
+ for (const message of messages) {
6284
+ if (message === undefined)
6285
+ continue;
6286
+ const bytes = eventByteSize(message);
6287
+ if (bytes > maxEventBytes) {
6288
+ dropped.push({
6289
+ event: typeof message.event == "string" ? message.event : "unknown",
6290
+ bytes
6291
+ });
6292
+ continue;
6293
+ }
6294
+ if (current.length > 0 && currentBytes + bytes > targetBatchBytes) {
6295
+ batches.push(current);
6296
+ current = [];
6297
+ currentBytes = 0;
6298
+ }
6299
+ current.push(message);
6300
+ currentBytes += bytes;
4574
6301
  }
6302
+ if (current.length > 0)
6303
+ batches.push(current);
6304
+ return {
6305
+ batches,
6306
+ dropped
6307
+ };
4575
6308
  }
4576
- var init_storage_memory = () => {};
6309
+ var encoder;
6310
+ var init_batching = __esm(() => {
6311
+ init_dist();
6312
+ init_routing2();
6313
+ encoder = new TextEncoder;
6314
+ });
4577
6315
 
4578
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/client.mjs
6316
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/client.mjs
4579
6317
  function emitDeprecationWarningOnce(id, message) {
4580
6318
  if (_emittedDeprecations.has(id))
4581
6319
  return;
@@ -4593,6 +6331,12 @@ function normalizeHost(value) {
4593
6331
  const normalizedValue = typeof value == "string" ? value.trim() : "";
4594
6332
  return normalizedValue || DEFAULT_NODE_HOST;
4595
6333
  }
6334
+ function normalizeUnsetPersonProperties(value) {
6335
+ const propertyNames = Array.isArray(value) ? value : [
6336
+ value
6337
+ ];
6338
+ return propertyNames.filter((propertyName) => typeof propertyName == "string" && propertyName.trim().length > 0);
6339
+ }
4596
6340
  function buildFlagEventProperties(flagValues) {
4597
6341
  if (!flagValues)
4598
6342
  return {};
@@ -4613,17 +6357,26 @@ var init_client = __esm(() => {
4613
6357
  init_feature_flags();
4614
6358
  init_error_tracking2();
4615
6359
  init_storage_memory();
6360
+ init_config2();
6361
+ init_routing();
6362
+ init_sender();
6363
+ init_batching();
6364
+ init_routing2();
4616
6365
  _emittedDeprecations = new Set;
4617
6366
  PostHogBackendClient = class PostHogBackendClient extends PostHogCoreStateless {
4618
6367
  constructor(apiKey, options = {}) {
4619
6368
  const normalizedApiKey = normalizeApiKey(apiKey);
4620
6369
  const normalizedOptions = {
4621
6370
  ...options,
6371
+ maxQueueSize: options.maxQueueSize ?? 1e4,
6372
+ flushInterval: options.flushInterval ?? 5000,
4622
6373
  host: normalizeHost(options.host),
4623
- personalApiKey: normalizePersonalApiKey(options.personalApiKey)
6374
+ personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
4624
6375
  };
4625
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage;
6376
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false;
4626
6377
  this.options = normalizedOptions;
6378
+ this.captureMode = resolveCaptureMode();
6379
+ this.enableFullAiCapture = normalizedOptions.enableFullAiCapture === true;
4627
6380
  this.context = this.initializeContext();
4628
6381
  this.options.featureFlagsPollingInterval = typeof normalizedOptions.featureFlagsPollingInterval == "number" ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
4629
6382
  if (typeof normalizedOptions.waitUntilDebounceMs == "number")
@@ -4648,21 +6401,24 @@ var init_client = __esm(() => {
4648
6401
  onLoad: (count) => {
4649
6402
  this._events.emit("localEvaluationFlagsLoaded", count);
4650
6403
  },
6404
+ onMinimalFlagCalledEvents: (enabled) => {
6405
+ this._minimalFlagCalledEvents = enabled;
6406
+ },
4651
6407
  customHeaders: this.getCustomHeaders(),
4652
6408
  cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
4653
6409
  strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
4654
6410
  });
4655
6411
  }
4656
- this.errorTracking = new ErrorTracking(this, normalizedOptions, this._logger);
6412
+ this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
4657
6413
  this.distinctIdHasSentFlagCalls = {};
4658
6414
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
4659
6415
  }
4660
- enqueue(type, message, options) {
4661
- super.enqueue(type, message, options);
6416
+ enqueue(type, message, options, explicitRoute) {
6417
+ super.enqueue(type, message, options, explicitRoute);
4662
6418
  this.scheduleDebouncedFlush();
4663
6419
  }
4664
6420
  async flush() {
4665
- const flushPromise = super.flush();
6421
+ const flushPromise = this.flushWithPendingPromises();
4666
6422
  const waitUntil = this.options.waitUntil;
4667
6423
  if (waitUntil && !this._waitUntilCycle)
4668
6424
  try {
@@ -4715,7 +6471,7 @@ var init_client = __esm(() => {
4715
6471
  async resolveWaitUntilFlush() {
4716
6472
  const resolve9 = this._consumeWaitUntilCycle();
4717
6473
  try {
4718
- await super.flush();
6474
+ await this.flushWithPendingPromises();
4719
6475
  } catch {} finally {
4720
6476
  resolve9?.();
4721
6477
  }
@@ -4729,12 +6485,103 @@ var init_client = __esm(() => {
4729
6485
  fetch(url, options) {
4730
6486
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
4731
6487
  }
6488
+ getQueueRouteKey(message) {
6489
+ return this.captureMode === "v1" && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;
6490
+ }
6491
+ persistedQueueKeyForRoute(route) {
6492
+ if (route === AI_CAPTURE_ROUTE)
6493
+ return types_PostHogPersistedProperty.AiCaptureQueue;
6494
+ return route === AI_ROUTE ? types_PostHogPersistedProperty.AiQueue : types_PostHogPersistedProperty.Queue;
6495
+ }
6496
+ getActiveQueueRoutes() {
6497
+ const routes = this.captureMode === "v1" ? [
6498
+ ANALYTICS_ROUTE,
6499
+ AI_ROUTE
6500
+ ] : [
6501
+ ANALYTICS_ROUTE
6502
+ ];
6503
+ if (this._aiCaptureRouteActive)
6504
+ routes.push(AI_CAPTURE_ROUTE);
6505
+ return routes;
6506
+ }
6507
+ getBatchEndpointPath(route) {
6508
+ return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
6509
+ }
6510
+ async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {
6511
+ if (route === AI_CAPTURE_ROUTE)
6512
+ return this.sendAiCaptureBatch(batchMessages, retryOptions);
6513
+ if (this.captureMode !== "v1" || route === AI_ROUTE)
6514
+ return super.sendBatch(batchMessages, retryOptions, route);
6515
+ const v1Events = batchMessages.filter((message) => message !== undefined);
6516
+ await this.getV1Sender().sendV1Batch(v1Events);
6517
+ }
6518
+ async sendAiCaptureBatch(batchMessages, retryOptions) {
6519
+ const { batches, dropped } = partitionAiBatch(batchMessages);
6520
+ for (const { event, bytes } of dropped) {
6521
+ const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
6522
+ this._logger.error(message);
6523
+ this._events.emit("error", new Error(message));
6524
+ }
6525
+ for (const batch of batches)
6526
+ await this.sendAiSubBatch(batch, retryOptions);
6527
+ }
6528
+ async sendAiSubBatch(batch, retryOptions) {
6529
+ try {
6530
+ await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);
6531
+ } catch (err) {
6532
+ if (!isPostHogFetchContentTooLargeError(err))
6533
+ throw err;
6534
+ if (batch.length === 1) {
6535
+ const [event] = batch;
6536
+ const eventName = typeof event.event == "string" ? event.event : "unknown";
6537
+ const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
6538
+ this._logger.error(message);
6539
+ this._events.emit("error", new Error(message));
6540
+ return;
6541
+ }
6542
+ const mid = Math.ceil(batch.length / 2);
6543
+ await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
6544
+ await this.sendAiSubBatch(batch.slice(mid), retryOptions);
6545
+ }
6546
+ }
6547
+ getV1Sender() {
6548
+ if (!this._v1Sender)
6549
+ this._v1Sender = new V1CaptureSender({
6550
+ host: this.host,
6551
+ apiKey: this.apiKey,
6552
+ libraryId: this.getLibraryId(),
6553
+ libraryVersion: this.getLibraryVersion(),
6554
+ userAgent: this.getCustomUserAgent() || undefined,
6555
+ historicalMigration: this.historicalMigration,
6556
+ compressionEnabled: !this.disableCompression,
6557
+ requestTimeoutMs: this.requestTimeout,
6558
+ maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
6559
+ initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
6560
+ isDebug: this.isDebug
6561
+ }, {
6562
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
6563
+ onError: (error) => this._events.emit("error", error),
6564
+ compress: (payload) => this.compressPayload(payload)
6565
+ });
6566
+ return this._v1Sender;
6567
+ }
4732
6568
  getLibraryVersion() {
4733
6569
  return version;
4734
6570
  }
6571
+ get metrics() {
6572
+ if (!this._metrics)
6573
+ this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
6574
+ return this._metrics;
6575
+ }
4735
6576
  getCustomUserAgent() {
4736
6577
  return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
4737
6578
  }
6579
+ getCommonEventProperties() {
6580
+ const commonProperties = super.getCommonEventProperties();
6581
+ if (this.options.isServer ?? true)
6582
+ commonProperties.$is_server = true;
6583
+ return commonProperties;
6584
+ }
4738
6585
  enable() {
4739
6586
  return super.optIn();
4740
6587
  }
@@ -4745,33 +6592,69 @@ var init_client = __esm(() => {
4745
6592
  super.debug(enabled);
4746
6593
  this.featureFlagsPoller?.debug(enabled);
4747
6594
  }
4748
- capture(props) {
6595
+ _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
4749
6596
  if (typeof props == "string")
4750
- this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
6597
+ this._logger.warn(stringArgumentWarning);
4751
6598
  if (props.event === "$exception" && !props._originatedFromCaptureException)
4752
- 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.");
4753
- this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
4754
- timestamp: options.timestamp,
4755
- disableGeoip: options.disableGeoip,
4756
- uuid: options.uuid
4757
- })).catch((err) => {
6599
+ this._logger.warn(exceptionCaptureWarning);
6600
+ }
6601
+ _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
6602
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options }) => {
6603
+ const captureOptions = {
6604
+ timestamp: options.timestamp,
6605
+ disableGeoip: options.disableGeoip,
6606
+ uuid: options.uuid
6607
+ };
6608
+ const message = {
6609
+ distinctId,
6610
+ event,
6611
+ properties: {
6612
+ ...properties,
6613
+ ...this.getCommonEventProperties()
6614
+ }
6615
+ };
6616
+ return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
6617
+ }).catch((err) => {
4758
6618
  if (err)
4759
6619
  console.error(err);
4760
6620
  }));
4761
6621
  }
6622
+ _capturePreparedEvent(props, immediate) {
6623
+ return this._sendPreparedEvent("capture", props, immediate);
6624
+ }
6625
+ capture(props) {
6626
+ this._warnIfInvalidCapture(props, "Called capture() with a string as the first argument when an object was expected.", "Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.");
6627
+ this._capturePreparedEvent(props, false);
6628
+ }
4762
6629
  async captureImmediate(props) {
4763
- if (typeof props == "string")
4764
- this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
4765
- if (props.event === "$exception" && !props._originatedFromCaptureException)
4766
- 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.");
4767
- return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
4768
- timestamp: options.timestamp,
4769
- disableGeoip: options.disableGeoip,
4770
- uuid: options.uuid
4771
- })).catch((err) => {
4772
- if (err)
4773
- console.error(err);
4774
- }));
6630
+ this._warnIfInvalidCapture(props, "Called captureImmediate() with a string as the first argument when an object was expected.", "Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.");
6631
+ return this._capturePreparedEvent(props, true);
6632
+ }
6633
+ captureAi(props) {
6634
+ if (this.disabled)
6635
+ return;
6636
+ const uuid = getEventUuid(props.uuid, uuidv7);
6637
+ this._sendPreparedAiEvent({
6638
+ ...props,
6639
+ uuid
6640
+ }, false);
6641
+ return uuid;
6642
+ }
6643
+ async captureAiImmediate(props) {
6644
+ if (this.disabled)
6645
+ return;
6646
+ const uuid = getEventUuid(props.uuid, uuidv7);
6647
+ await this._sendPreparedAiEvent({
6648
+ ...props,
6649
+ uuid
6650
+ }, true);
6651
+ return uuid;
6652
+ }
6653
+ _sendPreparedAiEvent(props, immediate) {
6654
+ if (typeof props?.event == "string" && !props.event.startsWith("$ai_"))
6655
+ this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);
6656
+ this._aiCaptureRouteActive = true;
6657
+ return this._sendPreparedEvent("capture", props, immediate, undefined, AI_CAPTURE_ROUTE);
4775
6658
  }
4776
6659
  identify({ distinctId, properties = {}, disableGeoip }) {
4777
6660
  const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
@@ -4782,8 +6665,13 @@ var init_client = __esm(() => {
4782
6665
  $set_once: setOnceProps,
4783
6666
  $anon_distinct_id: $anon_distinct_id ?? undefined
4784
6667
  };
4785
- super.identifyStateless(distinctId, eventProperties, {
6668
+ this._sendPreparedEvent("identify", {
6669
+ distinctId,
6670
+ event: "$identify",
6671
+ properties: eventProperties,
4786
6672
  disableGeoip
6673
+ }, false, {
6674
+ includeContextProperties: false
4787
6675
  });
4788
6676
  }
4789
6677
  async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
@@ -4795,18 +6683,65 @@ var init_client = __esm(() => {
4795
6683
  $set_once: setOnceProps,
4796
6684
  $anon_distinct_id: $anon_distinct_id ?? undefined
4797
6685
  };
4798
- await super.identifyStatelessImmediate(distinctId, eventProperties, {
6686
+ await this._sendPreparedEvent("identify", {
6687
+ distinctId,
6688
+ event: "$identify",
6689
+ properties: eventProperties,
4799
6690
  disableGeoip
6691
+ }, true, {
6692
+ includeContextProperties: false
6693
+ });
6694
+ }
6695
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
6696
+ if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0)
6697
+ return;
6698
+ const eventProperties = {};
6699
+ if (Object.keys(properties).length > 0)
6700
+ eventProperties.$set = properties;
6701
+ if (Object.keys(propertiesOnce).length > 0)
6702
+ eventProperties.$set_once = propertiesOnce;
6703
+ this.capture({
6704
+ distinctId,
6705
+ event: "$set",
6706
+ properties: eventProperties
6707
+ });
6708
+ }
6709
+ unsetPersonProperties({ distinctId, properties }) {
6710
+ const propertyNames = normalizeUnsetPersonProperties(properties);
6711
+ if (propertyNames.length === 0)
6712
+ return;
6713
+ this.capture({
6714
+ distinctId,
6715
+ event: "$set",
6716
+ properties: {
6717
+ $unset: propertyNames
6718
+ }
4800
6719
  });
4801
6720
  }
4802
6721
  alias(data) {
4803
- super.aliasStateless(data.alias, data.distinctId, undefined, {
6722
+ this._sendPreparedEvent("alias", {
6723
+ distinctId: data.distinctId,
6724
+ event: "$create_alias",
6725
+ properties: {
6726
+ distinct_id: data.distinctId,
6727
+ alias: data.alias
6728
+ },
4804
6729
  disableGeoip: data.disableGeoip
6730
+ }, false, {
6731
+ includeContextProperties: false
4805
6732
  });
4806
6733
  }
4807
6734
  async aliasImmediate(data) {
4808
- await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
6735
+ await this._sendPreparedEvent("alias", {
6736
+ distinctId: data.distinctId,
6737
+ event: "$create_alias",
6738
+ properties: {
6739
+ distinct_id: data.distinctId,
6740
+ alias: data.alias
6741
+ },
4809
6742
  disableGeoip: data.disableGeoip
6743
+ }, true, {
6744
+ includeContextProperties: false
4810
6745
  });
4811
6746
  }
4812
6747
  isLocalEvaluationReady() {
@@ -4861,7 +6796,7 @@ var init_client = __esm(() => {
4861
6796
  const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
4862
6797
  personProperties = adjustedProperties.allPersonProperties;
4863
6798
  groupProperties = adjustedProperties.allGroupProperties;
4864
- const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties);
6799
+ const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);
4865
6800
  if (onlyEvaluateLocally == undefined)
4866
6801
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
4867
6802
  let result;
@@ -4872,6 +6807,7 @@ var init_client = __esm(() => {
4872
6807
  let flagId;
4873
6808
  let flagVersion;
4874
6809
  let flagReason;
6810
+ let flagHasExperiment;
4875
6811
  const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
4876
6812
  if (localEvaluationEnabled) {
4877
6813
  await this.featureFlagsPoller?.loadFeatureFlags();
@@ -4886,6 +6822,7 @@ var init_client = __esm(() => {
4886
6822
  const value = localResult.value;
4887
6823
  flagId = flag.id;
4888
6824
  flagReason = "Evaluated locally";
6825
+ flagHasExperiment = flag.has_experiment;
4889
6826
  result = {
4890
6827
  key,
4891
6828
  enabled: value !== false,
@@ -4901,12 +6838,13 @@ var init_client = __esm(() => {
4901
6838
  }
4902
6839
  }
4903
6840
  if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
4904
- const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, [
6841
+ const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [
4905
6842
  key
4906
6843
  ]);
4907
6844
  if (flagsResponse === undefined)
4908
6845
  featureFlagError = FeatureFlagError2.UNKNOWN_ERROR;
4909
6846
  else {
6847
+ this._minimalFlagCalledEvents = flagsResponse.minimalFlagCalledEvents === true;
4910
6848
  requestId = flagsResponse.requestId;
4911
6849
  evaluatedAt = flagsResponse.evaluatedAt;
4912
6850
  const errors = [];
@@ -4921,6 +6859,7 @@ var init_client = __esm(() => {
4921
6859
  flagId = flagDetail.metadata?.id;
4922
6860
  flagVersion = flagDetail.metadata?.version;
4923
6861
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
6862
+ flagHasExperiment = flagDetail.metadata?.has_experiment;
4924
6863
  let parsedPayload;
4925
6864
  if (flagDetail.metadata?.payload !== undefined)
4926
6865
  try {
@@ -4931,7 +6870,7 @@ var init_client = __esm(() => {
4931
6870
  result = {
4932
6871
  key,
4933
6872
  enabled: flagDetail.enabled,
4934
- variant: flagDetail.variant,
6873
+ variant: flagDetail.variant ?? undefined,
4935
6874
  payload: parsedPayload
4936
6875
  };
4937
6876
  }
@@ -4952,6 +6891,8 @@ var init_client = __esm(() => {
4952
6891
  $feature_flag_request_id: requestId,
4953
6892
  $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt
4954
6893
  };
6894
+ if (flagHasExperiment !== undefined)
6895
+ properties.$feature_flag_has_experiment = flagHasExperiment;
4955
6896
  if (flagWasLocallyEvaluated && this.featureFlagsPoller) {
4956
6897
  const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();
4957
6898
  if (flagDefinitionsLoadedAt !== undefined)
@@ -5066,7 +7007,7 @@ var init_client = __esm(() => {
5066
7007
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
5067
7008
  personProperties = adjustedProperties.allPersonProperties;
5068
7009
  groupProperties = adjustedProperties.allGroupProperties;
5069
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
7010
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
5070
7011
  if (onlyEvaluateLocally == undefined)
5071
7012
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
5072
7013
  const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);
@@ -5079,7 +7020,7 @@ var init_client = __esm(() => {
5079
7020
  fallbackToFlags = localEvaluationResult.fallbackToFlags;
5080
7021
  }
5081
7022
  if (fallbackToFlags && !onlyEvaluateLocally) {
5082
- const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
7023
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
5083
7024
  featureFlags = {
5084
7025
  ...featureFlags,
5085
7026
  ...remoteEvaluationResult.flags || {}
@@ -5127,9 +7068,10 @@ var init_client = __esm(() => {
5127
7068
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
5128
7069
  personProperties = adjustedProperties.allPersonProperties;
5129
7070
  groupProperties = adjustedProperties.allGroupProperties;
5130
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
7071
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
5131
7072
  if (onlyEvaluateLocally == undefined)
5132
7073
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
7074
+ const requestedFlagKeys = flagKeys ? new Set(flagKeys) : undefined;
5133
7075
  const records = {};
5134
7076
  let requestId;
5135
7077
  let evaluatedAt;
@@ -5148,14 +7090,17 @@ var init_client = __esm(() => {
5148
7090
  id: flagDef?.id,
5149
7091
  version: undefined,
5150
7092
  reason: "Evaluated locally",
5151
- locallyEvaluated: true
7093
+ locallyEvaluated: true,
7094
+ hasExperiment: flagDef?.has_experiment
5152
7095
  };
5153
7096
  locallyEvaluatedKeys.add(key);
5154
7097
  }
5155
- const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;
7098
+ const requestedFlagMissingLocally = requestedFlagKeys !== undefined && Array.from(requestedFlagKeys).some((key) => this.featureFlagsPoller?.featureFlagsByKey[key] === undefined);
7099
+ const fallbackToFlags = localResult ? localResult.fallbackToFlags || requestedFlagMissingLocally : true;
5156
7100
  if (fallbackToFlags && !onlyEvaluateLocally) {
5157
- const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
7101
+ const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
5158
7102
  if (details) {
7103
+ this._minimalFlagCalledEvents = details.minimalFlagCalledEvents === true;
5159
7104
  requestId = details.requestId;
5160
7105
  evaluatedAt = details.evaluatedAt;
5161
7106
  errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);
@@ -5178,7 +7123,8 @@ var init_client = __esm(() => {
5178
7123
  id: detail.metadata?.id,
5179
7124
  version: detail.metadata?.version,
5180
7125
  reason: detail.reason?.description ?? detail.reason?.code,
5181
- locallyEvaluated: false
7126
+ locallyEvaluated: false,
7127
+ hasExperiment: detail.metadata?.has_experiment
5182
7128
  };
5183
7129
  }
5184
7130
  }
@@ -5198,7 +7144,8 @@ var init_client = __esm(() => {
5198
7144
  id: existing?.id,
5199
7145
  version: existing?.version,
5200
7146
  reason: existing?.reason,
5201
- locallyEvaluated: existing?.locallyEvaluated ?? false
7147
+ locallyEvaluated: existing?.locallyEvaluated ?? false,
7148
+ hasExperiment: existing?.hasExperiment
5202
7149
  };
5203
7150
  }
5204
7151
  if (this._payloadOverrides !== undefined)
@@ -5210,6 +7157,11 @@ var init_client = __esm(() => {
5210
7157
  payload
5211
7158
  };
5212
7159
  }
7160
+ if (requestedFlagKeys !== undefined) {
7161
+ for (const key of Object.keys(records))
7162
+ if (!requestedFlagKeys.has(key))
7163
+ delete records[key];
7164
+ }
5213
7165
  return new FeatureFlagEvaluations({
5214
7166
  host: this._getFeatureFlagEvaluationsHost(),
5215
7167
  distinctId: resolvedDistinctId,
@@ -5223,6 +7175,9 @@ var init_client = __esm(() => {
5223
7175
  quotaLimited
5224
7176
  });
5225
7177
  }
7178
+ _shouldSendMinimalFlagCalledEvent(event, properties) {
7179
+ return event === "$feature_flag_called" && this._minimalFlagCalledEvents && properties.$feature_flag_has_experiment === false;
7180
+ }
5226
7181
  _captureFlagCalledEventIfNeeded(params) {
5227
7182
  const { distinctId, key, response, groups, disableGeoip, properties } = params;
5228
7183
  const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))}` : "";
@@ -5257,9 +7212,32 @@ var init_client = __esm(() => {
5257
7212
  return this._featureFlagEvaluationsHost;
5258
7213
  }
5259
7214
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
5260
- super.groupIdentifyStateless(groupType, groupKey, properties, {
7215
+ this._sendPreparedEvent("capture", {
7216
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
7217
+ event: "$groupidentify",
7218
+ properties: {
7219
+ $group_type: groupType,
7220
+ $group_key: groupKey,
7221
+ $group_set: properties || {}
7222
+ },
7223
+ disableGeoip
7224
+ }, false, {
7225
+ includeContextProperties: false
7226
+ });
7227
+ }
7228
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
7229
+ await this._sendPreparedEvent("capture", {
7230
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
7231
+ event: "$groupidentify",
7232
+ properties: {
7233
+ $group_type: groupType,
7234
+ $group_key: groupKey,
7235
+ $group_set: properties || {}
7236
+ },
5261
7237
  disableGeoip
5262
- }, distinctId);
7238
+ }, true, {
7239
+ includeContextProperties: false
7240
+ });
5263
7241
  }
5264
7242
  async reloadFeatureFlags() {
5265
7243
  await this.featureFlagsPoller?.loadFeatureFlags(true);
@@ -5331,12 +7309,18 @@ var init_client = __esm(() => {
5331
7309
  this.context?.enter(data, options);
5332
7310
  }
5333
7311
  async _shutdown(shutdownTimeoutMs) {
7312
+ const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
5334
7313
  const resolve9 = this._consumeWaitUntilCycle();
5335
7314
  await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
5336
7315
  this.errorTracking.shutdown();
7316
+ if (this._metrics) {
7317
+ await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
7318
+ this._metrics.reset();
7319
+ }
5337
7320
  try {
5338
- return await super._shutdown(shutdownTimeoutMs);
7321
+ return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
5339
7322
  } finally {
7323
+ this.distinctIdHasSentFlagCalls = {};
5340
7324
  resolve9?.();
5341
7325
  }
5342
7326
  }
@@ -5431,7 +7415,6 @@ var init_client = __esm(() => {
5431
7415
  }
5432
7416
  addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
5433
7417
  const allPersonProperties = {
5434
- distinct_id: distinctId,
5435
7418
  ...personProperties || {}
5436
7419
  };
5437
7420
  const allGroupProperties = {};
@@ -5446,6 +7429,12 @@ var init_client = __esm(() => {
5446
7429
  allGroupProperties
5447
7430
  };
5448
7431
  }
7432
+ personPropertiesForLocalEvaluation(distinctId, personProperties) {
7433
+ return {
7434
+ distinct_id: distinctId,
7435
+ ...personProperties || {}
7436
+ };
7437
+ }
5449
7438
  createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {
5450
7439
  return {
5451
7440
  distinctId,
@@ -5456,21 +7445,21 @@ var init_client = __esm(() => {
5456
7445
  };
5457
7446
  }
5458
7447
  captureException(error, distinctId, additionalProperties, uuid, flags) {
5459
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
7448
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5460
7449
  const syntheticException = new Error("PostHog syntheticException");
5461
- this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
7450
+ this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5462
7451
  syntheticException
5463
- }, distinctId, additionalProperties).then((msg) => this.capture({
7452
+ }, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
5464
7453
  ...msg,
5465
7454
  uuid,
5466
7455
  flags
5467
- })));
7456
+ }, false)));
5468
7457
  }
5469
7458
  }
5470
7459
  async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
5471
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
7460
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5472
7461
  const syntheticException = new Error("PostHog syntheticException");
5473
- return this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
7462
+ return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5474
7463
  syntheticException
5475
7464
  }, distinctId, additionalProperties).then((msg) => this.captureImmediate({
5476
7465
  ...msg,
@@ -5479,24 +7468,31 @@ var init_client = __esm(() => {
5479
7468
  }
5480
7469
  }
5481
7470
  async prepareEventMessage(props) {
7471
+ return this._prepareEventMessage(props);
7472
+ }
7473
+ async _prepareEventMessage(props, options = {}) {
5482
7474
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
5483
7475
  const contextData = this.context?.get();
7476
+ const includeContextProperties = options.includeContextProperties ?? true;
5484
7477
  let mergedDistinctId = distinctId || contextData?.distinctId;
5485
- const mergedProperties = {
7478
+ const mergedProperties = includeContextProperties ? {
5486
7479
  ...this.props,
5487
7480
  ...contextData?.properties || {},
5488
7481
  ...properties || {}
7482
+ } : {
7483
+ ...properties || {}
5489
7484
  };
5490
7485
  if (!mergedDistinctId) {
5491
7486
  mergedDistinctId = uuidv7();
5492
7487
  mergedProperties.$process_person_profile = false;
5493
7488
  }
5494
- if (contextData?.sessionId && !mergedProperties.$session_id)
7489
+ if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id)
5495
7490
  mergedProperties.$session_id = contextData.sessionId;
7491
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;
5496
7492
  const eventMessage = this._runBeforeSend({
5497
7493
  distinctId: mergedDistinctId,
5498
7494
  event,
5499
- properties: mergedProperties,
7495
+ properties: finalProperties,
5500
7496
  groups,
5501
7497
  flags,
5502
7498
  sendFeatureFlags,
@@ -5520,12 +7516,14 @@ var init_client = __esm(() => {
5520
7516
  }
5521
7517
  return {};
5522
7518
  }).catch(() => ({})).then((additionalProperties) => {
5523
- const props2 = {
7519
+ const resolvedGroups = eventMessage.groups || groups;
7520
+ return {
5524
7521
  ...additionalProperties,
5525
7522
  ...eventMessage.properties || {},
5526
- $groups: eventMessage.groups || groups
7523
+ ...resolvedGroups !== undefined && Object.keys(resolvedGroups).length > 0 ? {
7524
+ $groups: resolvedGroups
7525
+ } : {}
5527
7526
  };
5528
- return props2;
5529
7527
  });
5530
7528
  if (eventMessage.event === "$pageview" && this.options.__preview_capture_bot_pageviews && typeof eventProperties.$raw_user_agent == "string") {
5531
7529
  if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
@@ -5552,23 +7550,27 @@ var init_client = __esm(() => {
5552
7550
  beforeSend
5553
7551
  ];
5554
7552
  let result = eventMessage;
5555
- for (const fn of fns) {
5556
- result = fn(result);
5557
- if (!result) {
5558
- this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7553
+ for (const fn of fns)
7554
+ try {
7555
+ result = fn(result);
7556
+ if (!result) {
7557
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7558
+ return null;
7559
+ }
7560
+ if (!result.properties || Object.keys(result.properties).length === 0) {
7561
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
7562
+ this._logger.warn(message);
7563
+ }
7564
+ } catch (error) {
7565
+ this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
5559
7566
  return null;
5560
7567
  }
5561
- if (!result.properties || Object.keys(result.properties).length === 0) {
5562
- const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
5563
- this._logger.warn(message);
5564
- }
5565
- }
5566
7568
  return result;
5567
7569
  }
5568
7570
  };
5569
7571
  });
5570
7572
 
5571
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/context/context.mjs
7573
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/context/context.mjs
5572
7574
  import { AsyncLocalStorage } from "node:async_hooks";
5573
7575
 
5574
7576
  class PostHogContext {
@@ -5600,7 +7602,25 @@ class PostHogContext {
5600
7602
  }
5601
7603
  var init_context = () => {};
5602
7604
 
5603
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
7605
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/gzip.node.mjs
7606
+ import { gzip } from "node:zlib";
7607
+ import { promisify } from "node:util";
7608
+ async function gzipCompress2(input, isDebug = true) {
7609
+ try {
7610
+ const compressed = await gzipAsync(input);
7611
+ return new Uint8Array(compressed);
7612
+ } catch (error) {
7613
+ if (isDebug)
7614
+ console.error("Failed to gzip compress data", error);
7615
+ return null;
7616
+ }
7617
+ }
7618
+ var gzipAsync;
7619
+ var init_gzip_node = __esm(() => {
7620
+ gzipAsync = promisify(gzip);
7621
+ });
7622
+
7623
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
5604
7624
  function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
5605
7625
  "error"
5606
7626
  ], sendExceptionsToPostHog = true } = {}) {
@@ -5639,6 +7659,9 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
5639
7659
  $sentry_exception_type: exceptions[0]?.type,
5640
7660
  $sentry_tags: event.tags
5641
7661
  };
7662
+ const injectedReleaseId = exports_error_tracking.getInjectedReleaseId();
7663
+ if (injectedReleaseId)
7664
+ properties.$release_id = injectedReleaseId;
5642
7665
  if (organization && projectId)
5643
7666
  properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
5644
7667
  if (sendExceptionsToPostHog)
@@ -5652,6 +7675,7 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
5652
7675
  }
5653
7676
  var NAME = "posthog-node", PostHogSentryIntegration;
5654
7677
  var init_sentry_integration = __esm(() => {
7678
+ init_dist();
5655
7679
  PostHogSentryIntegration = class PostHogSentryIntegration {
5656
7680
  static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
5657
7681
  constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
@@ -5671,16 +7695,22 @@ var init_sentry_integration = __esm(() => {
5671
7695
  };
5672
7696
  });
5673
7697
 
5674
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
7698
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/tracing-headers.mjs
5675
7699
  var init_tracing_headers2 = () => {};
5676
7700
 
5677
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/express.mjs
7701
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/url-utils.mjs
7702
+ var init_url_utils = __esm(() => {
7703
+ init_dist();
7704
+ });
7705
+
7706
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/express.mjs
5678
7707
  var init_express = __esm(() => {
5679
7708
  init_error_tracking2();
5680
7709
  init_tracing_headers2();
7710
+ init_url_utils();
5681
7711
  });
5682
7712
 
5683
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/exports.mjs
7713
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/exports.mjs
5684
7714
  var init_exports = __esm(() => {
5685
7715
  init_feature_flag_evaluations();
5686
7716
  init_dist();
@@ -5689,7 +7719,7 @@ var init_exports = __esm(() => {
5689
7719
  init_types3();
5690
7720
  });
5691
7721
 
5692
- // node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/entrypoints/index.node.mjs
7722
+ // node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/entrypoints/index.node.mjs
5693
7723
  var PostHog;
5694
7724
  var init_index_node = __esm(() => {
5695
7725
  init_module_node();
@@ -5698,11 +7728,15 @@ var init_index_node = __esm(() => {
5698
7728
  init_client();
5699
7729
  init_dist();
5700
7730
  init_context();
7731
+ init_gzip_node();
5701
7732
  init_exports();
5702
7733
  PostHog = class PostHog extends PostHogBackendClient {
5703
7734
  getLibraryId() {
5704
7735
  return "posthog-node";
5705
7736
  }
7737
+ compressPayload(payload) {
7738
+ return gzipCompress2(payload, this.isDebug);
7739
+ }
5706
7740
  initializeContext() {
5707
7741
  return new PostHogContext;
5708
7742
  }
@@ -5715,13 +7749,24 @@ var init_index_node = __esm(() => {
5715
7749
  new exports_error_tracking.PrimitiveCoercer
5716
7750
  ], exports_error_tracking.createStackParser("node:javascript", exports_error_tracking.nodeStackLineParser), [
5717
7751
  createModulerModifier(),
5718
- addSourceContext,
7752
+ (frames) => addSourceContext(frames, undefined, this._logger),
5719
7753
  createRelativePathModifier()
5720
7754
  ]);
5721
7755
  }
5722
7756
  };
5723
7757
  });
5724
7758
 
7759
+ // packages/telemetry-core/src/machine-id.ts
7760
+ import { createHash as createHash3 } from "node:crypto";
7761
+ import os2 from "node:os";
7762
+ function getDefaultTelemetryOsProvider() {
7763
+ return os2;
7764
+ }
7765
+ function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
7766
+ return createHash3("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
7767
+ }
7768
+ var init_machine_id = () => {};
7769
+
5725
7770
  // packages/telemetry-core/src/posthog-client.ts
5726
7771
  class PostHogTelemetryTransport {
5727
7772
  #client;
@@ -5743,7 +7788,7 @@ function createDefaultPostHogTransport(apiKey, options) {
5743
7788
  }
5744
7789
  function isTelemetryClientEnabled(input) {
5745
7790
  const env = input.env ?? process.env;
5746
- return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && getTelemetryApiKey(env, input.product.defaultApiKey).length > 0;
7791
+ return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && hasTelemetryApiKey(env, input.product.defaultApiKey);
5747
7792
  }
5748
7793
  function createTelemetryClient(input) {
5749
7794
  if (!isTelemetryClientEnabled(input)) {
@@ -5809,7 +7854,8 @@ function createTransport(input) {
5809
7854
  flushAt: 1,
5810
7855
  flushInterval: 0,
5811
7856
  host: getTelemetryHost(env, input.product.defaultHost),
5812
- disableGeoip: false
7857
+ disableGeoip: input.product.disableGeoip ?? false,
7858
+ ...input.product.transportOptions
5813
7859
  });
5814
7860
  } catch (error) {
5815
7861
  input.diagnostics?.({
@@ -5886,6 +7932,17 @@ var init_posthog_client = __esm(() => {
5886
7932
  };
5887
7933
  });
5888
7934
 
7935
+ // packages/telemetry-core/src/events.ts
7936
+ var ALLOWED_DOLLAR_KEYS;
7937
+ var init_events = __esm(() => {
7938
+ ALLOWED_DOLLAR_KEYS = new Set([
7939
+ "$os",
7940
+ "$os_version",
7941
+ "$process_person_profile",
7942
+ "$session_id"
7943
+ ]);
7944
+ });
7945
+
5889
7946
  // packages/telemetry-core/src/record-daily-active.ts
5890
7947
  var init_record_daily_active = () => {};
5891
7948
 
@@ -5894,6 +7951,7 @@ var init_src = __esm(() => {
5894
7951
  init_activity_state();
5895
7952
  init_diagnostics();
5896
7953
  init_env();
7954
+ init_events();
5897
7955
  init_machine_id();
5898
7956
  init_posthog_client();
5899
7957
  init_record_daily_active();
@@ -5904,7 +7962,7 @@ var package_default;
5904
7962
  var init_package = __esm(() => {
5905
7963
  package_default = {
5906
7964
  name: "@oh-my-opencode/omo-codex",
5907
- version: "5.0.0-beta.2",
7965
+ version: "5.0.0-beta.21",
5908
7966
  type: "module",
5909
7967
  private: true,
5910
7968
  description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",
@@ -5938,7 +7996,7 @@ var init_package = __esm(() => {
5938
7996
  "@oh-my-opencode/utils": "workspace:*"
5939
7997
  },
5940
7998
  devDependencies: {
5941
- "bun-types": "1.3.14"
7999
+ "bun-types": "1.4.0"
5942
8000
  }
5943
8001
  };
5944
8002
  });
@@ -6109,14 +8167,14 @@ var init_posthog = __esm(() => {
6109
8167
  // packages/omo-codex/src/telemetry/index.ts
6110
8168
  var exports_telemetry = {};
6111
8169
  __export(exports_telemetry, {
6112
- getPostHogDistinctId: () => getPostHogDistinctId,
6113
- createPluginPostHog: () => createPluginPostHog,
6114
- createInstallPostHog: () => createInstallPostHog,
6115
- createCliPostHog: () => createCliPostHog,
6116
- __setOsProviderForTesting: () => __setOsProviderForTesting,
6117
- __setActivityStateProviderForTesting: () => __setActivityStateProviderForTesting,
8170
+ __resetActivityStateProviderForTesting: () => __resetActivityStateProviderForTesting,
6118
8171
  __resetOsProviderForTesting: () => __resetOsProviderForTesting,
6119
- __resetActivityStateProviderForTesting: () => __resetActivityStateProviderForTesting
8172
+ __setActivityStateProviderForTesting: () => __setActivityStateProviderForTesting,
8173
+ __setOsProviderForTesting: () => __setOsProviderForTesting,
8174
+ createCliPostHog: () => createCliPostHog,
8175
+ createInstallPostHog: () => createInstallPostHog,
8176
+ createPluginPostHog: () => createPluginPostHog,
8177
+ getPostHogDistinctId: () => getPostHogDistinctId
6120
8178
  });
6121
8179
  var init_telemetry = __esm(() => {
6122
8180
  init_posthog();
@@ -6624,9 +8682,9 @@ var LEGACY_CODEX_COMPONENT_BINS = [
6624
8682
  { name: "codex-comment-checker", component: "comment-checker" },
6625
8683
  { name: "codex-lsp", component: "lsp" },
6626
8684
  { name: "codex-rules", component: "rules" },
6627
- { name: "codex-start-work-continuation", component: "start-work-continuation" },
6628
8685
  { name: "codex-telemetry", component: "telemetry" },
6629
- { name: "codex-ultrawork", component: "ultrawork" }
8686
+ { name: "codex-ultrawork", component: "ultrawork" },
8687
+ { name: "codex-ulw-execute-continuation", component: "ulw-execute-continuation" }
6630
8688
  ];
6631
8689
  var LEGACY_CODEX_COMPONENT_BIN_NAMES = LEGACY_CODEX_COMPONENT_BINS.map((entry) => entry.name);
6632
8690
  async function removeLegacyCodexComponentBins(binDir, platform) {
@@ -10796,6 +12854,7 @@ function runtimeSlug(platform = process.platform, arch = process.arch) {
10796
12854
 
10797
12855
  // packages/utils/src/ast-grep/install-script.ts
10798
12856
  var AST_GREP_BIN_DIR_ENV_KEY = "OMO_AST_GREP_BIN_DIR";
12857
+ var KILL_GRACE_MS = 1000;
10799
12858
  var AST_GREP_INSTALL_TIMEOUT_MS = 30000;
10800
12859
  function astGrepRuntimeDir(baseDir, platform = process.platform, arch = process.arch) {
10801
12860
  return join32(baseDir, "runtime", "ast-grep", runtimeSlug(platform, arch));
@@ -10847,16 +12906,30 @@ function invocationsForPlatform(scriptPath, platform) {
10847
12906
  async function runInvocation(input) {
10848
12907
  const child = input.spawnProcess(input.invocation.command, input.invocation.args, { cwd: input.skillDir, env: input.env });
10849
12908
  let timedOut = false;
12909
+ let terminateDeadline;
12910
+ let terminateDeadlineGrace;
12911
+ const killIgnored = new Promise((_, reject) => {
12912
+ terminateDeadline = () => reject(new Error("ast-grep install child ignored termination"));
12913
+ });
10850
12914
  const timeout = setTimeout(() => {
10851
12915
  timedOut = true;
10852
12916
  child.kill();
12917
+ terminateDeadlineGrace = setTimeout(() => terminateDeadline?.(), KILL_GRACE_MS);
10853
12918
  }, input.timeoutMs);
10854
- timeout.unref?.();
10855
12919
  try {
10856
- const outcome = await child.outcome;
10857
- return timedOut ? { kind: "timed-out" } : outcome;
12920
+ const outcome = await Promise.race([child.outcome, killIgnored]);
12921
+ if (timedOut)
12922
+ return { kind: "timed-out" };
12923
+ return outcome;
12924
+ } catch (error) {
12925
+ if (error instanceof Error && error.message.includes("ignored termination")) {
12926
+ return { kind: "spawn-error", error, missingExecutable: false };
12927
+ }
12928
+ throw error;
10858
12929
  } finally {
10859
12930
  clearTimeout(timeout);
12931
+ if (terminateDeadlineGrace !== undefined)
12932
+ clearTimeout(terminateDeadlineGrace);
10860
12933
  }
10861
12934
  }
10862
12935
  function failedReason(outcome) {
@@ -11809,23 +13882,23 @@ async function runLazyCodexInstallLocalCli(input) {
11809
13882
  return 0;
11810
13883
  }
11811
13884
  export {
11812
- updateCodexConfig,
11813
- stampGitBashMcpEnv,
11814
- runLazyCodexInstallLocalCli,
11815
- runDelegatedOmoCommand,
11816
- resolveDefaultRepoRootForEntrypoint,
11817
- resolveDefaultRepoRoot,
11818
- resolveCodexInstallerBinDir,
11819
- repairNearestProjectLocalCodexArtifacts,
11820
- readCodexModelCatalog,
11821
- parseLazyCodexInstallCliArgs,
11822
- linkRootRuntimeBin,
11823
- linkCachedPluginBins,
11824
- installMarketplaceLocally,
11825
- installCachedPlugin,
11826
- formatLazyCodexInstallHelp,
11827
- findMissingHookCommandTargets,
11828
- buildDelegatedOmoInvocation,
13885
+ PASSTHROUGH_COMMANDS,
11829
13886
  assertHookCommandTargets,
11830
- PASSTHROUGH_COMMANDS
13887
+ buildDelegatedOmoInvocation,
13888
+ findMissingHookCommandTargets,
13889
+ formatLazyCodexInstallHelp,
13890
+ installCachedPlugin,
13891
+ installMarketplaceLocally,
13892
+ linkCachedPluginBins,
13893
+ linkRootRuntimeBin,
13894
+ parseLazyCodexInstallCliArgs,
13895
+ readCodexModelCatalog,
13896
+ repairNearestProjectLocalCodexArtifacts,
13897
+ resolveCodexInstallerBinDir,
13898
+ resolveDefaultRepoRoot,
13899
+ resolveDefaultRepoRootForEntrypoint,
13900
+ runDelegatedOmoCommand,
13901
+ runLazyCodexInstallLocalCli,
13902
+ stampGitBashMcpEnv,
13903
+ updateCodexConfig
11831
13904
  };