oh-my-opencode 5.0.0-beta.5 → 5.0.0-beta.50

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 (952) hide show
  1. package/.agents/command/publish.md +44 -16
  2. package/.agents/skills/codex-qa/scripts/lsp-e2e.sh +1 -3
  3. package/.agents/skills/opencode-qa/scripts/lsp-e2e.sh +1 -1
  4. package/.agents/skills/pre-publish-review/SKILL.md +9 -12
  5. package/.agents/skills/publish/SKILL.md +44 -16
  6. package/.agents/skills/senpi-qa/SKILL.md +80 -0
  7. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.mjs +65 -0
  8. package/.agents/skills/senpi-qa/scripts/resolve-evidence-dir.test.mjs +171 -0
  9. package/.agents/skills/tech-debt-audit/SKILL.md +6 -76
  10. package/.agents/skills/work-with-pr/SKILL.md +37 -23
  11. package/.opencode/command/publish.md +44 -16
  12. package/.opencode/skills/pre-publish-review/SKILL.md +9 -12
  13. package/.opencode/skills/work-with-pr/SKILL.md +37 -23
  14. package/README.ja.md +58 -46
  15. package/README.ko.md +60 -48
  16. package/README.md +58 -58
  17. package/README.ru.md +55 -46
  18. package/README.zh-cn.md +54 -46
  19. package/THIRD-PARTY-NOTICES.md +27 -99
  20. package/dist/agents/atlas/agent.d.ts +0 -1
  21. package/dist/agents/gpt-prompt-identity.d.ts +1 -1
  22. package/dist/agents/sisyphus/grok-4.d.ts +20 -0
  23. package/dist/agents/sisyphus/index.d.ts +2 -0
  24. package/dist/agents/sisyphus-agent-config.d.ts +6 -0
  25. package/dist/agents/sisyphus-agent-factory.d.ts +1 -1
  26. package/dist/agents/sisyphus-runtime-prompt-reconciler.d.ts +15 -4
  27. package/dist/agents/types.d.ts +4 -2
  28. package/dist/cli/config-manager/parse-opencode-config-file.d.ts +2 -1
  29. package/dist/cli/doctor/checks/system-plugin.d.ts +4 -3
  30. package/dist/cli/fallback-lane-policy.d.ts +1 -0
  31. package/dist/cli/index.js +51536 -59608
  32. package/dist/cli/install-codex/install-codex-test-fixtures.d.ts +1 -1
  33. package/dist/cli/run/on-complete-hook.d.ts +2 -0
  34. package/dist/cli/runtime-commands.d.ts +1 -1
  35. package/dist/cli/worktree-sweep/classify.d.ts +16 -0
  36. package/dist/cli/worktree-sweep/format.d.ts +8 -0
  37. package/dist/cli/worktree-sweep/git.d.ts +19 -0
  38. package/dist/cli/worktree-sweep/index.d.ts +7 -0
  39. package/dist/cli/worktree-sweep/options.d.ts +2 -0
  40. package/dist/cli/worktree-sweep/parse-worktree-list.d.ts +8 -0
  41. package/dist/cli/worktree-sweep/sweep.d.ts +2 -0
  42. package/dist/cli/worktree-sweep/types.d.ts +65 -0
  43. package/dist/cli/worktree-sweep/worktree-sweep.d.ts +2 -0
  44. package/dist/cli-node/index.js +51554 -59603
  45. package/dist/config/index.d.ts +1 -1
  46. package/dist/config/schema/background-task.d.ts +1 -0
  47. package/dist/config/schema/commands.d.ts +1 -1
  48. package/dist/config/schema/hooks.d.ts +1 -2
  49. package/dist/config/schema/oh-my-opencode-config.d.ts +5 -11
  50. package/dist/config/schema/ulw-execute.d.ts +5 -0
  51. package/dist/config/schema.d.ts +0 -1
  52. package/dist/config/validate.d.ts +2 -0
  53. package/dist/create-hooks.d.ts +3 -2
  54. package/dist/features/background-agent/compaction-aware-message-resolver.d.ts +1 -0
  55. package/dist/features/background-agent/constants.d.ts +0 -7
  56. package/dist/features/background-agent/error-classifier.d.ts +1 -0
  57. package/dist/features/background-agent/manager.d.ts +2 -1
  58. package/dist/features/background-agent/parent-wake-dispatched-tracker.d.ts +0 -1
  59. package/dist/features/background-agent/parent-wake-notifier-types.d.ts +1 -1
  60. package/dist/features/background-agent/parent-wake-prompt-dispatch.d.ts +1 -1
  61. package/dist/features/background-agent/parent-wake-session-inspector.d.ts +1 -1
  62. package/dist/features/background-agent/subagent-spawn-limits.d.ts +8 -0
  63. package/dist/features/btw-side/btw-command-draft.d.ts +7 -0
  64. package/dist/features/btw-side/context-injector.d.ts +15 -0
  65. package/dist/features/btw-side/index.d.ts +8 -0
  66. package/dist/features/btw-side/metadata.d.ts +15 -0
  67. package/dist/features/btw-side/parent-context-budget.d.ts +9 -0
  68. package/dist/features/btw-side/server-session-registry.d.ts +8 -0
  69. package/dist/features/btw-side/tui-adoption-cache.d.ts +13 -0
  70. package/dist/features/btw-side/tui-adoption-guard.d.ts +5 -0
  71. package/dist/features/btw-side/tui-controller-types.d.ts +68 -0
  72. package/dist/features/btw-side/tui-controller.d.ts +19 -0
  73. package/dist/features/btw-side/tui-escape-return.d.ts +12 -0
  74. package/dist/features/btw-side/tui-keymap.d.ts +17 -0
  75. package/dist/features/btw-side/tui-parent-validator.d.ts +6 -0
  76. package/dist/features/btw-side/tui-picker-options.d.ts +20 -0
  77. package/dist/features/btw-side/tui-picker.d.ts +9 -0
  78. package/dist/features/btw-side/tui-prompt-queue.d.ts +8 -0
  79. package/dist/features/btw-side/tui-session-bridge.d.ts +11 -0
  80. package/dist/features/btw-side/tui-session-catalog.d.ts +35 -0
  81. package/dist/features/btw-side/tui-side-removal.d.ts +11 -0
  82. package/dist/features/btw-side/tui-side-start.d.ts +9 -0
  83. package/dist/features/btw-side/tui-wiring.d.ts +8 -0
  84. package/dist/features/builtin-commands/templates/ulw-execute.d.ts +1 -0
  85. package/dist/features/builtin-commands/types.d.ts +1 -1
  86. package/dist/features/monitor/manager-internals.d.ts +1 -1
  87. package/dist/features/monitor/output-injector-types.d.ts +1 -1
  88. package/dist/features/opengateway-provider/index.d.ts +13 -0
  89. package/dist/features/task-toast-manager/manager.d.ts +0 -24
  90. package/dist/features/team-mode/tools/messaging-fallback-wake.d.ts +17 -0
  91. package/dist/features/team-mode/tools/messaging-live-delivery-recipient.d.ts +3 -0
  92. package/dist/features/team-mode/tools/messaging-runtime.d.ts +7 -0
  93. package/dist/hooks/anthropic-context-window-limit-recovery/message-storage-directory.d.ts +0 -3
  94. package/dist/hooks/anthropic-context-window-limit-recovery/state.d.ts +1 -0
  95. package/dist/hooks/anthropic-context-window-limit-recovery/storage/empty-messages.d.ts +0 -1
  96. package/dist/hooks/anthropic-context-window-limit-recovery/tool-result-storage.d.ts +11 -0
  97. package/dist/hooks/atlas/atlas-hook.d.ts +1 -0
  98. package/dist/hooks/atlas/atlas-lifecycle-store.d.ts +50 -0
  99. package/dist/hooks/atlas/event-handler.d.ts +1 -0
  100. package/dist/hooks/atlas/final-wave-approval-gate.test-support.d.ts +50 -0
  101. package/dist/hooks/atlas/system-reminder-templates.d.ts +0 -1
  102. package/dist/hooks/atlas/tool-execute-before.d.ts +3 -0
  103. package/dist/hooks/atlas/types.d.ts +1 -0
  104. package/dist/hooks/claude-code-hooks/session-hook-state.d.ts +1 -0
  105. package/dist/hooks/claude-code-hooks/stop.d.ts +2 -0
  106. package/dist/hooks/claude-code-hooks/todo.d.ts +0 -1
  107. package/dist/hooks/claude-code-hooks/transcript.d.ts +2 -0
  108. package/dist/hooks/compaction-context-injector/validated-model.d.ts +2 -0
  109. package/dist/hooks/fsync-skip-warning/index.d.ts +4 -0
  110. package/dist/hooks/hashline-edit-diff-enhancer/hook.d.ts +1 -0
  111. package/dist/hooks/hashline-edit-diff-enhancer/pending-captures.d.ts +13 -0
  112. package/dist/hooks/index.d.ts +1 -2
  113. package/dist/hooks/keyword-detector/hook.d.ts +7 -0
  114. package/dist/hooks/keyword-detector/ultrawork/source-detector.d.ts +0 -1
  115. package/dist/hooks/model-fallback/hook.d.ts +1 -1
  116. package/dist/hooks/prometheus-md-only/agent-resolution.d.ts +2 -2
  117. package/dist/hooks/runtime-fallback/chat-message-handler.d.ts +2 -0
  118. package/dist/hooks/runtime-fallback/retry-model-payload.d.ts +1 -0
  119. package/dist/hooks/runtime-fallback/runtime-model-settings.d.ts +6 -0
  120. package/dist/hooks/runtime-fallback/session-status-handler.d.ts +1 -1
  121. package/dist/hooks/runtime-fallback/types.d.ts +3 -1
  122. package/dist/hooks/sisyphus-junior-notepad/constants.d.ts +1 -1
  123. package/dist/hooks/todo-continuation-enforcer/types.d.ts +1 -0
  124. package/dist/hooks/{start-work → ulw-execute}/context-info-builder.d.ts +1 -1
  125. package/dist/hooks/{start-work → ulw-execute}/index.d.ts +1 -1
  126. package/dist/hooks/ulw-execute/ulw-execute-hook.d.ts +23 -0
  127. package/dist/index.js +28955 -25346
  128. package/dist/mcp/index.d.ts +0 -4
  129. package/dist/mcp/types.d.ts +0 -1
  130. package/dist/oh-my-opencode.schema.json +21 -47
  131. package/dist/plugin/chat-message/types.d.ts +3 -3
  132. package/dist/plugin/chat-message/ulw-execute-message.d.ts +5 -0
  133. package/dist/plugin/event-session-lifecycle.d.ts +1 -0
  134. package/dist/plugin/hooks/create-core-hooks.d.ts +2 -2
  135. package/dist/plugin/hooks/create-session-hooks.d.ts +2 -3
  136. package/dist/plugin/hooks/create-transform-hooks.d.ts +2 -0
  137. package/dist/plugin/messages-transform.d.ts +1 -0
  138. package/dist/plugin-dispose.d.ts +3 -0
  139. package/dist/shared/agent-tool-restrictions.d.ts +0 -1
  140. package/dist/shared/compaction-agent-config-checkpoint.d.ts +1 -0
  141. package/dist/shared/index.d.ts +2 -0
  142. package/dist/shared/legacy-plugin-warning.d.ts +2 -1
  143. package/dist/shared/normalize-sdk-response.d.ts +1 -0
  144. package/dist/shared/omo-process-sweep.d.ts +2 -4
  145. package/dist/shared/plugin-entry-migrator.d.ts +4 -3
  146. package/dist/shared/plugin-entry-shape.d.ts +6 -0
  147. package/dist/shared/runtime-fallback-retry-marker.d.ts +16 -0
  148. package/dist/shared/shell-env.d.ts +1 -1
  149. package/dist/skills/ast-grep/AGENTS.md +51 -0
  150. package/dist/skills/ast-grep/SKILL.md +1 -1
  151. package/dist/skills/coding-agent-sessions/AGENTS.md +62 -0
  152. package/dist/skills/coding-agent-sessions/SKILL.md +3 -2
  153. package/dist/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  154. package/dist/skills/coding-agent-sessions/references/senpi.md +4 -4
  155. package/dist/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  156. package/dist/skills/data-scientist/SKILL.md +99 -239
  157. package/dist/skills/data-scientist/references/execution-surfaces.md +91 -0
  158. package/dist/skills/data-scientist/references/placement.md +74 -0
  159. package/dist/skills/data-scientist/references/polars-lane.md +95 -0
  160. package/dist/skills/data-scientist/references/uv-setup.md +1 -1
  161. package/dist/skills/data-scientist/references/visualization.md +64 -0
  162. package/dist/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  163. package/dist/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  164. package/dist/skills/debugging/SKILL.md +3 -1
  165. package/dist/skills/debugging/references/methodology/00-setup.md +12 -0
  166. package/dist/skills/debugging/references/methodology/02-investigate.md +21 -0
  167. package/dist/skills/debugging/references/runtimes/go.md +15 -1
  168. package/dist/skills/debugging/references/runtimes/native-binary.md +38 -0
  169. package/dist/skills/debugging/references/runtimes/node.md +25 -0
  170. package/dist/skills/debugging/references/runtimes/python.md +13 -0
  171. package/dist/skills/debugging/references/runtimes/rust.md +41 -0
  172. package/dist/skills/debugging/references/scripts/dap.mjs +267 -0
  173. package/dist/skills/debugging/references/scripts/dap.test.ts +86 -0
  174. package/dist/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  175. package/dist/skills/debugging/references/tools/dap.md +103 -0
  176. package/dist/skills/debugging/references/tools/frida.md +193 -0
  177. package/dist/skills/frontend/SKILL.md +12 -8
  178. package/dist/skills/frontend/references/design/_INDEX.md +1 -0
  179. package/dist/skills/frontend/references/design/print-paged-media.md +76 -0
  180. package/dist/skills/frontend/references/design/stylegallery.md +80 -0
  181. package/dist/skills/frontend/references/designpowers/README.md +1 -1
  182. package/dist/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  183. package/dist/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  184. package/dist/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  185. package/dist/skills/frontend/references/designpowers/orchestration.md +1 -1
  186. package/dist/skills/frontend/references/designpowers/routing.md +5 -5
  187. package/dist/skills/git-master/SKILL.md +1 -1
  188. package/dist/skills/init-deep/SKILL.md +14 -14
  189. package/dist/skills/lsp-setup/SKILL.md +1 -1
  190. package/dist/skills/programming/SKILL.md +1 -1
  191. package/dist/skills/refactor/SKILL.md +1 -1
  192. package/dist/skills/remove-ai-slops/SKILL.md +1 -1
  193. package/dist/skills/review-work/SKILL.md +100 -418
  194. package/dist/skills/ultimate-browsing/ATTRIBUTION.md +38 -11
  195. package/dist/skills/ultimate-browsing/SKILL.md +26 -9
  196. package/dist/skills/ultimate-browsing/engine/AGENTS.md +110 -0
  197. package/dist/skills/ultimate-browsing/engine/templates/package.json +1 -1
  198. package/dist/skills/ultimate-browsing/references/chrome-stealth.md +23 -18
  199. package/dist/skills/ultimate-browsing/references/insane-search/README.md +9 -2
  200. package/dist/skills/{start-work → ulw-execute}/SKILL.md +17 -16
  201. package/dist/skills/ulw-plan/SKILL.md +7 -8
  202. package/dist/skills/ulw-plan/references/full-workflow.md +31 -7
  203. package/dist/skills/ulw-plan/references/intent-clear.md +2 -1
  204. package/dist/skills/ulw-plan/references/intent-unclear.md +5 -5
  205. package/dist/skills/ulw-research/SKILL.md +8 -3
  206. package/dist/skills/visual-qa/AGENTS.md +58 -0
  207. package/dist/skills/visual-qa/SKILL.md +4 -3
  208. package/dist/tools/delegate-task/builtin-categories.d.ts +3 -1
  209. package/dist/tools/delegate-task/builtin-category-definition.d.ts +2 -1
  210. package/dist/tools/delegate-task/constants.d.ts +2 -2
  211. package/dist/tools/delegate-task/openai-categories.d.ts +7 -2
  212. package/dist/tools/delegate-task/sync-session-cleanup.d.ts +3 -0
  213. package/dist/tools/delegate-task/sync-session-poller.d.ts +1 -0
  214. package/dist/tools/delegate-task/tool-description.d.ts +3 -1
  215. package/dist/tools/delegate-task/types.d.ts +4 -0
  216. package/dist/tools/session-manager/directory-filter.d.ts +2 -0
  217. package/dist/tui.d.ts +12 -0
  218. package/dist/tui.js +37066 -46704
  219. package/package.json +47 -41
  220. package/packages/git-bash-mcp/dist/cli.js +6 -1
  221. package/packages/git-bash-mcp/package.json +1 -1
  222. package/packages/lsp-core/src/index.ts +1 -0
  223. package/packages/lsp-core/src/lsp/client-diagnostics-concurrency.integration.test.ts +44 -0
  224. package/packages/lsp-core/src/lsp/client-diagnostics-freshness.integration.test.ts +57 -48
  225. package/packages/lsp-core/src/lsp/client-diagnostics-pull-timeout.test.ts +64 -0
  226. package/packages/lsp-core/src/lsp/client-wrapper-outside-cwd.test.ts +78 -0
  227. package/packages/lsp-core/src/lsp/client-wrapper.test.ts +163 -13
  228. package/packages/lsp-core/src/lsp/client-wrapper.ts +110 -23
  229. package/packages/lsp-core/src/lsp/client.ts +32 -3
  230. package/packages/lsp-core/src/lsp/connection.ts +16 -0
  231. package/packages/lsp-core/src/lsp/constants.ts +6 -0
  232. package/packages/lsp-core/src/lsp/controlled-clock-test-support.ts +61 -0
  233. package/packages/lsp-core/src/lsp/errors.ts +15 -0
  234. package/packages/lsp-core/src/lsp/fixtures/workspace-edit-server.mjs +10 -3
  235. package/packages/lsp-core/src/lsp/format-document.test.ts +143 -0
  236. package/packages/lsp-core/src/lsp/format-document.ts +90 -0
  237. package/packages/lsp-core/src/lsp/json-rpc-connection.ts +11 -6
  238. package/packages/lsp-core/src/lsp/manager-lifecycle.test.ts +262 -0
  239. package/packages/lsp-core/src/lsp/manager-max-clients.test.ts +151 -0
  240. package/packages/lsp-core/src/lsp/manager.ts +138 -12
  241. package/packages/lsp-core/src/lsp/outside-context-workspace.ts +33 -0
  242. package/packages/lsp-core/src/lsp/server-definitions.ts +29 -0
  243. package/packages/lsp-core/src/lsp/server-installation.test.ts +376 -0
  244. package/packages/lsp-core/src/lsp/server-installation.ts +200 -27
  245. package/packages/lsp-core/src/lsp/server-resolution-local-binary.test.ts +170 -0
  246. package/packages/lsp-core/src/lsp/server-resolution.ts +18 -5
  247. package/packages/lsp-core/src/lsp/timer-provider.ts +13 -0
  248. package/packages/lsp-core/src/lsp/transport-request-timeout.test.ts +73 -0
  249. package/packages/lsp-core/src/lsp/transport.ts +16 -2
  250. package/packages/lsp-core/src/lsp/types.ts +8 -0
  251. package/packages/lsp-core/src/lsp/workspace-apply-edit-test-support.ts +29 -1
  252. package/packages/lsp-core/src/lsp/workspace-document-state.test.ts +84 -1
  253. package/packages/lsp-core/src/lsp/workspace-document-state.ts +30 -11
  254. package/packages/lsp-core/src/lsp/workspace-edit-adversarial.test.ts +20 -1
  255. package/packages/lsp-core/src/lsp/workspace-markers.ts +18 -0
  256. package/packages/lsp-core/src/mcp.ts +3 -0
  257. package/packages/lsp-core/src/request-context.test.ts +29 -0
  258. package/packages/lsp-core/src/request-context.ts +1 -1
  259. package/packages/lsp-core/src/tool-surface.test.ts +13 -1
  260. package/packages/lsp-core/src/tools/definitions.ts +14 -0
  261. package/packages/lsp-core/src/tools/diagnostics.ts +3 -3
  262. package/packages/lsp-core/src/tools/format.test.ts +56 -0
  263. package/packages/lsp-core/src/tools/format.ts +56 -0
  264. package/packages/lsp-core/src/tools/index.ts +1 -0
  265. package/packages/lsp-core/src/tools/navigation.ts +4 -2
  266. package/packages/lsp-core/src/tools/parameters.test.ts +51 -0
  267. package/packages/lsp-core/src/tools/rename.ts +4 -2
  268. package/packages/lsp-core/src/tools/symbols.ts +1 -1
  269. package/packages/lsp-core/src/tools/types.ts +10 -0
  270. package/packages/lsp-daemon/dist/cli.js +961 -483
  271. package/packages/lsp-daemon/dist/client.d.ts +10 -0
  272. package/packages/lsp-daemon/dist/client.js +976 -495
  273. package/packages/lsp-daemon/dist/daemon-client.d.ts +1 -0
  274. package/packages/lsp-daemon/dist/daemon-client.js +3 -0
  275. package/packages/lsp-daemon/dist/ensure-daemon.d.ts +6 -1
  276. package/packages/lsp-daemon/dist/ensure-daemon.js +10 -2
  277. package/packages/lsp-daemon/dist/index.js +881 -405
  278. package/packages/lsp-daemon/dist/proxy.js +3 -0
  279. package/packages/lsp-daemon/dist/version-reap.js +1 -1
  280. package/packages/lsp-daemon/package.json +1 -1
  281. package/packages/lsp-tools-mcp/dist/cli.js +820 -345
  282. package/packages/lsp-tools-mcp/dist/lsp/manager.js +272 -138
  283. package/packages/lsp-tools-mcp/dist/mcp.js +845 -372
  284. package/packages/lsp-tools-mcp/dist/request-context.js +12 -13
  285. package/packages/lsp-tools-mcp/dist/tools.js +775 -306
  286. package/packages/lsp-tools-mcp/package.json +1 -1
  287. package/packages/omo-codex/THIRD-PARTY-NOTICES.md +4 -21
  288. package/packages/omo-codex/plugin/.codex-plugin/plugin.json +4 -6
  289. package/packages/omo-codex/plugin/.mcp.json +0 -6
  290. package/packages/omo-codex/plugin/AGENTS.md +47 -0
  291. package/packages/omo-codex/plugin/README.md +6 -2
  292. package/packages/omo-codex/plugin/components/bootstrap/dist/cli.js +193 -148
  293. package/packages/omo-codex/plugin/components/bootstrap/hooks/hooks.json +1 -1
  294. package/packages/omo-codex/plugin/components/bootstrap/package.json +1 -1
  295. package/packages/omo-codex/plugin/components/bootstrap/src/hook.ts +1 -0
  296. package/packages/omo-codex/plugin/components/comment-checker/AGENTS.md +9 -0
  297. package/packages/omo-codex/plugin/components/comment-checker/biome.json +2 -2
  298. package/packages/omo-codex/plugin/components/comment-checker/dist/cli.js +2 -1
  299. package/packages/omo-codex/plugin/components/comment-checker/hooks/hooks.json +1 -1
  300. package/packages/omo-codex/plugin/components/comment-checker/package.json +5 -5
  301. package/packages/omo-codex/plugin/components/comment-checker/src/apply-patch.ts +2 -8
  302. package/packages/omo-codex/plugin/components/comment-checker/src/core.ts +1 -2
  303. package/packages/omo-codex/plugin/components/comment-checker/src/request-extractor.ts +1 -1
  304. package/packages/omo-codex/plugin/components/comment-checker/src/runner.ts +1 -0
  305. package/packages/omo-codex/plugin/components/git-bash/AGENTS.md +1 -1
  306. package/packages/omo-codex/plugin/components/git-bash/hooks/hooks.json +2 -2
  307. package/packages/omo-codex/plugin/components/git-bash/package.json +3 -4
  308. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/AGENTS.md +2 -2
  309. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/biome.json +2 -2
  310. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/directive.md +2 -0
  311. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/cli.js +36 -29
  312. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/codex-hook.js +32 -26
  313. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/dist/types.d.ts +3 -0
  314. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/hooks/hooks.json +1 -1
  315. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/package.json +5 -5
  316. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/src/codex-hook.ts +32 -28
  317. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/src/types.ts +3 -0
  318. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/test/cli.test.ts +1 -1
  319. package/packages/omo-codex/plugin/components/lazycodex-executor-verify/test/codex-hook.test.ts +137 -28
  320. package/packages/omo-codex/plugin/components/lcx/skills/lcx-doctor/SKILL.md +4 -2
  321. package/packages/omo-codex/plugin/components/lsp/AGENTS.md +30 -15
  322. package/packages/omo-codex/plugin/components/lsp/biome.json +2 -2
  323. package/packages/omo-codex/plugin/components/lsp/dist/.omo-runtime-manifest.json +4 -4
  324. package/packages/omo-codex/plugin/components/lsp/dist/cli.js +999 -544
  325. package/packages/omo-codex/plugin/components/lsp/dist/daemon-cli-path.js +1 -1
  326. package/packages/omo-codex/plugin/components/lsp/hooks/hooks.json +2 -2
  327. package/packages/omo-codex/plugin/components/lsp/package.json +5 -5
  328. package/packages/omo-codex/plugin/components/lsp/src/cli.ts +1 -1
  329. package/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts +1 -1
  330. package/packages/omo-codex/plugin/components/lsp/src/daemon-cli-path.ts +1 -5
  331. package/packages/omo-codex/plugin/components/lsp/test/codex-hook-unavailable.test.ts +6 -7
  332. package/packages/omo-codex/plugin/components/lsp/test/codex-hook.test.ts +1 -2
  333. package/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts +11 -1
  334. package/packages/omo-codex/plugin/components/rules/AGENTS.md +12 -0
  335. package/packages/omo-codex/plugin/components/rules/README.md +2 -0
  336. package/packages/omo-codex/plugin/components/rules/biome.json +2 -2
  337. package/packages/omo-codex/plugin/components/rules/bundled-rules/hephaestus/gpt-6.md +123 -0
  338. package/packages/omo-codex/plugin/components/rules/dist/cli.js +91 -68
  339. package/packages/omo-codex/plugin/components/rules/hooks/hooks.json +4 -4
  340. package/packages/omo-codex/plugin/components/rules/package.json +7 -7
  341. package/packages/omo-codex/plugin/components/rules/src/config.ts +1 -2
  342. package/packages/omo-codex/plugin/components/rules/src/persistent-cache.ts +1 -2
  343. package/packages/omo-codex/plugin/components/rules/src/post-compact-budget.ts +15 -5
  344. package/packages/omo-codex/plugin/components/rules/src/rules-engine-factory.ts +1 -4
  345. package/packages/omo-codex/plugin/components/rules/src/static-injection.ts +4 -9
  346. package/packages/omo-codex/plugin/components/rules/test/bundled-rules-priority.test.ts +11 -16
  347. package/packages/omo-codex/plugin/components/rules/test/bundled-rules.test.ts +17 -25
  348. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-budget.test.ts +9 -7
  349. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-context.test.ts +0 -6
  350. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-dedup.test.ts +6 -4
  351. package/packages/omo-codex/plugin/components/rules/test/codex-hook-post-compact-directive.test.ts +12 -9
  352. package/packages/omo-codex/plugin/components/rules/test/codex-hook.test.ts +28 -37
  353. package/packages/omo-codex/plugin/components/rules/test/dynamic-target-fingerprints.test.ts +1 -2
  354. package/packages/omo-codex/plugin/components/rules/test/engine.test.ts +7 -4
  355. package/packages/omo-codex/plugin/components/rules/test/finder.test.ts +2 -3
  356. package/packages/omo-codex/plugin/components/rules/test/formatter.test.ts +39 -72
  357. package/packages/omo-codex/plugin/components/rules/test/hephaestus-model-variant.test.ts +38 -3
  358. package/packages/omo-codex/plugin/components/rules/test/hook-output.test.ts +2 -3
  359. package/packages/omo-codex/plugin/components/rules/test/matcher.test.ts +2 -3
  360. package/packages/omo-codex/plugin/components/rules/test/package-smoke.test.ts +1 -1
  361. package/packages/omo-codex/plugin/components/rules/test/parser.test.ts +1 -2
  362. package/packages/omo-codex/plugin/components/rules/test/post-compact-budget.test.ts +29 -6
  363. package/packages/omo-codex/plugin/components/rules/test/rules-engine-consumption.test.ts +3 -6
  364. package/packages/omo-codex/plugin/components/rules/test/scanner.test.ts +1 -2
  365. package/packages/omo-codex/plugin/components/rules/test/sources.test.ts +2 -5
  366. package/packages/omo-codex/plugin/components/rules/test/windows-git-bash-bundled-rule.test.ts +2 -17
  367. package/packages/omo-codex/plugin/components/teammode/hooks/hooks.json +1 -1
  368. package/packages/omo-codex/plugin/components/teammode/package.json +5 -5
  369. package/packages/omo-codex/plugin/components/teammode/test/thread-title-hook.test.ts +4 -10
  370. package/packages/omo-codex/plugin/components/telemetry/AGENTS.md +8 -0
  371. package/packages/omo-codex/plugin/components/telemetry/biome.json +2 -2
  372. package/packages/omo-codex/plugin/components/telemetry/dist/cli.js +2435 -700
  373. package/packages/omo-codex/plugin/components/telemetry/dist/posthog.js +2439 -705
  374. package/packages/omo-codex/plugin/components/telemetry/hooks/hooks.json +1 -1
  375. package/packages/omo-codex/plugin/components/telemetry/package.json +5 -5
  376. package/packages/omo-codex/plugin/components/telemetry/src/codex-hook.ts +1 -4
  377. package/packages/omo-codex/plugin/components/telemetry/src/posthog.ts +4 -14
  378. package/packages/omo-codex/plugin/components/telemetry/src/product-identity.ts +1 -1
  379. package/packages/omo-codex/plugin/components/telemetry/test/diagnostics.test.ts +2 -5
  380. package/packages/omo-codex/plugin/components/ultrawork/AGENTS.md +10 -4
  381. package/packages/omo-codex/plugin/components/ultrawork/README.md +2 -0
  382. package/packages/omo-codex/plugin/components/ultrawork/agents/explorer.toml +1 -1
  383. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-clone-fidelity-reviewer.toml +1 -1
  384. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-code-reviewer.toml +1 -1
  385. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-gate-reviewer.toml +1 -1
  386. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-qa-executor.toml +1 -1
  387. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-worker-high.toml +1 -1
  388. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-worker-low.toml +1 -1
  389. package/packages/omo-codex/plugin/components/ultrawork/agents/lazycodex-worker-medium.toml +1 -1
  390. package/packages/omo-codex/plugin/components/ultrawork/agents/librarian.toml +1 -1
  391. package/packages/omo-codex/plugin/components/ultrawork/agents/metis.toml +1 -1
  392. package/packages/omo-codex/plugin/components/ultrawork/agents/momus.toml +1 -1
  393. package/packages/omo-codex/plugin/components/ultrawork/agents/plan.toml +1 -1
  394. package/packages/omo-codex/plugin/components/ultrawork/biome.json +2 -2
  395. package/packages/omo-codex/plugin/components/ultrawork/dist/cli.js +490 -4
  396. package/packages/omo-codex/plugin/components/ultrawork/hooks/hooks.json +1 -1
  397. package/packages/omo-codex/plugin/components/ultrawork/package.json +5 -6
  398. package/packages/omo-codex/plugin/components/ultrawork/scripts/sync-directive.mjs +30 -14
  399. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/SKILL.md +6 -7
  400. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/full-workflow.md +31 -7
  401. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-clear.md +2 -1
  402. package/packages/omo-codex/plugin/components/ultrawork/skills/ulw-plan/references/intent-unclear.md +5 -5
  403. package/packages/omo-codex/plugin/components/ultrawork/src/directive-content.ts +4 -0
  404. package/packages/omo-codex/plugin/components/ultrawork/src/directive.ts +5 -2
  405. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook-trigger-policy.test.ts +9 -1
  406. package/packages/omo-codex/plugin/components/ultrawork/test/codex-hook.test.ts +0 -136
  407. package/packages/omo-codex/plugin/components/ultrawork/test/directive-source.test.ts +14 -8
  408. package/packages/omo-codex/plugin/components/ultrawork/test/package-smoke.test.ts +12 -1
  409. package/packages/omo-codex/plugin/components/ultrawork/test/skill-pointer.test.ts +0 -2
  410. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/AGENTS.md +4 -4
  411. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/NOTICE +1 -1
  412. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/README.md +6 -6
  413. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/biome.json +2 -2
  414. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/directive.md +10 -10
  415. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/dist/cli.js +16 -16
  416. package/packages/omo-codex/plugin/components/ulw-execute-continuation/hooks/hooks.json +16 -0
  417. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/package.json +12 -12
  418. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/boulder-reader.ts +1 -1
  419. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/cli.ts +1 -1
  420. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/codex-hook.ts +4 -4
  421. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/directive.ts +1 -1
  422. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/index.ts +1 -1
  423. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/types.ts +1 -1
  424. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/boulder-reader.test.ts +3 -3
  425. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/cli.test.ts +4 -11
  426. package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/codex-hook.test.ts +24 -22
  427. package/packages/omo-codex/plugin/components/ulw-loop/AGENTS.md +19 -0
  428. package/packages/omo-codex/plugin/components/ulw-loop/CHANGELOG.md +1 -1
  429. package/packages/omo-codex/plugin/components/ulw-loop/README.md +12 -1
  430. package/packages/omo-codex/plugin/components/ulw-loop/biome.json +2 -2
  431. package/packages/omo-codex/plugin/components/ulw-loop/directive.md +26 -13
  432. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-codex-validation.d.ts +12 -0
  433. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-codex-validation.js +45 -0
  434. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-continuation.js +9 -0
  435. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-reconciliation.d.ts +15 -0
  436. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-reconciliation.js +15 -1
  437. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-template.d.ts +8 -0
  438. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint-template.js +113 -0
  439. package/packages/omo-codex/plugin/components/ulw-loop/dist/checkpoint.js +40 -39
  440. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-commands.js +21 -8
  441. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-output.d.ts +2 -1
  442. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-output.js +12 -1
  443. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli-subcommands.js +2 -0
  444. package/packages/omo-codex/plugin/components/ulw-loop/dist/cli.js +1264 -429
  445. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-instruction.d.ts +2 -0
  446. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-instruction.js +28 -8
  447. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-snapshot.d.ts +13 -0
  448. package/packages/omo-codex/plugin/components/ulw-loop/dist/codex-goal-snapshot.js +15 -1
  449. package/packages/omo-codex/plugin/components/ulw-loop/dist/constants.d.ts +1 -0
  450. package/packages/omo-codex/plugin/components/ulw-loop/dist/constants.js +1 -0
  451. package/packages/omo-codex/plugin/components/ulw-loop/dist/domain-types.d.ts +17 -9
  452. package/packages/omo-codex/plugin/components/ulw-loop/dist/paths.d.ts +1 -0
  453. package/packages/omo-codex/plugin/components/ulw-loop/dist/paths.js +13 -4
  454. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-io.d.ts +1 -0
  455. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-io.js +34 -4
  456. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-missing-recovery.d.ts +14 -0
  457. package/packages/omo-codex/plugin/components/ulw-loop/dist/plan-missing-recovery.js +29 -0
  458. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-aggregate.d.ts +7 -0
  459. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-aggregate.js +9 -0
  460. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-artifacts.d.ts +12 -0
  461. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-artifacts.js +104 -0
  462. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-fields.d.ts +13 -1
  463. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-fields.js +65 -9
  464. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate-verdicts.js +5 -1
  465. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate.d.ts +4 -2
  466. package/packages/omo-codex/plugin/components/ulw-loop/dist/quality-gate.js +72 -117
  467. package/packages/omo-codex/plugin/components/ulw-loop/dist/review-blockers.js +4 -2
  468. package/packages/omo-codex/plugin/components/ulw-loop/dist/spawn-guard.d.ts +6 -1
  469. package/packages/omo-codex/plugin/components/ulw-loop/dist/spawn-guard.js +189 -29
  470. package/packages/omo-codex/plugin/components/ulw-loop/dist/state-lock.d.ts +9 -0
  471. package/packages/omo-codex/plugin/components/ulw-loop/dist/state-lock.js +227 -0
  472. package/packages/omo-codex/plugin/components/ulw-loop/dist/status-next-actions.d.ts +6 -0
  473. package/packages/omo-codex/plugin/components/ulw-loop/dist/status-next-actions.js +33 -0
  474. package/packages/omo-codex/plugin/components/ulw-loop/dist/stop-resume-hook.js +20 -6
  475. package/packages/omo-codex/plugin/components/ulw-loop/dist/surface.d.ts +19 -0
  476. package/packages/omo-codex/plugin/components/ulw-loop/dist/surface.js +75 -0
  477. package/packages/omo-codex/plugin/components/ulw-loop/hooks/hooks.json +17 -4
  478. package/packages/omo-codex/plugin/components/ulw-loop/package.json +6 -6
  479. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/SKILL.md +6 -4
  480. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/define-goal.md +108 -0
  481. package/packages/omo-codex/plugin/components/ulw-loop/skills/ulw-loop/references/full-workflow.md +32 -8
  482. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-codex-validation.ts +81 -0
  483. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-continuation.ts +7 -0
  484. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-reconciliation.ts +31 -1
  485. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint-template.ts +128 -0
  486. package/packages/omo-codex/plugin/components/ulw-loop/src/checkpoint.ts +38 -71
  487. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-commands.ts +24 -8
  488. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-output.ts +14 -1
  489. package/packages/omo-codex/plugin/components/ulw-loop/src/cli-subcommands.ts +2 -0
  490. package/packages/omo-codex/plugin/components/ulw-loop/src/cli.ts +8 -6
  491. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-goal-instruction.ts +35 -7
  492. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-goal-snapshot.ts +26 -1
  493. package/packages/omo-codex/plugin/components/ulw-loop/src/codex-hook.ts +3 -1
  494. package/packages/omo-codex/plugin/components/ulw-loop/src/constants.ts +1 -0
  495. package/packages/omo-codex/plugin/components/ulw-loop/src/domain-types.ts +19 -9
  496. package/packages/omo-codex/plugin/components/ulw-loop/src/paths.ts +25 -4
  497. package/packages/omo-codex/plugin/components/ulw-loop/src/plan-io.ts +39 -4
  498. package/packages/omo-codex/plugin/components/ulw-loop/src/plan-missing-recovery.ts +38 -0
  499. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-aggregate.ts +11 -0
  500. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-artifacts.ts +123 -0
  501. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-fields.ts +71 -15
  502. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate-verdicts.ts +6 -1
  503. package/packages/omo-codex/plugin/components/ulw-loop/src/quality-gate.ts +92 -136
  504. package/packages/omo-codex/plugin/components/ulw-loop/src/review-blockers.ts +4 -2
  505. package/packages/omo-codex/plugin/components/ulw-loop/src/spawn-guard.ts +200 -28
  506. package/packages/omo-codex/plugin/components/ulw-loop/src/state-lock.ts +239 -0
  507. package/packages/omo-codex/plugin/components/ulw-loop/src/status-next-actions.ts +36 -0
  508. package/packages/omo-codex/plugin/components/ulw-loop/src/stop-resume-hook.ts +19 -6
  509. package/packages/omo-codex/plugin/components/ulw-loop/src/surface.ts +107 -0
  510. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-continuation.test.ts +0 -1
  511. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-final.test.ts +132 -1
  512. package/packages/omo-codex/plugin/components/ulw-loop/test/checkpoint-template.test.ts +147 -0
  513. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-checkpoint-continuation.test.ts +4 -2
  514. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-checkpoint.test.ts +4 -2
  515. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-commands.test.ts +2 -0
  516. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-complete-goals.test.ts +3 -1
  517. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-create-goals.test.ts +35 -8
  518. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-entrypoint.test.ts +38 -4
  519. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-json-errors.test.ts +2 -0
  520. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-scope-required.test.ts +144 -0
  521. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-status-next-actions.test.ts +185 -0
  522. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-steering-batch.test.ts +8 -3
  523. package/packages/omo-codex/plugin/components/ulw-loop/test/cli-validation-batch.test.ts +6 -0
  524. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-instruction.test.ts +37 -2
  525. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-goal-snapshot.test.ts +18 -0
  526. package/packages/omo-codex/plugin/components/ulw-loop/test/codex-hook.test.ts +0 -3
  527. package/packages/omo-codex/plugin/components/ulw-loop/test/fixtures/cli-session.ts +4 -0
  528. package/packages/omo-codex/plugin/components/ulw-loop/test/fixtures/quality-gate-builder.ts +9 -4
  529. package/packages/omo-codex/plugin/components/ulw-loop/test/guided-recovery.test.ts +105 -0
  530. package/packages/omo-codex/plugin/components/ulw-loop/test/package-smoke.test.ts +5 -37
  531. package/packages/omo-codex/plugin/components/ulw-loop/test/paths.test.ts +9 -0
  532. package/packages/omo-codex/plugin/components/ulw-loop/test/plan-io-cross-process.test.ts +106 -0
  533. package/packages/omo-codex/plugin/components/ulw-loop/test/plan-io.test.ts +36 -2
  534. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-aggregate-basics.test.ts +258 -0
  535. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-cap-and-dedupe.test.ts +22 -0
  536. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-fields-messages.test.ts +98 -0
  537. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-lazycodex-surface.test.ts +93 -0
  538. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-poisoning-cascades.test.ts +97 -0
  539. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-roles.test.ts +51 -2
  540. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-senpi-surface.test.ts +131 -0
  541. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate-single-report.test.ts +241 -0
  542. package/packages/omo-codex/plugin/components/ulw-loop/test/quality-gate.test.ts +58 -3
  543. package/packages/omo-codex/plugin/components/ulw-loop/test/spawn-guard.test.ts +423 -6
  544. package/packages/omo-codex/plugin/components/ulw-loop/test/state-lock.test.ts +218 -0
  545. package/packages/omo-codex/plugin/components/ulw-loop/test/steering.test.ts +8 -5
  546. package/packages/omo-codex/plugin/components/ulw-loop/test/stop-resume-hook.test.ts +1 -1
  547. package/packages/omo-codex/plugin/components/ulw-loop/test/surface.test.ts +74 -0
  548. package/packages/omo-codex/plugin/components/ulw-loop/test/ultrawork-directive.test.ts +13 -8
  549. package/packages/omo-codex/plugin/components/ulw-loop/vitest.config.ts +1 -0
  550. package/packages/omo-codex/plugin/hooks/post-compact-resetting-git-bash-mcp-reminder.json +1 -1
  551. package/packages/omo-codex/plugin/hooks/post-compact-resetting-lsp-diagnostics-cache.json +1 -1
  552. package/packages/omo-codex/plugin/hooks/post-compact-resetting-project-rule-cache.json +1 -1
  553. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-comments.json +1 -1
  554. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-lsp-diagnostics.json +1 -1
  555. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-thread-title-hygiene.json +1 -1
  556. package/packages/omo-codex/plugin/hooks/post-tool-use-matching-project-rules.json +1 -1
  557. package/packages/omo-codex/plugin/hooks/post-tool-use-recording-spawn-admission.json +18 -0
  558. package/packages/omo-codex/plugin/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json +1 -1
  559. package/packages/omo-codex/plugin/hooks/pre-tool-use-guarding-ulw-loop-spawns.json +1 -1
  560. package/packages/omo-codex/plugin/hooks/pre-tool-use-recommending-git-bash-mcp.json +1 -1
  561. package/packages/omo-codex/plugin/hooks/session-start-checking-auto-update.json +1 -1
  562. package/packages/omo-codex/plugin/hooks/session-start-checking-bootstrap-provisioning.json +1 -1
  563. package/packages/omo-codex/plugin/hooks/session-start-loading-project-rules.json +1 -1
  564. package/packages/omo-codex/plugin/hooks/session-start-recording-session-telemetry.json +1 -1
  565. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-execute-continuation.json +17 -0
  566. package/packages/omo-codex/plugin/hooks/stop-checking-ulw-loop-resume.json +1 -1
  567. package/packages/omo-codex/plugin/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json +1 -1
  568. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ultrawork-trigger.json +1 -1
  569. package/packages/omo-codex/plugin/hooks/user-prompt-submit-checking-ulw-loop-steering.json +1 -1
  570. package/packages/omo-codex/plugin/hooks/user-prompt-submit-loading-project-rules.json +1 -1
  571. package/packages/omo-codex/plugin/model-catalog.json +16 -7
  572. package/packages/omo-codex/plugin/package-lock.json +676 -524
  573. package/packages/omo-codex/plugin/package.json +2 -3
  574. package/packages/omo-codex/plugin/scripts/AGENTS.md +39 -0
  575. package/packages/omo-codex/plugin/scripts/auto-update-plan.mjs +1 -2
  576. package/packages/omo-codex/plugin/scripts/auto-update.mjs +0 -9
  577. package/packages/omo-codex/plugin/scripts/canonical-ultrawork-directive.mjs +17 -0
  578. package/packages/omo-codex/plugin/scripts/hook-status-message.mjs +0 -1
  579. package/packages/omo-codex/plugin/scripts/migrate-codex-config/catalog.mjs +16 -7
  580. package/packages/omo-codex/plugin/scripts/migrate-codex-config/multi-agent-v2-guard.mjs +8 -4
  581. package/packages/omo-codex/plugin/scripts/migrate-codex-config/subagent-limit-guard.mjs +18 -90
  582. package/packages/omo-codex/plugin/scripts/migrate-codex-config/toml-section-editor.mjs +1 -1
  583. package/packages/omo-codex/plugin/scripts/sync-skills.mjs +94 -55
  584. package/packages/omo-codex/plugin/shared/package.json +3 -4
  585. package/packages/omo-codex/plugin/shared/src/config-loader.ts +2 -102
  586. package/packages/omo-codex/plugin/shared/src/config-migration.ts +0 -1
  587. package/packages/omo-codex/plugin/shared/test/config-loader.test.ts +41 -130
  588. package/packages/omo-codex/plugin/skills/ast-grep/AGENTS.md +51 -0
  589. package/packages/omo-codex/plugin/skills/ast-grep/SKILL.md +1 -1
  590. package/packages/omo-codex/plugin/skills/coding-agent-sessions/AGENTS.md +62 -0
  591. package/packages/omo-codex/plugin/skills/coding-agent-sessions/SKILL.md +3 -2
  592. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  593. package/packages/omo-codex/plugin/skills/coding-agent-sessions/references/senpi.md +4 -4
  594. package/packages/omo-codex/plugin/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  595. package/packages/omo-codex/plugin/skills/data-scientist/SKILL.md +99 -239
  596. package/packages/omo-codex/plugin/skills/data-scientist/references/execution-surfaces.md +91 -0
  597. package/packages/omo-codex/plugin/skills/data-scientist/references/placement.md +74 -0
  598. package/packages/omo-codex/plugin/skills/data-scientist/references/polars-lane.md +95 -0
  599. package/packages/omo-codex/plugin/skills/data-scientist/references/uv-setup.md +1 -1
  600. package/packages/omo-codex/plugin/skills/data-scientist/references/visualization.md +64 -0
  601. package/packages/omo-codex/plugin/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  602. package/packages/omo-codex/plugin/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  603. package/packages/omo-codex/plugin/skills/debugging/SKILL.md +3 -1
  604. package/packages/omo-codex/plugin/skills/debugging/references/methodology/00-setup.md +12 -0
  605. package/packages/omo-codex/plugin/skills/debugging/references/methodology/02-investigate.md +21 -0
  606. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/go.md +15 -1
  607. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/native-binary.md +38 -0
  608. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/node.md +25 -0
  609. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/python.md +13 -0
  610. package/packages/omo-codex/plugin/skills/debugging/references/runtimes/rust.md +41 -0
  611. package/packages/omo-codex/plugin/skills/debugging/references/scripts/dap.mjs +267 -0
  612. package/packages/omo-codex/plugin/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  613. package/packages/omo-codex/plugin/skills/debugging/references/tools/dap.md +103 -0
  614. package/packages/omo-codex/plugin/skills/debugging/references/tools/frida.md +193 -0
  615. package/packages/omo-codex/plugin/skills/frontend/SKILL.md +12 -8
  616. package/packages/omo-codex/plugin/skills/frontend/references/design/_INDEX.md +1 -0
  617. package/packages/omo-codex/plugin/skills/frontend/references/design/print-paged-media.md +76 -0
  618. package/packages/omo-codex/plugin/skills/frontend/references/design/stylegallery.md +80 -0
  619. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/README.md +1 -1
  620. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  621. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  622. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  623. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/orchestration.md +1 -1
  624. package/packages/omo-codex/plugin/skills/frontend/references/designpowers/routing.md +5 -5
  625. package/packages/omo-codex/plugin/skills/git-master/SKILL.md +1 -1
  626. package/packages/omo-codex/plugin/skills/init-deep/SKILL.md +18 -16
  627. package/packages/omo-codex/plugin/skills/lcx-doctor/SKILL.md +4 -2
  628. package/packages/omo-codex/plugin/skills/lsp-setup/SKILL.md +1 -1
  629. package/packages/omo-codex/plugin/skills/programming/SKILL.md +1 -1
  630. package/packages/omo-codex/plugin/skills/refactor/SKILL.md +5 -3
  631. package/packages/omo-codex/plugin/skills/remove-ai-slops/SKILL.md +5 -3
  632. package/packages/omo-codex/plugin/skills/review-work/SKILL.md +114 -422
  633. package/packages/omo-codex/plugin/skills/ultimate-browsing/ATTRIBUTION.md +38 -11
  634. package/packages/omo-codex/plugin/skills/ultimate-browsing/SKILL.md +26 -9
  635. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/AGENTS.md +110 -0
  636. package/packages/omo-codex/plugin/skills/ultimate-browsing/engine/templates/package.json +1 -1
  637. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/chrome-stealth.md +23 -18
  638. package/packages/omo-codex/plugin/skills/ultimate-browsing/references/insane-search/README.md +9 -2
  639. package/packages/omo-codex/plugin/skills/ultrawork/SKILL.md +26 -13
  640. package/packages/omo-codex/plugin/skills/{start-work → ulw-execute}/SKILL.md +26 -28
  641. package/packages/omo-codex/plugin/skills/ulw-execute/agents/openai.yaml +2 -0
  642. package/packages/omo-codex/plugin/skills/ulw-loop/SKILL.md +30 -4
  643. package/packages/omo-codex/plugin/skills/ulw-loop/references/define-goal.md +108 -0
  644. package/packages/omo-codex/plugin/skills/ulw-loop/references/full-workflow.md +32 -8
  645. package/packages/omo-codex/plugin/skills/ulw-plan/SKILL.md +6 -7
  646. package/packages/omo-codex/plugin/skills/ulw-plan/references/full-workflow.md +31 -7
  647. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-clear.md +2 -1
  648. package/packages/omo-codex/plugin/skills/ulw-plan/references/intent-unclear.md +5 -5
  649. package/packages/omo-codex/plugin/skills/ulw-research/SKILL.md +12 -5
  650. package/packages/omo-codex/plugin/skills/visual-qa/AGENTS.md +58 -0
  651. package/packages/omo-codex/plugin/skills/visual-qa/SKILL.md +8 -5
  652. package/packages/omo-codex/plugin/test/AGENTS.md +47 -0
  653. package/packages/omo-codex/plugin/test/aggregate-agents.test.mjs +19 -173
  654. package/packages/omo-codex/plugin/test/aggregate-hooks.test.mjs +16 -51
  655. package/packages/omo-codex/plugin/test/aggregate-manifest.test.mjs +2 -3
  656. package/packages/omo-codex/plugin/test/aggregate-mcp.test.mjs +2 -7
  657. package/packages/omo-codex/plugin/test/aggregate-model-catalog.test.mjs +14 -4
  658. package/packages/omo-codex/plugin/test/aggregate-plugin-fixture.mjs +175 -13
  659. package/packages/omo-codex/plugin/test/aggregate.test.mjs +78 -2
  660. package/packages/omo-codex/plugin/test/auto-update-release-notes.test.mjs +19 -33
  661. package/packages/omo-codex/plugin/test/auto-update.test.mjs +4 -29
  662. package/packages/omo-codex/plugin/test/bootstrap-setup.test.mjs +0 -31
  663. package/packages/omo-codex/plugin/test/canonical-ultrawork-directive.test.mjs +53 -0
  664. package/packages/omo-codex/plugin/test/component-bin-names.test.mjs +2 -2
  665. package/packages/omo-codex/plugin/test/component-bundled-cli.test.mjs +1 -51
  666. package/packages/omo-codex/plugin/test/component-hook-contract-cases.mjs +88 -2
  667. package/packages/omo-codex/plugin/test/hook-status-message.test.mjs +5 -6
  668. package/packages/omo-codex/plugin/test/lcx-contribute-bug-fix-template.test.mjs +21 -27
  669. package/packages/omo-codex/plugin/test/mcp-research-servers.test.mjs +1 -3
  670. package/packages/omo-codex/plugin/test/migrate-codex-config.test.mjs +35 -35
  671. package/packages/omo-codex/plugin/test/multi-agent-v2-regression.test.mjs +1 -1
  672. package/packages/omo-codex/plugin/test/scaffold-plan.test.mjs +0 -36
  673. package/packages/omo-codex/plugin/test/subagent-limit-migration.test.mjs +107 -15
  674. package/packages/omo-codex/plugin/test/sync-skills-codex-compatibility.test.mjs +168 -0
  675. package/packages/omo-codex/plugin/test/sync-skills-test-support.mjs +54 -24
  676. package/packages/omo-codex/plugin/test/sync-skills.test.mjs +18 -119
  677. package/packages/omo-codex/plugin/test/teammode-archive-ambiguity.test.mjs +0 -40
  678. package/packages/omo-codex/plugin/test/teammode-communication.test.mjs +6 -62
  679. package/packages/omo-codex/plugin/test/teammode-thread-links.test.mjs +3 -36
  680. package/packages/omo-codex/plugin/test/teammode-transport.test.mjs +0 -44
  681. package/packages/omo-codex/plugin/test/teammode-worktree.test.mjs +2 -6
  682. package/packages/omo-codex/plugin/test/ultrawork-skill-pointer.test.mjs +5 -5
  683. package/packages/omo-codex/plugin/test/ulw-plan-review-state-contract.test.mjs +0 -3
  684. package/packages/omo-codex/scripts/AGENTS.md +36 -0
  685. package/packages/omo-codex/scripts/check-model-catalog-parity.mjs +42 -0
  686. package/packages/omo-codex/scripts/install-cache-copy.test.mjs +27 -1
  687. package/packages/omo-codex/scripts/install-config-autonomous-features.test.mjs +1 -1
  688. package/packages/omo-codex/scripts/install-config-autonomous.test.mjs +2 -1
  689. package/packages/omo-codex/scripts/install-config-git-bash.test.mjs +0 -23
  690. package/packages/omo-codex/scripts/install-config-reasoning.test.mjs +5 -5
  691. package/packages/omo-codex/scripts/install-config.test.mjs +15 -17
  692. package/packages/omo-codex/scripts/install-dist/install-local.mjs +3028 -1392
  693. package/packages/omo-codex/scripts/install-generated-bundle.test.mjs +3 -4
  694. package/packages/omo-codex/scripts/install-git-bash-mcp-env.test.mjs +1 -25
  695. package/packages/omo-codex/scripts/install-lazycodex-version-stamp.test.mjs +7 -2
  696. package/packages/omo-codex/scripts/install-mcp-runtime.test.mjs +0 -36
  697. package/packages/omo-codex/scripts/install-packaged-local.test.mjs +1 -6
  698. package/packages/{omo-codex/plugin/components/ultrawork/skills/ultrawork/SKILL.md → prompts-core/prompts/ultrawork/codex.md} +26 -20
  699. package/packages/shared-skills/package.json +7 -1
  700. package/packages/shared-skills/skill-source-filter.d.ts +16 -0
  701. package/packages/shared-skills/skill-source-filter.mjs +44 -0
  702. package/packages/shared-skills/skills/ast-grep/AGENTS.md +51 -0
  703. package/packages/shared-skills/skills/ast-grep/SKILL.md +1 -1
  704. package/packages/shared-skills/skills/coding-agent-sessions/AGENTS.md +62 -0
  705. package/packages/shared-skills/skills/coding-agent-sessions/SKILL.md +3 -2
  706. package/packages/shared-skills/skills/coding-agent-sessions/references/all-platforms.md +1 -1
  707. package/packages/shared-skills/skills/coding-agent-sessions/references/senpi.md +4 -4
  708. package/packages/shared-skills/skills/coding-agent-sessions/scripts/agent_sessions/pi_family.py +1 -1
  709. package/packages/shared-skills/skills/data-scientist/SKILL.md +99 -239
  710. package/packages/shared-skills/skills/data-scientist/references/execution-surfaces.md +91 -0
  711. package/packages/shared-skills/skills/data-scientist/references/placement.md +74 -0
  712. package/packages/shared-skills/skills/data-scientist/references/polars-lane.md +95 -0
  713. package/packages/shared-skills/skills/data-scientist/references/uv-setup.md +1 -1
  714. package/packages/shared-skills/skills/data-scientist/references/visualization.md +64 -0
  715. package/packages/shared-skills/skills/data-scientist/scripts/ensure-js-deps.sh +28 -0
  716. package/packages/shared-skills/skills/data-scientist/scripts/ensure-py-deps.sh +37 -0
  717. package/packages/shared-skills/skills/debugging/SKILL.md +3 -1
  718. package/packages/shared-skills/skills/debugging/references/methodology/00-setup.md +12 -0
  719. package/packages/shared-skills/skills/debugging/references/methodology/02-investigate.md +21 -0
  720. package/packages/shared-skills/skills/debugging/references/runtimes/go.md +15 -1
  721. package/packages/shared-skills/skills/debugging/references/runtimes/native-binary.md +38 -0
  722. package/packages/shared-skills/skills/debugging/references/runtimes/node.md +25 -0
  723. package/packages/shared-skills/skills/debugging/references/runtimes/python.md +13 -0
  724. package/packages/shared-skills/skills/debugging/references/runtimes/rust.md +41 -0
  725. package/packages/shared-skills/skills/debugging/references/scripts/dap.mjs +267 -0
  726. package/packages/shared-skills/skills/debugging/references/scripts/dap.test.ts +86 -0
  727. package/packages/shared-skills/skills/debugging/references/scripts/fixture-adapter.mjs +59 -0
  728. package/packages/shared-skills/skills/debugging/references/tools/dap.md +103 -0
  729. package/packages/shared-skills/skills/debugging/references/tools/frida.md +193 -0
  730. package/packages/shared-skills/skills/frontend/SKILL.md +12 -8
  731. package/packages/shared-skills/skills/frontend/references/design/_INDEX.md +1 -0
  732. package/packages/shared-skills/skills/frontend/references/design/print-paged-media.md +76 -0
  733. package/packages/shared-skills/skills/frontend/references/design/stylegallery.md +80 -0
  734. package/packages/shared-skills/skills/frontend/references/designpowers/README.md +1 -1
  735. package/packages/shared-skills/skills/frontend/references/designpowers/lane-a-direction.md +1 -1
  736. package/packages/shared-skills/skills/frontend/references/designpowers/lane-b-execution.md +11 -11
  737. package/packages/shared-skills/skills/frontend/references/designpowers/lane-d-memory.md +3 -3
  738. package/packages/shared-skills/skills/frontend/references/designpowers/orchestration.md +1 -1
  739. package/packages/shared-skills/skills/frontend/references/designpowers/routing.md +5 -5
  740. package/packages/shared-skills/skills/git-master/SKILL.md +1 -1
  741. package/packages/shared-skills/skills/init-deep/SKILL.md +14 -14
  742. package/packages/shared-skills/skills/lsp-setup/SKILL.md +1 -1
  743. package/packages/shared-skills/skills/programming/SKILL.md +1 -1
  744. package/packages/shared-skills/skills/refactor/SKILL.md +1 -1
  745. package/packages/shared-skills/skills/remove-ai-slops/SKILL.md +1 -1
  746. package/packages/shared-skills/skills/review-work/SKILL.md +100 -418
  747. package/packages/shared-skills/skills/ultimate-browsing/ATTRIBUTION.md +38 -11
  748. package/packages/shared-skills/skills/ultimate-browsing/SKILL.md +26 -9
  749. package/packages/shared-skills/skills/ultimate-browsing/engine/AGENTS.md +110 -0
  750. package/packages/shared-skills/skills/ultimate-browsing/engine/templates/package.json +1 -1
  751. package/packages/shared-skills/skills/ultimate-browsing/references/chrome-stealth.md +23 -18
  752. package/packages/shared-skills/skills/ultimate-browsing/references/insane-search/README.md +9 -2
  753. package/packages/shared-skills/skills/{start-work → ulw-execute}/SKILL.md +17 -16
  754. package/packages/shared-skills/skills/ulw-plan/SKILL.md +7 -8
  755. package/packages/shared-skills/skills/ulw-plan/references/full-workflow.md +31 -7
  756. package/packages/shared-skills/skills/ulw-plan/references/intent-clear.md +2 -1
  757. package/packages/shared-skills/skills/ulw-plan/references/intent-unclear.md +5 -5
  758. package/packages/shared-skills/skills/ulw-research/SKILL.md +8 -3
  759. package/packages/shared-skills/skills/visual-qa/AGENTS.md +58 -0
  760. package/packages/shared-skills/skills/visual-qa/SKILL.md +4 -3
  761. package/postinstall.mjs +2 -0
  762. package/script/qa/web-terminal-visual-qa.mjs +2 -0
  763. package/script/qa/xterm-live-terminal.mjs +18 -2
  764. package/dist/config/schema/codegraph.d.ts +0 -12
  765. package/dist/config/schema/start-work.d.ts +0 -5
  766. package/dist/features/builtin-commands/templates/start-work.d.ts +0 -1
  767. package/dist/features/builtin-skills/index.d.ts +0 -1
  768. package/dist/features/builtin-skills/skill-file-loader.d.ts +0 -1
  769. package/dist/features/builtin-skills/skills/agent-browser-skill.d.ts +0 -1
  770. package/dist/features/builtin-skills/skills/agent-browser-template.d.ts +0 -1
  771. package/dist/features/builtin-skills/skills/debugging.d.ts +0 -1
  772. package/dist/features/builtin-skills/skills/dev-browser.d.ts +0 -1
  773. package/dist/features/builtin-skills/skills/frontend.d.ts +0 -1
  774. package/dist/features/builtin-skills/skills/git-master-sections/commit-atomic-planning.d.ts +0 -1
  775. package/dist/features/builtin-skills/skills/git-master-sections/commit-context-analysis.d.ts +0 -1
  776. package/dist/features/builtin-skills/skills/git-master-sections/commit-execution-verification.d.ts +0 -1
  777. package/dist/features/builtin-skills/skills/git-master-sections/commit-workflow.d.ts +0 -1
  778. package/dist/features/builtin-skills/skills/git-master-sections/history-search-workflow.d.ts +0 -1
  779. package/dist/features/builtin-skills/skills/git-master-sections/overview.d.ts +0 -1
  780. package/dist/features/builtin-skills/skills/git-master-sections/quick-reference.d.ts +0 -1
  781. package/dist/features/builtin-skills/skills/git-master-sections/rebase-workflow.d.ts +0 -1
  782. package/dist/features/builtin-skills/skills/git-master-skill-metadata.d.ts +0 -1
  783. package/dist/features/builtin-skills/skills/git-master.d.ts +0 -1
  784. package/dist/features/builtin-skills/skills/index.d.ts +0 -1
  785. package/dist/features/builtin-skills/skills/init-deep.d.ts +0 -1
  786. package/dist/features/builtin-skills/skills/playwright-cli.d.ts +0 -1
  787. package/dist/features/builtin-skills/skills/playwright-mcp-skill.d.ts +0 -1
  788. package/dist/features/builtin-skills/skills/playwright.d.ts +0 -1
  789. package/dist/features/builtin-skills/skills/remove-ai-slops.d.ts +0 -1
  790. package/dist/features/builtin-skills/skills/review-work.d.ts +0 -1
  791. package/dist/features/builtin-skills/skills/security-research.d.ts +0 -1
  792. package/dist/features/builtin-skills/skills/security-review.d.ts +0 -1
  793. package/dist/features/builtin-skills/skills/team-mode.d.ts +0 -1
  794. package/dist/features/builtin-skills/skills/visual-qa.d.ts +0 -1
  795. package/dist/features/builtin-skills/skills.d.ts +0 -1
  796. package/dist/features/builtin-skills/types.d.ts +0 -1
  797. package/dist/features/claude-code-plugin-loader/agent-loader.d.ts +0 -1
  798. package/dist/features/claude-code-plugin-loader/command-loader.d.ts +0 -1
  799. package/dist/features/claude-code-plugin-loader/discovery-core.d.ts +0 -1
  800. package/dist/features/claude-code-plugin-loader/discovery-paths.d.ts +0 -1
  801. package/dist/features/claude-code-plugin-loader/discovery.d.ts +0 -1
  802. package/dist/features/claude-code-plugin-loader/hook-loader.d.ts +0 -1
  803. package/dist/features/claude-code-plugin-loader/index.d.ts +0 -1
  804. package/dist/features/claude-code-plugin-loader/install-path-resolver.d.ts +0 -1
  805. package/dist/features/claude-code-plugin-loader/installed-plugin-database.d.ts +0 -1
  806. package/dist/features/claude-code-plugin-loader/loaded-plugin.d.ts +0 -1
  807. package/dist/features/claude-code-plugin-loader/loader.d.ts +0 -1
  808. package/dist/features/claude-code-plugin-loader/mcp-server-loader.d.ts +0 -1
  809. package/dist/features/claude-code-plugin-loader/plugin-key.d.ts +0 -1
  810. package/dist/features/claude-code-plugin-loader/plugin-manifest.d.ts +0 -1
  811. package/dist/features/claude-code-plugin-loader/plugin-path-resolver.d.ts +0 -1
  812. package/dist/features/claude-code-plugin-loader/plugin-settings.d.ts +0 -1
  813. package/dist/features/claude-code-plugin-loader/scope-filter.d.ts +0 -1
  814. package/dist/features/claude-code-plugin-loader/skill-loader.d.ts +0 -1
  815. package/dist/features/claude-code-plugin-loader/types.d.ts +0 -1
  816. package/dist/hooks/codegraph-bootstrap/command-runner.d.ts +0 -17
  817. package/dist/hooks/codegraph-bootstrap/hook.d.ts +0 -35
  818. package/dist/hooks/codegraph-bootstrap/index.d.ts +0 -1
  819. package/dist/hooks/codegraph-bootstrap/project-root.d.ts +0 -1
  820. package/dist/hooks/codegraph-bootstrap/status.d.ts +0 -11
  821. package/dist/hooks/ralph-loop/completion-promise-detector-test-input.d.ts +0 -11
  822. package/dist/hooks/ralph-loop/loop-session-recovery.d.ts +0 -7
  823. package/dist/hooks/start-work/start-work-hook.d.ts +0 -23
  824. package/dist/mcp/codegraph.d.ts +0 -16
  825. package/dist/plugin/chat-message/start-work-message.d.ts +0 -5
  826. package/dist/shared/prompt-async-gate/message-inspection-error.d.ts +0 -1
  827. package/dist/shared/prompt-async-gate/pending-tool-turn.d.ts +0 -1
  828. package/dist/shared/prompt-async-gate/prompt-message-state.d.ts +0 -1
  829. package/dist/shared/prompt-async-gate/queue.d.ts +0 -1
  830. package/dist/shared/prompt-async-gate/recent-dispatches.d.ts +0 -1
  831. package/dist/shared/prompt-async-gate/reservations.d.ts +0 -1
  832. package/dist/shared/prompt-async-gate/semantic-dedupe.d.ts +0 -1
  833. package/dist/shared/prompt-async-gate/session-idle-dispatch.d.ts +0 -1
  834. package/dist/shared/prompt-async-gate/timing.d.ts +0 -1
  835. package/dist/shared/prompt-async-gate/types.d.ts +0 -1
  836. package/dist/skills/data-scientist/references/common-scenarios.md +0 -176
  837. package/dist/skills/data-scientist/references/execution-templates.md +0 -197
  838. package/dist/skills/data-scientist/references/integration-patterns.md +0 -153
  839. package/dist/skills/data-scientist/references/performance-benchmarks.md +0 -37
  840. package/dist/tools/call-omo-agent/background-agent-executor.d.ts +0 -5
  841. package/dist/tools/call-omo-agent/message-storage-directory.d.ts +0 -1
  842. package/dist/tools/delegate-task/anthropic-categories.d.ts +0 -2
  843. package/dist/tools/delegate-task/model-string-parser.d.ts +0 -1
  844. package/packages/lsp-tools-mcp/dist/lsp/cleanup-errors.d.ts +0 -1
  845. package/packages/lsp-tools-mcp/dist/lsp/constants.d.ts +0 -1
  846. package/packages/lsp-tools-mcp/dist/lsp/language-mappings.d.ts +0 -1
  847. package/packages/lsp-tools-mcp/dist/lsp/process-signal-cleanup.d.ts +0 -1
  848. package/packages/lsp-tools-mcp/dist/missing-dependency-result.d.ts +0 -1
  849. package/packages/omo-codex/plugin/components/codegraph/AGENTS.md +0 -58
  850. package/packages/omo-codex/plugin/components/codegraph/NODE-RUNTIME-LICENSES.md +0 -2951
  851. package/packages/omo-codex/plugin/components/codegraph/NOTICE +0 -16
  852. package/packages/omo-codex/plugin/components/codegraph/dist/cli.js +0 -12136
  853. package/packages/omo-codex/plugin/components/codegraph/dist/serve.js +0 -9734
  854. package/packages/omo-codex/plugin/components/codegraph/package.json +0 -33
  855. package/packages/omo-codex/plugin/components/codegraph/src/cache-gc.ts +0 -29
  856. package/packages/omo-codex/plugin/components/codegraph/src/cli.ts +0 -79
  857. package/packages/omo-codex/plugin/components/codegraph/src/hook-input.ts +0 -33
  858. package/packages/omo-codex/plugin/components/codegraph/src/hook-sweep.ts +0 -25
  859. package/packages/omo-codex/plugin/components/codegraph/src/hook-types.ts +0 -131
  860. package/packages/omo-codex/plugin/components/codegraph/src/hook.ts +0 -258
  861. package/packages/omo-codex/plugin/components/codegraph/src/mcp-bridge.ts +0 -309
  862. package/packages/omo-codex/plugin/components/codegraph/src/mcp-unavailable.ts +0 -80
  863. package/packages/omo-codex/plugin/components/codegraph/src/post-tool-use-hook.ts +0 -34
  864. package/packages/omo-codex/plugin/components/codegraph/src/serve-invocation.ts +0 -29
  865. package/packages/omo-codex/plugin/components/codegraph/src/serve.ts +0 -263
  866. package/packages/omo-codex/plugin/components/codegraph/src/session-start-command.ts +0 -106
  867. package/packages/omo-codex/plugin/components/codegraph/src/session-start-cooldown.ts +0 -145
  868. package/packages/omo-codex/plugin/components/codegraph/src/session-start-hook-runtime.ts +0 -21
  869. package/packages/omo-codex/plugin/components/codegraph/src/session-start-lock.ts +0 -139
  870. package/packages/omo-codex/plugin/components/codegraph/src/session-start-outcome.ts +0 -15
  871. package/packages/omo-codex/plugin/components/codegraph/src/session-start-paths.ts +0 -32
  872. package/packages/omo-codex/plugin/components/codegraph/src/session-start-project.ts +0 -109
  873. package/packages/omo-codex/plugin/components/codegraph/src/session-start-worker-result.ts +0 -148
  874. package/packages/omo-codex/plugin/components/codegraph/src/session-start-worker.ts +0 -175
  875. package/packages/omo-codex/plugin/components/codegraph/src/sweep-cli.ts +0 -81
  876. package/packages/omo-codex/plugin/components/codegraph/test/cache-gc.test.ts +0 -34
  877. package/packages/omo-codex/plugin/components/codegraph/test/hook-exclusion.test.ts +0 -112
  878. package/packages/omo-codex/plugin/components/codegraph/test/hook-registration.test.ts +0 -26
  879. package/packages/omo-codex/plugin/components/codegraph/test/hook-session-start-guard.test.ts +0 -160
  880. package/packages/omo-codex/plugin/components/codegraph/test/hook-store-upgrade.test.ts +0 -50
  881. package/packages/omo-codex/plugin/components/codegraph/test/hook-sweep.test.ts +0 -29
  882. package/packages/omo-codex/plugin/components/codegraph/test/hook.test.ts +0 -320
  883. package/packages/omo-codex/plugin/components/codegraph/test/mcp-bridge-fixtures.ts +0 -172
  884. package/packages/omo-codex/plugin/components/codegraph/test/package-runtime.test.ts +0 -91
  885. package/packages/omo-codex/plugin/components/codegraph/test/provisioned-node-guard.test.ts +0 -100
  886. package/packages/omo-codex/plugin/components/codegraph/test/serve-built-wrapper.test.ts +0 -76
  887. package/packages/omo-codex/plugin/components/codegraph/test/serve-mcp-bridge-lifecycle.test.ts +0 -133
  888. package/packages/omo-codex/plugin/components/codegraph/test/serve-mcp-bridge.test.ts +0 -245
  889. package/packages/omo-codex/plugin/components/codegraph/test/serve-mcp-facade.test.ts +0 -69
  890. package/packages/omo-codex/plugin/components/codegraph/test/serve-node-support.test.ts +0 -43
  891. package/packages/omo-codex/plugin/components/codegraph/test/serve-provision.test.ts +0 -147
  892. package/packages/omo-codex/plugin/components/codegraph/test/serve-unavailable.test.ts +0 -175
  893. package/packages/omo-codex/plugin/components/codegraph/test/serve.test.ts +0 -385
  894. package/packages/omo-codex/plugin/components/codegraph/test/session-start-node-support.test.ts +0 -206
  895. package/packages/omo-codex/plugin/components/codegraph/test/session-start-project.test.ts +0 -58
  896. package/packages/omo-codex/plugin/components/codegraph/test/session-start-state.test.ts +0 -104
  897. package/packages/omo-codex/plugin/components/codegraph/test/session-start-trust-boundary.test.ts +0 -65
  898. package/packages/omo-codex/plugin/components/codegraph/test/session-start-worker-availability.test.ts +0 -106
  899. package/packages/omo-codex/plugin/components/codegraph/test/session-start-worker-cooldown.test.ts +0 -116
  900. package/packages/omo-codex/plugin/components/codegraph/test/session-start-worker-flow.test.ts +0 -258
  901. package/packages/omo-codex/plugin/components/codegraph/test/sweep-cli.test.ts +0 -56
  902. package/packages/omo-codex/plugin/components/codegraph/tsconfig.build.json +0 -13
  903. package/packages/omo-codex/plugin/components/codegraph/tsconfig.json +0 -25
  904. package/packages/omo-codex/plugin/components/start-work-continuation/LICENSE +0 -21
  905. package/packages/omo-codex/plugin/components/start-work-continuation/hooks/hooks.json +0 -28
  906. package/packages/omo-codex/plugin/components/ultrawork/directive.md +0 -471
  907. package/packages/omo-codex/plugin/hooks/post-tool-use-checking-codegraph-init-guidance.json +0 -18
  908. package/packages/omo-codex/plugin/hooks/session-start-checking-codegraph-bootstrap.json +0 -17
  909. package/packages/omo-codex/plugin/hooks/stop-checking-start-work-continuation.json +0 -17
  910. package/packages/omo-codex/plugin/hooks/subagent-stop-checking-start-work-continuation.json +0 -17
  911. package/packages/omo-codex/plugin/scripts/migrate-omo-sot/editor.mjs +0 -125
  912. package/packages/omo-codex/plugin/scripts/migrate-omo-sot/jsonc.mjs +0 -43
  913. package/packages/omo-codex/plugin/scripts/migrate-omo-sot/scaffold.mjs +0 -29
  914. package/packages/omo-codex/plugin/scripts/migrate-omo-sot.mjs +0 -121
  915. package/packages/omo-codex/plugin/skills/data-scientist/references/common-scenarios.md +0 -176
  916. package/packages/omo-codex/plugin/skills/data-scientist/references/execution-templates.md +0 -197
  917. package/packages/omo-codex/plugin/skills/data-scientist/references/integration-patterns.md +0 -153
  918. package/packages/omo-codex/plugin/skills/data-scientist/references/performance-benchmarks.md +0 -37
  919. package/packages/omo-codex/plugin/skills/start-work/agents/openai.yaml +0 -2
  920. package/packages/omo-codex/plugin/test/aggregate-skills.test.mjs +0 -92
  921. package/packages/omo-codex/plugin/test/component-codegraph-mcp-smoke.test.mjs +0 -76
  922. package/packages/omo-codex/plugin/test/migrate-omo-sot.test.mjs +0 -179
  923. package/packages/omo-codex/plugin/test/sync-skills-orchestration.test.mjs +0 -314
  924. package/packages/omo-codex/plugin/test/ulw-plan-scope-contract.test.mjs +0 -24
  925. package/packages/shared-skills/skills/data-scientist/references/common-scenarios.md +0 -176
  926. package/packages/shared-skills/skills/data-scientist/references/execution-templates.md +0 -197
  927. package/packages/shared-skills/skills/data-scientist/references/integration-patterns.md +0 -153
  928. package/packages/shared-skills/skills/data-scientist/references/performance-benchmarks.md +0 -37
  929. /package/dist/hooks/{start-work → ulw-execute}/context-info-formatters.d.ts +0 -0
  930. /package/dist/hooks/{start-work → ulw-execute}/explicit-plan-context.d.ts +0 -0
  931. /package/dist/hooks/{start-work → ulw-execute}/notepad-scaffold.d.ts +0 -0
  932. /package/dist/hooks/{start-work → ulw-execute}/parse-user-request.d.ts +0 -0
  933. /package/dist/hooks/{start-work → ulw-execute}/plan-discovery-context.d.ts +0 -0
  934. /package/dist/hooks/{start-work → ulw-execute}/plan-selection.d.ts +0 -0
  935. /package/dist/hooks/{start-work → ulw-execute}/session-plan-affinity.d.ts +0 -0
  936. /package/dist/hooks/{start-work → ulw-execute}/work-initializer.d.ts +0 -0
  937. /package/dist/hooks/{start-work → ulw-execute}/worktree-block.d.ts +0 -0
  938. /package/dist/hooks/{start-work → ulw-execute}/worktree-detector.d.ts +0 -0
  939. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/.gitattributes +0 -0
  940. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/CHANGELOG.md +0 -0
  941. /package/packages/omo-codex/plugin/components/{codegraph → ulw-execute-continuation}/LICENSE +0 -0
  942. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/src/plan-checklist.ts +0 -0
  943. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-completed.json +0 -0
  944. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-mixed-platforms.json +0 -0
  945. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/boulder-single-codex-work.json +0 -0
  946. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-all-done.md +0 -0
  947. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-scaffold.md +0 -0
  948. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-nested-checkboxes.md +0 -0
  949. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/test/fixtures/plan-with-unchecked.md +0 -0
  950. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.build.json +0 -0
  951. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/tsconfig.json +0 -0
  952. /package/packages/omo-codex/plugin/components/{start-work-continuation → ulw-execute-continuation}/vitest.config.ts +0 -0
@@ -1,18 +1,4 @@
1
1
  #!/usr/bin/env node
2
- var __defProp = Object.defineProperty;
3
- var __returnValue = (v) => v;
4
- function __exportSetter(name, newValue) {
5
- this[name] = __returnValue.bind(null, newValue);
6
- }
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, {
10
- get: all[name],
11
- enumerable: true,
12
- configurable: true,
13
- set: __exportSetter.bind(all, name)
14
- });
15
- };
16
2
 
17
3
  // components/telemetry/src/cli.ts
18
4
  import { stdin as processStdin, stdout as processStdout } from "node:process";
@@ -27,9 +13,12 @@ import {
27
13
  fsyncSync,
28
14
  openSync,
29
15
  renameSync,
16
+ rmSync,
30
17
  unlinkSync,
31
18
  writeFileSync
32
19
  } from "node:fs";
20
+ import { randomUUID } from "node:crypto";
21
+ import { dirname } from "node:path";
33
22
  var TOLERATED_FSYNC_CODES = new Set([
34
23
  "EPERM",
35
24
  "EACCES",
@@ -51,24 +40,36 @@ function tolerantFsyncSync(fileDescriptor, fsyncImpl) {
51
40
  }
52
41
  }
53
42
  function writeFileAtomically(filePath, content, options = {}) {
54
- const tempPath = `${filePath}.tmp`;
55
- writeFileSync(tempPath, content, "utf-8");
56
- const tempFileDescriptor = openSync(tempPath, "r+");
57
- try {
58
- tolerantFsyncSync(tempFileDescriptor, options.fsyncSync ?? fsyncSync);
59
- } finally {
60
- closeSync(tempFileDescriptor);
61
- }
43
+ const platform = options.platform ?? process.platform;
44
+ const fsyncImpl = options.fsyncSync ?? fsyncSync;
45
+ const tempPath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
62
46
  try {
63
- renameSync(tempPath, filePath);
64
- } catch (error) {
65
- const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));
66
- if ((options.platform ?? process.platform) === "win32" && isPermissionError) {
47
+ writeFileSync(tempPath, content, "utf-8");
48
+ const tempFileDescriptor = openSync(tempPath, "r+");
49
+ try {
50
+ tolerantFsyncSync(tempFileDescriptor, fsyncImpl);
51
+ } finally {
52
+ closeSync(tempFileDescriptor);
53
+ }
54
+ try {
55
+ renameSync(tempPath, filePath);
56
+ } catch (error) {
57
+ const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));
58
+ if (platform !== "win32" || !isPermissionError)
59
+ throw error;
67
60
  unlinkSync(filePath);
68
61
  renameSync(tempPath, filePath);
62
+ }
63
+ if (platform === "win32")
69
64
  return;
65
+ const directoryFileDescriptor = openSync(dirname(filePath), "r");
66
+ try {
67
+ tolerantFsyncSync(directoryFileDescriptor, fsyncImpl);
68
+ } finally {
69
+ closeSync(directoryFileDescriptor);
70
70
  }
71
- throw error;
71
+ } finally {
72
+ rmSync(tempPath, { force: true });
72
73
  }
73
74
  }
74
75
 
@@ -174,6 +175,7 @@ function writePostHogActivityState(stateDir, nextState, diagnostics) {
174
175
  // ../../telemetry-core/src/constants.ts
175
176
  var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
176
177
  var DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74";
178
+ var UNCONFIGURED_POSTHOG_API_KEY = "phc_REPLACE_ME_OMO_NATIVE";
177
179
 
178
180
  // ../../telemetry-core/src/diagnostics.ts
179
181
  import { appendFileSync, existsSync as existsSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync2 } from "node:fs";
@@ -310,6 +312,9 @@ function shouldDisableTelemetry(input) {
310
312
  const env = input.env ?? process.env;
311
313
  const globalPrefix = input.globalEnvPrefix ?? "OMO";
312
314
  const prefixes = Array.from(new Set([globalPrefix, input.productEnvPrefix]));
315
+ if (isDisableFlag(env["DO_NOT_TRACK"])) {
316
+ return true;
317
+ }
313
318
  for (const prefix of prefixes) {
314
319
  if (isDisableFlag(env[`${prefix}_DISABLE_POSTHOG`])) {
315
320
  return true;
@@ -323,22 +328,19 @@ function shouldDisableTelemetry(input) {
323
328
  function getTelemetryApiKey(env = process.env, defaultApiKey = DEFAULT_POSTHOG_API_KEY) {
324
329
  return env["POSTHOG_API_KEY"]?.trim() ?? defaultApiKey;
325
330
  }
326
- function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST) {
327
- return env["POSTHOG_HOST"]?.trim() || defaultHost;
331
+ function isConfiguredTelemetryApiKey(apiKey) {
332
+ const normalized = apiKey.trim();
333
+ return normalized.length > 0 && normalized !== UNCONFIGURED_POSTHOG_API_KEY;
328
334
  }
329
-
330
- // ../../telemetry-core/src/machine-id.ts
331
- import { createHash } from "node:crypto";
332
- import os2 from "node:os";
333
- function getDefaultTelemetryOsProvider() {
334
- return os2;
335
+ function hasTelemetryApiKey(env, defaultApiKey) {
336
+ return isConfiguredTelemetryApiKey(getTelemetryApiKey(env, defaultApiKey));
335
337
  }
336
- function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
337
- return createHash("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
338
+ function getTelemetryHost(env = process.env, defaultHost = DEFAULT_POSTHOG_HOST) {
339
+ return env["POSTHOG_HOST"]?.trim() || defaultHost;
338
340
  }
339
341
 
340
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
341
- import { dirname, posix, sep } from "node:path";
342
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs
343
+ import { dirname as dirname2, posix, sep } from "node:path";
342
344
  function createModulerModifier() {
343
345
  const getModuleFromFileName = createGetModuleFromFilename();
344
346
  return async (frames) => {
@@ -347,7 +349,7 @@ function createModulerModifier() {
347
349
  return frames;
348
350
  };
349
351
  }
350
- function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
352
+ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname2(process.argv[1]) : process.cwd(), isWindows = sep === "\\") {
351
353
  const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;
352
354
  return (filename) => {
353
355
  if (!filename)
@@ -369,11 +371,11 @@ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname(proces
369
371
  return decodedFile;
370
372
  };
371
373
  }
372
- function normalizeWindowsPath(path2) {
373
- return path2.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
374
+ function normalizeWindowsPath(path) {
375
+ return path.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
374
376
  }
375
377
 
376
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/featureFlagUtils.mjs
378
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/featureFlagUtils.mjs
377
379
  var normalizeFlagsResponse = (flagsResponse) => {
378
380
  if ("flags" in flagsResponse) {
379
381
  const featureFlags = getFlagValuesFromFlags(flagsResponse.flags);
@@ -443,8 +445,69 @@ var parsePayload = (response) => {
443
445
  return response;
444
446
  }
445
447
  };
448
+ var MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES = [
449
+ "utm_source",
450
+ "utm_medium",
451
+ "utm_campaign",
452
+ "utm_content",
453
+ "utm_term",
454
+ "gad_source",
455
+ "mc_cid",
456
+ "gclid",
457
+ "gclsrc",
458
+ "dclid",
459
+ "gbraid",
460
+ "wbraid",
461
+ "fbclid",
462
+ "msclkid",
463
+ "twclid",
464
+ "li_fat_id",
465
+ "igshid",
466
+ "ttclid",
467
+ "rdt_cid",
468
+ "epik",
469
+ "qclid",
470
+ "sccid",
471
+ "irclid",
472
+ "_kx"
473
+ ];
474
+ var MINIMAL_FLAG_CALLED_EVENT_PROPERTIES = [
475
+ "$feature_flag",
476
+ "$feature_flag_response",
477
+ "$feature_flag_has_experiment",
478
+ "$feature_flag_id",
479
+ "$feature_flag_version",
480
+ "$feature_flag_reason",
481
+ "$feature_flag_request_id",
482
+ "$feature_flag_evaluated_at",
483
+ "$feature_flag_error",
484
+ "locally_evaluated",
485
+ "$groups",
486
+ "$process_person_profile",
487
+ "$geoip_disable",
488
+ "$current_url",
489
+ "$pathname",
490
+ "$referring_domain",
491
+ ...MINIMAL_FLAG_CALLED_EVENT_CAMPAIGN_PROPERTIES,
492
+ "$session_id",
493
+ "$window_id",
494
+ "$lib",
495
+ "$lib_version",
496
+ "$device_id",
497
+ "$is_server"
498
+ ];
499
+ var minimizeFlagCalledEventProperties = (properties, transportKeys = []) => {
500
+ const minimal = {};
501
+ const copyKey = (key) => {
502
+ if (properties[key] !== undefined)
503
+ minimal[key] = properties[key];
504
+ };
505
+ MINIMAL_FLAG_CALLED_EVENT_PROPERTIES.forEach(copyKey);
506
+ transportKeys.forEach(copyKey);
507
+ return minimal;
508
+ };
446
509
 
447
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/types.mjs
510
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/types.mjs
448
511
  var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedProperty) {
449
512
  PostHogPersistedProperty["AnonymousId"] = "anonymous_id";
450
513
  PostHogPersistedProperty["DistinctId"] = "distinct_id";
@@ -459,6 +522,8 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
459
522
  PostHogPersistedProperty["BootstrapFeatureFlagPayloads"] = "bootstrap_feature_flag_payloads";
460
523
  PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
461
524
  PostHogPersistedProperty["Queue"] = "queue";
525
+ PostHogPersistedProperty["AiQueue"] = "ai_queue";
526
+ PostHogPersistedProperty["AiCaptureQueue"] = "ai_capture_queue";
462
527
  PostHogPersistedProperty["LogsQueue"] = "logs_queue";
463
528
  PostHogPersistedProperty["OptedOut"] = "opted_out";
464
529
  PostHogPersistedProperty["SessionId"] = "session_id";
@@ -469,6 +534,8 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
469
534
  PostHogPersistedProperty["InstalledAppBuild"] = "installed_app_build";
470
535
  PostHogPersistedProperty["InstalledAppVersion"] = "installed_app_version";
471
536
  PostHogPersistedProperty["SessionReplay"] = "session_replay";
537
+ PostHogPersistedProperty["PushRegistered"] = "push_registered";
538
+ PostHogPersistedProperty["SessionReplayEventTriggerActivatedSession"] = "session_replay_event_trigger_activated_session";
472
539
  PostHogPersistedProperty["SurveyLastSeenDate"] = "survey_last_seen_date";
473
540
  PostHogPersistedProperty["SurveysSeen"] = "surveys_seen";
474
541
  PostHogPersistedProperty["Surveys"] = "surveys";
@@ -478,7 +545,7 @@ var types_PostHogPersistedProperty = /* @__PURE__ */ function(PostHogPersistedPr
478
545
  return PostHogPersistedProperty;
479
546
  }({});
480
547
 
481
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/gzip.mjs
548
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/gzip.mjs
482
549
  function isGzipSupported() {
483
550
  return "CompressionStream" in globalThis && "TextEncoder" in globalThis && "Response" in globalThis && typeof Response.prototype.blob == "function";
484
551
  }
@@ -528,7 +595,7 @@ var validateNativeGzip = async (compressed, inputBytes) => {
528
595
  async function gzipCompress(input, isDebug = true, options) {
529
596
  try {
530
597
  const inputBytes = new TextEncoder().encode(input);
531
- const compressedStream = new CompressionStream("gzip");
598
+ const compressedStream = new globalThis.CompressionStream("gzip");
532
599
  const writer = compressedStream.writable.getWriter();
533
600
  const writePromise = writer.write(inputBytes).then(() => writer.close()).catch(async (err) => {
534
601
  try {
@@ -552,7 +619,34 @@ async function gzipCompress(input, isDebug = true, options) {
552
619
  }
553
620
  }
554
621
 
555
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bot-detection.mjs
622
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/json-utils.mjs
623
+ var MAX_JSON_SAFE_VALUE_DEPTH = 20;
624
+ var MAX_JSON_SAFE_VALUE_ITEMS = 1000;
625
+ var MAX_JSON_SAFE_VALUE_NODES = 1e4;
626
+ var CIRCULAR_VALUE = "[Circular]";
627
+ var TRUNCATED_VALUE = "[Truncated]";
628
+ var UNSERIALIZABLE_VALUE = "[Unserializable]";
629
+ var FUNCTION_VALUE = "[Function]";
630
+ var dateGetTime = Date.prototype.getTime;
631
+ var dateToISOString = Date.prototype.toISOString;
632
+ function sanitizeString(value) {
633
+ let output = "";
634
+ for (let index = 0;index < value.length; index++) {
635
+ const codeUnit = value.charCodeAt(index);
636
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
637
+ const nextCodeUnit = value.charCodeAt(index + 1);
638
+ if (nextCodeUnit >= 56320 && nextCodeUnit <= 57343) {
639
+ output += value[index] + value[index + 1];
640
+ index++;
641
+ } else
642
+ output += "�";
643
+ } else
644
+ output += codeUnit >= 56320 && codeUnit <= 57343 ? "�" : value[index];
645
+ }
646
+ return output;
647
+ }
648
+
649
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bot-detection.mjs
556
650
  var DEFAULT_BLOCKED_UA_STRS = [
557
651
  "amazonbot",
558
652
  "amazonproductbot",
@@ -641,7 +735,31 @@ var isBlockedUA = function(ua, customBlockedUserAgents = []) {
641
735
  return uaLower.indexOf(blockedUaLower) !== -1;
642
736
  });
643
737
  };
644
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/type-utils.mjs
738
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/string-utils.mjs
739
+ function safeJsonStringify(value) {
740
+ const ancestors = [];
741
+ return JSON.stringify(value, function(_key, replacementValue) {
742
+ if (typeof replacementValue == "bigint")
743
+ return replacementValue.toString();
744
+ if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
745
+ return;
746
+ if (replacementValue instanceof Error)
747
+ return {
748
+ name: replacementValue.name,
749
+ message: replacementValue.message,
750
+ stack: replacementValue.stack
751
+ };
752
+ if (replacementValue && typeof replacementValue == "object") {
753
+ while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this)
754
+ ancestors.pop();
755
+ if (ancestors.includes(replacementValue))
756
+ return "[Circular]";
757
+ ancestors.push(replacementValue);
758
+ }
759
+ return replacementValue;
760
+ }) ?? "null";
761
+ }
762
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/type-utils.mjs
645
763
  var nativeIsArray = Array.isArray;
646
764
  var ObjProto = Object.prototype;
647
765
  var type_utils_hasOwnProperty = ObjProto.hasOwnProperty;
@@ -653,16 +771,27 @@ var isObject = (x) => x === Object(x) && !isArray(x);
653
771
  var isUndefined = (x) => x === undefined;
654
772
  var isString = (x) => type_utils_toString.call(x) == "[object String]";
655
773
  var isEmptyString = (x) => isString(x) && x.trim().length === 0;
774
+ var isNull = (x) => x === null;
775
+ var isNullish = (x) => isUndefined(x) || isNull(x);
656
776
  var isNumber = (x) => type_utils_toString.call(x) == "[object Number]" && x === x;
657
- var isPlainError = (x) => x instanceof Error;
777
+ var isBoolean = (x) => type_utils_toString.call(x) === "[object Boolean]";
658
778
  function isPrimitive(value) {
659
779
  return value === null || typeof value != "object";
660
780
  }
661
781
  function isBuiltin(candidate, className) {
662
782
  return Object.prototype.toString.call(candidate) === `[object ${className}]`;
663
783
  }
664
- function isErrorEvent(event) {
665
- return isBuiltin(event, "ErrorEvent");
784
+ function isError(candidate) {
785
+ switch (Object.prototype.toString.call(candidate)) {
786
+ case "[object Error]":
787
+ case "[object Exception]":
788
+ case "[object DOMException]":
789
+ case "[object DOMError]":
790
+ case "[object WebAssembly.Exception]":
791
+ return true;
792
+ default:
793
+ return isInstanceOf(candidate, Error);
794
+ }
666
795
  }
667
796
  function isEvent(candidate) {
668
797
  return typeof Event != "undefined" && isInstanceOf(candidate, Event);
@@ -678,7 +807,7 @@ function isInstanceOf(candidate, base) {
678
807
  }
679
808
  }
680
809
 
681
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/number-utils.mjs
810
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/number-utils.mjs
682
811
  function clampToRange(value, min, max, logger, fallbackValue) {
683
812
  if (min > max) {
684
813
  logger.warn("min cannot be greater than max.");
@@ -698,8 +827,16 @@ function clampToRange(value, min, max, logger, fallbackValue) {
698
827
  return clampToRange(fallbackValue || max, min, max, logger);
699
828
  }
700
829
 
701
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
830
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/bucketed-rate-limiter.mjs
702
831
  var ONE_DAY_IN_MS = 86400000;
832
+ var DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE = 1;
833
+ var DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE = 10;
834
+ function resolveExceptionRateLimiterConfig(config = {}) {
835
+ return {
836
+ refillRate: config.exceptionRateLimiterRefillRate ?? config.__exceptionRateLimiterRefillRate ?? DEFAULT_EXCEPTION_RATE_LIMITER_REFILL_RATE,
837
+ bucketSize: config.exceptionRateLimiterBucketSize ?? config.__exceptionRateLimiterBucketSize ?? DEFAULT_EXCEPTION_RATE_LIMITER_BUCKET_SIZE
838
+ };
839
+ }
703
840
 
704
841
  class BucketedRateLimiter {
705
842
  constructor(options) {
@@ -742,7 +879,7 @@ class BucketedRateLimiter {
742
879
  this._buckets = {};
743
880
  }
744
881
  }
745
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
882
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/vendor/uuidv7.mjs
746
883
  /*! For license information please see uuidv7.mjs.LICENSE.txt */
747
884
  var DIGITS = "0123456789abcdef";
748
885
 
@@ -920,33 +1057,45 @@ var defaultGenerator;
920
1057
  var uuidv7 = () => uuidv7obj().toString();
921
1058
  var uuidv7obj = () => (defaultGenerator || (defaultGenerator = new V7Generator)).generate();
922
1059
 
923
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/promise-queue.mjs
1060
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/promise-queue.mjs
924
1061
  class PromiseQueue {
925
1062
  add(promise) {
926
1063
  const promiseUUID = uuidv7();
927
- this.promiseByIds[promiseUUID] = promise;
1064
+ const id = ++this.nextId;
1065
+ this.promiseByIds[promiseUUID] = {
1066
+ id,
1067
+ promise
1068
+ };
928
1069
  promise.catch(() => {}).finally(() => {
929
1070
  delete this.promiseByIds[promiseUUID];
930
1071
  });
931
1072
  return promise;
932
1073
  }
933
1074
  async join() {
934
- let promises = Object.values(this.promiseByIds);
1075
+ let promises = Object.values(this.promiseByIds).map((item) => item.promise);
935
1076
  let length = promises.length;
936
1077
  while (length > 0) {
937
1078
  await Promise.all(promises);
938
- promises = Object.values(this.promiseByIds);
1079
+ promises = Object.values(this.promiseByIds).map((item) => item.promise);
939
1080
  length = promises.length;
940
1081
  }
941
1082
  }
1083
+ getPromises(ignoredPromises = [], maxId = this.nextId) {
1084
+ const ignoredPromiseSet = new Set(ignoredPromises);
1085
+ return Object.values(this.promiseByIds).filter((item) => item.id <= maxId && !ignoredPromiseSet.has(item.promise)).map((item) => item.promise);
1086
+ }
1087
+ get maxId() {
1088
+ return this.nextId;
1089
+ }
942
1090
  get length() {
943
1091
  return Object.keys(this.promiseByIds).length;
944
1092
  }
945
1093
  constructor() {
946
1094
  this.promiseByIds = {};
1095
+ this.nextId = 0;
947
1096
  }
948
1097
  }
949
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/logger.mjs
1098
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/logger.mjs
950
1099
  function createConsole(consoleLike = console) {
951
1100
  const lockedMethods = {
952
1101
  log: consoleLike.log.bind(consoleLike),
@@ -987,7 +1136,7 @@ var passThrough = (fn) => fn();
987
1136
  function createLogger(prefix, maybeCall = passThrough) {
988
1137
  return _createLogger(prefix, maybeCall, createConsole());
989
1138
  }
990
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
1139
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/user-agent-utils.mjs
991
1140
  var MOBILE = "Mobile";
992
1141
  var IOS = "iOS";
993
1142
  var ANDROID = "Android";
@@ -1030,6 +1179,7 @@ var DUCKDUCKGO = "DuckDuckGo";
1030
1179
  var PALE_MOON = "Pale Moon";
1031
1180
  var WATERFOX = "Waterfox";
1032
1181
  var BRAVE = "Brave";
1182
+ var GOOGLE_SEARCH_APP = "Google Search App";
1033
1183
  var BROWSER_VERSION_REGEX_SUFFIX = "(\\d+(\\.\\d+)?)";
1034
1184
  var DEFAULT_BROWSER_VERSION_REGEX = new RegExp("Version/" + BROWSER_VERSION_REGEX_SUFFIX);
1035
1185
  var XBOX_REGEX = new RegExp(XBOX, "i");
@@ -1117,6 +1267,9 @@ var versionRegexes = {
1117
1267
  [WATERFOX]: [
1118
1268
  new RegExp(WATERFOX + "\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1119
1269
  ],
1270
+ [GOOGLE_SEARCH_APP]: [
1271
+ new RegExp("GSA\\/" + BROWSER_VERSION_REGEX_SUFFIX)
1272
+ ],
1120
1273
  [INTERNET_EXPLORER]: [
1121
1274
  new RegExp("(rv:|MSIE )" + BROWSER_VERSION_REGEX_SUFFIX)
1122
1275
  ],
@@ -1276,8 +1429,15 @@ var osMatchers = [
1276
1429
  ]
1277
1430
  ];
1278
1431
 
1279
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/utils/index.mjs
1432
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/utils/index.mjs
1280
1433
  var STRING_FORMAT = "utf8";
1434
+ var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1435
+ function isValidUUID(value) {
1436
+ return typeof value == "string" && UUID_REGEX.test(value);
1437
+ }
1438
+ function getEventUuid(uuid, generateUuid) {
1439
+ return isValidUUID(uuid) ? uuid : generateUuid();
1440
+ }
1281
1441
  function removeTrailingSlash(url) {
1282
1442
  return url?.replace(/\/+$/, "");
1283
1443
  }
@@ -1305,7 +1465,26 @@ function safeSetTimeout(fn, timeout) {
1305
1465
  t?.unref && t?.unref();
1306
1466
  return t;
1307
1467
  }
1308
- var isError = (x) => x instanceof Error;
1468
+ async function raceWithTimeout(promise, timeoutMs, onTimeout) {
1469
+ let timeoutHandle;
1470
+ try {
1471
+ return await Promise.race([
1472
+ promise,
1473
+ new Promise((resolve, reject) => {
1474
+ timeoutHandle = safeSetTimeout(() => {
1475
+ try {
1476
+ onTimeout?.();
1477
+ resolve();
1478
+ } catch (error) {
1479
+ reject(error);
1480
+ }
1481
+ }, timeoutMs);
1482
+ })
1483
+ ]);
1484
+ } finally {
1485
+ clearTimeout(timeoutHandle);
1486
+ }
1487
+ }
1309
1488
  function allSettled(promises) {
1310
1489
  return Promise.all(promises.map((p) => (p ?? Promise.resolve()).then((value) => ({
1311
1490
  status: "fulfilled",
@@ -1316,7 +1495,7 @@ function allSettled(promises) {
1316
1495
  }))));
1317
1496
  }
1318
1497
 
1319
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1498
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/logs/logs-utils.mjs
1320
1499
  var OTLP_SEVERITY_MAP = {
1321
1500
  trace: {
1322
1501
  text: "TRACE",
@@ -1344,7 +1523,570 @@ var OTLP_SEVERITY_MAP = {
1344
1523
  }
1345
1524
  };
1346
1525
  var DEFAULT_OTLP_SEVERITY = OTLP_SEVERITY_MAP.info;
1347
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/eventemitter.mjs
1526
+ var INT64_RANGE_LIMIT = 9223372036854776000;
1527
+ var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
1528
+ function newState() {
1529
+ return {
1530
+ ancestors: new WeakSet,
1531
+ remainingNodes: MAX_JSON_SAFE_VALUE_NODES
1532
+ };
1533
+ }
1534
+ function toOtlpKeyValueList(attrs, logger) {
1535
+ try {
1536
+ return encodeKeyValueList(attrs, logger, newState(), 0);
1537
+ } catch {
1538
+ return [];
1539
+ }
1540
+ }
1541
+ function encodeAnyValue(value, logger, state, depth) {
1542
+ if (state.remainingNodes <= 0)
1543
+ return {
1544
+ stringValue: TRUNCATED_VALUE
1545
+ };
1546
+ state.remainingNodes--;
1547
+ if (isBoolean(value))
1548
+ return {
1549
+ boolValue: value
1550
+ };
1551
+ if (typeof value == "number") {
1552
+ if (!Number.isFinite(value))
1553
+ return {
1554
+ stringValue: String(value)
1555
+ };
1556
+ if (Number.isInteger(value)) {
1557
+ if (Number.isSafeInteger(value))
1558
+ return {
1559
+ intValue: String(value)
1560
+ };
1561
+ if (typeof BigInt == "undefined")
1562
+ return {
1563
+ stringValue: String(value)
1564
+ };
1565
+ const decimal = BigInt(value).toString();
1566
+ if (value >= INT64_RANGE_LIMIT || value < -INT64_RANGE_LIMIT) {
1567
+ logger?.debug(`Attribute ${decimal} is outside the int64 range; encoding it as a string`);
1568
+ return {
1569
+ stringValue: decimal
1570
+ };
1571
+ }
1572
+ return {
1573
+ intValue: decimal
1574
+ };
1575
+ }
1576
+ return {
1577
+ doubleValue: value
1578
+ };
1579
+ }
1580
+ if (typeof value == "string")
1581
+ return {
1582
+ stringValue: sanitizeString(value)
1583
+ };
1584
+ if (typeof value == "function")
1585
+ return {
1586
+ stringValue: FUNCTION_VALUE
1587
+ };
1588
+ if (typeof value == "symbol")
1589
+ return {
1590
+ stringValue: String(value)
1591
+ };
1592
+ if (typeof value == "object" && value !== null) {
1593
+ if (state.ancestors.has(value))
1594
+ return {
1595
+ stringValue: CIRCULAR_VALUE
1596
+ };
1597
+ if (depth >= MAX_JSON_SAFE_VALUE_DEPTH)
1598
+ return {
1599
+ stringValue: TRUNCATED_VALUE
1600
+ };
1601
+ if (value instanceof Date) {
1602
+ const time = value.getTime();
1603
+ const iso = Number.isFinite(time) ? value.toISOString() : String(value);
1604
+ return {
1605
+ stringValue: typeof iso == "string" ? sanitizeString(iso) : String(iso)
1606
+ };
1607
+ }
1608
+ state.ancestors.add(value);
1609
+ try {
1610
+ try {
1611
+ const toJSON = value.toJSON;
1612
+ if (typeof toJSON == "function")
1613
+ return encodeAnyValue(toJSON.call(value), logger, state, depth + 1);
1614
+ } catch {}
1615
+ if (isArray(value))
1616
+ return {
1617
+ arrayValue: {
1618
+ values: encodeArrayValues(value, logger, state, depth + 1)
1619
+ }
1620
+ };
1621
+ return {
1622
+ kvlistValue: {
1623
+ values: encodeKeyValueList(value, logger, state, depth + 1)
1624
+ }
1625
+ };
1626
+ } finally {
1627
+ state.ancestors.delete(value);
1628
+ }
1629
+ }
1630
+ return {
1631
+ stringValue: sanitizeString(String(value))
1632
+ };
1633
+ }
1634
+ function encodeArrayValues(values, logger, state, depth) {
1635
+ const result = [];
1636
+ const itemCount = Math.min(values.length, MAX_JSON_SAFE_VALUE_ITEMS);
1637
+ let index = 0;
1638
+ for (;index < itemCount && state.remainingNodes > 0; index++)
1639
+ try {
1640
+ const element = index in values ? values[index] : undefined;
1641
+ if (isNullish(element))
1642
+ continue;
1643
+ result.push(encodeAnyValue(element, logger, state, depth));
1644
+ } catch {
1645
+ result.push({
1646
+ stringValue: UNSERIALIZABLE_VALUE
1647
+ });
1648
+ }
1649
+ if (values.length > index)
1650
+ result.push({
1651
+ stringValue: TRUNCATED_VALUE
1652
+ });
1653
+ return result;
1654
+ }
1655
+ function encodeKeyValueList(attrs, logger, state, depth) {
1656
+ const result = [];
1657
+ for (const key in attrs)
1658
+ if (propertyIsEnumerable.call(attrs, key)) {
1659
+ if (result.length >= MAX_JSON_SAFE_VALUE_ITEMS || state.remainingNodes <= 0) {
1660
+ logger?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");
1661
+ break;
1662
+ }
1663
+ try {
1664
+ const value = attrs[key];
1665
+ if (isNull(value) || isUndefined(value))
1666
+ continue;
1667
+ result.push({
1668
+ key: sanitizeString(key),
1669
+ value: encodeAnyValue(value, logger, state, depth)
1670
+ });
1671
+ } catch {
1672
+ result.push({
1673
+ key: sanitizeString(key),
1674
+ value: {
1675
+ stringValue: UNSERIALIZABLE_VALUE
1676
+ }
1677
+ });
1678
+ }
1679
+ }
1680
+ return result;
1681
+ }
1682
+
1683
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/metrics-utils.mjs
1684
+ var DEFAULT_HISTOGRAM_BOUNDS = [
1685
+ 0,
1686
+ 5,
1687
+ 10,
1688
+ 25,
1689
+ 50,
1690
+ 75,
1691
+ 100,
1692
+ 250,
1693
+ 500,
1694
+ 750,
1695
+ 1000,
1696
+ 2500,
1697
+ 5000,
1698
+ 7500,
1699
+ 1e4
1700
+ ];
1701
+ function msToUnixNano(ms) {
1702
+ return String(ms) + "000000";
1703
+ }
1704
+ function seriesKey(type, name, unit, attributes) {
1705
+ let attrsKey = "";
1706
+ if (attributes) {
1707
+ const keys = Object.keys(attributes).sort();
1708
+ attrsKey = keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(attributes[k])}`).join(",");
1709
+ }
1710
+ return `${type}\x00${name}\x00${unit ?? ""}\x00${attrsKey}`;
1711
+ }
1712
+ function bucketIndexFor(value, bounds) {
1713
+ for (let i = 0;i < bounds.length; i++)
1714
+ if (value <= bounds[i])
1715
+ return i;
1716
+ return bounds.length;
1717
+ }
1718
+ function buildMetricsResourceAttributes(config, scopeName, scopeVersion) {
1719
+ return {
1720
+ ...config.resourceAttributes,
1721
+ "service.name": config.serviceName || "unknown_service",
1722
+ ...config.environment && {
1723
+ "deployment.environment": config.environment
1724
+ },
1725
+ ...config.serviceVersion && {
1726
+ "service.version": config.serviceVersion
1727
+ },
1728
+ "telemetry.sdk.name": scopeName,
1729
+ "telemetry.sdk.version": scopeVersion
1730
+ };
1731
+ }
1732
+ function buildOtlpMetricsPayload(metrics, resourceAttributes, scopeName, scopeVersion) {
1733
+ return {
1734
+ resourceMetrics: [
1735
+ {
1736
+ resource: {
1737
+ attributes: toOtlpKeyValueList(resourceAttributes)
1738
+ },
1739
+ scopeMetrics: [
1740
+ {
1741
+ scope: {
1742
+ name: scopeName,
1743
+ version: scopeVersion
1744
+ },
1745
+ metrics
1746
+ }
1747
+ ]
1748
+ }
1749
+ ]
1750
+ };
1751
+ }
1752
+
1753
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/config.mjs
1754
+ var DEFAULT_FLUSH_INTERVAL_MS = 1e4;
1755
+ var DEFAULT_MAX_SERIES_PER_FLUSH = 1000;
1756
+ function resolveMetricsConfig(config) {
1757
+ const resourceAttributes = config?.resourceAttributes;
1758
+ return {
1759
+ serviceName: resourceAttributes?.["service.name"] ?? config?.serviceName,
1760
+ serviceVersion: resourceAttributes?.["service.version"] ?? config?.serviceVersion,
1761
+ environment: resourceAttributes?.["deployment.environment"] ?? config?.environment,
1762
+ resourceAttributes,
1763
+ beforeSend: config?.beforeSend,
1764
+ flushIntervalMs: config?.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS,
1765
+ maxSeriesPerFlush: config?.maxSeriesPerFlush ?? DEFAULT_MAX_SERIES_PER_FLUSH
1766
+ };
1767
+ }
1768
+
1769
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/metrics/index.mjs
1770
+ var OTLP_TEMPORALITY_DELTA = 1;
1771
+
1772
+ class PostHogMetrics {
1773
+ constructor(_instance, _config, _logger) {
1774
+ this._instance = _instance;
1775
+ this._config = _config;
1776
+ this._logger = _logger;
1777
+ this._series = new Map;
1778
+ this._flushPromise = null;
1779
+ this._seriesCapWarned = false;
1780
+ this._typeByName = new Map;
1781
+ this._typeCollisionWarned = new Set;
1782
+ this._generation = 0;
1783
+ }
1784
+ count(name, value = 1, options) {
1785
+ this._capture({
1786
+ name,
1787
+ type: "count",
1788
+ value,
1789
+ unit: options?.unit,
1790
+ attributes: options?.attributes
1791
+ });
1792
+ }
1793
+ gauge(name, value, options) {
1794
+ this._capture({
1795
+ name,
1796
+ type: "gauge",
1797
+ value,
1798
+ unit: options?.unit,
1799
+ attributes: options?.attributes
1800
+ });
1801
+ }
1802
+ histogram(name, value, options) {
1803
+ this._capture({
1804
+ name,
1805
+ type: "histogram",
1806
+ value,
1807
+ unit: options?.unit,
1808
+ attributes: options?.attributes
1809
+ });
1810
+ }
1811
+ flush() {
1812
+ const prev = this._flushPromise;
1813
+ const run = async () => {
1814
+ if (prev)
1815
+ await prev.catch(() => {});
1816
+ await this._doFlush();
1817
+ };
1818
+ const p = run().finally(() => {
1819
+ if (this._flushPromise === p)
1820
+ this._flushPromise = null;
1821
+ });
1822
+ this._flushPromise = p;
1823
+ return p;
1824
+ }
1825
+ drainWindow() {
1826
+ if (this._series.size === 0)
1827
+ return null;
1828
+ const window = this._series;
1829
+ this._series = new Map;
1830
+ this._seriesCapWarned = false;
1831
+ this._typeByName = new Map;
1832
+ this._typeCollisionWarned = new Set;
1833
+ return this._buildPayload(window);
1834
+ }
1835
+ reset() {
1836
+ this._generation++;
1837
+ this._clearFlushTimer();
1838
+ this._series = new Map;
1839
+ this._flushPromise = null;
1840
+ this._seriesCapWarned = false;
1841
+ this._typeByName = new Map;
1842
+ this._typeCollisionWarned = new Set;
1843
+ }
1844
+ _capture(sample) {
1845
+ if (this._instance.isDisabled || this._instance.optedOut)
1846
+ return;
1847
+ const filtered = this._runBeforeSend(sample);
1848
+ if (filtered === null)
1849
+ return;
1850
+ if (!filtered.name || typeof filtered.name != "string")
1851
+ return void this._logger.warn("Dropping metric with empty name");
1852
+ if (typeof filtered.value != "number" || !Number.isFinite(filtered.value))
1853
+ return void this._logger.warn(`Dropping metric '${filtered.name}': value must be a finite number`);
1854
+ if (filtered.type === "count" && filtered.value < 0)
1855
+ return void this._logger.warn(`Dropping count '${filtered.name}': counters are monotonic, value must be >= 0`);
1856
+ let attributes;
1857
+ let key;
1858
+ try {
1859
+ attributes = filtered.attributes ? {
1860
+ ...filtered.attributes
1861
+ } : undefined;
1862
+ key = seriesKey(filtered.type, filtered.name, filtered.unit, attributes);
1863
+ } catch (e) {
1864
+ this._logger.warn(`Dropping metric '${filtered.name}': attributes could not be serialized`, e);
1865
+ return;
1866
+ }
1867
+ let state = this._series.get(key);
1868
+ if (!state) {
1869
+ if (!this._admitNewSeries())
1870
+ return;
1871
+ state = {
1872
+ name: filtered.name,
1873
+ type: filtered.type,
1874
+ unit: filtered.unit,
1875
+ attributes,
1876
+ windowStartMs: Date.now()
1877
+ };
1878
+ this._series.set(key, state);
1879
+ }
1880
+ const seenType = this._typeByName.get(filtered.name);
1881
+ if (seenType === undefined)
1882
+ this._typeByName.set(filtered.name, filtered.type);
1883
+ else if (seenType !== filtered.type && !this._typeCollisionWarned.has(filtered.name)) {
1884
+ this._typeCollisionWarned.add(filtered.name);
1885
+ 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.`);
1886
+ }
1887
+ this._fold(state, filtered.value);
1888
+ this._armFlushTimer();
1889
+ }
1890
+ _admitNewSeries() {
1891
+ if (this._series.size < this._config.maxSeriesPerFlush)
1892
+ return true;
1893
+ if (!this._seriesCapWarned) {
1894
+ this._seriesCapWarned = true;
1895
+ this._logger.warn(`Metric series cap reached (${this._config.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`);
1896
+ }
1897
+ return false;
1898
+ }
1899
+ _fold(state, value) {
1900
+ switch (state.type) {
1901
+ case "count":
1902
+ state.total = (state.total ?? 0) + value;
1903
+ break;
1904
+ case "gauge":
1905
+ state.last = value;
1906
+ break;
1907
+ case "histogram": {
1908
+ if (!state.hist)
1909
+ state.hist = {
1910
+ count: 0,
1911
+ sum: 0,
1912
+ min: value,
1913
+ max: value,
1914
+ bucketCounts: new Array(DEFAULT_HISTOGRAM_BOUNDS.length + 1).fill(0)
1915
+ };
1916
+ const hist = state.hist;
1917
+ hist.count += 1;
1918
+ hist.sum += value;
1919
+ hist.min = Math.min(hist.min, value);
1920
+ hist.max = Math.max(hist.max, value);
1921
+ hist.bucketCounts[bucketIndexFor(value, DEFAULT_HISTOGRAM_BOUNDS)] += 1;
1922
+ break;
1923
+ }
1924
+ }
1925
+ }
1926
+ _runBeforeSend(sample) {
1927
+ const beforeSend = this._config.beforeSend;
1928
+ if (!beforeSend)
1929
+ return sample;
1930
+ const fns = isArray(beforeSend) ? beforeSend : [
1931
+ beforeSend
1932
+ ];
1933
+ let result = sample;
1934
+ for (const fn of fns)
1935
+ try {
1936
+ const next = fn(result);
1937
+ if (!next) {
1938
+ this._logger.info("Metric was rejected in beforeSend function");
1939
+ return null;
1940
+ }
1941
+ result = next;
1942
+ } catch (e) {
1943
+ this._logger.error("Error in beforeSend function for metric:", e);
1944
+ return null;
1945
+ }
1946
+ return result;
1947
+ }
1948
+ _armFlushTimer() {
1949
+ if (this._flushTimer)
1950
+ return;
1951
+ this._flushTimer = safeSetTimeout(() => {
1952
+ this._flushTimer = undefined;
1953
+ this.flush().catch((e) => {
1954
+ this._logger.error("Metrics flush failed:", e);
1955
+ });
1956
+ }, this._config.flushIntervalMs);
1957
+ }
1958
+ _clearFlushTimer() {
1959
+ if (this._flushTimer) {
1960
+ clearTimeout(this._flushTimer);
1961
+ this._flushTimer = undefined;
1962
+ }
1963
+ }
1964
+ async _doFlush() {
1965
+ if (this._series.size === 0)
1966
+ return;
1967
+ const window = this._series;
1968
+ this._series = new Map;
1969
+ this._seriesCapWarned = false;
1970
+ this._typeByName = new Map;
1971
+ this._typeCollisionWarned = new Set;
1972
+ const generation = this._generation;
1973
+ const outcome = await this._instance._sendMetricsBatch(this._buildPayload(window));
1974
+ if (generation !== this._generation)
1975
+ return;
1976
+ switch (outcome.kind) {
1977
+ case "ok":
1978
+ return;
1979
+ case "retry-later":
1980
+ this._mergeWindowBack(window);
1981
+ this._armFlushTimer();
1982
+ return;
1983
+ case "too-large":
1984
+ this._logger.warn("Metrics batch exceeded the server size limit and was dropped");
1985
+ return;
1986
+ case "fatal":
1987
+ this._logger.error("Failed to send metrics batch:", outcome.error);
1988
+ return;
1989
+ }
1990
+ }
1991
+ _buildPayload(window) {
1992
+ return buildOtlpMetricsPayload(this._buildMetrics(window), buildMetricsResourceAttributes(this._config, this._instance.getLibraryId(), this._instance.getLibraryVersion()), this._instance.getLibraryId(), this._instance.getLibraryVersion());
1993
+ }
1994
+ _buildMetrics(window) {
1995
+ const nowNano = msToUnixNano(Date.now());
1996
+ const byMetric = new Map;
1997
+ for (const state of window.values()) {
1998
+ const metricKey = seriesKey(state.type, state.name, state.unit, undefined);
1999
+ let metric = byMetric.get(metricKey);
2000
+ if (!metric) {
2001
+ metric = {
2002
+ name: state.name,
2003
+ ...state.unit && {
2004
+ unit: state.unit
2005
+ }
2006
+ };
2007
+ if (state.type === "count")
2008
+ metric.sum = {
2009
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2010
+ isMonotonic: true,
2011
+ dataPoints: []
2012
+ };
2013
+ else if (state.type === "gauge")
2014
+ metric.gauge = {
2015
+ dataPoints: []
2016
+ };
2017
+ else
2018
+ metric.histogram = {
2019
+ aggregationTemporality: OTLP_TEMPORALITY_DELTA,
2020
+ dataPoints: []
2021
+ };
2022
+ byMetric.set(metricKey, metric);
2023
+ }
2024
+ const attributes = toOtlpKeyValueList(state.attributes ?? {}, this._logger);
2025
+ const startNano = msToUnixNano(state.windowStartMs);
2026
+ if (state.type === "count") {
2027
+ const dp = {
2028
+ attributes,
2029
+ startTimeUnixNano: startNano,
2030
+ timeUnixNano: nowNano,
2031
+ asDouble: state.total ?? 0
2032
+ };
2033
+ metric.sum.dataPoints.push(dp);
2034
+ } else if (state.type === "gauge") {
2035
+ const dp = {
2036
+ attributes,
2037
+ timeUnixNano: nowNano,
2038
+ asDouble: state.last ?? 0
2039
+ };
2040
+ metric.gauge.dataPoints.push(dp);
2041
+ } else if (state.hist) {
2042
+ const dp = {
2043
+ attributes,
2044
+ startTimeUnixNano: startNano,
2045
+ timeUnixNano: nowNano,
2046
+ count: state.hist.count,
2047
+ sum: state.hist.sum,
2048
+ min: state.hist.min,
2049
+ max: state.hist.max,
2050
+ bucketCounts: state.hist.bucketCounts,
2051
+ explicitBounds: DEFAULT_HISTOGRAM_BOUNDS
2052
+ };
2053
+ metric.histogram.dataPoints.push(dp);
2054
+ }
2055
+ }
2056
+ return Array.from(byMetric.values());
2057
+ }
2058
+ _mergeWindowBack(window) {
2059
+ for (const [key, old] of window) {
2060
+ const current = this._series.get(key);
2061
+ if (!current) {
2062
+ if (this._admitNewSeries())
2063
+ this._series.set(key, old);
2064
+ continue;
2065
+ }
2066
+ current.windowStartMs = Math.min(current.windowStartMs, old.windowStartMs);
2067
+ switch (current.type) {
2068
+ case "count":
2069
+ current.total = (current.total ?? 0) + (old.total ?? 0);
2070
+ break;
2071
+ case "gauge":
2072
+ break;
2073
+ case "histogram":
2074
+ if (old.hist)
2075
+ if (current.hist) {
2076
+ current.hist.count += old.hist.count;
2077
+ current.hist.sum += old.hist.sum;
2078
+ current.hist.min = Math.min(current.hist.min, old.hist.min);
2079
+ current.hist.max = Math.max(current.hist.max, old.hist.max);
2080
+ for (let i = 0;i < current.hist.bucketCounts.length; i++)
2081
+ current.hist.bucketCounts[i] += old.hist.bucketCounts[i];
2082
+ } else
2083
+ current.hist = old.hist;
2084
+ break;
2085
+ }
2086
+ }
2087
+ }
2088
+ }
2089
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/eventemitter.mjs
1348
2090
  class SimpleEventEmitter {
1349
2091
  constructor() {
1350
2092
  this.events = {};
@@ -1366,37 +2108,7 @@ class SimpleEventEmitter {
1366
2108
  }
1367
2109
  }
1368
2110
 
1369
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/index.mjs
1370
- var exports_error_tracking = {};
1371
- __export(exports_error_tracking, {
1372
- winjsStackLineParser: () => winjsStackLineParser,
1373
- stripReservedExceptionStepFields: () => stripReservedExceptionStepFields,
1374
- reverseAndStripFrames: () => reverseAndStripFrames,
1375
- resolveExceptionStepsConfig: () => resolveExceptionStepsConfig,
1376
- opera11StackLineParser: () => opera11StackLineParser,
1377
- opera10StackLineParser: () => opera10StackLineParser,
1378
- nodeStackLineParser: () => nodeStackLineParser,
1379
- getUtf8ByteLength: () => getUtf8ByteLength,
1380
- geckoStackLineParser: () => geckoStackLineParser,
1381
- createStackParser: () => createStackParser,
1382
- createDefaultStackParser: () => createDefaultStackParser,
1383
- chromeStackLineParser: () => chromeStackLineParser,
1384
- StringCoercer: () => StringCoercer,
1385
- ReduceableCache: () => ReduceableCache,
1386
- PromiseRejectionEventCoercer: () => PromiseRejectionEventCoercer,
1387
- PrimitiveCoercer: () => PrimitiveCoercer,
1388
- ObjectCoercer: () => ObjectCoercer,
1389
- ExceptionStepsBuffer: () => ExceptionStepsBuffer,
1390
- EventCoercer: () => EventCoercer,
1391
- ErrorPropertiesBuilder: () => ErrorPropertiesBuilder,
1392
- ErrorEventCoercer: () => ErrorEventCoercer,
1393
- ErrorCoercer: () => ErrorCoercer,
1394
- EXCEPTION_STEP_INTERNAL_FIELDS: () => EXCEPTION_STEP_INTERNAL_FIELDS,
1395
- DOMExceptionCoercer: () => DOMExceptionCoercer,
1396
- DEFAULT_EXCEPTION_STEPS_CONFIG: () => DEFAULT_EXCEPTION_STEPS_CONFIG
1397
- });
1398
-
1399
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
2111
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/chunk-ids.mjs
1400
2112
  var parsedStackResults;
1401
2113
  var lastKeysCount;
1402
2114
  var cachedFilenameChunkIds;
@@ -1435,7 +2147,7 @@ function getFilenameToChunkIdMap(stackParser) {
1435
2147
  return cachedFilenameChunkIds;
1436
2148
  }
1437
2149
 
1438
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
2150
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/error-properties-builder.mjs
1439
2151
  var MAX_CAUSE_RECURSION = 4;
1440
2152
 
1441
2153
  class ErrorPropertiesBuilder {
@@ -1539,11 +2251,11 @@ class ErrorPropertiesBuilder {
1539
2251
  return context;
1540
2252
  }
1541
2253
  buildCoercingContext(mechanism, hint, depth = 0) {
1542
- const coerce = (input, depth2) => {
1543
- if (!(depth2 <= MAX_CAUSE_RECURSION))
2254
+ const coerce = (input, depth) => {
2255
+ if (!(depth <= MAX_CAUSE_RECURSION))
1544
2256
  return;
1545
2257
  {
1546
- const ctx = this.buildCoercingContext(mechanism, hint, depth2);
2258
+ const ctx = this.buildCoercingContext(mechanism, hint, depth);
1547
2259
  return this.applyCoercers(input, ctx);
1548
2260
  }
1549
2261
  };
@@ -1557,14 +2269,16 @@ class ErrorPropertiesBuilder {
1557
2269
  return context;
1558
2270
  }
1559
2271
  }
1560
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
2272
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/base.mjs
1561
2273
  var UNKNOWN_FUNCTION = "?";
2274
+ var MASKED_URL_PREFIX = "webkit-masked-url://";
2275
+ var ANONYMOUS_FILENAME = "<anonymous>";
1562
2276
  function createFrame(platform, filename, func, lineno, colno) {
1563
2277
  const frame = {
1564
2278
  platform,
1565
2279
  filename,
1566
2280
  function: func === "<anonymous>" ? UNKNOWN_FUNCTION : func,
1567
- in_app: true
2281
+ in_app: !filename?.startsWith(MASKED_URL_PREFIX) && filename !== ANONYMOUS_FILENAME
1568
2282
  };
1569
2283
  if (!isUndefined(lineno))
1570
2284
  frame.lineno = lineno;
@@ -1573,7 +2287,7 @@ function createFrame(platform, filename, func, lineno, colno) {
1573
2287
  return frame;
1574
2288
  }
1575
2289
 
1576
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
2290
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/safari.mjs
1577
2291
  var extractSafariExtensionDetails = (func, filename) => {
1578
2292
  const isSafariExtension = func.indexOf("safari-extension") !== -1;
1579
2293
  const isSafariWebExtension = func.indexOf("safari-web-extension") !== -1;
@@ -1586,15 +2300,15 @@ var extractSafariExtensionDetails = (func, filename) => {
1586
2300
  ];
1587
2301
  };
1588
2302
 
1589
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
2303
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/chrome.mjs
1590
2304
  var chromeRegexNoFnName = /^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i;
1591
2305
  var chromeRegex = /^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i;
1592
2306
  var chromeEvalRegex = /\((\S*)(?::(\d+))(?::(\d+))\)/;
1593
2307
  var chromeStackLineParser = (line, platform) => {
1594
2308
  const noFnParts = chromeRegexNoFnName.exec(line);
1595
2309
  if (noFnParts) {
1596
- const [, filename, line2, col] = noFnParts;
1597
- return createFrame(platform, filename, UNKNOWN_FUNCTION, +line2, +col);
2310
+ const [, filename, line, col] = noFnParts;
2311
+ return createFrame(platform, filename, UNKNOWN_FUNCTION, +line, +col);
1598
2312
  }
1599
2313
  const parts = chromeRegex.exec(line);
1600
2314
  if (parts) {
@@ -1612,7 +2326,7 @@ var chromeStackLineParser = (line, platform) => {
1612
2326
  }
1613
2327
  };
1614
2328
 
1615
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
2329
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/gecko.mjs
1616
2330
  var geckoREgex = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i;
1617
2331
  var geckoEvalRegex = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i;
1618
2332
  var geckoStackLineParser = (line, platform) => {
@@ -1635,28 +2349,12 @@ var geckoStackLineParser = (line, platform) => {
1635
2349
  }
1636
2350
  };
1637
2351
 
1638
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/winjs.mjs
1639
- var winjsRegex = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i;
1640
- var winjsStackLineParser = (line, platform) => {
1641
- const parts = winjsRegex.exec(line);
1642
- return parts ? createFrame(platform, parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined) : undefined;
1643
- };
1644
-
1645
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/opera.mjs
1646
- var opera10Regex = / line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i;
1647
- var opera10StackLineParser = (line, platform) => {
1648
- const parts = opera10Regex.exec(line);
1649
- return parts ? createFrame(platform, parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;
1650
- };
1651
- var opera11Regex = / line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i;
1652
- var opera11StackLineParser = (line, platform) => {
1653
- const parts = opera11Regex.exec(line);
1654
- return parts ? createFrame(platform, parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;
1655
- };
1656
-
1657
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
2352
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/node.mjs
1658
2353
  var FILENAME_MATCH = /^\s*[-]{4,}$/;
1659
2354
  var FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
2355
+ var PROMISE_COMBINATOR = /^Promise\.(?:all|any)$/;
2356
+ var PROMISE_INDEX = /^index \d+$/;
2357
+ var PROMISE_FRAME_FILENAME = "node:internal/promise";
1660
2358
  var nodeStackLineParser = (line, platform) => {
1661
2359
  const lineMatch = line.match(FULL_MATCH);
1662
2360
  if (lineMatch) {
@@ -1699,6 +2397,8 @@ var nodeStackLineParser = (line, platform) => {
1699
2397
  filename = filename.slice(1);
1700
2398
  if (!filename && lineMatch[5] && !isNative)
1701
2399
  filename = lineMatch[5];
2400
+ if (PROMISE_COMBINATOR.test(functionName) && PROMISE_INDEX.test(filename || ""))
2401
+ filename = PROMISE_FRAME_FILENAME;
1702
2402
  return {
1703
2403
  filename: filename ? decodeURI(filename) : undefined,
1704
2404
  module: undefined,
@@ -1723,7 +2423,7 @@ function _parseIntOrUndefined(input) {
1723
2423
  return parseInt(input || "", 10) || undefined;
1724
2424
  }
1725
2425
 
1726
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
2426
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/parsers/index.mjs
1727
2427
  var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
1728
2428
  var STACKTRACE_FRAME_LIMIT = 50;
1729
2429
  function reverseAndStripFrames(stack) {
@@ -1768,52 +2468,24 @@ function createStackParser(platform, ...parsers) {
1768
2468
  return reverseAndStripFrames(frames);
1769
2469
  };
1770
2470
  }
1771
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/dom-exception-coercer.mjs
1772
- class DOMExceptionCoercer {
2471
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
2472
+ class ErrorCoercer {
1773
2473
  match(err) {
1774
- return this.isDOMException(err) || this.isDOMError(err);
2474
+ return isError(err);
1775
2475
  }
1776
2476
  coerce(err, ctx) {
1777
- const hasStack = isString(err.stack);
2477
+ const stack = this.getStack(err);
2478
+ const synthetic = stack === undefined;
1778
2479
  return {
1779
2480
  type: this.getType(err),
1780
- value: this.getValue(err),
1781
- stack: hasStack ? err.stack : undefined,
2481
+ value: this.getMessage(err, ctx),
2482
+ stack: stack ?? ctx.syntheticException?.stack,
1782
2483
  cause: err.cause ? ctx.next(err.cause) : undefined,
1783
- synthetic: false
2484
+ synthetic
1784
2485
  };
1785
2486
  }
1786
- getType(candidate) {
1787
- return this.isDOMError(candidate) ? "DOMError" : "DOMException";
1788
- }
1789
- getValue(err) {
1790
- const name = err.name || (this.isDOMError(err) ? "DOMError" : "DOMException");
1791
- const message = err.message ? `${name}: ${err.message}` : name;
1792
- return message;
1793
- }
1794
- isDOMException(err) {
1795
- return isBuiltin(err, "DOMException");
1796
- }
1797
- isDOMError(err) {
1798
- return isBuiltin(err, "DOMError");
1799
- }
1800
- }
1801
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-coercer.mjs
1802
- class ErrorCoercer {
1803
- match(err) {
1804
- return isPlainError(err);
1805
- }
1806
- coerce(err, ctx) {
1807
- return {
1808
- type: this.getType(err),
1809
- value: this.getMessage(err, ctx),
1810
- stack: this.getStack(err),
1811
- cause: err.cause ? ctx.next(err.cause) : undefined,
1812
- synthetic: false
1813
- };
1814
- }
1815
- getType(err) {
1816
- return err.name || err.constructor.name;
2487
+ getType(err) {
2488
+ return err.name || err.constructor.name;
1817
2489
  }
1818
2490
  getMessage(err, _ctx) {
1819
2491
  const message = err.message;
@@ -1825,25 +2497,7 @@ class ErrorCoercer {
1825
2497
  return err.stacktrace || err.stack || undefined;
1826
2498
  }
1827
2499
  }
1828
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/error-event-coercer.mjs
1829
- class ErrorEventCoercer {
1830
- constructor() {}
1831
- match(err) {
1832
- return isErrorEvent(err) && err.error != null;
1833
- }
1834
- coerce(err, ctx) {
1835
- const exceptionLike = ctx.apply(err.error);
1836
- if (!exceptionLike)
1837
- return {
1838
- type: "ErrorEvent",
1839
- value: err.message,
1840
- stack: ctx.syntheticException?.stack,
1841
- synthetic: true
1842
- };
1843
- return exceptionLike;
1844
- }
1845
- }
1846
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
2500
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/string-coercer.mjs
1847
2501
  var ERROR_TYPES_PATTERN = /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;
1848
2502
 
1849
2503
  class StringCoercer {
@@ -1873,7 +2527,7 @@ class StringCoercer {
1873
2527
  ];
1874
2528
  }
1875
2529
  }
1876
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/types.mjs
2530
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/types.mjs
1877
2531
  var severityLevels = [
1878
2532
  "fatal",
1879
2533
  "error",
@@ -1883,7 +2537,7 @@ var severityLevels = [
1883
2537
  "debug"
1884
2538
  ];
1885
2539
 
1886
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
2540
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/utils.mjs
1887
2541
  function extractExceptionKeysForMessage(err, maxLength = 40) {
1888
2542
  const keys = Object.keys(err);
1889
2543
  keys.sort();
@@ -1900,7 +2554,7 @@ function extractExceptionKeysForMessage(err, maxLength = 40) {
1900
2554
  return "";
1901
2555
  }
1902
2556
 
1903
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
2557
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/object-coercer.mjs
1904
2558
  class ObjectCoercer {
1905
2559
  match(candidate) {
1906
2560
  return typeof candidate == "object" && candidate !== null;
@@ -1912,13 +2566,16 @@ class ObjectCoercer {
1912
2566
  return {
1913
2567
  type: this.getType(candidate),
1914
2568
  value: this.getValue(candidate),
1915
- stack: ctx.syntheticException?.stack,
2569
+ stack: this.getStack(candidate) ?? ctx.syntheticException?.stack,
1916
2570
  level: this.isSeverityLevel(candidate.level) ? candidate.level : "error",
1917
2571
  synthetic: true
1918
2572
  };
1919
2573
  }
1920
2574
  getType(err) {
1921
- return isEvent(err) ? err.constructor.name : "Error";
2575
+ if (isEvent(err))
2576
+ return err.constructor.name;
2577
+ const name = "name" in err ? err.name : undefined;
2578
+ return isString(name) && !isEmptyString(name) ? name : "Error";
1922
2579
  }
1923
2580
  getValue(err) {
1924
2581
  if ("name" in err && typeof err.name == "string") {
@@ -1936,6 +2593,15 @@ class ObjectCoercer {
1936
2593
  isSeverityLevel(x) {
1937
2594
  return isString(x) && !isEmptyString(x) && severityLevels.indexOf(x) >= 0;
1938
2595
  }
2596
+ getStack(candidate) {
2597
+ try {
2598
+ if (isString(candidate.stacktrace) && candidate.stacktrace.length > 0)
2599
+ return candidate.stacktrace;
2600
+ return isString(candidate.stack) && candidate.stack.length > 0 ? candidate.stack : undefined;
2601
+ } catch {
2602
+ return;
2603
+ }
2604
+ }
1939
2605
  getErrorPropertyFromObject(obj) {
1940
2606
  for (const prop in obj)
1941
2607
  if (Object.prototype.hasOwnProperty.call(obj, prop)) {
@@ -1953,7 +2619,7 @@ class ObjectCoercer {
1953
2619
  }
1954
2620
  }
1955
2621
  }
1956
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
2622
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/event-coercer.mjs
1957
2623
  class EventCoercer {
1958
2624
  match(err) {
1959
2625
  return isEvent(err);
@@ -1968,7 +2634,7 @@ class EventCoercer {
1968
2634
  };
1969
2635
  }
1970
2636
  }
1971
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
2637
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/coercers/primitive-coercer.mjs
1972
2638
  class PrimitiveCoercer {
1973
2639
  match(candidate) {
1974
2640
  return isPrimitive(candidate);
@@ -1982,43 +2648,7 @@ class PrimitiveCoercer {
1982
2648
  };
1983
2649
  }
1984
2650
  }
1985
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/coercers/promise-rejection-event.mjs
1986
- class PromiseRejectionEventCoercer {
1987
- match(err) {
1988
- return isBuiltin(err, "PromiseRejectionEvent") || this.isCustomEventWrappingRejection(err);
1989
- }
1990
- isCustomEventWrappingRejection(err) {
1991
- if (!isEvent(err))
1992
- return false;
1993
- try {
1994
- const detail = err.detail;
1995
- return detail != null && typeof detail == "object" && "reason" in detail;
1996
- } catch {
1997
- return false;
1998
- }
1999
- }
2000
- coerce(err, ctx) {
2001
- const reason = this.getUnhandledRejectionReason(err);
2002
- if (isPrimitive(reason))
2003
- return {
2004
- type: "UnhandledRejection",
2005
- value: `Non-Error promise rejection captured with value: ${String(reason)}`,
2006
- stack: ctx.syntheticException?.stack,
2007
- synthetic: true
2008
- };
2009
- return ctx.apply(reason);
2010
- }
2011
- getUnhandledRejectionReason(error) {
2012
- try {
2013
- if ("reason" in error)
2014
- return error.reason;
2015
- if ("detail" in error && error.detail != null && typeof error.detail == "object" && "reason" in error.detail)
2016
- return error.detail.reason;
2017
- } catch {}
2018
- return error;
2019
- }
2020
- }
2021
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2651
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/utils.mjs
2022
2652
  class ReduceableCache {
2023
2653
  constructor(_maxSize) {
2024
2654
  this._maxSize = _maxSize;
@@ -2043,7 +2673,7 @@ class ReduceableCache {
2043
2673
  }
2044
2674
  }
2045
2675
  }
2046
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2676
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/exception-steps.mjs
2047
2677
  var EXCEPTION_STEP_INTERNAL_FIELDS = {
2048
2678
  MESSAGE: "$message",
2049
2679
  TIMESTAMP: "$timestamp"
@@ -2052,167 +2682,65 @@ var RESERVED_EXCEPTION_STEP_KEYS = new Set([
2052
2682
  EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE,
2053
2683
  EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP
2054
2684
  ]);
2055
- var DEFAULT_EXCEPTION_STEPS_CONFIG = {
2056
- enabled: true,
2057
- max_bytes: 32768
2058
- };
2059
- function resolveExceptionStepsConfig(config) {
2060
- if (!config)
2061
- return {
2062
- ...DEFAULT_EXCEPTION_STEPS_CONFIG
2063
- };
2064
- return {
2065
- enabled: config.enabled ?? DEFAULT_EXCEPTION_STEPS_CONFIG.enabled,
2066
- max_bytes: normalizePositiveInteger(config.max_bytes, DEFAULT_EXCEPTION_STEPS_CONFIG.max_bytes)
2067
- };
2068
- }
2069
- function stripReservedExceptionStepFields(properties) {
2070
- if (!properties)
2071
- return {
2072
- sanitizedProperties: {},
2073
- droppedKeys: []
2074
- };
2075
- const droppedKeys = [];
2076
- const sanitizedProperties = Object.keys(properties).reduce((acc, key) => {
2077
- if (RESERVED_EXCEPTION_STEP_KEYS.has(key)) {
2078
- droppedKeys.push(key);
2079
- return acc;
2080
- }
2081
- acc[key] = properties[key];
2082
- return acc;
2083
- }, {});
2084
- return {
2085
- sanitizedProperties,
2086
- droppedKeys
2087
- };
2088
- }
2089
-
2090
- class ExceptionStepsBuffer {
2091
- constructor(config) {
2092
- this._entries = [];
2093
- this._totalBytes = 0;
2094
- this._config = resolveExceptionStepsConfig(config);
2095
- }
2096
- setConfig(config) {
2097
- this._config = resolveExceptionStepsConfig(config);
2098
- this._trimToMaxBytes();
2099
- }
2100
- add(step) {
2101
- const serialized = normalizeAndSerializeStep(step);
2102
- if (!serialized)
2103
- return;
2104
- const bytes = getUtf8ByteLength(serialized.json);
2105
- if (bytes > this._config.max_bytes)
2106
- return;
2107
- this._entries.push({
2108
- step: serialized.step,
2109
- bytes
2110
- });
2111
- this._totalBytes += bytes;
2112
- this._trimToMaxBytes();
2113
- }
2114
- getAttachable() {
2115
- return this._entries.map((e) => e.step);
2116
- }
2117
- clear() {
2118
- this._entries = [];
2119
- this._totalBytes = 0;
2120
- }
2121
- size() {
2122
- return this._entries.length;
2123
- }
2124
- _trimToMaxBytes() {
2125
- while (this._totalBytes > this._config.max_bytes && this._entries.length > 0) {
2126
- const evicted = this._entries.shift();
2127
- if (evicted)
2128
- this._totalBytes -= evicted.bytes;
2129
- }
2130
- }
2131
- }
2132
- function normalizePositiveInteger(input, fallback) {
2133
- if (!isNumber(input) || input === 1 / 0 || input === -1 / 0)
2134
- return fallback;
2135
- const normalized = Math.floor(input);
2136
- if (normalized < 0)
2137
- return fallback;
2138
- return normalized;
2139
- }
2140
- function normalizeAndSerializeStep(step) {
2141
- const json = safeStringify(step);
2142
- if (!json)
2143
- return;
2144
- try {
2145
- const parsed = JSON.parse(json);
2146
- if (!isObject(parsed))
2147
- return;
2148
- const parsedStep = parsed;
2149
- const message = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.MESSAGE];
2150
- const timestamp = parsedStep[EXCEPTION_STEP_INTERNAL_FIELDS.TIMESTAMP];
2151
- if (!isString(message) || message.trim().length === 0)
2152
- return;
2153
- if (!isString(timestamp) && !isNumber(timestamp))
2154
- return;
2155
- return {
2156
- step: parsedStep,
2157
- json
2158
- };
2159
- } catch {
2160
- return;
2161
- }
2685
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/error-tracking/release.mjs
2686
+ function getInjectedReleaseId() {
2687
+ const injected = globalThis._posthogReleaseId;
2688
+ return typeof injected == "string" && injected.length > 0 ? injected : undefined;
2162
2689
  }
2163
- function safeStringify(value) {
2164
- const seen = new WeakSet;
2165
- try {
2166
- return JSON.stringify(value, (_key, replacementValue) => {
2167
- if (typeof replacementValue == "bigint")
2168
- return replacementValue.toString();
2169
- if (typeof replacementValue == "function" || typeof replacementValue == "symbol")
2170
- return;
2171
- if (replacementValue instanceof Date)
2172
- return replacementValue.toISOString();
2173
- if (replacementValue instanceof Error)
2174
- return {
2175
- name: replacementValue.name,
2176
- message: replacementValue.message,
2177
- stack: replacementValue.stack
2178
- };
2179
- if (replacementValue && typeof replacementValue == "object") {
2180
- if (seen.has(replacementValue))
2181
- return "[Circular]";
2182
- seen.add(replacementValue);
2183
- }
2184
- return replacementValue;
2185
- });
2186
- } catch {
2187
- return;
2188
- }
2189
- }
2190
- function getUtf8ByteLength(value) {
2191
- if (typeof TextEncoder != "undefined")
2192
- return new TextEncoder().encode(value).length;
2193
- const encoded = encodeURIComponent(value);
2194
- let byteLength = 0;
2195
- for (let i = 0;i < encoded.length; i++)
2196
- if (encoded[i] === "%") {
2197
- byteLength += 1;
2198
- i += 2;
2199
- } else
2200
- byteLength += 1;
2201
- return byteLength;
2202
- }
2203
- // ../../../node_modules/.bun/@posthog+core@1.30.3/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
2690
+ // ../../../node_modules/.bun/@posthog+core@1.48.9/node_modules/@posthog/core/dist/posthog-core-stateless.mjs
2204
2691
  class PostHogFetchHttpError extends Error {
2205
- constructor(response, reqByteLength) {
2206
- super("HTTP error while fetching PostHog: status=" + response.status + ", reqByteLength=" + reqByteLength), this.response = response, this.reqByteLength = reqByteLength, this.name = "PostHogFetchHttpError";
2692
+ constructor(response, reqByteLength, responseBodyDeadline, abortController) {
2693
+ 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;
2207
2694
  }
2208
2695
  get status() {
2209
2696
  return this.response.status;
2210
2697
  }
2698
+ get bodyReadTimedOut() {
2699
+ return this._bodyReadTimedOut;
2700
+ }
2211
2701
  get text() {
2212
- return this.response.text();
2702
+ if (!this.responseBodyTextPromise)
2703
+ if (Date.now() >= this.responseBodyDeadline) {
2704
+ this._bodyReadTimedOut = true;
2705
+ const timeoutError = new Error("Response body read timed out");
2706
+ timeoutError.name = "AbortError";
2707
+ this.cancelResponseBody(timeoutError);
2708
+ this.responseBodyTextPromise = Promise.reject(timeoutError);
2709
+ } else {
2710
+ const responseBodyTimeout = new Promise((_resolve, reject) => {
2711
+ this.responseBodyTimer = safeSetTimeout(() => {
2712
+ this._bodyReadTimedOut = true;
2713
+ const timeoutError = new Error("Response body read timed out");
2714
+ timeoutError.name = "AbortError";
2715
+ reject(timeoutError);
2716
+ this.cancelResponseBody(timeoutError);
2717
+ }, this.responseBodyDeadline - Date.now());
2718
+ });
2719
+ let responseBodyText;
2720
+ try {
2721
+ responseBodyText = Promise.resolve(this.response.text());
2722
+ } catch (error) {
2723
+ responseBodyText = Promise.reject(error);
2724
+ }
2725
+ this.responseBodyTextPromise = Promise.race([
2726
+ responseBodyText,
2727
+ responseBodyTimeout
2728
+ ]).finally(() => clearTimeout(this.responseBodyTimer));
2729
+ }
2730
+ return this.responseBodyTextPromise;
2213
2731
  }
2214
2732
  get json() {
2215
- return this.response.json();
2733
+ return this.text.then((text) => JSON.parse(text));
2734
+ }
2735
+ cancelResponseBody(reason) {
2736
+ clearTimeout(this.responseBodyTimer);
2737
+ if (!this.abortController.signal.aborted)
2738
+ this.abortController.abort(reason);
2739
+ (async () => {
2740
+ try {
2741
+ await this.response.body?.cancel();
2742
+ } catch {}
2743
+ })();
2216
2744
  }
2217
2745
  }
2218
2746
 
@@ -2223,12 +2751,20 @@ class PostHogFetchNetworkError extends Error {
2223
2751
  } : {}), this.error = error, this.name = "PostHogFetchNetworkError";
2224
2752
  }
2225
2753
  }
2754
+ var applyCallerFeatureFlagOverrides = (target, callerProperties) => {
2755
+ for (const key of Object.keys(callerProperties))
2756
+ if (key.startsWith("$feature/") || key === "$active_feature_flags")
2757
+ target[key] = callerProperties[key];
2758
+ };
2226
2759
  async function logFlushError(err) {
2227
2760
  if (err instanceof PostHogFetchHttpError) {
2228
2761
  let text = "";
2229
2762
  try {
2230
2763
  text = await err.text;
2231
- } catch {}
2764
+ } catch {
2765
+ if (err.bodyReadTimedOut)
2766
+ text = "<response body read timed out>";
2767
+ }
2232
2768
  console.error(`Error while flushing PostHog: message=${err.message}, response body=${text}`, err);
2233
2769
  } else
2234
2770
  console.error("Error while flushing PostHog", err);
@@ -2240,9 +2776,28 @@ function isPostHogFetchError(err) {
2240
2776
  function isPostHogFetchNetworkError(err) {
2241
2777
  return err instanceof PostHogFetchNetworkError;
2242
2778
  }
2779
+ function isRetryableFlagsFetchError(err) {
2780
+ if (err instanceof PostHogFetchHttpError)
2781
+ return err.status === 502 || err.status === 504;
2782
+ if (!(err instanceof PostHogFetchNetworkError))
2783
+ return false;
2784
+ const cause = err.error;
2785
+ const code = cause?.code ?? cause?.cause?.code;
2786
+ return code !== "ECONNREFUSED";
2787
+ }
2243
2788
  function isPostHogFetchContentTooLargeError(err) {
2244
2789
  return typeof err == "object" && err instanceof PostHogFetchHttpError && err.status === 413;
2245
2790
  }
2791
+ function isPostHogFetchRetryableError(err) {
2792
+ if (err instanceof PostHogFetchHttpError)
2793
+ return err.status === 408 || err.status === 429 || err.status >= 500;
2794
+ return isPostHogFetchNetworkError(err);
2795
+ }
2796
+ function isPostHogEventProperties(value) {
2797
+ return value !== null && typeof value == "object" && !Array.isArray(value);
2798
+ }
2799
+ var DEFAULT_QUEUE_ROUTE = "default";
2800
+
2246
2801
  class PostHogCoreStateless {
2247
2802
  getErrorPropertiesBuilder() {
2248
2803
  if (!this._errorPropertiesBuilder)
@@ -2259,6 +2814,9 @@ class PostHogCoreStateless {
2259
2814
  }
2260
2815
  constructor(apiKey, options = {}) {
2261
2816
  this.flushPromise = null;
2817
+ this.pendingFlushPromise = null;
2818
+ this.flushPromises = new Set;
2819
+ this._dequeuedMessagesCount = 0;
2262
2820
  this.shutdownPromise = null;
2263
2821
  this.promiseQueue = new PromiseQueue;
2264
2822
  this._events = new SimpleEventEmitter;
@@ -2281,10 +2839,11 @@ class PostHogCoreStateless {
2281
2839
  this._retryOptions = {
2282
2840
  retryCount: options.fetchRetryCount ?? 3,
2283
2841
  retryDelay: options.fetchRetryDelay ?? 3000,
2284
- retryCheck: isPostHogFetchError
2842
+ retryCheck: isPostHogFetchRetryableError
2285
2843
  };
2286
2844
  this.requestTimeout = options.requestTimeout ?? 1e4;
2287
2845
  this.featureFlagsRequestTimeoutMs = options.featureFlagsRequestTimeoutMs ?? 3000;
2846
+ this.featureFlagsRequestMaxRetries = options.featureFlagsRequestMaxRetries ?? 1;
2288
2847
  this.remoteConfigRequestTimeoutMs = options.remoteConfigRequestTimeoutMs ?? 3000;
2289
2848
  this.disableGeoip = options.disableGeoip ?? true;
2290
2849
  this.disabled = (options.disabled ?? false) || missingApiKey;
@@ -2346,15 +2905,23 @@ class PostHogCoreStateless {
2346
2905
  return this.disabled;
2347
2906
  }
2348
2907
  buildPayload(payload) {
2908
+ const userProperties = payload.properties || {};
2909
+ let properties = {
2910
+ ...userProperties,
2911
+ ...this.getCommonEventProperties()
2912
+ };
2913
+ applyCallerFeatureFlagOverrides(properties, userProperties);
2914
+ if (payload.event === "$feature_flag_called" && properties.$feature_flag_has_experiment === false && this.isMinimalFlagCalledEventsEnabled())
2915
+ properties = minimizeFlagCalledEventProperties(properties);
2349
2916
  return {
2350
2917
  distinct_id: payload.distinct_id,
2351
2918
  event: payload.event,
2352
- properties: {
2353
- ...payload.properties || {},
2354
- ...this.getCommonEventProperties()
2355
- }
2919
+ properties
2356
2920
  };
2357
2921
  }
2922
+ isMinimalFlagCalledEventsEnabled() {
2923
+ return false;
2924
+ }
2358
2925
  addPendingPromise(promise) {
2359
2926
  return this.promiseQueue.add(promise);
2360
2927
  }
@@ -2439,6 +3006,19 @@ class PostHogCoreStateless {
2439
3006
  this.enqueue("capture", payload, options);
2440
3007
  });
2441
3008
  }
3009
+ async groupIdentifyStatelessImmediate(groupType, groupKey, groupProperties, options, distinctId, eventProperties) {
3010
+ const payload = this.buildPayload({
3011
+ distinct_id: distinctId || `$${groupType}_${groupKey}`,
3012
+ event: "$groupidentify",
3013
+ properties: {
3014
+ $group_type: groupType,
3015
+ $group_key: groupKey,
3016
+ $group_set: groupProperties || {},
3017
+ ...eventProperties || {}
3018
+ }
3019
+ });
3020
+ await this.sendImmediate("capture", payload, options);
3021
+ }
2442
3022
  async getRemoteConfig() {
2443
3023
  await this._initPromise;
2444
3024
  let host = this.host;
@@ -2455,8 +3035,11 @@ class PostHogCoreStateless {
2455
3035
  }
2456
3036
  };
2457
3037
  return this.fetchWithRetry(url, fetchOptions, {
3038
+ type: "required",
3039
+ consume: (response) => response.json()
3040
+ }, {
2458
3041
  retryCount: 0
2459
- }, this.remoteConfigRequestTimeoutMs).then((response) => response.json()).catch((error) => {
3042
+ }, this.remoteConfigRequestTimeoutMs).catch((error) => {
2460
3043
  this._logger.error("Remote config could not be loaded", error);
2461
3044
  this._events.emit("error", error);
2462
3045
  });
@@ -2487,8 +3070,12 @@ class PostHogCoreStateless {
2487
3070
  };
2488
3071
  this._logger.info("Flags URL", url);
2489
3072
  return this.fetchWithRetry(url, fetchOptions, {
2490
- retryCount: 0
2491
- }, this.featureFlagsRequestTimeoutMs).then((response) => response.json()).then((response) => ({
3073
+ type: "required",
3074
+ consume: (response) => response.json()
3075
+ }, {
3076
+ retryCount: this.featureFlagsRequestMaxRetries,
3077
+ retryCheck: isRetryableFlagsFetchError
3078
+ }, this.featureFlagsRequestTimeoutMs).then((response) => ({
2492
3079
  success: true,
2493
3080
  response: normalizeFlagsResponse(response)
2494
3081
  })).catch((error) => {
@@ -2588,9 +3175,9 @@ class PostHogCoreStateless {
2588
3175
  }
2589
3176
  async getFeatureFlagDetailsStateless(distinctId, groups = {}, personProperties = {}, groupProperties = {}, disableGeoip, flagKeysToEvaluate) {
2590
3177
  await this._initPromise;
2591
- const extraPayload = {};
2592
- if (disableGeoip ?? this.disableGeoip)
2593
- extraPayload["geoip_disable"] = true;
3178
+ const extraPayload = {
3179
+ geoip_disable: disableGeoip ?? this.disableGeoip
3180
+ };
2594
3181
  if (flagKeysToEvaluate)
2595
3182
  extraPayload["flag_keys_to_evaluate"] = flagKeysToEvaluate;
2596
3183
  const result = await this.getFlags(distinctId, groups, personProperties, groupProperties, extraPayload);
@@ -2627,15 +3214,18 @@ class PostHogCoreStateless {
2627
3214
  "Content-Type": "application/json"
2628
3215
  }
2629
3216
  };
2630
- const response = await this.fetchWithRetry(url, fetchOptions).then((response2) => {
2631
- if (response2.status !== 200 || !response2.json) {
2632
- const msg = `Surveys API could not be loaded: ${response2.status}`;
2633
- const error = new Error(msg);
2634
- this._logger.error(error);
2635
- this._events.emit("error", new Error(msg));
2636
- return;
3217
+ const response = await this.fetchWithRetry(url, fetchOptions, {
3218
+ type: "required",
3219
+ consume: (response) => {
3220
+ if (response.status !== 200 || !response.json) {
3221
+ const msg = `Surveys API could not be loaded: ${response.status}`;
3222
+ const error = new Error(msg);
3223
+ this._logger.error(error);
3224
+ this._events.emit("error", new Error(msg));
3225
+ return Promise.resolve(undefined);
3226
+ }
3227
+ return response.json();
2637
3228
  }
2638
- return response2.json();
2639
3229
  }).catch((error) => {
2640
3230
  this._logger.error("Surveys API could not be loaded", error);
2641
3231
  this._events.emit("error", error);
@@ -2672,23 +3262,39 @@ class PostHogCoreStateless {
2672
3262
  return message;
2673
3263
  }
2674
3264
  async flushStorage() {}
2675
- enqueue(type, _message, options) {
3265
+ getQueueRouteKey(_message) {
3266
+ return DEFAULT_QUEUE_ROUTE;
3267
+ }
3268
+ persistedQueueKeyForRoute(_route) {
3269
+ return types_PostHogPersistedProperty.Queue;
3270
+ }
3271
+ getActiveQueueRoutes() {
3272
+ return [
3273
+ DEFAULT_QUEUE_ROUTE
3274
+ ];
3275
+ }
3276
+ getRouteQueue(route) {
3277
+ return this.getPersistedProperty(this.persistedQueueKeyForRoute(route)) || [];
3278
+ }
3279
+ enqueue(type, _message, options, explicitRoute) {
2676
3280
  this.wrap(() => {
2677
3281
  if (this.optedOut)
2678
3282
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2679
- let message = this.prepareMessage(type, _message, options);
3283
+ let message = this.prepareMessage(_message, options);
2680
3284
  message = this.processBeforeEnqueue(message);
2681
3285
  if (message === null)
2682
3286
  return;
2683
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
3287
+ message = this.normalizeMessage(message);
3288
+ const queueKey = this.persistedQueueKeyForRoute(explicitRoute ?? this.getQueueRouteKey(message));
3289
+ const queue = this.getPersistedProperty(queueKey) || [];
2684
3290
  if (queue.length >= this.maxQueueSize) {
2685
3291
  queue.shift();
2686
- this._logger.info("Queue is full, the oldest event is dropped.");
3292
+ this._logger.warn("Queue is full, the oldest event is dropped.");
2687
3293
  }
2688
3294
  queue.push({
2689
3295
  message
2690
3296
  });
2691
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, queue);
3297
+ this.setPersistedProperty(queueKey, queue);
2692
3298
  this._events.emit(type, message);
2693
3299
  if (queue.length >= this.flushAt)
2694
3300
  this.flushBackground();
@@ -2696,61 +3302,63 @@ class PostHogCoreStateless {
2696
3302
  this._flushTimer = safeSetTimeout(() => this.flushBackground(), this.flushInterval);
2697
3303
  });
2698
3304
  }
2699
- async sendImmediate(type, _message, options) {
3305
+ async sendImmediate(type, _message, options, explicitRoute) {
2700
3306
  if (this.disabled)
2701
3307
  return void this._logger.warn("The client is disabled");
2702
3308
  if (!this._isInitialized)
2703
3309
  await this._initPromise;
2704
3310
  if (this.optedOut)
2705
3311
  return void this._events.emit(type, "Library is disabled. Not sending event. To re-enable, call posthog.optIn()");
2706
- let message = this.prepareMessage(type, _message, options);
3312
+ let message = this.prepareMessage(_message, options);
2707
3313
  message = this.processBeforeEnqueue(message);
2708
3314
  if (message === null)
2709
3315
  return;
2710
- const data = {
2711
- api_key: this.apiKey,
2712
- batch: [
2713
- message
2714
- ],
2715
- sent_at: currentISOTime()
2716
- };
2717
- if (this.historicalMigration)
2718
- data.historical_migration = true;
2719
- const payload = JSON.stringify(data);
2720
- const url = `${this.host}/batch/`;
2721
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2722
- const fetchOptions = {
2723
- method: "POST",
2724
- headers: {
2725
- ...this.getCustomHeaders(),
2726
- "Content-Type": "application/json",
2727
- ...gzippedPayload !== null && {
2728
- "Content-Encoding": "gzip"
2729
- }
2730
- },
2731
- body: gzippedPayload || payload
2732
- };
3316
+ message = this.normalizeMessage(message);
2733
3317
  try {
2734
- const response = await this.fetchWithRetry(url, fetchOptions);
2735
- await response.body?.cancel()?.catch(() => {});
3318
+ await this.sendBatch([
3319
+ message
3320
+ ], undefined, explicitRoute ?? this.getQueueRouteKey(message));
2736
3321
  } catch (err) {
2737
3322
  this._events.emit("error", err);
2738
3323
  }
2739
3324
  }
2740
- prepareMessage(type, _message, options) {
3325
+ normalizeMessage(message) {
3326
+ const { type: _type, library, library_version, ...sanitizedMessage } = message;
3327
+ let properties = isPostHogEventProperties(sanitizedMessage.properties) ? sanitizedMessage.properties : undefined;
3328
+ if (library !== undefined && properties?.$lib === undefined)
3329
+ properties = {
3330
+ ...properties || {},
3331
+ $lib: library
3332
+ };
3333
+ if (library_version !== undefined && properties?.$lib_version === undefined)
3334
+ properties = {
3335
+ ...properties || {},
3336
+ $lib_version: library_version
3337
+ };
3338
+ if (properties)
3339
+ sanitizedMessage.properties = properties;
3340
+ sanitizedMessage.uuid = getEventUuid(sanitizedMessage.uuid, uuidv7);
3341
+ return sanitizedMessage;
3342
+ }
3343
+ normalizeTimestampForWire(timestamp) {
3344
+ const parsedTimestamp = timestamp instanceof Date ? timestamp : typeof timestamp == "string" ? new Date(timestamp) : null;
3345
+ if (!parsedTimestamp || Number.isNaN(parsedTimestamp.getTime()))
3346
+ return timestamp;
3347
+ const normalized = parsedTimestamp.toISOString();
3348
+ const fractionalSeconds = typeof timestamp == "string" ? timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1] : undefined;
3349
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
3350
+ }
3351
+ prepareMessage(_message, options) {
2741
3352
  const message = {
2742
3353
  ..._message,
2743
- type,
2744
- library: this.getLibraryId(),
2745
- library_version: this.getLibraryVersion(),
2746
3354
  timestamp: options?.timestamp ? options?.timestamp : currentISOTime(),
2747
- uuid: options?.uuid ? options.uuid : uuidv7()
3355
+ uuid: getEventUuid(options?.uuid, uuidv7)
2748
3356
  };
2749
3357
  const addGeoipDisableProperty = options?.disableGeoip ?? this.disableGeoip;
2750
3358
  if (addGeoipDisableProperty) {
2751
- if (!message.properties)
3359
+ if (!isPostHogEventProperties(message.properties))
2752
3360
  message.properties = {};
2753
- message["properties"]["$geoip_disable"] = true;
3361
+ message.properties["$geoip_disable"] = true;
2754
3362
  }
2755
3363
  if (message.distinctId) {
2756
3364
  message.distinct_id = message.distinctId;
@@ -2765,21 +3373,64 @@ class PostHogCoreStateless {
2765
3373
  }
2766
3374
  }
2767
3375
  flushBackground() {
3376
+ if (this.pendingFlushPromise)
3377
+ return;
2768
3378
  this.flush().catch(async (err) => {
2769
3379
  await logFlushError(err);
2770
3380
  });
2771
3381
  }
2772
- async flush() {
3382
+ async waitForPendingPromises(maxPromiseId, ignoredPromises = []) {
3383
+ const ignoredPendingPromises = ignoredPromises.filter((promise) => !!promise);
3384
+ let iteration = 0;
3385
+ while (true) {
3386
+ const promises = this.promiseQueue.getPromises([
3387
+ ...ignoredPendingPromises,
3388
+ ...this.flushPromises
3389
+ ], maxPromiseId);
3390
+ if (promises.length === 0)
3391
+ return;
3392
+ if (iteration > 0)
3393
+ this._logger.debug(`flush() re-checking ${promises.length} pending promise(s) before flushing`);
3394
+ await Promise.all(promises.map((promise) => promise.catch(() => {})));
3395
+ iteration++;
3396
+ }
3397
+ }
3398
+ flushWithPendingPromises() {
3399
+ return this.flushInternal(true);
3400
+ }
3401
+ flush() {
3402
+ return this.flushInternal(false);
3403
+ }
3404
+ flushInternal(waitForPendingPromises) {
2773
3405
  if (this.disabled)
2774
- return;
2775
- const nextFlushPromise = allSettled([
2776
- this.flushPromise
2777
- ]).then(() => this._flush());
3406
+ return Promise.resolve();
3407
+ if (!waitForPendingPromises && this.pendingFlushPromise)
3408
+ return this.pendingFlushPromise;
3409
+ const previousFlushPromise = this.flushPromise;
3410
+ const maxPromiseId = this.promiseQueue.maxId;
3411
+ const nextFlushPromise = Promise.resolve().then(() => {
3412
+ if (waitForPendingPromises)
3413
+ return this.waitForPendingPromises(maxPromiseId, [
3414
+ previousFlushPromise,
3415
+ nextFlushPromise
3416
+ ]);
3417
+ }).then(() => allSettled([
3418
+ previousFlushPromise
3419
+ ])).then(() => {
3420
+ if (this.pendingFlushPromise === nextFlushPromise)
3421
+ this.pendingFlushPromise = null;
3422
+ return this._flush();
3423
+ });
3424
+ this.pendingFlushPromise = nextFlushPromise;
2778
3425
  this.flushPromise = nextFlushPromise;
3426
+ this.flushPromises.add(nextFlushPromise);
2779
3427
  this.addPendingPromise(nextFlushPromise);
2780
3428
  allSettled([
2781
3429
  nextFlushPromise
2782
3430
  ]).then(() => {
3431
+ this.flushPromises.delete(nextFlushPromise);
3432
+ if (this.pendingFlushPromise === nextFlushPromise)
3433
+ this.pendingFlushPromise = null;
2783
3434
  if (this.flushPromise === nextFlushPromise)
2784
3435
  this.flushPromise = null;
2785
3436
  });
@@ -2792,55 +3443,102 @@ class PostHogCoreStateless {
2792
3443
  headers["User-Agent"] = customUserAgent;
2793
3444
  return headers;
2794
3445
  }
3446
+ compressPayload(payload) {
3447
+ return gzipCompress(payload, this.isDebug);
3448
+ }
3449
+ getBatchEndpointPath(_route) {
3450
+ return "/batch/";
3451
+ }
3452
+ async sendBatch(batchMessages, retryOptions, route = DEFAULT_QUEUE_ROUTE) {
3453
+ const data = {
3454
+ api_key: this.apiKey,
3455
+ batch: batchMessages.map((message) => {
3456
+ if (!message)
3457
+ return message;
3458
+ const timestamp = this.normalizeTimestampForWire(message.timestamp);
3459
+ return timestamp === message.timestamp ? message : {
3460
+ ...message,
3461
+ timestamp
3462
+ };
3463
+ }),
3464
+ sent_at: currentISOTime()
3465
+ };
3466
+ if (this.historicalMigration)
3467
+ data.historical_migration = true;
3468
+ const payload = safeJsonStringify(data);
3469
+ const url = `${this.host}${this.getBatchEndpointPath(route)}`;
3470
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(payload);
3471
+ const fetchOptions = {
3472
+ method: "POST",
3473
+ headers: {
3474
+ ...this.getCustomHeaders(),
3475
+ "Content-Type": "application/json",
3476
+ ...gzippedPayload !== null && {
3477
+ "Content-Encoding": "gzip"
3478
+ }
3479
+ },
3480
+ body: gzippedPayload || payload
3481
+ };
3482
+ await this.fetchWithRetry(url, fetchOptions, {
3483
+ type: "successful-write"
3484
+ }, retryOptions);
3485
+ }
2795
3486
  async _flush() {
2796
3487
  this.clearFlushTimer();
2797
3488
  await this._initPromise;
2798
- let queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2799
- if (!queue.length)
3489
+ const routes = this.getActiveQueueRoutes();
3490
+ if (!routes.some((route) => this.getRouteQueue(route).length > 0))
2800
3491
  return;
2801
3492
  const sentMessages = [];
3493
+ let firstError;
3494
+ for (const route of routes)
3495
+ try {
3496
+ await this._flushRoute(route, sentMessages);
3497
+ } catch (err) {
3498
+ if (firstError === undefined)
3499
+ firstError = err;
3500
+ }
3501
+ if (firstError !== undefined)
3502
+ throw firstError;
3503
+ this._events.emit("flush", sentMessages);
3504
+ }
3505
+ async _flushRoute(route, sentMessages) {
3506
+ const queueKey = this.persistedQueueKeyForRoute(route);
3507
+ let queue = this.getPersistedProperty(queueKey) || [];
3508
+ if (!queue.length)
3509
+ return;
2802
3510
  const originalQueueLength = queue.length;
2803
- while (queue.length > 0 && sentMessages.length < originalQueueLength) {
3511
+ let sentFromRoute = 0;
3512
+ while (queue.length > 0 && sentFromRoute < originalQueueLength) {
2804
3513
  const batchItems = queue.slice(0, this.maxBatchSize);
2805
- const batchMessages = batchItems.map((item) => item.message);
3514
+ const batchMessages = batchItems.map((item) => item.message === undefined ? item.message : this.normalizeMessage(item.message));
2806
3515
  const persistQueueChange = async () => {
2807
- const refreshedQueue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2808
- const newQueue = refreshedQueue.slice(batchItems.length);
2809
- this.setPersistedProperty(types_PostHogPersistedProperty.Queue, newQueue);
3516
+ const refreshedQueue = this.getPersistedProperty(queueKey) || [];
3517
+ const remainingBatchItems = [
3518
+ ...batchItems
3519
+ ];
3520
+ const newQueue = refreshedQueue.filter((item) => {
3521
+ const itemUuid = item.message?.uuid;
3522
+ const batchItemIndex = remainingBatchItems.findIndex((batchItem) => batchItem === item || typeof itemUuid == "string" && itemUuid.length > 0 && batchItem.message?.uuid === itemUuid);
3523
+ if (batchItemIndex === -1)
3524
+ return true;
3525
+ remainingBatchItems.splice(batchItemIndex, 1);
3526
+ return false;
3527
+ });
3528
+ this.setPersistedProperty(queueKey, newQueue);
2810
3529
  queue = newQueue;
3530
+ this._dequeuedMessagesCount += batchItems.length;
2811
3531
  await this.flushStorage();
2812
3532
  };
2813
- const data = {
2814
- api_key: this.apiKey,
2815
- batch: batchMessages,
2816
- sent_at: currentISOTime()
2817
- };
2818
- if (this.historicalMigration)
2819
- data.historical_migration = true;
2820
- const payload = JSON.stringify(data);
2821
- const url = `${this.host}/batch/`;
2822
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(payload, this.isDebug);
2823
- const fetchOptions = {
2824
- method: "POST",
2825
- headers: {
2826
- ...this.getCustomHeaders(),
2827
- "Content-Type": "application/json",
2828
- ...gzippedPayload !== null && {
2829
- "Content-Encoding": "gzip"
2830
- }
2831
- },
2832
- body: gzippedPayload || payload
2833
- };
2834
3533
  const retryOptions = {
2835
3534
  retryCheck: (err) => {
2836
3535
  if (isPostHogFetchContentTooLargeError(err))
2837
3536
  return false;
2838
- return isPostHogFetchError(err);
3537
+ return isPostHogFetchRetryableError(err);
2839
3538
  }
2840
3539
  };
2841
3540
  try {
2842
- const response = await this.fetchWithRetry(url, fetchOptions, retryOptions);
2843
- await response.body?.cancel()?.catch(() => {});
3541
+ await this.sendBatch(batchMessages, retryOptions, route);
2844
3542
  } catch (err) {
2845
3543
  if (isPostHogFetchContentTooLargeError(err) && batchMessages.length > 1) {
2846
3544
  this.maxBatchSize = Math.max(1, Math.floor(batchMessages.length / 2));
@@ -2854,8 +3552,8 @@ class PostHogCoreStateless {
2854
3552
  }
2855
3553
  await persistQueueChange();
2856
3554
  sentMessages.push(...batchMessages);
3555
+ sentFromRoute += batchMessages.length;
2857
3556
  }
2858
- this._events.emit("flush", sentMessages);
2859
3557
  }
2860
3558
  async _sendLogsBatch(payload) {
2861
3559
  if (this.disabled)
@@ -2865,7 +3563,7 @@ class PostHogCoreStateless {
2865
3563
  };
2866
3564
  const serialized = JSON.stringify(payload);
2867
3565
  const url = `${this.host}/i/v1/logs?token=${encodeURIComponent(this.apiKey)}`;
2868
- const gzippedPayload = this.disableCompression ? null : await gzipCompress(serialized, this.isDebug);
3566
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
2869
3567
  const fetchOptions = {
2870
3568
  method: "POST",
2871
3569
  headers: {
@@ -2879,10 +3577,12 @@ class PostHogCoreStateless {
2879
3577
  };
2880
3578
  try {
2881
3579
  await this.fetchWithRetry(url, fetchOptions, {
3580
+ type: "successful-write"
3581
+ }, {
2882
3582
  retryCheck: (err) => {
2883
3583
  if (isPostHogFetchContentTooLargeError(err))
2884
3584
  return false;
2885
- return isPostHogFetchError(err);
3585
+ return isPostHogFetchRetryableError(err);
2886
3586
  }
2887
3587
  });
2888
3588
  return {
@@ -2904,41 +3604,155 @@ class PostHogCoreStateless {
2904
3604
  };
2905
3605
  }
2906
3606
  }
2907
- async fetchWithRetry(url, options, retryOptions, requestTimeout) {
3607
+ async _sendMetricsBatch(payload) {
3608
+ if (this.disabled)
3609
+ return {
3610
+ kind: "fatal",
3611
+ error: new Error("The client is disabled")
3612
+ };
3613
+ const serialized = JSON.stringify(payload);
3614
+ const url = `${this.host}/i/v1/metrics?token=${encodeURIComponent(this.apiKey)}`;
3615
+ const gzippedPayload = this.disableCompression ? null : await this.compressPayload(serialized);
3616
+ const fetchOptions = {
3617
+ method: "POST",
3618
+ headers: {
3619
+ ...this.getCustomHeaders(),
3620
+ "Content-Type": "application/json",
3621
+ ...gzippedPayload !== null && {
3622
+ "Content-Encoding": "gzip"
3623
+ }
3624
+ },
3625
+ body: gzippedPayload || serialized
3626
+ };
3627
+ try {
3628
+ await this.fetchWithRetry(url, fetchOptions, {
3629
+ type: "successful-write"
3630
+ }, {
3631
+ retryCheck: (err) => {
3632
+ if (isPostHogFetchContentTooLargeError(err))
3633
+ return false;
3634
+ return isPostHogFetchRetryableError(err);
3635
+ }
3636
+ });
3637
+ return {
3638
+ kind: "ok"
3639
+ };
3640
+ } catch (err) {
3641
+ if (isPostHogFetchContentTooLargeError(err))
3642
+ return {
3643
+ kind: "too-large"
3644
+ };
3645
+ if (isPostHogFetchRetryableError(err))
3646
+ return {
3647
+ kind: "retry-later",
3648
+ error: err
3649
+ };
3650
+ return {
3651
+ kind: "fatal",
3652
+ error: err
3653
+ };
3654
+ }
3655
+ }
3656
+ async fetchWithRetry(url, options, responseHandling, retryOptions, requestTimeout) {
2908
3657
  const body = options.body ? options.body : "";
2909
3658
  let reqByteLength = -1;
2910
3659
  try {
2911
- reqByteLength = body instanceof Blob ? body.size : Buffer.byteLength(body, STRING_FORMAT);
3660
+ reqByteLength = body instanceof Blob ? body.size : body instanceof Uint8Array ? body.byteLength : Buffer.byteLength(body, STRING_FORMAT);
2912
3661
  } catch {
2913
3662
  if (body instanceof Blob)
2914
3663
  reqByteLength = body.size;
3664
+ else if (body instanceof Uint8Array)
3665
+ reqByteLength = body.byteLength;
2915
3666
  else {
2916
3667
  const encoded = new TextEncoder().encode(body);
2917
3668
  reqByteLength = encoded.length;
2918
3669
  }
2919
3670
  }
3671
+ const retriableOptions = {
3672
+ ...this._retryOptions,
3673
+ ...retryOptions
3674
+ };
3675
+ let attempt = 0;
2920
3676
  return await retriable(async () => {
3677
+ attempt++;
2921
3678
  const ctrl = new AbortController;
2922
3679
  const timeoutMs = requestTimeout ?? this.requestTimeout;
2923
- const timer = safeSetTimeout(() => ctrl.abort(), timeoutMs);
2924
- let res = null;
3680
+ const requestDeadline = Date.now() + timeoutMs;
3681
+ let timer;
3682
+ const deadline = new Promise((_resolve, reject) => {
3683
+ timer = safeSetTimeout(() => {
3684
+ const timeoutError = new Error(`Request timed out after ${timeoutMs}ms`);
3685
+ timeoutError.name = "AbortError";
3686
+ reject(timeoutError);
3687
+ ctrl.abort(timeoutError);
3688
+ }, timeoutMs);
3689
+ });
3690
+ let res;
3691
+ let responseAccepted = false;
3692
+ let cancellation;
3693
+ const cancelBody = () => cancellation ??= (async () => {
3694
+ try {
3695
+ await res?.body?.cancel();
3696
+ } catch {}
3697
+ })();
2925
3698
  try {
2926
- res = await this.fetch(url, {
2927
- signal: ctrl.signal,
2928
- ...options
2929
- });
2930
- } catch (e) {
2931
- throw new PostHogFetchNetworkError(e);
3699
+ let fetchPromise;
3700
+ try {
3701
+ fetchPromise = this.fetch(url, {
3702
+ signal: ctrl.signal,
3703
+ ...options
3704
+ });
3705
+ } catch (e) {
3706
+ throw new PostHogFetchNetworkError(e);
3707
+ }
3708
+ fetchPromise.then((lateResponse) => {
3709
+ if (ctrl.signal.aborted && !responseAccepted)
3710
+ Promise.resolve(lateResponse.body?.cancel()).catch(() => {});
3711
+ }).catch(() => {});
3712
+ try {
3713
+ res = await Promise.race([
3714
+ fetchPromise,
3715
+ deadline
3716
+ ]);
3717
+ responseAccepted = true;
3718
+ } catch (e) {
3719
+ throw new PostHogFetchNetworkError(e);
3720
+ }
3721
+ const isNoCors = options.mode === "no-cors";
3722
+ if (!isNoCors && (res.status < 200 || res.status >= 400))
3723
+ throw new PostHogFetchHttpError(res, reqByteLength, requestDeadline, ctrl);
3724
+ if (responseHandling.type === "successful-write") {
3725
+ try {
3726
+ await Promise.race([
3727
+ cancelBody(),
3728
+ deadline
3729
+ ]);
3730
+ } catch {}
3731
+ return;
3732
+ }
3733
+ try {
3734
+ return await Promise.race([
3735
+ responseHandling.consume(res),
3736
+ deadline
3737
+ ]);
3738
+ } catch (e) {
3739
+ if (ctrl.signal.aborted)
3740
+ throw new PostHogFetchNetworkError(e);
3741
+ throw e;
3742
+ }
2932
3743
  } finally {
2933
3744
  clearTimeout(timer);
3745
+ if (ctrl.signal.aborted && res)
3746
+ cancelBody();
2934
3747
  }
2935
- const isNoCors = options.mode === "no-cors";
2936
- if (!isNoCors && (res.status < 200 || res.status >= 400))
2937
- throw new PostHogFetchHttpError(res, reqByteLength);
2938
- return res;
2939
3748
  }, {
2940
- ...this._retryOptions,
2941
- ...retryOptions
3749
+ ...retriableOptions,
3750
+ retryCheck: (error) => {
3751
+ const shouldRetry = retriableOptions.retryCheck(error);
3752
+ if (shouldRetry && attempt <= retriableOptions.retryCount && error instanceof PostHogFetchHttpError)
3753
+ error.cancelResponseBody();
3754
+ return shouldRetry;
3755
+ }
2942
3756
  });
2943
3757
  }
2944
3758
  async _shutdown(shutdownTimeoutMs = 30000) {
@@ -2951,12 +3765,17 @@ class PostHogCoreStateless {
2951
3765
  try {
2952
3766
  await this.promiseQueue.join();
2953
3767
  while (true) {
2954
- const queue = this.getPersistedProperty(types_PostHogPersistedProperty.Queue) || [];
2955
- if (queue.length === 0)
3768
+ const hasQueuedEvents = this.getActiveQueueRoutes().some((route) => this.getRouteQueue(route).length > 0);
3769
+ if (!hasQueuedEvents)
2956
3770
  break;
3771
+ const dequeuedBeforeFlush = this._dequeuedMessagesCount;
2957
3772
  await this.flush();
2958
3773
  if (hasTimedOut)
2959
3774
  break;
3775
+ if (this._dequeuedMessagesCount === dequeuedBeforeFlush) {
3776
+ this._logger.warn("Shutdown flush completed but did not send any queued events. Stopping drain to avoid a loop.");
3777
+ break;
3778
+ }
2960
3779
  }
2961
3780
  } catch (e) {
2962
3781
  if (!isPostHogFetchError(e))
@@ -2964,21 +3783,12 @@ class PostHogCoreStateless {
2964
3783
  await logFlushError(e);
2965
3784
  }
2966
3785
  };
2967
- let timeoutHandle;
2968
- try {
2969
- return await Promise.race([
2970
- new Promise((_, reject) => {
2971
- timeoutHandle = safeSetTimeout(() => {
2972
- this._logger.error("Timed out while shutting down PostHog");
2973
- hasTimedOut = true;
2974
- reject("Timeout while shutting down PostHog. Some events may not have been sent.");
2975
- }, shutdownTimeoutMs);
2976
- }),
2977
- doShutdown()
2978
- ]);
2979
- } finally {
2980
- clearTimeout(timeoutHandle);
2981
- }
3786
+ return raceWithTimeout(doShutdown(), shutdownTimeoutMs, () => {
3787
+ this._logger.critical("Timeout while shutting down PostHog. Some events may not have been sent.", {
3788
+ shutdownTimeoutMs
3789
+ });
3790
+ hasTimedOut = true;
3791
+ });
2982
3792
  }
2983
3793
  async shutdown(shutdownTimeoutMs = 30000) {
2984
3794
  if (this.shutdownPromise)
@@ -2990,21 +3800,30 @@ class PostHogCoreStateless {
2990
3800
  return this.shutdownPromise;
2991
3801
  }
2992
3802
  }
2993
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
2994
- import { createReadStream } from "node:fs";
3803
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/context-lines.node.mjs
3804
+ import { constants as constants2 } from "node:fs";
3805
+ import { open as promises_open } from "node:fs/promises";
3806
+ import { isAbsolute } from "node:path";
2995
3807
  import { createInterface } from "node:readline";
2996
- var LRU_FILE_CONTENTS_CACHE = new exports_error_tracking.ReduceableCache(25);
2997
- var LRU_FILE_CONTENTS_FS_READ_FAILED = new exports_error_tracking.ReduceableCache(20);
3808
+ var LRU_FILE_CONTENTS_CACHE = new ReduceableCache(25);
3809
+ var LRU_FILE_CONTENTS_FS_READ_FAILED = new ReduceableCache(20);
2998
3810
  var DEFAULT_LINES_OF_CONTEXT = 7;
2999
3811
  var MAX_CONTEXTLINES_COLNO = 1000;
3000
3812
  var MAX_CONTEXTLINES_LINENO = 1e4;
3001
- async function addSourceContext(frames) {
3813
+ var MAX_CONTEXTLINES_FILE_SIZE = 10485760;
3814
+ async function addSourceContext(frames, openSourceFile = promises_open, logger) {
3002
3815
  const filesToLines = {};
3816
+ let basePath;
3817
+ try {
3818
+ basePath = process.cwd();
3819
+ } catch {}
3003
3820
  for (let i = frames.length - 1;i >= 0; i--) {
3004
3821
  const frame = frames[i];
3005
3822
  const filename = frame?.filename;
3006
3823
  if (!frame || typeof filename != "string" || typeof frame.lineno != "number" || shouldSkipContextLinesForFile(filename) || shouldSkipContextLinesForFrame(frame))
3007
3824
  continue;
3825
+ if (!isAbsolute(filename) && basePath === undefined)
3826
+ continue;
3008
3827
  const filesToLinesOutput = filesToLines[filename];
3009
3828
  if (!filesToLinesOutput)
3010
3829
  filesToLines[filename] = [];
@@ -3015,50 +3834,98 @@ async function addSourceContext(frames) {
3015
3834
  return frames;
3016
3835
  const readlinePromises = [];
3017
3836
  for (const file of files) {
3018
- if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file))
3837
+ const cacheKey = makeSourceCacheKey(file, basePath);
3838
+ if (cacheKey === undefined)
3839
+ continue;
3840
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(cacheKey))
3019
3841
  continue;
3020
3842
  const filesToLineRanges = filesToLines[file];
3021
3843
  if (!filesToLineRanges)
3022
3844
  continue;
3023
3845
  filesToLineRanges.sort((a, b) => a - b);
3024
3846
  const ranges = makeLineReaderRanges(filesToLineRanges);
3025
- if (ranges.every((r) => rangeExistsInContentCache(file, r)))
3847
+ if (ranges.every((r) => rangeExistsInContentCache(cacheKey, r)))
3026
3848
  continue;
3027
- const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
3028
- readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
3849
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, cacheKey, {});
3850
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache, cacheKey, openSourceFile, logger));
3029
3851
  }
3030
3852
  await Promise.all(readlinePromises).catch(() => {});
3031
3853
  if (frames && frames.length > 0)
3032
- addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE);
3854
+ addSourceContextToFrames(frames, LRU_FILE_CONTENTS_CACHE, basePath);
3033
3855
  LRU_FILE_CONTENTS_CACHE.reduce();
3034
3856
  return frames;
3035
3857
  }
3036
- function getContextLinesFromFile(path2, ranges, output) {
3858
+ async function openRegularSourceFile(path, openSourceFile, logger) {
3859
+ let fileHandle;
3860
+ let isValid = false;
3861
+ try {
3862
+ fileHandle = await openSourceFile(path, constants2.O_RDONLY | constants2.O_NONBLOCK);
3863
+ const fileStat = await fileHandle.stat();
3864
+ if (!fileStat.isFile())
3865
+ return;
3866
+ if (fileStat.size > MAX_CONTEXTLINES_FILE_SIZE)
3867
+ return void logger?.debug(`Skipping source context for oversized file ${path}: ${fileStat.size} bytes exceeds ${MAX_CONTEXTLINES_FILE_SIZE}`);
3868
+ isValid = true;
3869
+ return fileHandle;
3870
+ } catch {
3871
+ return;
3872
+ } finally {
3873
+ if (fileHandle && !isValid)
3874
+ await fileHandle.close().catch(() => {});
3875
+ }
3876
+ }
3877
+ async function getContextLinesFromFile(path, ranges, output, cacheKey, openSourceFile, logger) {
3878
+ const fileHandle = await openRegularSourceFile(path, openSourceFile, logger);
3879
+ if (fileHandle === undefined)
3880
+ return void LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3881
+ const openedFileHandle = fileHandle;
3037
3882
  return new Promise((resolve) => {
3038
- const stream = createReadStream(path2);
3039
- const lineReaded = createInterface({
3040
- input: stream
3041
- });
3042
- function destroyStreamAndResolve() {
3043
- stream.destroy();
3044
- resolve();
3883
+ let finished = false;
3884
+ function destroyStreamAndResolve(stream) {
3885
+ if (finished)
3886
+ return;
3887
+ finished = true;
3888
+ stream?.destroy();
3889
+ openedFileHandle.close().then(resolve, resolve);
3890
+ }
3891
+ let stream;
3892
+ try {
3893
+ stream = openedFileHandle.createReadStream({
3894
+ autoClose: false,
3895
+ start: 0,
3896
+ end: MAX_CONTEXTLINES_FILE_SIZE - 1
3897
+ });
3898
+ } catch {
3899
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3900
+ destroyStreamAndResolve();
3901
+ return;
3902
+ }
3903
+ let lineReaded;
3904
+ try {
3905
+ lineReaded = createInterface({
3906
+ input: stream
3907
+ });
3908
+ } catch {
3909
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3910
+ destroyStreamAndResolve(stream);
3911
+ return;
3045
3912
  }
3046
3913
  let lineNumber = 0;
3047
3914
  let currentRangeIndex = 0;
3048
3915
  const range = ranges[currentRangeIndex];
3049
3916
  if (range === undefined)
3050
- return void destroyStreamAndResolve();
3917
+ return void destroyStreamAndResolve(stream);
3051
3918
  let rangeStart = range[0];
3052
3919
  let rangeEnd = range[1];
3053
3920
  function onStreamError() {
3054
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path2, 1);
3921
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(cacheKey, 1);
3055
3922
  lineReaded.close();
3056
3923
  lineReaded.removeAllListeners();
3057
- destroyStreamAndResolve();
3924
+ destroyStreamAndResolve(stream);
3058
3925
  }
3059
3926
  stream.on("error", onStreamError);
3060
3927
  lineReaded.on("error", onStreamError);
3061
- lineReaded.on("close", destroyStreamAndResolve);
3928
+ lineReaded.on("close", () => destroyStreamAndResolve(stream));
3062
3929
  lineReaded.on("line", (line) => {
3063
3930
  lineNumber++;
3064
3931
  if (lineNumber < rangeStart)
@@ -3071,22 +3938,23 @@ function getContextLinesFromFile(path2, ranges, output) {
3071
3938
  return;
3072
3939
  }
3073
3940
  currentRangeIndex++;
3074
- const range2 = ranges[currentRangeIndex];
3075
- if (range2 === undefined) {
3941
+ const range = ranges[currentRangeIndex];
3942
+ if (range === undefined) {
3076
3943
  lineReaded.close();
3077
3944
  lineReaded.removeAllListeners();
3078
3945
  return;
3079
3946
  }
3080
- rangeStart = range2[0];
3081
- rangeEnd = range2[1];
3947
+ rangeStart = range[0];
3948
+ rangeEnd = range[1];
3082
3949
  }
3083
3950
  });
3084
3951
  });
3085
3952
  }
3086
- function addSourceContextToFrames(frames, cache) {
3953
+ function addSourceContextToFrames(frames, cache, basePath) {
3087
3954
  for (const frame of frames)
3088
3955
  if (frame.filename && frame.context_line === undefined && typeof frame.lineno == "number") {
3089
- const contents = cache.get(frame.filename);
3956
+ const cacheKey = makeSourceCacheKey(frame.filename, basePath);
3957
+ const contents = cacheKey === undefined ? undefined : cache.get(cacheKey);
3090
3958
  if (contents === undefined)
3091
3959
  continue;
3092
3960
  addContextToFrame(frame.lineno, frame, contents);
@@ -3119,8 +3987,8 @@ function clearLineContext(frame) {
3119
3987
  delete frame.context_line;
3120
3988
  delete frame.post_context;
3121
3989
  }
3122
- function shouldSkipContextLinesForFile(path2) {
3123
- return path2.startsWith("node:") || path2.endsWith(".min.js") || path2.endsWith(".min.cjs") || path2.endsWith(".min.mjs") || path2.startsWith("data:");
3990
+ function shouldSkipContextLinesForFile(path) {
3991
+ return path.startsWith("node:") || path.endsWith(".min.js") || path.endsWith(".min.cjs") || path.endsWith(".min.mjs") || path.startsWith("data:");
3124
3992
  }
3125
3993
  function shouldSkipContextLinesForFrame(frame) {
3126
3994
  if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO)
@@ -3129,8 +3997,19 @@ function shouldSkipContextLinesForFrame(frame) {
3129
3997
  return true;
3130
3998
  return false;
3131
3999
  }
3132
- function rangeExistsInContentCache(file, range) {
3133
- const contents = LRU_FILE_CONTENTS_CACHE.get(file);
4000
+ function makeSourceCacheKey(path, basePath) {
4001
+ if (isAbsolute(path))
4002
+ return JSON.stringify([
4003
+ null,
4004
+ path
4005
+ ]);
4006
+ return basePath === undefined ? undefined : JSON.stringify([
4007
+ basePath,
4008
+ path
4009
+ ]);
4010
+ }
4011
+ function rangeExistsInContentCache(cacheKey, range) {
4012
+ const contents = LRU_FILE_CONTENTS_CACHE.get(cacheKey);
3134
4013
  if (contents === undefined)
3135
4014
  return false;
3136
4015
  for (let i = range[0];i <= range[1]; i++)
@@ -3208,8 +4087,8 @@ function snipLine(line, colno) {
3208
4087
  return newLine;
3209
4088
  }
3210
4089
 
3211
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
3212
- import { isAbsolute, relative, sep as sep2 } from "node:path";
4090
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/relative-path.node.mjs
4091
+ import { isAbsolute as isAbsolute2, relative, sep as sep2 } from "node:path";
3213
4092
  function createRelativePathModifier(basePath = process.cwd()) {
3214
4093
  const isWindows = sep2 === "\\";
3215
4094
  const toUnix = (p) => isWindows ? p.replace(/\\/g, "/") : p;
@@ -3217,17 +4096,17 @@ function createRelativePathModifier(basePath = process.cwd()) {
3217
4096
  return async (frames) => {
3218
4097
  for (const frame of frames)
3219
4098
  if (!(!frame.filename || frame.filename.startsWith("node:") || frame.filename.startsWith("data:"))) {
3220
- if (isAbsolute(frame.filename))
4099
+ if (isAbsolute2(frame.filename))
3221
4100
  frame.filename = toUnix(relative(normalizedBase, toUnix(frame.filename)));
3222
4101
  }
3223
4102
  return frames;
3224
4103
  };
3225
4104
  }
3226
4105
 
3227
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/version.mjs
3228
- var version = "5.35.12";
4106
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/version.mjs
4107
+ var version = "5.51.1";
3229
4108
 
3230
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/types.mjs
4109
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/types.mjs
3231
4110
  var FeatureFlagError2 = {
3232
4111
  ERRORS_WHILE_COMPUTING: "errors_while_computing_flags",
3233
4112
  FLAG_MISSING: "flag_missing",
@@ -3235,7 +4114,7 @@ var FeatureFlagError2 = {
3235
4114
  UNKNOWN_ERROR: "unknown_error"
3236
4115
  };
3237
4116
 
3238
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
4117
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/feature-flag-evaluations.mjs
3239
4118
  class FeatureFlagEvaluations {
3240
4119
  constructor(init) {
3241
4120
  this._host = init.host;
@@ -3251,10 +4130,10 @@ class FeatureFlagEvaluations {
3251
4130
  this._accessed = init.accessed ?? new Set;
3252
4131
  this._isSlice = init.isSlice ?? false;
3253
4132
  }
3254
- isEnabled(key) {
4133
+ isEnabled(key, options = {}) {
3255
4134
  const flag = this._flags[key];
3256
4135
  this._recordAccess(key);
3257
- return flag?.enabled ?? false;
4136
+ return flag?.enabled ?? options.defaultValue ?? false;
3258
4137
  }
3259
4138
  getFlag(key) {
3260
4139
  const flag = this._flags[key];
@@ -3344,6 +4223,8 @@ class FeatureFlagEvaluations {
3344
4223
  $feature_flag_request_id: this._requestId,
3345
4224
  $feature_flag_evaluated_at: flag?.locallyEvaluated ? Date.now() : this._evaluatedAt
3346
4225
  };
4226
+ if (flag?.hasExperiment !== undefined)
4227
+ properties.$feature_flag_has_experiment = flag.hasExperiment;
3347
4228
  if (flag?.locallyEvaluated && this._flagDefinitionsLoadedAt !== undefined)
3348
4229
  properties.$feature_flag_definitions_loaded_at = this._flagDefinitionsLoadedAt;
3349
4230
  const errors = [];
@@ -3366,7 +4247,7 @@ class FeatureFlagEvaluations {
3366
4247
  }
3367
4248
  }
3368
4249
 
3369
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
4250
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/crypto.mjs
3370
4251
  async function hashSHA1(text) {
3371
4252
  const subtle = globalThis.crypto?.subtle;
3372
4253
  if (!subtle)
@@ -3376,7 +4257,7 @@ async function hashSHA1(text) {
3376
4257
  return hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
3377
4258
  }
3378
4259
 
3379
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
4260
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/feature-flags/feature-flags.mjs
3380
4261
  var SIXTY_SECONDS = 60000;
3381
4262
  var LONG_SCALE = 1152921504606847000;
3382
4263
  var NULL_VALUES_ALLOWED_OPERATORS = [
@@ -3393,22 +4274,23 @@ class ClientError extends Error {
3393
4274
  Object.setPrototypeOf(this, ClientError.prototype);
3394
4275
  }
3395
4276
  }
4277
+ function setCustomErrorPrototype(error, constructor) {
4278
+ error.name = constructor.name;
4279
+ Error.captureStackTrace(error, constructor);
4280
+ Object.setPrototypeOf(error, constructor.prototype);
4281
+ }
3396
4282
 
3397
4283
  class InconclusiveMatchError extends Error {
3398
4284
  constructor(message) {
3399
4285
  super(message);
3400
- this.name = this.constructor.name;
3401
- Error.captureStackTrace(this, this.constructor);
3402
- Object.setPrototypeOf(this, InconclusiveMatchError.prototype);
4286
+ setCustomErrorPrototype(this, InconclusiveMatchError);
3403
4287
  }
3404
4288
  }
3405
4289
 
3406
4290
  class RequiresServerEvaluation extends Error {
3407
4291
  constructor(message) {
3408
4292
  super(message);
3409
- this.name = this.constructor.name;
3410
- Error.captureStackTrace(this, this.constructor);
3411
- Object.setPrototypeOf(this, RequiresServerEvaluation.prototype);
4293
+ setCustomErrorPrototype(this, RequiresServerEvaluation);
3412
4294
  }
3413
4295
  }
3414
4296
 
@@ -3417,6 +4299,7 @@ class FeatureFlagsPoller {
3417
4299
  this.debugMode = false;
3418
4300
  this.shouldBeginExponentialBackoff = false;
3419
4301
  this.backOffCount = 0;
4302
+ this.pollerStopped = false;
3420
4303
  this.pollingInterval = pollingInterval;
3421
4304
  this.personalApiKey = personalApiKey;
3422
4305
  this.featureFlags = [];
@@ -3432,6 +4315,7 @@ class FeatureFlagsPoller {
3432
4315
  this.onError = options.onError;
3433
4316
  this.customHeaders = customHeaders;
3434
4317
  this.onLoad = options.onLoad;
4318
+ this.onMinimalFlagCalledEvents = options.onMinimalFlagCalledEvents;
3435
4319
  this.cacheProvider = options.cacheProvider;
3436
4320
  this.strictLocalEvaluation = options.strictLocalEvaluation ?? false;
3437
4321
  this.loadFeatureFlags();
@@ -3629,6 +4513,7 @@ class FeatureFlagsPoller {
3629
4513
  const flagFilters = flag.filters || {};
3630
4514
  const flagConditions = flagFilters.groups || [];
3631
4515
  const flagAggregation = flagFilters.aggregation_group_type_index;
4516
+ const earlyExitEnabled = flagFilters.early_exit ?? false;
3632
4517
  const { groups, groupProperties } = evaluationContext;
3633
4518
  let isInconclusive = false;
3634
4519
  let result;
@@ -3652,12 +4537,15 @@ class FeatureFlagsPoller {
3652
4537
  effectiveBucketingValue = groups[groupName];
3653
4538
  }
3654
4539
  }
3655
- if (await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext)) {
4540
+ const matchResult = await this.isConditionMatch(flag, effectiveBucketingValue, condition, effectiveProperties, evaluationContext);
4541
+ if (matchResult === "match") {
3656
4542
  const variantOverride = condition.variant;
3657
4543
  const flagVariants = flagFilters.multivariate?.variants || [];
3658
4544
  result = variantOverride && flagVariants.some((variant) => variant.key === variantOverride) ? variantOverride : await this.getMatchingVariant(flag, effectiveBucketingValue) || true;
3659
4545
  break;
3660
4546
  }
4547
+ if (earlyExitEnabled && matchResult === "out_of_rollout_bound")
4548
+ return false;
3661
4549
  } catch (e) {
3662
4550
  if (e instanceof RequiresServerEvaluation)
3663
4551
  throw e;
@@ -3681,16 +4569,20 @@ class FeatureFlagsPoller {
3681
4569
  for (const prop of condition.properties) {
3682
4570
  const propertyType = prop.type;
3683
4571
  let matches = false;
3684
- 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);
4572
+ if (propertyType === "cohort") {
4573
+ const inCohort = await matchCohort(prop, properties, this.cohorts, this.debugMode, (depProp) => this.evaluateFlagDependency(depProp, properties, evaluationContext));
4574
+ matches = prop.operator === "not_in" ? !inCohort : inCohort;
4575
+ } else
4576
+ matches = propertyType === "flag" ? await this.evaluateFlagDependency(prop, properties, evaluationContext) : matchProperty(prop, properties, warnFunction);
3685
4577
  if (!matches)
3686
- return false;
4578
+ return "no_match";
3687
4579
  }
3688
4580
  if (rolloutPercentage == undefined)
3689
- return true;
4581
+ return "match";
3690
4582
  }
3691
4583
  if (rolloutPercentage != null && await _hash(flag.key, bucketingValue) > rolloutPercentage / 100)
3692
- return false;
3693
- return true;
4584
+ return "out_of_rollout_bound";
4585
+ return "match";
3694
4586
  }
3695
4587
  async getMatchingVariant(flag, bucketingValue) {
3696
4588
  const hashValue = await _hash(flag.key, bucketingValue, "variant");
@@ -3721,6 +4613,7 @@ class FeatureFlagsPoller {
3721
4613
  this.groupTypeMapping = flagData.groupTypeMapping;
3722
4614
  this.cohorts = flagData.cohorts;
3723
4615
  this.loadedSuccessfullyOnce = true;
4616
+ this.onMinimalFlagCalledEvents?.(flagData.minimalFlagCalledEvents === true);
3724
4617
  }
3725
4618
  warnAboutExperienceContinuityFlags(flags) {
3726
4619
  if (this.strictLocalEvaluation)
@@ -3784,7 +4677,6 @@ class FeatureFlagsPoller {
3784
4677
  clearTimeout(this.poller);
3785
4678
  this.poller = undefined;
3786
4679
  }
3787
- this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3788
4680
  try {
3789
4681
  let shouldFetch = true;
3790
4682
  if (this.cacheProvider)
@@ -3812,17 +4704,18 @@ class FeatureFlagsPoller {
3812
4704
  return;
3813
4705
  case 401:
3814
4706
  this.beginBackoff();
3815
- 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`);
4707
+ 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`);
3816
4708
  case 402:
3817
4709
  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");
3818
4710
  this.featureFlags = [];
3819
4711
  this.featureFlagsByKey = {};
3820
4712
  this.groupTypeMapping = {};
3821
4713
  this.cohorts = {};
4714
+ this.onMinimalFlagCalledEvents?.(false);
3822
4715
  return;
3823
4716
  case 403:
3824
4717
  this.beginBackoff();
3825
- 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`);
4718
+ 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`);
3826
4719
  case 429:
3827
4720
  this.beginBackoff();
3828
4721
  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`);
@@ -3834,7 +4727,8 @@ class FeatureFlagsPoller {
3834
4727
  const flagData = {
3835
4728
  flags: responseJson.flags ?? [],
3836
4729
  groupTypeMapping: responseJson.group_type_mapping || {},
3837
- cohorts: responseJson.cohorts || {}
4730
+ cohorts: responseJson.cohorts || {},
4731
+ minimalFlagCalledEvents: responseJson.minimal_flag_called_events === true
3838
4732
  };
3839
4733
  this.updateFlagState(flagData);
3840
4734
  this.flagDefinitionsLoadedAt = Date.now();
@@ -3855,6 +4749,9 @@ class FeatureFlagsPoller {
3855
4749
  } catch (err) {
3856
4750
  if (err instanceof ClientError)
3857
4751
  this.onError?.(err);
4752
+ } finally {
4753
+ if (!this.pollerStopped)
4754
+ this.poller = setTimeout(() => this.loadFeatureFlags(true), this.getPollingInterval());
3858
4755
  }
3859
4756
  }
3860
4757
  getPersonalApiKeyRequestOptions(method = "GET", etag) {
@@ -3870,7 +4767,7 @@ class FeatureFlagsPoller {
3870
4767
  headers
3871
4768
  };
3872
4769
  }
3873
- _requestFeatureFlagDefinitions() {
4770
+ async _requestFeatureFlagDefinitions() {
3874
4771
  const url = `${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`;
3875
4772
  const options = this.getPersonalApiKeyRequestOptions("GET", this.flagsEtag);
3876
4773
  let abortTimeout = null;
@@ -3881,23 +4778,49 @@ class FeatureFlagsPoller {
3881
4778
  }, this.timeout);
3882
4779
  options.signal = controller.signal;
3883
4780
  }
4781
+ const clearAbortTimeout = () => clearTimeout(abortTimeout);
3884
4782
  try {
3885
4783
  const fetch1 = this.fetch;
3886
- return fetch1(url, options);
3887
- } finally {
3888
- clearTimeout(abortTimeout);
4784
+ const res = await fetch1(url, options);
4785
+ if (res.status !== 200) {
4786
+ clearAbortTimeout();
4787
+ return res;
4788
+ }
4789
+ return {
4790
+ status: res.status,
4791
+ headers: res.headers,
4792
+ body: res.body,
4793
+ text: async () => {
4794
+ try {
4795
+ return await res.text();
4796
+ } finally {
4797
+ clearAbortTimeout();
4798
+ }
4799
+ },
4800
+ json: async () => {
4801
+ try {
4802
+ return await res.json();
4803
+ } finally {
4804
+ clearAbortTimeout();
4805
+ }
4806
+ }
4807
+ };
4808
+ } catch (err) {
4809
+ clearAbortTimeout();
4810
+ throw err;
3889
4811
  }
3890
4812
  }
3891
4813
  async stopPoller(timeoutMs = 30000) {
4814
+ this.pollerStopped = true;
3892
4815
  clearTimeout(this.poller);
4816
+ this.poller = undefined;
3893
4817
  if (this.cacheProvider)
3894
4818
  try {
3895
4819
  const shutdownResult = this.cacheProvider.shutdown();
3896
4820
  if (shutdownResult instanceof Promise)
3897
- await Promise.race([
3898
- shutdownResult,
3899
- new Promise((_, reject) => setTimeout(() => reject(new Error(`Cache shutdown timeout after ${timeoutMs}ms`)), timeoutMs))
3900
- ]);
4821
+ await raceWithTimeout(shutdownResult, timeoutMs, () => {
4822
+ throw new Error(`Cache shutdown timeout after ${timeoutMs}ms`);
4823
+ });
3901
4824
  } catch (err) {
3902
4825
  this.onError?.(new Error(`Error during cache shutdown: ${err}`));
3903
4826
  }
@@ -3925,21 +4848,21 @@ function matchProperty(property, propertyValues, warnFunction) {
3925
4848
  warnFunction(`Property ${key} cannot have a value of null/undefined with the ${operator} operator`);
3926
4849
  return false;
3927
4850
  }
3928
- function computeExactMatch(value2, overrideValue2) {
3929
- if (Array.isArray(value2))
3930
- return value2.map((val) => String(val).toLowerCase()).includes(String(overrideValue2).toLowerCase());
3931
- return String(value2).toLowerCase() === String(overrideValue2).toLowerCase();
4851
+ function computeExactMatch(value, overrideValue) {
4852
+ if (Array.isArray(value))
4853
+ return value.map((val) => String(val).toLowerCase()).includes(String(overrideValue).toLowerCase());
4854
+ return String(value).toLowerCase() === String(overrideValue).toLowerCase();
3932
4855
  }
3933
- function compare(lhs, rhs, operator2) {
3934
- if (operator2 === "gt")
4856
+ function compare(lhs, rhs, operator) {
4857
+ if (operator === "gt")
3935
4858
  return lhs > rhs;
3936
- if (operator2 === "gte")
4859
+ if (operator === "gte")
3937
4860
  return lhs >= rhs;
3938
- if (operator2 === "lt")
4861
+ if (operator === "lt")
3939
4862
  return lhs < rhs;
3940
- if (operator2 === "lte")
4863
+ if (operator === "lte")
3941
4864
  return lhs <= rhs;
3942
- throw new Error(`Invalid operator: ${operator2}`);
4865
+ throw new Error(`Invalid operator: ${operator}`);
3943
4866
  }
3944
4867
  switch (operator) {
3945
4868
  case "exact":
@@ -3952,6 +4875,14 @@ function matchProperty(property, propertyValues, warnFunction) {
3952
4875
  return String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
3953
4876
  case "not_icontains":
3954
4877
  return !String(overrideValue).toLowerCase().includes(String(value).toLowerCase());
4878
+ case "starts_with":
4879
+ return String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
4880
+ case "not_starts_with":
4881
+ return !String(overrideValue).toLowerCase().startsWith(String(value).toLowerCase());
4882
+ case "ends_with":
4883
+ return String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
4884
+ case "not_ends_with":
4885
+ return !String(overrideValue).toLowerCase().endsWith(String(value).toLowerCase());
3955
4886
  case "regex":
3956
4887
  return isValidRegex(String(value)) && String(overrideValue).match(String(value)) !== null;
3957
4888
  case "not_regex":
@@ -4278,19 +5209,75 @@ function relativeDateParseForFeatureFlagMatching(value) {
4278
5209
  }
4279
5210
  }
4280
5211
 
4281
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5212
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/autocapture.mjs
5213
+ var UNHANDLED_REJECTION_OPTION_NAMES = [
5214
+ "--unhandled-rejections",
5215
+ "--unhandled_rejections"
5216
+ ];
5217
+ var UNHANDLED_REJECTION_MODES = new Set([
5218
+ "throw",
5219
+ "strict",
5220
+ "warn",
5221
+ "warn-with-error-code",
5222
+ "none"
5223
+ ]);
5224
+ var STARTUP_EXEC_ARGV = [
5225
+ ...globalThis.process?.execArgv ?? []
5226
+ ];
5227
+ var STARTUP_NODE_OPTIONS = globalThis.process?.env?.NODE_OPTIONS;
5228
+ function splitNodeOptions(nodeOptions) {
5229
+ const args = [];
5230
+ let current = "";
5231
+ let isInString = false;
5232
+ for (let index = 0;index < nodeOptions.length; index++) {
5233
+ const character = nodeOptions[index];
5234
+ if (character === "\\" && isInString && index + 1 < nodeOptions.length)
5235
+ current += nodeOptions[++index];
5236
+ else if (character !== " " || isInString)
5237
+ if (character === '"')
5238
+ isInString = !isInString;
5239
+ else
5240
+ current += character;
5241
+ else if (current) {
5242
+ args.push(current);
5243
+ current = "";
5244
+ }
5245
+ }
5246
+ if (current)
5247
+ args.push(current);
5248
+ return args;
5249
+ }
5250
+ function findUnhandledRejectionMode(args) {
5251
+ let mode;
5252
+ for (let index = 0;index < args.length; index++) {
5253
+ const argument = args[index];
5254
+ const optionName = UNHANDLED_REJECTION_OPTION_NAMES.find((name) => argument === name || argument.startsWith(`${name}=`));
5255
+ if (!optionName)
5256
+ continue;
5257
+ const value = argument === optionName ? args[++index] : argument.slice(optionName.length + 1);
5258
+ if (UNHANDLED_REJECTION_MODES.has(value))
5259
+ mode = value;
5260
+ }
5261
+ return mode;
5262
+ }
5263
+ function getUnhandledRejectionMode(execArgv = STARTUP_EXEC_ARGV, nodeOptions = STARTUP_NODE_OPTIONS) {
5264
+ return findUnhandledRejectionMode(execArgv) ?? findUnhandledRejectionMode(splitNodeOptions(nodeOptions ?? "")) ?? "throw";
5265
+ }
5266
+ var STARTUP_UNHANDLED_REJECTION_MODE = getUnhandledRejectionMode();
5267
+ function captureUncaughtException(captureFn, error, origin) {
5268
+ captureFn(error, {
5269
+ mechanism: {
5270
+ type: origin === "unhandledRejection" ? "onunhandledrejection" : "onuncaughtexception",
5271
+ handled: false
5272
+ }
5273
+ });
5274
+ }
4282
5275
  function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4283
5276
  let calledFatalError = false;
4284
- return Object.assign((error) => {
5277
+ return Object.assign((error, origin) => {
4285
5278
  const userProvidedListenersCount = global.process.listeners("uncaughtException").filter((listener) => listener.name !== "domainUncaughtExceptionClear" && listener._posthogErrorHandler !== true).length;
4286
- const processWouldExit = userProvidedListenersCount === 0;
4287
- captureFn(error, {
4288
- mechanism: {
4289
- type: "onuncaughtexception",
4290
- handled: false
4291
- }
4292
- });
4293
- if (!calledFatalError && processWouldExit) {
5279
+ captureUncaughtException(captureFn, error, origin);
5280
+ if (!calledFatalError && userProvidedListenersCount === 0) {
4294
5281
  calledFatalError = true;
4295
5282
  onFatalFn(error);
4296
5283
  }
@@ -4298,29 +5285,38 @@ function makeUncaughtExceptionHandler(captureFn, onFatalFn) {
4298
5285
  _posthogErrorHandler: true
4299
5286
  });
4300
5287
  }
4301
- function addUncaughtExceptionListener(captureFn, onFatalFn) {
4302
- globalThis.process?.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
5288
+ function addUncaughtExceptionListener(captureFn, onFatalFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5289
+ const process2 = globalThis.process;
5290
+ if (!process2)
5291
+ return;
5292
+ if (mode === "strict")
5293
+ return void process2.on("uncaughtExceptionMonitor", (error, origin) => captureUncaughtException(captureFn, error, origin));
5294
+ process2.on("uncaughtException", makeUncaughtExceptionHandler(captureFn, onFatalFn));
4303
5295
  }
4304
- function addUnhandledRejectionListener(captureFn) {
4305
- globalThis.process?.on("unhandledRejection", (reason) => captureFn(reason, {
4306
- mechanism: {
4307
- type: "onunhandledrejection",
4308
- handled: false
4309
- }
4310
- }));
5296
+ function addUnhandledRejectionListener(captureFn, mode = STARTUP_UNHANDLED_REJECTION_MODE) {
5297
+ const process2 = globalThis.process;
5298
+ if (!process2 || mode === "throw" || mode === "strict" || mode === "warn-with-error-code")
5299
+ return;
5300
+ process2.on("unhandledRejection", (reason) => {
5301
+ captureFn(reason, {
5302
+ mechanism: {
5303
+ type: "onunhandledrejection",
5304
+ handled: false
5305
+ }
5306
+ });
5307
+ });
4311
5308
  }
4312
5309
 
4313
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
5310
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/error-tracking/index.mjs
4314
5311
  var SHUTDOWN_TIMEOUT = 2000;
4315
5312
 
4316
- class ErrorTracking {
5313
+ class error_tracking_ErrorTracking {
4317
5314
  constructor(client, options, _logger) {
4318
5315
  this.client = client;
4319
5316
  this._exceptionAutocaptureEnabled = options.enableExceptionAutocapture || false;
4320
5317
  this._logger = _logger;
4321
5318
  this._rateLimiter = new BucketedRateLimiter({
4322
- refillRate: 1,
4323
- bucketSize: 10,
5319
+ ...resolveExceptionRateLimiterConfig(options),
4324
5320
  refillInterval: 1e4,
4325
5321
  _logger: this._logger
4326
5322
  });
@@ -4335,6 +5331,9 @@ class ErrorTracking {
4335
5331
  };
4336
5332
  const exceptionProperties = builder.buildFromUnknown(error, hint);
4337
5333
  exceptionProperties.$exception_list = await builder.modifyFrames(exceptionProperties.$exception_list);
5334
+ const injectedReleaseId = getInjectedReleaseId();
5335
+ if (injectedReleaseId)
5336
+ properties.$release_id = injectedReleaseId;
4338
5337
  return {
4339
5338
  event: "$exception",
4340
5339
  distinctId,
@@ -4353,8 +5352,8 @@ class ErrorTracking {
4353
5352
  }
4354
5353
  onException(exception, hint) {
4355
5354
  this.client.addPendingPromise((async () => {
4356
- if (!ErrorTracking.isPreviouslyCapturedError(exception)) {
4357
- const eventMessage = await ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
5355
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(exception)) {
5356
+ const eventMessage = await error_tracking_ErrorTracking.buildEventMessage(this.client.getErrorPropertiesBuilder(), exception, hint);
4358
5357
  const exceptionProperties = eventMessage.properties;
4359
5358
  const exceptionType = exceptionProperties?.$exception_list[0]?.type ?? "Exception";
4360
5359
  const isRateLimited = this._rateLimiter.consumeRateLimit(exceptionType);
@@ -4362,14 +5361,14 @@ class ErrorTracking {
4362
5361
  return void this._logger.info("Skipping exception capture because of client rate limiting.", {
4363
5362
  exception: exceptionType
4364
5363
  });
4365
- return this.client.capture(eventMessage);
5364
+ return this.client._capturePreparedEvent(eventMessage, false);
4366
5365
  }
4367
5366
  })());
4368
5367
  }
4369
5368
  async onFatalError(exception) {
4370
5369
  console.error(exception);
4371
5370
  await this.client.shutdown(SHUTDOWN_TIMEOUT);
4372
- process.exit(1);
5371
+ globalThis.process.exit(1);
4373
5372
  }
4374
5373
  isEnabled() {
4375
5374
  return !this.client.isDisabled && this._exceptionAutocaptureEnabled;
@@ -4379,7 +5378,7 @@ class ErrorTracking {
4379
5378
  }
4380
5379
  }
4381
5380
 
4382
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/storage-memory.mjs
5381
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/storage-memory.mjs
4383
5382
  class PostHogMemoryStorage {
4384
5383
  getProperty(key) {
4385
5384
  return this._memoryStorage[key];
@@ -4392,7 +5391,452 @@ class PostHogMemoryStorage {
4392
5391
  }
4393
5392
  }
4394
5393
 
4395
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/client.mjs
5394
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/config.mjs
5395
+ function isCaptureMode(value) {
5396
+ return value === "v0" || value === "v1";
5397
+ }
5398
+ function resolveCaptureMode() {
5399
+ const envMode = typeof process != "undefined" ? process.env?.POSTHOG_CAPTURE_MODE : undefined;
5400
+ return isCaptureMode(envMode) ? envMode : "v0";
5401
+ }
5402
+
5403
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/routing.mjs
5404
+ var AI_EVENT_PREFIX = "$ai_";
5405
+ var ANALYTICS_ROUTE = "analytics";
5406
+ var AI_ROUTE = "ai";
5407
+ function isLegacyOnlyEvent(message) {
5408
+ return typeof message.event == "string" && message.event.startsWith(AI_EVENT_PREFIX);
5409
+ }
5410
+
5411
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/errors.mjs
5412
+ class CaptureV1Error extends Error {
5413
+ constructor({ requestId, drops, retryExhausted, cause }) {
5414
+ super(CaptureV1Error.buildMessage(requestId, drops, retryExhausted, cause)), this.name = "CaptureV1Error";
5415
+ this.requestId = requestId;
5416
+ this.drops = drops;
5417
+ this.retryExhausted = retryExhausted;
5418
+ this.cause = cause;
5419
+ }
5420
+ static buildMessage(requestId, drops, retryExhausted, cause) {
5421
+ let message = `Capture V1 batch ${requestId} did not fully deliver: ${drops.length} dropped, ${retryExhausted.length} undelivered`;
5422
+ if (cause instanceof Error)
5423
+ message += ` (${cause.message})`;
5424
+ return message;
5425
+ }
5426
+ }
5427
+
5428
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/transform.mjs
5429
+ function coerceBool(value) {
5430
+ if (typeof value == "boolean")
5431
+ return value;
5432
+ if (typeof value == "number")
5433
+ return value !== 0;
5434
+ if (typeof value == "string") {
5435
+ const normalized = value.trim().toLowerCase();
5436
+ if (normalized === "true" || normalized === "1")
5437
+ return true;
5438
+ if (normalized === "false" || normalized === "0")
5439
+ return false;
5440
+ }
5441
+ }
5442
+ function coerceString(value) {
5443
+ return typeof value == "string" ? value : undefined;
5444
+ }
5445
+ var OPTION_SENTINELS = [
5446
+ {
5447
+ property: "$cookieless_mode",
5448
+ optionKey: "cookieless_mode",
5449
+ coerce: coerceBool
5450
+ },
5451
+ {
5452
+ property: "$ignore_sent_at",
5453
+ optionKey: "disable_skew_correction",
5454
+ coerce: coerceBool
5455
+ },
5456
+ {
5457
+ property: "$process_person_profile",
5458
+ optionKey: "process_person_profile",
5459
+ coerce: coerceBool
5460
+ },
5461
+ {
5462
+ property: "$product_tour_id",
5463
+ optionKey: "product_tour_id",
5464
+ coerce: coerceString
5465
+ }
5466
+ ];
5467
+ var TOPLEVEL_SENTINELS = [
5468
+ {
5469
+ property: "$session_id",
5470
+ field: "session_id"
5471
+ },
5472
+ {
5473
+ property: "$window_id",
5474
+ field: "window_id"
5475
+ }
5476
+ ];
5477
+ function isRecord2(value) {
5478
+ return typeof value == "object" && value !== null && !Array.isArray(value);
5479
+ }
5480
+ function toRfc3339(timestamp) {
5481
+ if (typeof timestamp == "string") {
5482
+ const asDate = new Date(timestamp);
5483
+ if (Number.isNaN(asDate.getTime()))
5484
+ return new Date().toISOString();
5485
+ const normalized = asDate.toISOString();
5486
+ const fractionalSeconds = timestamp.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})?$/i)?.[1];
5487
+ return fractionalSeconds && fractionalSeconds.length > 3 ? normalized.replace(/\.\d{3}Z$/, `.${fractionalSeconds}Z`) : normalized;
5488
+ }
5489
+ if (timestamp instanceof Date)
5490
+ return Number.isNaN(timestamp.getTime()) ? new Date().toISOString() : timestamp.toISOString();
5491
+ const asDate = timestamp == null ? new Date : new Date(timestamp);
5492
+ return Number.isNaN(asDate.getTime()) ? new Date().toISOString() : asDate.toISOString();
5493
+ }
5494
+ function relocateInto(properties, key, value) {
5495
+ if (value !== undefined && !(key in properties))
5496
+ properties[key] = value;
5497
+ }
5498
+ function buildV1Event(message) {
5499
+ const sourceProperties = isRecord2(message.properties) ? message.properties : {};
5500
+ const properties = {
5501
+ ...sourceProperties
5502
+ };
5503
+ const options = {};
5504
+ for (const { property, optionKey, coerce } of OPTION_SENTINELS)
5505
+ if (property in properties) {
5506
+ const coerced = coerce(properties[property]);
5507
+ if (coerced !== undefined)
5508
+ options[optionKey] = coerced;
5509
+ delete properties[property];
5510
+ }
5511
+ const topLevel = {};
5512
+ for (const { property, field } of TOPLEVEL_SENTINELS)
5513
+ if (property in properties) {
5514
+ const value = properties[property];
5515
+ if (typeof value == "string")
5516
+ topLevel[field] = value;
5517
+ delete properties[property];
5518
+ }
5519
+ delete properties.$lib;
5520
+ delete properties.$lib_version;
5521
+ relocateInto(properties, "$set", message.$set);
5522
+ relocateInto(properties, "$set_once", message.$set_once);
5523
+ return {
5524
+ event: String(message.event ?? ""),
5525
+ uuid: String(message.uuid ?? ""),
5526
+ distinct_id: String(message.distinct_id ?? ""),
5527
+ timestamp: toRfc3339(message.timestamp),
5528
+ ...topLevel,
5529
+ options,
5530
+ properties
5531
+ };
5532
+ }
5533
+ function buildV1Batch(messages, { createdAt, historicalMigration }) {
5534
+ const batch = {
5535
+ created_at: createdAt,
5536
+ batch: messages.map(buildV1Event)
5537
+ };
5538
+ if (historicalMigration)
5539
+ batch.historical_migration = true;
5540
+ return batch;
5541
+ }
5542
+
5543
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/capture-v1/sender.mjs
5544
+ var V1_ANALYTICS_PATH = "/i/v1/analytics/events";
5545
+ var DEFAULT_MAX_BACKOFF_MS = 30000;
5546
+ var RETRYABLE_STATUSES = new Set([
5547
+ 408,
5548
+ 500,
5549
+ 502,
5550
+ 503,
5551
+ 504
5552
+ ]);
5553
+
5554
+ class V1CaptureSender {
5555
+ constructor(config, hooks) {
5556
+ this.config = config;
5557
+ this.maxBackoffMs = config.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
5558
+ this.fetchFn = hooks.fetch;
5559
+ this.onError = hooks.onError;
5560
+ this.now = hooks.now ?? Date.now;
5561
+ this.sleep = hooks.sleep ?? ((ms) => new Promise((resolve) => safeSetTimeout(resolve, ms)));
5562
+ this.generateRequestId = hooks.generateRequestId ?? uuidv7;
5563
+ this.compress = hooks.compress ?? gzipCompress;
5564
+ }
5565
+ async sendV1Batch(messages) {
5566
+ if (messages.length === 0)
5567
+ return;
5568
+ const requestId = this.generateRequestId();
5569
+ const createdAt = new Date(this.now()).toISOString();
5570
+ const { batch } = buildV1Batch(messages, {
5571
+ createdAt,
5572
+ historicalMigration: this.config.historicalMigration
5573
+ });
5574
+ const url = `${this.config.host}${V1_ANALYTICS_PATH}`;
5575
+ const drops = [];
5576
+ let pending = batch;
5577
+ const maxAttempts = Math.max(1, this.config.maxAttempts);
5578
+ for (let attempt = 1;attempt <= maxAttempts; attempt++) {
5579
+ const isLastAttempt = attempt === maxAttempts;
5580
+ const payload = safeJsonStringify({
5581
+ created_at: createdAt,
5582
+ ...this.config.historicalMigration ? {
5583
+ historical_migration: true
5584
+ } : {},
5585
+ batch: pending
5586
+ });
5587
+ let captureAttempt;
5588
+ let retryDelayMs;
5589
+ try {
5590
+ captureAttempt = await this.sendOnce(url, payload, attempt, requestId);
5591
+ const { response, signal } = captureAttempt;
5592
+ const { status } = response;
5593
+ if (status < 200 || status >= 300)
5594
+ if (!isLastAttempt && RETRYABLE_STATUSES.has(status)) {
5595
+ const retryAfterMs = this.parseRetryAfter(response);
5596
+ await captureAttempt.waitFor(captureAttempt.cancelBody()).catch(() => {});
5597
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
5598
+ } else {
5599
+ const httpError = await this.buildHttpError(response, status, captureAttempt.waitFor);
5600
+ return this.surfaceBatchFailure(requestId, drops, pending, httpError);
5601
+ }
5602
+ else {
5603
+ let parsed;
5604
+ try {
5605
+ parsed = await captureAttempt.waitFor(this.parseResponse(response));
5606
+ } catch (error) {
5607
+ if (signal.aborted)
5608
+ throw error;
5609
+ return this.surfaceBatchFailure(requestId, drops, pending, new Error(`Capture V1 returned an unparseable ${status} response body`));
5610
+ }
5611
+ const retryable = this.classify(pending, parsed, drops);
5612
+ if (retryable.length === 0)
5613
+ return this.surfacePartialDrops(requestId, drops);
5614
+ if (isLastAttempt)
5615
+ return void this.onError(new CaptureV1Error({
5616
+ requestId,
5617
+ drops,
5618
+ retryExhausted: retryable.map((event) => event.uuid)
5619
+ }));
5620
+ pending = retryable;
5621
+ const retryAfterMs = this.parseRetryAfter(response);
5622
+ retryDelayMs = this.backoffDelay(attempt, retryAfterMs);
5623
+ }
5624
+ } catch (transportError) {
5625
+ if (captureAttempt && !captureAttempt.signal.aborted)
5626
+ throw transportError;
5627
+ if (isLastAttempt)
5628
+ return this.surfaceBatchFailure(requestId, drops, pending, transportError);
5629
+ retryDelayMs = this.backoffDelay(attempt);
5630
+ } finally {
5631
+ captureAttempt?.cleanup();
5632
+ }
5633
+ if (retryDelayMs !== undefined)
5634
+ await this.sleep(retryDelayMs);
5635
+ }
5636
+ }
5637
+ async sendOnce(url, payload, attempt, requestId) {
5638
+ const headers = this.buildHeaders(attempt, requestId);
5639
+ let body = payload;
5640
+ if (this.config.compressionEnabled) {
5641
+ const compressed = await this.compress(payload, this.config.isDebug);
5642
+ if (compressed !== null) {
5643
+ body = compressed;
5644
+ headers["Content-Encoding"] = "gzip";
5645
+ }
5646
+ }
5647
+ const controller = new AbortController;
5648
+ let timeoutPhase = "waiting for response headers";
5649
+ let timer;
5650
+ const deadline = new Promise((_resolve, reject) => {
5651
+ timer = safeSetTimeout(() => {
5652
+ const timeoutError = new Error(`Capture V1 request timed out ${timeoutPhase} after ${this.config.requestTimeoutMs}ms`);
5653
+ timeoutError.name = "AbortError";
5654
+ reject(timeoutError);
5655
+ controller.abort(timeoutError);
5656
+ }, this.config.requestTimeoutMs);
5657
+ });
5658
+ try {
5659
+ const fetchPromise = this.fetchFn(url, {
5660
+ method: "POST",
5661
+ headers,
5662
+ body,
5663
+ signal: controller.signal
5664
+ });
5665
+ let responseAccepted = false;
5666
+ fetchPromise.then((lateResponse) => {
5667
+ if (controller.signal.aborted && !responseAccepted)
5668
+ this.cancelBody(lateResponse);
5669
+ }).catch(() => {});
5670
+ const response = await Promise.race([
5671
+ fetchPromise,
5672
+ deadline
5673
+ ]);
5674
+ responseAccepted = true;
5675
+ timeoutPhase = "while reading the response body";
5676
+ let cleanedUp = false;
5677
+ let cancellation;
5678
+ const cancelBody = () => cancellation ??= this.cancelBody(response);
5679
+ return {
5680
+ response,
5681
+ signal: controller.signal,
5682
+ waitFor: (operation) => Promise.race([
5683
+ operation,
5684
+ deadline
5685
+ ]),
5686
+ cancelBody,
5687
+ cleanup: () => {
5688
+ if (cleanedUp)
5689
+ return;
5690
+ cleanedUp = true;
5691
+ clearTimeout(timer);
5692
+ if (controller.signal.aborted)
5693
+ cancelBody();
5694
+ }
5695
+ };
5696
+ } catch (error) {
5697
+ clearTimeout(timer);
5698
+ throw error;
5699
+ }
5700
+ }
5701
+ buildHeaders(attempt, requestId) {
5702
+ const sdkInfo = `${this.config.libraryId}/${this.config.libraryVersion}`;
5703
+ const headers = {
5704
+ "Content-Type": "application/json",
5705
+ Authorization: `Bearer ${this.config.apiKey}`,
5706
+ "PostHog-Sdk-Info": sdkInfo,
5707
+ "PostHog-Attempt": String(attempt),
5708
+ "PostHog-Request-Id": requestId,
5709
+ "PostHog-Request-Timestamp": new Date(this.now()).toISOString()
5710
+ };
5711
+ if (this.config.userAgent)
5712
+ headers["User-Agent"] = this.config.userAgent;
5713
+ return headers;
5714
+ }
5715
+ classify(pending, parsed, drops) {
5716
+ const results = parsed.results ?? {};
5717
+ const retryable = [];
5718
+ for (const event of pending) {
5719
+ const result = results[event.uuid];
5720
+ if (result) {
5721
+ if (result.result === "drop")
5722
+ drops.push({
5723
+ uuid: event.uuid,
5724
+ details: result.details ?? undefined
5725
+ });
5726
+ else if (result.result === "retry")
5727
+ retryable.push(event);
5728
+ }
5729
+ }
5730
+ return retryable;
5731
+ }
5732
+ backoffDelay(attempt, retryAfterMs) {
5733
+ const exponential = Math.min(this.config.initialRetryDelayMs * 2 ** (attempt - 1), this.maxBackoffMs);
5734
+ if (retryAfterMs === undefined)
5735
+ return exponential;
5736
+ return Math.max(exponential, Math.min(retryAfterMs, this.maxBackoffMs));
5737
+ }
5738
+ parseRetryAfter(response) {
5739
+ const raw = response.headers?.get("Retry-After");
5740
+ if (!raw)
5741
+ return;
5742
+ const trimmed = raw.trim();
5743
+ if (/^\d+$/.test(trimmed)) {
5744
+ const seconds = parseInt(trimmed, 10);
5745
+ return Number.isFinite(seconds) && seconds > 0 ? 1000 * seconds : undefined;
5746
+ }
5747
+ const dateMs = Date.parse(trimmed);
5748
+ if (Number.isNaN(dateMs))
5749
+ return;
5750
+ const delta = dateMs - this.now();
5751
+ return delta > 0 ? delta : undefined;
5752
+ }
5753
+ async parseResponse(response) {
5754
+ const text = await response.text();
5755
+ const parsed = JSON.parse(text);
5756
+ if (typeof parsed != "object" || parsed === null || Array.isArray(parsed))
5757
+ throw new Error("unexpected response shape");
5758
+ const results = parsed.results;
5759
+ if (results !== undefined && (typeof results != "object" || results === null || Array.isArray(results)))
5760
+ throw new Error("unexpected results shape");
5761
+ return {
5762
+ results: results ?? {}
5763
+ };
5764
+ }
5765
+ async buildHttpError(response, status, waitFor) {
5766
+ let bodyText = "";
5767
+ try {
5768
+ bodyText = (await waitFor(response.text())).slice(0, 512);
5769
+ } catch {}
5770
+ const suffix = bodyText ? `: ${bodyText}` : "";
5771
+ return new Error(`Capture V1 request failed with HTTP ${status}${suffix}`);
5772
+ }
5773
+ surfaceBatchFailure(requestId, drops, pending, cause) {
5774
+ this.onError(new CaptureV1Error({
5775
+ requestId,
5776
+ drops,
5777
+ retryExhausted: pending.map((event) => event.uuid),
5778
+ cause
5779
+ }));
5780
+ }
5781
+ surfacePartialDrops(requestId, drops) {
5782
+ if (drops.length > 0)
5783
+ this.onError(new CaptureV1Error({
5784
+ requestId,
5785
+ drops,
5786
+ retryExhausted: []
5787
+ }));
5788
+ }
5789
+ async cancelBody(response) {
5790
+ try {
5791
+ await response.body?.cancel();
5792
+ } catch {}
5793
+ }
5794
+ }
5795
+
5796
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/routing.mjs
5797
+ var AI_CAPTURE_ROUTE = "ai-capture";
5798
+ var AI_CAPTURE_ENDPOINT_PATH = "/i/v0/ai/batch/";
5799
+ var AI_MAX_EVENT_BYTES = 8388608;
5800
+ var AI_BATCH_TARGET_BYTES = 5242880;
5801
+
5802
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/ai-capture/batching.mjs
5803
+ var encoder = new TextEncoder;
5804
+ function eventByteSize(message) {
5805
+ return encoder.encode(safeJsonStringify(message)).length;
5806
+ }
5807
+ function partitionAiBatch(messages, maxEventBytes = AI_MAX_EVENT_BYTES, targetBatchBytes = AI_BATCH_TARGET_BYTES) {
5808
+ const batches = [];
5809
+ const dropped = [];
5810
+ let current = [];
5811
+ let currentBytes = 0;
5812
+ for (const message of messages) {
5813
+ if (message === undefined)
5814
+ continue;
5815
+ const bytes = eventByteSize(message);
5816
+ if (bytes > maxEventBytes) {
5817
+ dropped.push({
5818
+ event: typeof message.event == "string" ? message.event : "unknown",
5819
+ bytes
5820
+ });
5821
+ continue;
5822
+ }
5823
+ if (current.length > 0 && currentBytes + bytes > targetBatchBytes) {
5824
+ batches.push(current);
5825
+ current = [];
5826
+ currentBytes = 0;
5827
+ }
5828
+ current.push(message);
5829
+ currentBytes += bytes;
5830
+ }
5831
+ if (current.length > 0)
5832
+ batches.push(current);
5833
+ return {
5834
+ batches,
5835
+ dropped
5836
+ };
5837
+ }
5838
+
5839
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/client.mjs
4396
5840
  var MINIMUM_POLLING_INTERVAL = 100;
4397
5841
  var THIRTY_SECONDS = 30000;
4398
5842
  var MAX_CACHE_SIZE = 50000;
@@ -4417,6 +5861,12 @@ function normalizeHost(value) {
4417
5861
  const normalizedValue = typeof value == "string" ? value.trim() : "";
4418
5862
  return normalizedValue || DEFAULT_NODE_HOST;
4419
5863
  }
5864
+ function normalizeUnsetPersonProperties(value) {
5865
+ const propertyNames = Array.isArray(value) ? value : [
5866
+ value
5867
+ ];
5868
+ return propertyNames.filter((propertyName) => typeof propertyName == "string" && propertyName.trim().length > 0);
5869
+ }
4420
5870
  function buildFlagEventProperties(flagValues) {
4421
5871
  if (!flagValues)
4422
5872
  return {};
@@ -4434,11 +5884,15 @@ class PostHogBackendClient extends PostHogCoreStateless {
4434
5884
  const normalizedApiKey = normalizeApiKey(apiKey);
4435
5885
  const normalizedOptions = {
4436
5886
  ...options,
5887
+ maxQueueSize: options.maxQueueSize ?? 1e4,
5888
+ flushInterval: options.flushInterval ?? 5000,
4437
5889
  host: normalizeHost(options.host),
4438
- personalApiKey: normalizePersonalApiKey(options.personalApiKey)
5890
+ personalApiKey: normalizePersonalApiKey(options.secretKey ?? options.personalApiKey)
4439
5891
  };
4440
- super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage;
5892
+ super(normalizedApiKey, normalizedOptions), this._memoryStorage = new PostHogMemoryStorage, this._aiCaptureRouteActive = false, this._minimalFlagCalledEvents = false;
4441
5893
  this.options = normalizedOptions;
5894
+ this.captureMode = resolveCaptureMode();
5895
+ this.enableFullAiCapture = normalizedOptions.enableFullAiCapture === true;
4442
5896
  this.context = this.initializeContext();
4443
5897
  this.options.featureFlagsPollingInterval = typeof normalizedOptions.featureFlagsPollingInterval == "number" ? Math.max(normalizedOptions.featureFlagsPollingInterval, MINIMUM_POLLING_INTERVAL) : THIRTY_SECONDS;
4444
5898
  if (typeof normalizedOptions.waitUntilDebounceMs == "number")
@@ -4463,21 +5917,24 @@ class PostHogBackendClient extends PostHogCoreStateless {
4463
5917
  onLoad: (count) => {
4464
5918
  this._events.emit("localEvaluationFlagsLoaded", count);
4465
5919
  },
5920
+ onMinimalFlagCalledEvents: (enabled) => {
5921
+ this._minimalFlagCalledEvents = enabled;
5922
+ },
4466
5923
  customHeaders: this.getCustomHeaders(),
4467
5924
  cacheProvider: normalizedOptions.flagDefinitionCacheProvider,
4468
5925
  strictLocalEvaluation: normalizedOptions.strictLocalEvaluation
4469
5926
  });
4470
5927
  }
4471
- this.errorTracking = new ErrorTracking(this, normalizedOptions, this._logger);
5928
+ this.errorTracking = new error_tracking_ErrorTracking(this, normalizedOptions, this._logger);
4472
5929
  this.distinctIdHasSentFlagCalls = {};
4473
5930
  this.maxCacheSize = normalizedOptions.maxCacheSize || MAX_CACHE_SIZE;
4474
5931
  }
4475
- enqueue(type, message, options) {
4476
- super.enqueue(type, message, options);
5932
+ enqueue(type, message, options, explicitRoute) {
5933
+ super.enqueue(type, message, options, explicitRoute);
4477
5934
  this.scheduleDebouncedFlush();
4478
5935
  }
4479
5936
  async flush() {
4480
- const flushPromise = super.flush();
5937
+ const flushPromise = this.flushWithPendingPromises();
4481
5938
  const waitUntil = this.options.waitUntil;
4482
5939
  if (waitUntil && !this._waitUntilCycle)
4483
5940
  try {
@@ -4530,7 +5987,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4530
5987
  async resolveWaitUntilFlush() {
4531
5988
  const resolve = this._consumeWaitUntilCycle();
4532
5989
  try {
4533
- await super.flush();
5990
+ await this.flushWithPendingPromises();
4534
5991
  } catch {} finally {
4535
5992
  resolve?.();
4536
5993
  }
@@ -4544,12 +6001,103 @@ class PostHogBackendClient extends PostHogCoreStateless {
4544
6001
  fetch(url, options) {
4545
6002
  return this.options.fetch ? this.options.fetch(url, options) : fetch(url, options);
4546
6003
  }
6004
+ getQueueRouteKey(message) {
6005
+ return this.captureMode === "v1" && isLegacyOnlyEvent(message) ? AI_ROUTE : ANALYTICS_ROUTE;
6006
+ }
6007
+ persistedQueueKeyForRoute(route) {
6008
+ if (route === AI_CAPTURE_ROUTE)
6009
+ return types_PostHogPersistedProperty.AiCaptureQueue;
6010
+ return route === AI_ROUTE ? types_PostHogPersistedProperty.AiQueue : types_PostHogPersistedProperty.Queue;
6011
+ }
6012
+ getActiveQueueRoutes() {
6013
+ const routes = this.captureMode === "v1" ? [
6014
+ ANALYTICS_ROUTE,
6015
+ AI_ROUTE
6016
+ ] : [
6017
+ ANALYTICS_ROUTE
6018
+ ];
6019
+ if (this._aiCaptureRouteActive)
6020
+ routes.push(AI_CAPTURE_ROUTE);
6021
+ return routes;
6022
+ }
6023
+ getBatchEndpointPath(route) {
6024
+ return route === AI_CAPTURE_ROUTE ? AI_CAPTURE_ENDPOINT_PATH : super.getBatchEndpointPath(route);
6025
+ }
6026
+ async sendBatch(batchMessages, retryOptions, route = ANALYTICS_ROUTE) {
6027
+ if (route === AI_CAPTURE_ROUTE)
6028
+ return this.sendAiCaptureBatch(batchMessages, retryOptions);
6029
+ if (this.captureMode !== "v1" || route === AI_ROUTE)
6030
+ return super.sendBatch(batchMessages, retryOptions, route);
6031
+ const v1Events = batchMessages.filter((message) => message !== undefined);
6032
+ await this.getV1Sender().sendV1Batch(v1Events);
6033
+ }
6034
+ async sendAiCaptureBatch(batchMessages, retryOptions) {
6035
+ const { batches, dropped } = partitionAiBatch(batchMessages);
6036
+ for (const { event, bytes } of dropped) {
6037
+ const message = `Event ${event} (${bytes} bytes) exceeds the ${AI_MAX_EVENT_BYTES / 1048576}MiB limit for ${AI_CAPTURE_ENDPOINT_PATH}, dropping.`;
6038
+ this._logger.error(message);
6039
+ this._events.emit("error", new Error(message));
6040
+ }
6041
+ for (const batch of batches)
6042
+ await this.sendAiSubBatch(batch, retryOptions);
6043
+ }
6044
+ async sendAiSubBatch(batch, retryOptions) {
6045
+ try {
6046
+ await super.sendBatch(batch, retryOptions, AI_CAPTURE_ROUTE);
6047
+ } catch (err) {
6048
+ if (!isPostHogFetchContentTooLargeError(err))
6049
+ throw err;
6050
+ if (batch.length === 1) {
6051
+ const [event] = batch;
6052
+ const eventName = typeof event.event == "string" ? event.event : "unknown";
6053
+ const message = `Event ${eventName} (${eventByteSize(event)} bytes) was rejected with 413 by ${AI_CAPTURE_ENDPOINT_PATH} on its own, dropping.`;
6054
+ this._logger.error(message);
6055
+ this._events.emit("error", new Error(message));
6056
+ return;
6057
+ }
6058
+ const mid = Math.ceil(batch.length / 2);
6059
+ await this.sendAiSubBatch(batch.slice(0, mid), retryOptions);
6060
+ await this.sendAiSubBatch(batch.slice(mid), retryOptions);
6061
+ }
6062
+ }
6063
+ getV1Sender() {
6064
+ if (!this._v1Sender)
6065
+ this._v1Sender = new V1CaptureSender({
6066
+ host: this.host,
6067
+ apiKey: this.apiKey,
6068
+ libraryId: this.getLibraryId(),
6069
+ libraryVersion: this.getLibraryVersion(),
6070
+ userAgent: this.getCustomUserAgent() || undefined,
6071
+ historicalMigration: this.historicalMigration,
6072
+ compressionEnabled: !this.disableCompression,
6073
+ requestTimeoutMs: this.requestTimeout,
6074
+ maxAttempts: (this.options.fetchRetryCount ?? 3) + 1,
6075
+ initialRetryDelayMs: this.options.fetchRetryDelay ?? 3000,
6076
+ isDebug: this.isDebug
6077
+ }, {
6078
+ fetch: (url, fetchOptions) => this.fetch(url, fetchOptions),
6079
+ onError: (error) => this._events.emit("error", error),
6080
+ compress: (payload) => this.compressPayload(payload)
6081
+ });
6082
+ return this._v1Sender;
6083
+ }
4547
6084
  getLibraryVersion() {
4548
6085
  return version;
4549
6086
  }
6087
+ get metrics() {
6088
+ if (!this._metrics)
6089
+ this._metrics = new PostHogMetrics(this, resolveMetricsConfig(this.options.metrics), this._logger);
6090
+ return this._metrics;
6091
+ }
4550
6092
  getCustomUserAgent() {
4551
6093
  return `${this.getLibraryId()}/${this.getLibraryVersion()}`;
4552
6094
  }
6095
+ getCommonEventProperties() {
6096
+ const commonProperties = super.getCommonEventProperties();
6097
+ if (this.options.isServer ?? true)
6098
+ commonProperties.$is_server = true;
6099
+ return commonProperties;
6100
+ }
4553
6101
  enable() {
4554
6102
  return super.optIn();
4555
6103
  }
@@ -4560,33 +6108,69 @@ class PostHogBackendClient extends PostHogCoreStateless {
4560
6108
  super.debug(enabled);
4561
6109
  this.featureFlagsPoller?.debug(enabled);
4562
6110
  }
4563
- capture(props) {
6111
+ _warnIfInvalidCapture(props, stringArgumentWarning, exceptionCaptureWarning) {
4564
6112
  if (typeof props == "string")
4565
- this._logger.warn("Called capture() with a string as the first argument when an object was expected.");
6113
+ this._logger.warn(stringArgumentWarning);
4566
6114
  if (props.event === "$exception" && !props._originatedFromCaptureException)
4567
- 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.");
4568
- this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStateless(distinctId, event, properties, {
4569
- timestamp: options.timestamp,
4570
- disableGeoip: options.disableGeoip,
4571
- uuid: options.uuid
4572
- })).catch((err) => {
6115
+ this._logger.warn(exceptionCaptureWarning);
6116
+ }
6117
+ _sendPreparedEvent(type, props, immediate, prepareOptions, explicitRoute) {
6118
+ return this.addPendingPromise(this._prepareEventMessage(props, prepareOptions).then(({ distinctId, event, properties, options }) => {
6119
+ const captureOptions = {
6120
+ timestamp: options.timestamp,
6121
+ disableGeoip: options.disableGeoip,
6122
+ uuid: options.uuid
6123
+ };
6124
+ const message = {
6125
+ distinctId,
6126
+ event,
6127
+ properties: {
6128
+ ...properties,
6129
+ ...this.getCommonEventProperties()
6130
+ }
6131
+ };
6132
+ return immediate ? this.sendImmediate(type, message, captureOptions, explicitRoute) : this.enqueue(type, message, captureOptions, explicitRoute);
6133
+ }).catch((err) => {
4573
6134
  if (err)
4574
6135
  console.error(err);
4575
6136
  }));
4576
6137
  }
6138
+ _capturePreparedEvent(props, immediate) {
6139
+ return this._sendPreparedEvent("capture", props, immediate);
6140
+ }
6141
+ capture(props) {
6142
+ 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.");
6143
+ this._capturePreparedEvent(props, false);
6144
+ }
4577
6145
  async captureImmediate(props) {
4578
- if (typeof props == "string")
4579
- this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");
4580
- if (props.event === "$exception" && !props._originatedFromCaptureException)
4581
- 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.");
4582
- return this.addPendingPromise(this.prepareEventMessage(props).then(({ distinctId, event, properties, options }) => super.captureStatelessImmediate(distinctId, event, properties, {
4583
- timestamp: options.timestamp,
4584
- disableGeoip: options.disableGeoip,
4585
- uuid: options.uuid
4586
- })).catch((err) => {
4587
- if (err)
4588
- console.error(err);
4589
- }));
6146
+ 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.");
6147
+ return this._capturePreparedEvent(props, true);
6148
+ }
6149
+ captureAi(props) {
6150
+ if (this.disabled)
6151
+ return;
6152
+ const uuid = getEventUuid(props.uuid, uuidv7);
6153
+ this._sendPreparedAiEvent({
6154
+ ...props,
6155
+ uuid
6156
+ }, false);
6157
+ return uuid;
6158
+ }
6159
+ async captureAiImmediate(props) {
6160
+ if (this.disabled)
6161
+ return;
6162
+ const uuid = getEventUuid(props.uuid, uuidv7);
6163
+ await this._sendPreparedAiEvent({
6164
+ ...props,
6165
+ uuid
6166
+ }, true);
6167
+ return uuid;
6168
+ }
6169
+ _sendPreparedAiEvent(props, immediate) {
6170
+ if (typeof props?.event == "string" && !props.event.startsWith("$ai_"))
6171
+ this._logger.debug(`captureAi called with non-AI event ${props.event}; routing it to the AI endpoint anyway.`);
6172
+ this._aiCaptureRouteActive = true;
6173
+ return this._sendPreparedEvent("capture", props, immediate, undefined, AI_CAPTURE_ROUTE);
4590
6174
  }
4591
6175
  identify({ distinctId, properties = {}, disableGeoip }) {
4592
6176
  const { $set, $set_once, $anon_distinct_id, ...rest } = properties;
@@ -4597,8 +6181,13 @@ class PostHogBackendClient extends PostHogCoreStateless {
4597
6181
  $set_once: setOnceProps,
4598
6182
  $anon_distinct_id: $anon_distinct_id ?? undefined
4599
6183
  };
4600
- super.identifyStateless(distinctId, eventProperties, {
6184
+ this._sendPreparedEvent("identify", {
6185
+ distinctId,
6186
+ event: "$identify",
6187
+ properties: eventProperties,
4601
6188
  disableGeoip
6189
+ }, false, {
6190
+ includeContextProperties: false
4602
6191
  });
4603
6192
  }
4604
6193
  async identifyImmediate({ distinctId, properties = {}, disableGeoip }) {
@@ -4610,18 +6199,65 @@ class PostHogBackendClient extends PostHogCoreStateless {
4610
6199
  $set_once: setOnceProps,
4611
6200
  $anon_distinct_id: $anon_distinct_id ?? undefined
4612
6201
  };
4613
- await super.identifyStatelessImmediate(distinctId, eventProperties, {
6202
+ await this._sendPreparedEvent("identify", {
6203
+ distinctId,
6204
+ event: "$identify",
6205
+ properties: eventProperties,
4614
6206
  disableGeoip
6207
+ }, true, {
6208
+ includeContextProperties: false
6209
+ });
6210
+ }
6211
+ setPersonProperties({ distinctId, properties = {}, propertiesOnce = {} }) {
6212
+ if (Object.keys(properties).length === 0 && Object.keys(propertiesOnce).length === 0)
6213
+ return;
6214
+ const eventProperties = {};
6215
+ if (Object.keys(properties).length > 0)
6216
+ eventProperties.$set = properties;
6217
+ if (Object.keys(propertiesOnce).length > 0)
6218
+ eventProperties.$set_once = propertiesOnce;
6219
+ this.capture({
6220
+ distinctId,
6221
+ event: "$set",
6222
+ properties: eventProperties
6223
+ });
6224
+ }
6225
+ unsetPersonProperties({ distinctId, properties }) {
6226
+ const propertyNames = normalizeUnsetPersonProperties(properties);
6227
+ if (propertyNames.length === 0)
6228
+ return;
6229
+ this.capture({
6230
+ distinctId,
6231
+ event: "$set",
6232
+ properties: {
6233
+ $unset: propertyNames
6234
+ }
4615
6235
  });
4616
6236
  }
4617
6237
  alias(data) {
4618
- super.aliasStateless(data.alias, data.distinctId, undefined, {
6238
+ this._sendPreparedEvent("alias", {
6239
+ distinctId: data.distinctId,
6240
+ event: "$create_alias",
6241
+ properties: {
6242
+ distinct_id: data.distinctId,
6243
+ alias: data.alias
6244
+ },
4619
6245
  disableGeoip: data.disableGeoip
6246
+ }, false, {
6247
+ includeContextProperties: false
4620
6248
  });
4621
6249
  }
4622
6250
  async aliasImmediate(data) {
4623
- await super.aliasStatelessImmediate(data.alias, data.distinctId, undefined, {
6251
+ await this._sendPreparedEvent("alias", {
6252
+ distinctId: data.distinctId,
6253
+ event: "$create_alias",
6254
+ properties: {
6255
+ distinct_id: data.distinctId,
6256
+ alias: data.alias
6257
+ },
4624
6258
  disableGeoip: data.disableGeoip
6259
+ }, true, {
6260
+ includeContextProperties: false
4625
6261
  });
4626
6262
  }
4627
6263
  isLocalEvaluationReady() {
@@ -4676,7 +6312,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4676
6312
  const adjustedProperties = this.addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties);
4677
6313
  personProperties = adjustedProperties.allPersonProperties;
4678
6314
  groupProperties = adjustedProperties.allGroupProperties;
4679
- const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties);
6315
+ const evaluationContext = this.createFeatureFlagEvaluationContext(distinctId, groups, this.personPropertiesForLocalEvaluation(distinctId, personProperties), groupProperties);
4680
6316
  if (onlyEvaluateLocally == undefined)
4681
6317
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
4682
6318
  let result;
@@ -4687,6 +6323,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4687
6323
  let flagId;
4688
6324
  let flagVersion;
4689
6325
  let flagReason;
6326
+ let flagHasExperiment;
4690
6327
  const localEvaluationEnabled = this.featureFlagsPoller !== undefined;
4691
6328
  if (localEvaluationEnabled) {
4692
6329
  await this.featureFlagsPoller?.loadFeatureFlags();
@@ -4701,6 +6338,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4701
6338
  const value = localResult.value;
4702
6339
  flagId = flag.id;
4703
6340
  flagReason = "Evaluated locally";
6341
+ flagHasExperiment = flag.has_experiment;
4704
6342
  result = {
4705
6343
  key,
4706
6344
  enabled: value !== false,
@@ -4716,12 +6354,13 @@ class PostHogBackendClient extends PostHogCoreStateless {
4716
6354
  }
4717
6355
  }
4718
6356
  if (!flagWasLocallyEvaluated && !onlyEvaluateLocally) {
4719
- const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, [
6357
+ const flagsResponse = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, [
4720
6358
  key
4721
6359
  ]);
4722
6360
  if (flagsResponse === undefined)
4723
6361
  featureFlagError = FeatureFlagError2.UNKNOWN_ERROR;
4724
6362
  else {
6363
+ this._minimalFlagCalledEvents = flagsResponse.minimalFlagCalledEvents === true;
4725
6364
  requestId = flagsResponse.requestId;
4726
6365
  evaluatedAt = flagsResponse.evaluatedAt;
4727
6366
  const errors = [];
@@ -4736,6 +6375,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4736
6375
  flagId = flagDetail.metadata?.id;
4737
6376
  flagVersion = flagDetail.metadata?.version;
4738
6377
  flagReason = flagDetail.reason?.description ?? flagDetail.reason?.code;
6378
+ flagHasExperiment = flagDetail.metadata?.has_experiment;
4739
6379
  let parsedPayload;
4740
6380
  if (flagDetail.metadata?.payload !== undefined)
4741
6381
  try {
@@ -4746,7 +6386,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4746
6386
  result = {
4747
6387
  key,
4748
6388
  enabled: flagDetail.enabled,
4749
- variant: flagDetail.variant,
6389
+ variant: flagDetail.variant ?? undefined,
4750
6390
  payload: parsedPayload
4751
6391
  };
4752
6392
  }
@@ -4767,6 +6407,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
4767
6407
  $feature_flag_request_id: requestId,
4768
6408
  $feature_flag_evaluated_at: flagWasLocallyEvaluated ? Date.now() : evaluatedAt
4769
6409
  };
6410
+ if (flagHasExperiment !== undefined)
6411
+ properties.$feature_flag_has_experiment = flagHasExperiment;
4770
6412
  if (flagWasLocallyEvaluated && this.featureFlagsPoller) {
4771
6413
  const flagDefinitionsLoadedAt = this.featureFlagsPoller.getFlagDefinitionsLoadedAt();
4772
6414
  if (flagDefinitionsLoadedAt !== undefined)
@@ -4881,7 +6523,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4881
6523
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
4882
6524
  personProperties = adjustedProperties.allPersonProperties;
4883
6525
  groupProperties = adjustedProperties.allGroupProperties;
4884
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
6526
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
4885
6527
  if (onlyEvaluateLocally == undefined)
4886
6528
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
4887
6529
  const localEvaluationResult = await this.featureFlagsPoller?.getAllFlagsAndPayloads(evaluationContext, flagKeys);
@@ -4894,7 +6536,7 @@ class PostHogBackendClient extends PostHogCoreStateless {
4894
6536
  fallbackToFlags = localEvaluationResult.fallbackToFlags;
4895
6537
  }
4896
6538
  if (fallbackToFlags && !onlyEvaluateLocally) {
4897
- const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
6539
+ const remoteEvaluationResult = await super.getFeatureFlagsAndPayloadsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
4898
6540
  featureFlags = {
4899
6541
  ...featureFlags,
4900
6542
  ...remoteEvaluationResult.flags || {}
@@ -4942,9 +6584,10 @@ class PostHogBackendClient extends PostHogCoreStateless {
4942
6584
  const adjustedProperties = this.addLocalPersonAndGroupProperties(resolvedDistinctId, groups, personProperties, groupProperties);
4943
6585
  personProperties = adjustedProperties.allPersonProperties;
4944
6586
  groupProperties = adjustedProperties.allGroupProperties;
4945
- const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, personProperties, groupProperties);
6587
+ const evaluationContext = this.createFeatureFlagEvaluationContext(resolvedDistinctId, groups, this.personPropertiesForLocalEvaluation(resolvedDistinctId, personProperties), groupProperties);
4946
6588
  if (onlyEvaluateLocally == undefined)
4947
6589
  onlyEvaluateLocally = this.options.strictLocalEvaluation ?? false;
6590
+ const requestedFlagKeys = flagKeys ? new Set(flagKeys) : undefined;
4948
6591
  const records = {};
4949
6592
  let requestId;
4950
6593
  let evaluatedAt;
@@ -4963,14 +6606,17 @@ class PostHogBackendClient extends PostHogCoreStateless {
4963
6606
  id: flagDef?.id,
4964
6607
  version: undefined,
4965
6608
  reason: "Evaluated locally",
4966
- locallyEvaluated: true
6609
+ locallyEvaluated: true,
6610
+ hasExperiment: flagDef?.has_experiment
4967
6611
  };
4968
6612
  locallyEvaluatedKeys.add(key);
4969
6613
  }
4970
- const fallbackToFlags = localResult ? localResult.fallbackToFlags : true;
6614
+ const requestedFlagMissingLocally = requestedFlagKeys !== undefined && Array.from(requestedFlagKeys).some((key) => this.featureFlagsPoller?.featureFlagsByKey[key] === undefined);
6615
+ const fallbackToFlags = localResult ? localResult.fallbackToFlags || requestedFlagMissingLocally : true;
4971
6616
  if (fallbackToFlags && !onlyEvaluateLocally) {
4972
- const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, evaluationContext.personProperties, evaluationContext.groupProperties, disableGeoip, flagKeys);
6617
+ const details = await super.getFeatureFlagDetailsStateless(evaluationContext.distinctId, evaluationContext.groups, personProperties, groupProperties, disableGeoip, flagKeys);
4973
6618
  if (details) {
6619
+ this._minimalFlagCalledEvents = details.minimalFlagCalledEvents === true;
4974
6620
  requestId = details.requestId;
4975
6621
  evaluatedAt = details.evaluatedAt;
4976
6622
  errorsWhileComputing = Boolean(details.errorsWhileComputingFlags);
@@ -4993,7 +6639,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
4993
6639
  id: detail.metadata?.id,
4994
6640
  version: detail.metadata?.version,
4995
6641
  reason: detail.reason?.description ?? detail.reason?.code,
4996
- locallyEvaluated: false
6642
+ locallyEvaluated: false,
6643
+ hasExperiment: detail.metadata?.has_experiment
4997
6644
  };
4998
6645
  }
4999
6646
  }
@@ -5013,7 +6660,8 @@ class PostHogBackendClient extends PostHogCoreStateless {
5013
6660
  id: existing?.id,
5014
6661
  version: existing?.version,
5015
6662
  reason: existing?.reason,
5016
- locallyEvaluated: existing?.locallyEvaluated ?? false
6663
+ locallyEvaluated: existing?.locallyEvaluated ?? false,
6664
+ hasExperiment: existing?.hasExperiment
5017
6665
  };
5018
6666
  }
5019
6667
  if (this._payloadOverrides !== undefined)
@@ -5025,6 +6673,11 @@ class PostHogBackendClient extends PostHogCoreStateless {
5025
6673
  payload
5026
6674
  };
5027
6675
  }
6676
+ if (requestedFlagKeys !== undefined) {
6677
+ for (const key of Object.keys(records))
6678
+ if (!requestedFlagKeys.has(key))
6679
+ delete records[key];
6680
+ }
5028
6681
  return new FeatureFlagEvaluations({
5029
6682
  host: this._getFeatureFlagEvaluationsHost(),
5030
6683
  distinctId: resolvedDistinctId,
@@ -5038,6 +6691,9 @@ class PostHogBackendClient extends PostHogCoreStateless {
5038
6691
  quotaLimited
5039
6692
  });
5040
6693
  }
6694
+ _shouldSendMinimalFlagCalledEvent(event, properties) {
6695
+ return event === "$feature_flag_called" && this._minimalFlagCalledEvents && properties.$feature_flag_has_experiment === false;
6696
+ }
5041
6697
  _captureFlagCalledEventIfNeeded(params) {
5042
6698
  const { distinctId, key, response, groups, disableGeoip, properties } = params;
5043
6699
  const groupSuffix = groups && Object.keys(groups).length > 0 ? `_${JSON.stringify(Object.entries(groups).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))}` : "";
@@ -5072,9 +6728,32 @@ class PostHogBackendClient extends PostHogCoreStateless {
5072
6728
  return this._featureFlagEvaluationsHost;
5073
6729
  }
5074
6730
  groupIdentify({ groupType, groupKey, properties, distinctId, disableGeoip }) {
5075
- super.groupIdentifyStateless(groupType, groupKey, properties, {
6731
+ this._sendPreparedEvent("capture", {
6732
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
6733
+ event: "$groupidentify",
6734
+ properties: {
6735
+ $group_type: groupType,
6736
+ $group_key: groupKey,
6737
+ $group_set: properties || {}
6738
+ },
6739
+ disableGeoip
6740
+ }, false, {
6741
+ includeContextProperties: false
6742
+ });
6743
+ }
6744
+ async groupIdentifyImmediate({ groupType, groupKey, properties, distinctId, disableGeoip }) {
6745
+ await this._sendPreparedEvent("capture", {
6746
+ distinctId: distinctId || `$${groupType}_${groupKey}`,
6747
+ event: "$groupidentify",
6748
+ properties: {
6749
+ $group_type: groupType,
6750
+ $group_key: groupKey,
6751
+ $group_set: properties || {}
6752
+ },
5076
6753
  disableGeoip
5077
- }, distinctId);
6754
+ }, true, {
6755
+ includeContextProperties: false
6756
+ });
5078
6757
  }
5079
6758
  async reloadFeatureFlags() {
5080
6759
  await this.featureFlagsPoller?.loadFeatureFlags(true);
@@ -5146,12 +6825,18 @@ class PostHogBackendClient extends PostHogCoreStateless {
5146
6825
  this.context?.enter(data, options);
5147
6826
  }
5148
6827
  async _shutdown(shutdownTimeoutMs) {
6828
+ const shutdownDeadlineMs = Date.now() + (shutdownTimeoutMs ?? 30000);
5149
6829
  const resolve = this._consumeWaitUntilCycle();
5150
6830
  await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
5151
6831
  this.errorTracking.shutdown();
6832
+ if (this._metrics) {
6833
+ await raceWithTimeout(this._metrics.flush().catch(() => {}), Math.max(0, shutdownDeadlineMs - Date.now()));
6834
+ this._metrics.reset();
6835
+ }
5152
6836
  try {
5153
- return await super._shutdown(shutdownTimeoutMs);
6837
+ return await super._shutdown(Math.max(0, shutdownDeadlineMs - Date.now()));
5154
6838
  } finally {
6839
+ this.distinctIdHasSentFlagCalls = {};
5155
6840
  resolve?.();
5156
6841
  }
5157
6842
  }
@@ -5246,7 +6931,6 @@ class PostHogBackendClient extends PostHogCoreStateless {
5246
6931
  }
5247
6932
  addLocalPersonAndGroupProperties(distinctId, groups, personProperties, groupProperties) {
5248
6933
  const allPersonProperties = {
5249
- distinct_id: distinctId,
5250
6934
  ...personProperties || {}
5251
6935
  };
5252
6936
  const allGroupProperties = {};
@@ -5261,6 +6945,12 @@ class PostHogBackendClient extends PostHogCoreStateless {
5261
6945
  allGroupProperties
5262
6946
  };
5263
6947
  }
6948
+ personPropertiesForLocalEvaluation(distinctId, personProperties) {
6949
+ return {
6950
+ distinct_id: distinctId,
6951
+ ...personProperties || {}
6952
+ };
6953
+ }
5264
6954
  createFeatureFlagEvaluationContext(distinctId, groups, personProperties, groupProperties) {
5265
6955
  return {
5266
6956
  distinctId,
@@ -5271,21 +6961,21 @@ class PostHogBackendClient extends PostHogCoreStateless {
5271
6961
  };
5272
6962
  }
5273
6963
  captureException(error, distinctId, additionalProperties, uuid, flags) {
5274
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
6964
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5275
6965
  const syntheticException = new Error("PostHog syntheticException");
5276
- this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
6966
+ this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5277
6967
  syntheticException
5278
- }, distinctId, additionalProperties).then((msg) => this.capture({
6968
+ }, distinctId, additionalProperties).then((msg) => this._capturePreparedEvent({
5279
6969
  ...msg,
5280
6970
  uuid,
5281
6971
  flags
5282
- })));
6972
+ }, false)));
5283
6973
  }
5284
6974
  }
5285
6975
  async captureExceptionImmediate(error, distinctId, additionalProperties, flags) {
5286
- if (!ErrorTracking.isPreviouslyCapturedError(error)) {
6976
+ if (!error_tracking_ErrorTracking.isPreviouslyCapturedError(error)) {
5287
6977
  const syntheticException = new Error("PostHog syntheticException");
5288
- return this.addPendingPromise(ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
6978
+ return this.addPendingPromise(error_tracking_ErrorTracking.buildEventMessage(this.getErrorPropertiesBuilder(), error, {
5289
6979
  syntheticException
5290
6980
  }, distinctId, additionalProperties).then((msg) => this.captureImmediate({
5291
6981
  ...msg,
@@ -5294,24 +6984,31 @@ class PostHogBackendClient extends PostHogCoreStateless {
5294
6984
  }
5295
6985
  }
5296
6986
  async prepareEventMessage(props) {
6987
+ return this._prepareEventMessage(props);
6988
+ }
6989
+ async _prepareEventMessage(props, options = {}) {
5297
6990
  const { distinctId, event, properties, groups, flags, sendFeatureFlags, timestamp, disableGeoip, uuid } = props;
5298
6991
  const contextData = this.context?.get();
6992
+ const includeContextProperties = options.includeContextProperties ?? true;
5299
6993
  let mergedDistinctId = distinctId || contextData?.distinctId;
5300
- const mergedProperties = {
6994
+ const mergedProperties = includeContextProperties ? {
5301
6995
  ...this.props,
5302
6996
  ...contextData?.properties || {},
5303
6997
  ...properties || {}
6998
+ } : {
6999
+ ...properties || {}
5304
7000
  };
5305
7001
  if (!mergedDistinctId) {
5306
7002
  mergedDistinctId = uuidv7();
5307
7003
  mergedProperties.$process_person_profile = false;
5308
7004
  }
5309
- if (contextData?.sessionId && !mergedProperties.$session_id)
7005
+ if (includeContextProperties && contextData?.sessionId && !mergedProperties.$session_id)
5310
7006
  mergedProperties.$session_id = contextData.sessionId;
7007
+ const finalProperties = this._shouldSendMinimalFlagCalledEvent(event, mergedProperties) ? minimizeFlagCalledEventProperties(mergedProperties) : mergedProperties;
5311
7008
  const eventMessage = this._runBeforeSend({
5312
7009
  distinctId: mergedDistinctId,
5313
7010
  event,
5314
- properties: mergedProperties,
7011
+ properties: finalProperties,
5315
7012
  groups,
5316
7013
  flags,
5317
7014
  sendFeatureFlags,
@@ -5335,12 +7032,14 @@ class PostHogBackendClient extends PostHogCoreStateless {
5335
7032
  }
5336
7033
  return {};
5337
7034
  }).catch(() => ({})).then((additionalProperties) => {
5338
- const props2 = {
7035
+ const resolvedGroups = eventMessage.groups || groups;
7036
+ return {
5339
7037
  ...additionalProperties,
5340
7038
  ...eventMessage.properties || {},
5341
- $groups: eventMessage.groups || groups
7039
+ ...resolvedGroups !== undefined && Object.keys(resolvedGroups).length > 0 ? {
7040
+ $groups: resolvedGroups
7041
+ } : {}
5342
7042
  };
5343
- return props2;
5344
7043
  });
5345
7044
  if (eventMessage.event === "$pageview" && this.options.__preview_capture_bot_pageviews && typeof eventProperties.$raw_user_agent == "string") {
5346
7045
  if (isBlockedUA(eventProperties.$raw_user_agent, this.options.custom_blocked_useragents || [])) {
@@ -5367,22 +7066,26 @@ class PostHogBackendClient extends PostHogCoreStateless {
5367
7066
  beforeSend
5368
7067
  ];
5369
7068
  let result = eventMessage;
5370
- for (const fn of fns) {
5371
- result = fn(result);
5372
- if (!result) {
5373
- this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7069
+ for (const fn of fns)
7070
+ try {
7071
+ result = fn(result);
7072
+ if (!result) {
7073
+ this._logger.info(`Event '${eventMessage.event}' was rejected in beforeSend function`);
7074
+ return null;
7075
+ }
7076
+ if (!result.properties || Object.keys(result.properties).length === 0) {
7077
+ const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
7078
+ this._logger.warn(message);
7079
+ }
7080
+ } catch (error) {
7081
+ this._logger.error(`Error in before_send function for event '${eventMessage.event}':`, error);
5374
7082
  return null;
5375
7083
  }
5376
- if (!result.properties || Object.keys(result.properties).length === 0) {
5377
- const message = `Event '${result.event}' has no properties after beforeSend function, this is likely an error.`;
5378
- this._logger.warn(message);
5379
- }
5380
- }
5381
7084
  return result;
5382
7085
  }
5383
7086
  }
5384
7087
 
5385
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/context/context.mjs
7088
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/context/context.mjs
5386
7089
  import { AsyncLocalStorage } from "node:async_hooks";
5387
7090
 
5388
7091
  class PostHogContext {
@@ -5413,7 +7116,22 @@ class PostHogContext {
5413
7116
  }
5414
7117
  }
5415
7118
 
5416
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
7119
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/gzip.node.mjs
7120
+ import { gzip } from "node:zlib";
7121
+ import { promisify } from "node:util";
7122
+ var gzipAsync = promisify(gzip);
7123
+ async function gzipCompress2(input, isDebug = true) {
7124
+ try {
7125
+ const compressed = await gzipAsync(input);
7126
+ return new Uint8Array(compressed);
7127
+ } catch (error) {
7128
+ if (isDebug)
7129
+ console.error("Failed to gzip compress data", error);
7130
+ return null;
7131
+ }
7132
+ }
7133
+
7134
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/extensions/sentry-integration.mjs
5417
7135
  var NAME = "posthog-node";
5418
7136
  function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
5419
7137
  "error"
@@ -5453,6 +7171,9 @@ function createEventProcessor(_posthog, { organization, projectId, prefix, sever
5453
7171
  $sentry_exception_type: exceptions[0]?.type,
5454
7172
  $sentry_tags: event.tags
5455
7173
  };
7174
+ const injectedReleaseId = getInjectedReleaseId();
7175
+ if (injectedReleaseId)
7176
+ properties.$release_id = injectedReleaseId;
5456
7177
  if (organization && projectId)
5457
7178
  properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
5458
7179
  if (sendExceptionsToPostHog)
@@ -5481,29 +7202,42 @@ class PostHogSentryIntegration {
5481
7202
  };
5482
7203
  }
5483
7204
  }
5484
- // ../../../node_modules/.bun/posthog-node@5.35.12/node_modules/posthog-node/dist/entrypoints/index.node.mjs
7205
+ // ../../../node_modules/.bun/posthog-node@5.51.1/node_modules/posthog-node/dist/entrypoints/index.node.mjs
5485
7206
  class PostHog extends PostHogBackendClient {
5486
7207
  getLibraryId() {
5487
7208
  return "posthog-node";
5488
7209
  }
7210
+ compressPayload(payload) {
7211
+ return gzipCompress2(payload, this.isDebug);
7212
+ }
5489
7213
  initializeContext() {
5490
7214
  return new PostHogContext;
5491
7215
  }
5492
7216
  createErrorPropertiesBuilder() {
5493
- return new exports_error_tracking.ErrorPropertiesBuilder([
5494
- new exports_error_tracking.EventCoercer,
5495
- new exports_error_tracking.ErrorCoercer,
5496
- new exports_error_tracking.ObjectCoercer,
5497
- new exports_error_tracking.StringCoercer,
5498
- new exports_error_tracking.PrimitiveCoercer
5499
- ], exports_error_tracking.createStackParser("node:javascript", exports_error_tracking.nodeStackLineParser), [
7217
+ return new ErrorPropertiesBuilder([
7218
+ new EventCoercer,
7219
+ new ErrorCoercer,
7220
+ new ObjectCoercer,
7221
+ new StringCoercer,
7222
+ new PrimitiveCoercer
7223
+ ], createStackParser("node:javascript", nodeStackLineParser), [
5500
7224
  createModulerModifier(),
5501
- addSourceContext,
7225
+ (frames) => addSourceContext(frames, undefined, this._logger),
5502
7226
  createRelativePathModifier()
5503
7227
  ]);
5504
7228
  }
5505
7229
  }
5506
7230
 
7231
+ // ../../telemetry-core/src/machine-id.ts
7232
+ import { createHash } from "node:crypto";
7233
+ import os2 from "node:os";
7234
+ function getDefaultTelemetryOsProvider() {
7235
+ return os2;
7236
+ }
7237
+ function getTelemetryDistinctId(machineIdPrefix, osProvider = getDefaultTelemetryOsProvider()) {
7238
+ return createHash("sha256").update(`${machineIdPrefix}${osProvider.hostname()}`).digest("hex");
7239
+ }
7240
+
5507
7241
  // ../../telemetry-core/src/posthog-client.ts
5508
7242
  var NO_OP_CLIENT = {
5509
7243
  enabled: false,
@@ -5538,7 +7272,7 @@ function createDefaultPostHogTransport(apiKey, options) {
5538
7272
  }
5539
7273
  function isTelemetryClientEnabled(input) {
5540
7274
  const env = input.env ?? process.env;
5541
- return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && getTelemetryApiKey(env, input.product.defaultApiKey).length > 0;
7275
+ return !shouldDisableTelemetry({ env, productEnvPrefix: input.product.productEnvPrefix }) && hasTelemetryApiKey(env, input.product.defaultApiKey);
5542
7276
  }
5543
7277
  function createTelemetryClient(input) {
5544
7278
  if (!isTelemetryClientEnabled(input)) {
@@ -5604,7 +7338,8 @@ function createTransport(input) {
5604
7338
  flushAt: 1,
5605
7339
  flushInterval: 0,
5606
7340
  host: getTelemetryHost(env, input.product.defaultHost),
5607
- disableGeoip: false
7341
+ disableGeoip: input.product.disableGeoip ?? false,
7342
+ ...input.product.transportOptions
5608
7343
  });
5609
7344
  } catch (error) {
5610
7345
  input.diagnostics?.({
@@ -5872,12 +7607,12 @@ function parseHookInput(raw) {
5872
7607
  }
5873
7608
  }
5874
7609
  function isCodexSessionStartInput(value) {
5875
- return isRecord2(value) && value["hook_event_name"] === "SessionStart" && typeof value["session_id"] === "string" && isStringOrNull(value["transcript_path"]) && typeof value["cwd"] === "string" && typeof value["model"] === "string" && typeof value["permission_mode"] === "string" && typeof value["source"] === "string";
7610
+ return isRecord3(value) && value["hook_event_name"] === "SessionStart" && typeof value["session_id"] === "string" && isStringOrNull(value["transcript_path"]) && typeof value["cwd"] === "string" && typeof value["model"] === "string" && typeof value["permission_mode"] === "string" && typeof value["source"] === "string";
5876
7611
  }
5877
7612
  function isStringOrNull(value) {
5878
7613
  return typeof value === "string" || value === null;
5879
7614
  }
5880
- function isRecord2(value) {
7615
+ function isRecord3(value) {
5881
7616
  return typeof value === "object" && value !== null && !Array.isArray(value);
5882
7617
  }
5883
7618
  function readStdin() {