@posthog/wizard 2.79.1 → 2.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/README.md +187 -57
  2. package/dist/{PickerMenu-dG5DQCZA.js → PickerMenu-BGGeYqd-.js} +112 -12
  3. package/dist/PickerMenu-BGGeYqd-.js.map +1 -0
  4. package/dist/README.md +9 -6
  5. package/dist/{agent-interface-FkbaBJwz.js → agent-interface-CemBvTAA.js} +130 -324
  6. package/dist/agent-interface-CemBvTAA.js.map +1 -0
  7. package/dist/{agent-prompt-loader-D0weQ-7k.js → agent-prompt-loader-DPnj6SwU.js} +6 -5
  8. package/dist/agent-prompt-loader-DPnj6SwU.js.map +1 -0
  9. package/dist/analytics-B3ROGuIr.js +2 -0
  10. package/dist/analytics-D21z3E5l.js +732 -0
  11. package/dist/analytics-D21z3E5l.js.map +1 -0
  12. package/dist/{api-CrbCIQOz.js → api-DtGIqQ2U.js} +2 -3
  13. package/dist/api-DtGIqQ2U.js.map +1 -0
  14. package/dist/api-IhROOQNv.js +2 -0
  15. package/dist/api-key-login-OEntFvu5.js +2 -0
  16. package/dist/api-key-login-h3E2G3zu.js +55 -0
  17. package/dist/api-key-login-h3E2G3zu.js.map +1 -0
  18. package/dist/bin.js +2 -2
  19. package/dist/bin.js.map +1 -1
  20. package/dist/{bounded-fs-vAq-T-K7.js → bounded-fs-CAsuF6al.js} +3 -3
  21. package/dist/{bounded-fs-vAq-T-K7.js.map → bounded-fs-CAsuF6al.js.map} +1 -1
  22. package/dist/{ci-install-COcV8SY2.js → ci-install-CEYE02t-.js} +22 -26
  23. package/dist/ci-install-CEYE02t-.js.map +1 -0
  24. package/dist/console-log-O828zyiq.js +32 -0
  25. package/dist/console-log-O828zyiq.js.map +1 -0
  26. package/dist/{debug-kAHwWGg7.js → debug-BfQPD2Hg.js} +18 -52
  27. package/dist/debug-BfQPD2Hg.js.map +1 -0
  28. package/dist/{defaults-a9TelDhJ.js → defaults-DDVl3tKN.js} +2 -51
  29. package/dist/defaults-DDVl3tKN.js.map +1 -0
  30. package/dist/{emit-BSetXzDV.js → emit-RfAewcWv.js} +1 -1
  31. package/dist/{emit-BSetXzDV.js.map → emit-RfAewcWv.js.map} +1 -1
  32. package/dist/{errors-C2domSkK.js → errors-CHrJzAZb.js} +4 -4
  33. package/dist/{errors-C2domSkK.js.map → errors-CHrJzAZb.js.map} +1 -1
  34. package/dist/family-picker-BKs-tTyu.js +46 -0
  35. package/dist/family-picker-BKs-tTyu.js.map +1 -0
  36. package/dist/{gateway-C9-GlLO9.js → gateway-D3gIlR6b.js} +122 -11
  37. package/dist/gateway-D3gIlR6b.js.map +1 -0
  38. package/dist/headless-BJjhP0SI.js +10 -0
  39. package/dist/headless-BJjhP0SI.js.map +1 -0
  40. package/dist/headless-DIX68UUA.js +3 -0
  41. package/dist/host-resolution-D8GhEVoX.js +114 -0
  42. package/dist/host-resolution-D8GhEVoX.js.map +1 -0
  43. package/dist/install-Bw8tvDvS.js +2 -0
  44. package/dist/{add-mcp-server-to-clients-DIaTRWMY.js → install-paPCzPHI.js} +34 -100
  45. package/dist/install-paPCzPHI.js.map +1 -0
  46. package/dist/interactive-tdxZKWax.js +11 -0
  47. package/dist/interactive-tdxZKWax.js.map +1 -0
  48. package/dist/{telemetry-B7zJdRmA.js → links-Cyj6v8kg.js} +4 -13
  49. package/dist/links-Cyj6v8kg.js.map +1 -0
  50. package/dist/{main-CgKxbwMP.js → main-0p-YxUNa.js} +233 -490
  51. package/dist/main-0p-YxUNa.js.map +1 -0
  52. package/dist/{mcp-DnAyW0-w.js → mcp-D3Z5MXhA.js} +3 -4
  53. package/dist/{mcp-DnAyW0-w.js.map → mcp-D3Z5MXhA.js.map} +1 -1
  54. package/dist/mcp-install-smoke-test.ts +2 -2
  55. package/dist/{mcp-prompt-streaming-DDWQ-FCA.js → mcp-prompt-streaming-COVbWnHt.js} +12 -12
  56. package/dist/mcp-prompt-streaming-COVbWnHt.js.map +1 -0
  57. package/dist/mode-label-DB3ol_sj.js +9 -0
  58. package/dist/mode-label-DB3ol_sj.js.map +1 -0
  59. package/dist/{models-WcwUnSKb.js → models-D1SnCzvl.js} +2 -2
  60. package/dist/{models-WcwUnSKb.js.map → models-D1SnCzvl.js.map} +1 -1
  61. package/dist/non-interactive-DxRBc73O.js +18 -0
  62. package/dist/non-interactive-DxRBc73O.js.map +1 -0
  63. package/dist/{oauth-session-DYM2Hrl2.js → oauth-session-Dde79Ycm.js} +3 -3
  64. package/dist/{oauth-session-DYM2Hrl2.js.map → oauth-session-Dde79Ycm.js.map} +1 -1
  65. package/dist/{orchestrator-tools-DbgNBFGA.js → orchestrator-tools-BSNhzzkT.js} +3 -3
  66. package/dist/{orchestrator-tools-DbgNBFGA.js.map → orchestrator-tools-BSNhzzkT.js.map} +1 -1
  67. package/dist/{package-json-Atg34fa4.js → package-json-2UrhE6kP.js} +1 -1
  68. package/dist/{package-json-Atg34fa4.js.map → package-json-2UrhE6kP.js.map} +1 -1
  69. package/dist/package-json-Dblip2_X.js +2 -0
  70. package/dist/package-manager-BRXlXo0p.js +105 -0
  71. package/dist/package-manager-BRXlXo0p.js.map +1 -0
  72. package/dist/{pi-8KsYsPmM.js → pi-cM_4Gd_9.js} +19 -20
  73. package/dist/pi-cM_4Gd_9.js.map +1 -0
  74. package/dist/playground-DTKy0XHT.js +12 -0
  75. package/dist/playground-DTKy0XHT.js.map +1 -0
  76. package/dist/posthog-integration-bwHwE87a.js +10291 -0
  77. package/dist/posthog-integration-bwHwE87a.js.map +1 -0
  78. package/dist/programs-BhtyA3lE.js +3 -0
  79. package/dist/programs-SeT1qNik.js +5348 -0
  80. package/dist/programs-SeT1qNik.js.map +1 -0
  81. package/dist/provisioning-BcXfeCMc.js +2 -0
  82. package/dist/{provisioning-Bo2NRxFz.js → provisioning-JbJtq7hq.js} +5 -67
  83. package/dist/provisioning-JbJtq7hq.js.map +1 -0
  84. package/dist/{queue-tools-C8mXOh7e.js → queue-tools-BIZSJyt6.js} +7 -9
  85. package/dist/queue-tools-BIZSJyt6.js.map +1 -0
  86. package/dist/results-DtKICAdz.js +55 -0
  87. package/dist/results-DtKICAdz.js.map +1 -0
  88. package/dist/run-CDurA5tO.js +248 -0
  89. package/dist/run-CDurA5tO.js.map +1 -0
  90. package/dist/run-DDCvLILJ.js +246 -0
  91. package/dist/run-DDCvLILJ.js.map +1 -0
  92. package/dist/run-tool-CTq9OOdT.js +2 -0
  93. package/dist/run-tool-DML8JJvt.js +2420 -0
  94. package/dist/run-tool-DML8JJvt.js.map +1 -0
  95. package/dist/runners-Dhu4pZTN.js +253 -0
  96. package/dist/runners-Dhu4pZTN.js.map +1 -0
  97. package/dist/{security-C71pkwqH.js → security-DEH8Rn0_.js} +5 -5
  98. package/dist/security-DEH8Rn0_.js.map +1 -0
  99. package/dist/setup-utils-C5-WM-hS.js +118 -0
  100. package/dist/setup-utils-C5-WM-hS.js.map +1 -0
  101. package/dist/smoke-test.sh +1 -1
  102. package/dist/{playground-BlYRBMj7.js → start-playground-DL4mVEUx.js} +63 -54
  103. package/dist/start-playground-DL4mVEUx.js.map +1 -0
  104. package/dist/{subagent-D1TrTchE.js → subagent-CnFvAq6E.js} +3 -3
  105. package/dist/{subagent-D1TrTchE.js.map → subagent-CnFvAq6E.js.map} +1 -1
  106. package/dist/{task-DqRlQBfs.js → task-BOScSm4W.js} +17 -18
  107. package/dist/task-BOScSm4W.js.map +1 -0
  108. package/dist/{tasks-ChWufsdO.js → tasks-BfJhVky2.js} +1 -1
  109. package/dist/tasks-BfJhVky2.js.map +1 -0
  110. package/dist/telemetry-CP4rGicd.js +13 -0
  111. package/dist/telemetry-CP4rGicd.js.map +1 -0
  112. package/dist/terminal-J3OD3dN0.js +16162 -0
  113. package/dist/terminal-J3OD3dN0.js.map +1 -0
  114. package/dist/tools-CCMV3DmB.js +544 -0
  115. package/dist/tools-CCMV3DmB.js.map +1 -0
  116. package/dist/{tools-CkJ2y9Wt.js → tools-Cz8tDptL.js} +9 -9
  117. package/dist/tools-Cz8tDptL.js.map +1 -0
  118. package/dist/tui-BUZ2PWqN.js +2 -0
  119. package/dist/tui-Csf7VJxt.js +25 -0
  120. package/dist/tui-Csf7VJxt.js.map +1 -0
  121. package/dist/{steps-BPcg3_3Q.js → upload-step-CEacB2RV.js} +17 -19
  122. package/dist/upload-step-CEacB2RV.js.map +1 -0
  123. package/dist/urls-BDELGZHq.js +67 -0
  124. package/dist/urls-BDELGZHq.js.map +1 -0
  125. package/dist/warlock-smoke-test.ts +1 -2
  126. package/dist/{wizard-abort-BPdv07np.js → wizard-abort-D3-75KyV.js} +41 -32
  127. package/dist/wizard-abort-D3-75KyV.js.map +1 -0
  128. package/dist/yara-hooks-CZ1tKxy_.js +2 -0
  129. package/dist/{yara-hooks-BnxejtXK.js → yara-hooks-D8YDyX7o.js} +283 -21
  130. package/dist/yara-hooks-D8YDyX7o.js.map +1 -0
  131. package/package.json +7 -8
  132. package/dist/PickerMenu-dG5DQCZA.js.map +0 -1
  133. package/dist/add-mcp-server-to-clients-DIaTRWMY.js.map +0 -1
  134. package/dist/add-mcp-server-to-clients-artmN7mz.js +0 -2
  135. package/dist/agent-BEjARD2a.js +0 -6
  136. package/dist/agent-BWFhuLgo.js +0 -3178
  137. package/dist/agent-BWFhuLgo.js.map +0 -1
  138. package/dist/agent-interface-FkbaBJwz.js.map +0 -1
  139. package/dist/agent-prompt-loader-D0weQ-7k.js.map +0 -1
  140. package/dist/analytics-DFtbRjYh.js +0 -2
  141. package/dist/analytics-DXK1gc12.js +0 -301
  142. package/dist/analytics-DXK1gc12.js.map +0 -1
  143. package/dist/api-Cm9UtKZh.js +0 -2
  144. package/dist/api-CrbCIQOz.js.map +0 -1
  145. package/dist/check-screens.tsx +0 -190
  146. package/dist/ci-install-COcV8SY2.js.map +0 -1
  147. package/dist/constants-DHCBSfnx.js +0 -260
  148. package/dist/constants-DHCBSfnx.js.map +0 -1
  149. package/dist/debug-BuYHGr6_.js +0 -2
  150. package/dist/debug-kAHwWGg7.js.map +0 -1
  151. package/dist/defaults-a9TelDhJ.js.map +0 -1
  152. package/dist/endpoints-BVMYm9F4.js +0 -108
  153. package/dist/endpoints-BVMYm9F4.js.map +0 -1
  154. package/dist/env-api-key-BP-NFFXt.js +0 -17
  155. package/dist/env-api-key-BP-NFFXt.js.map +0 -1
  156. package/dist/env-api-key-CaWEDj_9.js +0 -2
  157. package/dist/environment-BATlQxcQ.js +0 -39
  158. package/dist/environment-BATlQxcQ.js.map +0 -1
  159. package/dist/environment-CwD8OPYj.js +0 -2
  160. package/dist/file-C5JMsyR1.js +0 -2
  161. package/dist/file-DcRKycV8.js +0 -60
  162. package/dist/file-DcRKycV8.js.map +0 -1
  163. package/dist/file-watcher-Brq2nnHV.js +0 -123
  164. package/dist/file-watcher-Brq2nnHV.js.map +0 -1
  165. package/dist/gateway-C9-GlLO9.js.map +0 -1
  166. package/dist/headless-ui-CqI2gXlD.js +0 -44
  167. package/dist/headless-ui-CqI2gXlD.js.map +0 -1
  168. package/dist/interactive-B_Ti_CsS.js +0 -11
  169. package/dist/interactive-B_Ti_CsS.js.map +0 -1
  170. package/dist/local-dev-McsurOC-.js +0 -135
  171. package/dist/local-dev-McsurOC-.js.map +0 -1
  172. package/dist/logging-ui-Dza4D0MK.js +0 -226
  173. package/dist/logging-ui-Dza4D0MK.js.map +0 -1
  174. package/dist/main-CgKxbwMP.js.map +0 -1
  175. package/dist/mcp-prompt-streaming-DDWQ-FCA.js.map +0 -1
  176. package/dist/mint-failure-u8xQKNOn.js +0 -6392
  177. package/dist/mint-failure-u8xQKNOn.js.map +0 -1
  178. package/dist/non-interactive-DyVC1AGc.js +0 -18
  179. package/dist/non-interactive-DyVC1AGc.js.map +0 -1
  180. package/dist/package-json-D8Ga03tK.js +0 -2
  181. package/dist/pi-8KsYsPmM.js.map +0 -1
  182. package/dist/playground-BlYRBMj7.js.map +0 -1
  183. package/dist/posthog-Bt0Aplb8.js +0 -124
  184. package/dist/posthog-Bt0Aplb8.js.map +0 -1
  185. package/dist/posthog-CUgCEhH0.js +0 -2
  186. package/dist/provisioning-Bo2NRxFz.js.map +0 -1
  187. package/dist/provisioning-OGFGlzf7.js +0 -2
  188. package/dist/queue-tools-C8mXOh7e.js.map +0 -1
  189. package/dist/registry-C06e_x-p.js +0 -2
  190. package/dist/registry-CD5RQt38.js +0 -3464
  191. package/dist/registry-CD5RQt38.js.map +0 -1
  192. package/dist/run-agent-legacy-ChacZImU.js +0 -2
  193. package/dist/run-agent-legacy-DOlM6DQu.js +0 -3540
  194. package/dist/run-agent-legacy-DOlM6DQu.js.map +0 -1
  195. package/dist/runners-ov3EXF1n.js +0 -834
  196. package/dist/runners-ov3EXF1n.js.map +0 -1
  197. package/dist/security-C71pkwqH.js.map +0 -1
  198. package/dist/setup-utils-B26Lf2yF.js +0 -1512
  199. package/dist/setup-utils-B26Lf2yF.js.map +0 -1
  200. package/dist/setup-utils-CVS86NYR.js +0 -2
  201. package/dist/start-tui-Bo2L0bar.js +0 -6962
  202. package/dist/start-tui-Bo2L0bar.js.map +0 -1
  203. package/dist/steps-BPcg3_3Q.js.map +0 -1
  204. package/dist/store-BTzcvRGT.js +0 -992
  205. package/dist/store-BTzcvRGT.js.map +0 -1
  206. package/dist/store-BpqySPXm.js +0 -5
  207. package/dist/task-DqRlQBfs.js.map +0 -1
  208. package/dist/task-stream-Bw6JaLCX.js +0 -363
  209. package/dist/task-stream-Bw6JaLCX.js.map +0 -1
  210. package/dist/tasks-ChWufsdO.js.map +0 -1
  211. package/dist/telemetry-B7zJdRmA.js.map +0 -1
  212. package/dist/terminal-zgkEfoCL.js +0 -7196
  213. package/dist/terminal-zgkEfoCL.js.map +0 -1
  214. package/dist/tools-CkJ2y9Wt.js.map +0 -1
  215. package/dist/ui-Q6-RvERF.js +0 -15
  216. package/dist/ui-Q6-RvERF.js.map +0 -1
  217. package/dist/version-CHhJjz_H.js +0 -6
  218. package/dist/version-CHhJjz_H.js.map +0 -1
  219. package/dist/wizard-abort-BPdv07np.js.map +0 -1
  220. package/dist/wizard-abort-Br1qMDNa.js +0 -3
  221. package/dist/wizard-session-2w4Ru-Wz.js +0 -131
  222. package/dist/wizard-session-2w4Ru-Wz.js.map +0 -1
  223. package/dist/wizard-session-DGaUHOF3.js +0 -2
  224. package/dist/wizard-ui-DVqrYaOM.js +0 -16
  225. package/dist/wizard-ui-DVqrYaOM.js.map +0 -1
  226. package/dist/yara-hooks-BnxejtXK.js.map +0 -1
  227. package/dist/yara-hooks-DSuExwb4.js +0 -2
@@ -1,1512 +0,0 @@
1
- import { s as logToFile } from "./debug-kAHwWGg7.js";
2
- import { n as MCP_LOCAL_URL } from "./local-dev-McsurOC-.js";
3
- import { B as WIZARD_CONTACT_EMAIL, C as ISSUES_URL, E as OAUTH_TIMEOUT_MS, J as WIZARD_PROVISIONING_SCOPES, N as POSTHOG_PROXY_CLIENT_ID, O as POSTHOG_DEV_CLIENT_ID, P as POSTHOG_STATUS_PAGE_URL, Q as WIZARD_USER_AGENT, T as OAUTH_PORTS, W as WIZARD_OAUTH_SCOPES, d as DUMMY_PROJECT_API_KEY } from "./constants-DHCBSfnx.js";
4
- import "./wizard-session-2w4Ru-Wz.js";
5
- import { n as analytics } from "./analytics-DXK1gc12.js";
6
- import { i as withUtm, n as openTrackedLink, t as withProgress } from "./telemetry-B7zJdRmA.js";
7
- import { r as readFileHead } from "./bounded-fs-vAq-T-K7.js";
8
- import { t as getUI } from "./ui-Q6-RvERF.js";
9
- import { a as getCloudUrl, c as getOAuthUrl, i as detectRegion, l as getUiHostFromHost, n as provisionNewAccount, o as getHost, t as ProvisionedAccountUnreadableError, u as resolveBaseUrl } from "./provisioning-Bo2NRxFz.js";
10
- import { c as fetchUserData, o as fetchProjectData } from "./api-CrbCIQOz.js";
11
- import { i as wizardAbort } from "./wizard-abort-BPdv07np.js";
12
- import { major, minVersion } from "semver";
13
- import * as fs$2 from "fs";
14
- import * as path$2 from "path";
15
- import { basename, join as join$1 } from "node:path";
16
- import * as childProcess from "node:child_process";
17
- import { execSync } from "node:child_process";
18
- import * as fs$1 from "node:fs";
19
- import axios from "axios";
20
- import * as crypto from "node:crypto";
21
- import * as http from "node:http";
22
- import { z } from "zod";
23
- //#region src/shared/utils/package-manager.ts
24
- function hasLockfile(installDir, file) {
25
- return fs$2.existsSync(path$2.join(installDir, file));
26
- }
27
- function lockfileHeaderContains(installDir, file, needle) {
28
- return readFileHead(path$2.join(installDir, file), 500)?.includes(needle) ?? false;
29
- }
30
- async function writeOverride(slot, pkgName, pkgVersion, { installDir }) {
31
- const pkg = await getPackageDotJson({ installDir });
32
- let next;
33
- if (slot === "yarn") next = {
34
- ...pkg,
35
- resolutions: {
36
- ...pkg.resolutions ?? {},
37
- [pkgName]: pkgVersion
38
- }
39
- };
40
- else if (slot === "pnpm") next = {
41
- ...pkg,
42
- pnpm: {
43
- ...pkg.pnpm ?? {},
44
- overrides: {
45
- ...pkg.pnpm?.overrides ?? {},
46
- [pkgName]: pkgVersion
47
- }
48
- }
49
- };
50
- else next = {
51
- ...pkg,
52
- overrides: {
53
- ...pkg.overrides ?? {},
54
- [pkgName]: pkgVersion
55
- }
56
- };
57
- await updatePackageDotJson(next, { installDir });
58
- }
59
- const packageManagers = [
60
- {
61
- name: "bun",
62
- label: "Bun",
63
- installCommand: "bun add",
64
- buildCommand: "bun run build",
65
- runScriptCommand: "bun run",
66
- flags: "",
67
- detect: ({ installDir }) => hasLockfile(installDir, "bun.lockb") || hasLockfile(installDir, "bun.lock"),
68
- addOverride: (pkgName, pkgVersion, opts) => writeOverride("npm", pkgName, pkgVersion, opts)
69
- },
70
- {
71
- name: "yarn",
72
- label: "Yarn V1",
73
- installCommand: "yarn add",
74
- buildCommand: "yarn build",
75
- runScriptCommand: "yarn",
76
- flags: "--ignore-workspace-root-check",
77
- detect: ({ installDir }) => lockfileHeaderContains(installDir, "yarn.lock", "yarn lockfile v1"),
78
- addOverride: (pkgName, pkgVersion, opts) => writeOverride("yarn", pkgName, pkgVersion, opts)
79
- },
80
- {
81
- name: "yarn",
82
- label: "Yarn V2/3/4",
83
- installCommand: "yarn add",
84
- buildCommand: "yarn build",
85
- runScriptCommand: "yarn",
86
- flags: "",
87
- detect: ({ installDir }) => lockfileHeaderContains(installDir, "yarn.lock", "__metadata"),
88
- addOverride: (pkgName, pkgVersion, opts) => writeOverride("yarn", pkgName, pkgVersion, opts)
89
- },
90
- {
91
- name: "pnpm",
92
- label: "pnpm",
93
- installCommand: "pnpm add",
94
- buildCommand: "pnpm build",
95
- runScriptCommand: "pnpm",
96
- flags: "--ignore-workspace-root-check",
97
- detect: ({ installDir }) => hasLockfile(installDir, "pnpm-lock.yaml"),
98
- addOverride: (pkgName, pkgVersion, opts) => writeOverride("pnpm", pkgName, pkgVersion, opts)
99
- },
100
- {
101
- name: "npm",
102
- label: "npm",
103
- installCommand: "npm add",
104
- buildCommand: "npm run build",
105
- runScriptCommand: "npm run",
106
- flags: "",
107
- detect: ({ installDir }) => hasLockfile(installDir, "package-lock.json"),
108
- addOverride: (pkgName, pkgVersion, opts) => writeOverride("npm", pkgName, pkgVersion, opts)
109
- },
110
- {
111
- name: "expo",
112
- label: "Expo",
113
- installCommand: "npx expo install",
114
- buildCommand: "npx expo build",
115
- runScriptCommand: "npx expo run",
116
- flags: "",
117
- detect: () => false,
118
- addOverride: (pkgName, pkgVersion, opts) => writeOverride("npm", pkgName, pkgVersion, opts)
119
- }
120
- ];
121
- function detectAllPackageManagers({ installDir }) {
122
- return withProgress("detect-package-manager", () => {
123
- const matches = packageManagers.filter((pm) => pm.detect({ installDir }));
124
- if (matches.length === 0) analytics.setTag("package-manager", "not-detected");
125
- return matches;
126
- });
127
- }
128
- function serializeNodePM(pm) {
129
- return {
130
- name: pm.name,
131
- label: pm.label,
132
- installCommand: pm.installCommand,
133
- runCommand: pm.runScriptCommand
134
- };
135
- }
136
- /**
137
- * Detect Node.js package managers via lockfiles.
138
- * Wraps detectAllPackageManagers() above.
139
- */
140
- function detectNodePackageManagers(installDir) {
141
- const detected = detectAllPackageManagers({ installDir }).map(serializeNodePM);
142
- if (detected.length === 0) return Promise.resolve({
143
- detected: [],
144
- primary: null,
145
- recommendation: "No lockfile found. Default to npm (npm add, npm run)."
146
- });
147
- const primary = detected[0];
148
- return Promise.resolve({
149
- detected,
150
- primary,
151
- recommendation: detected.length === 1 ? `Use ${primary.label} (${primary.installCommand}).` : `Multiple package managers detected. Prefer ${primary.label} (${primary.installCommand}).`
152
- });
153
- }
154
- //#endregion
155
- //#region src/programs/oauth/program-scopes.ts
156
- /**
157
- * Extra scopes the MCP tutorial needs on top of `WIZARD_OAUTH_SCOPES`.
158
- *
159
- * Every scope requested here must stay within the wizard OAuth app's
160
- * ceiling on the PostHog side (`OAuthApplication.scopes`) — the full
161
- * list lives in the README under "OAuth app scope ceiling". The
162
- * tutorial's prompts and follow-ups touch most of the read surface,
163
- * plus annotation write for the "PostHog wizard install" verify-prompt.
164
- *
165
- * Already in the base `WIZARD_OAUTH_SCOPES` (and therefore not
166
- * repeated here):
167
- * • user:read, project:read, llm_gateway:read — auth + gateway
168
- * • query:read — HogQL
169
- * • dashboard:write, insight:write, notebook:write — Phase-5 persist
170
- *
171
- * Deliberately omitted (writes on read-only product surfaces):
172
- * • feature_flag:write, experiment:write, survey:write,
173
- * cohort:write, session_recording:write, error_tracking:write,
174
- * alert:write, subscription:write
175
- */
176
- const MCP_TUTORIAL_SCOPE_ADDITIONS = [
177
- "dashboard:read",
178
- "insight:read",
179
- "notebook:read",
180
- "feature_flag:read",
181
- "experiment:read",
182
- "experiment_saved_metric:read",
183
- "survey:read",
184
- "session_recording:read",
185
- "error_tracking:read",
186
- "web_analytics:read",
187
- "llm_analytics:read",
188
- "cohort:read",
189
- "person:read",
190
- "annotation:read",
191
- "annotation:write",
192
- "activity_log:read",
193
- "property_definition:read",
194
- "event_definition:read",
195
- "action:read",
196
- "warehouse_table:read",
197
- "warehouse_view:read",
198
- "alert:read",
199
- "subscription:read",
200
- "integration:read"
201
- ];
202
- /**
203
- * Extra scopes the agent-skill program needs on top of `WIZARD_OAUTH_SCOPES`.
204
- *
205
- * Skills under this program (e.g. `creating-product-tours`) create feature
206
- * flags during the install flow. PostHog's consent grants exactly the scope
207
- * strings requested — `:write` does not imply `:read` — so listing existing
208
- * flags to avoid key collisions needs `feature_flag:read` explicitly.
209
- * `property_definition:read` lets the agent discover person properties when
210
- * building flag rollout filters instead of having to ask the user verbatim.
211
- */
212
- const AGENT_SKILL_SCOPE_ADDITIONS = [
213
- "feature_flag:read",
214
- "feature_flag:write",
215
- "property_definition:read"
216
- ];
217
- /**
218
- * Extra scopes the self-driving program needs on top of
219
- * `WIZARD_OAUTH_SCOPES`. All consumed by the PostHog MCP tools the
220
- * agent drives during the run:
221
- * • task:read / task:write — the signal source config API
222
- * (`inbox-source-configs-*`) is permissioned under the generic
223
- * `task` scope object, NOT a signals-specific one. Unrelated to
224
- * the Tasks product.
225
- * • integration:read — `integrations-list`, to check whether the
226
- * team already has a GitHub integration and to verify the connect
227
- * flow completed.
228
- * • signal_scout:read / signal_scout:write — list, sync, and tune
229
- * the Signals scout troop (`signals-scout-config-*`).
230
- * • session_recording:read / survey:read / error_tracking:read —
231
- * server-side product-usage probes (`query-session-recordings-list`,
232
- * `survey-list`, `error-issue-list`). Product usage is a
233
- * project-level fact (often instrumented in another repo or via
234
- * the snippet), so the agent asks the server instead of inferring
235
- * only from the local setup report. All three are read-only and
236
- * already in the wizard OAuth app's production scope ceiling (the
237
- * mcp-tutorial program requests them).
238
- * • external_data_source:read / external_data_source:write — the
239
- * connected-tools step creates the GitHub Issues / Linear warehouse
240
- * sources directly (`external-data-sources-create`) and verifies
241
- * what's actually connected (`external-data-sources-list`) instead
242
- * of taking the user's word for it.
243
- * • llm_skill:read / llm_skill:write — the custom-scouts step
244
- * (skill step 6b): read the seeded `authoring-signals-scouts`
245
- * guide and canonical scout bodies (`llma-skill-get` /
246
- * `llma-skill-file-get`) and author the user-approved custom
247
- * `signals-scout-*` skills (`llma-skill-create`). Canonical scout
248
- * bodies are never edited.
249
- * • product_enablement:write — the "Enable products" step turns on
250
- * Session Replay / Error Tracking / Support so their sources have
251
- * data to read (`products-enable`). A purpose-built scope: the
252
- * server owns each enable recipe, so this can flip the product
253
- * toggles without the far broader `project:write`.
254
- * • replay_scanner:read / replay_scanner:write — the Replay Vision
255
- * scanners step (skill step 6c) lists the team's existing scanners
256
- * and creates the `emits_signals` ones whose findings land in the
257
- * inbox (`vision-scanners-list` / `-create` / `-update`, and the
258
- * advisory `vision-scanners-estimate-create` / `vision-quota-retrieve`).
259
- * The scope OBJECT is `replay_scanner` — the `vision-scanners-*`
260
- * names are MCP tool names, not scopes. Configuring a scanner also
261
- * requires `session_recording:read` (the API pairs the two, since a
262
- * scanner's config indirectly exposes recording contents); that one
263
- * is already in this list for the step-2 usage probes.
264
- *
265
- * No OAuth-ceiling edit is needed for any scope here: they are all normal
266
- * public (unprivileged, non-internal, non-hidden) scope objects, and the
267
- * live wizard apps' ceiling is the `@default` sentinel, which resolves to
268
- * every such scope (`UNPRIVILEGED_SCOPES`) and auto-tracks new ones. Only a
269
- * privileged/internal/hidden object (e.g. `llm_gateway:*`) would need a
270
- * manual per-app edit. See README → "OAuth app scope ceiling".
271
- */
272
- const SELF_DRIVING_SCOPE_ADDITIONS = [
273
- "task:read",
274
- "task:write",
275
- "integration:read",
276
- "signal_scout:read",
277
- "signal_scout:write",
278
- "session_recording:read",
279
- "survey:read",
280
- "error_tracking:read",
281
- "external_data_source:read",
282
- "external_data_source:write",
283
- "llm_skill:read",
284
- "llm_skill:write",
285
- "product_enablement:write",
286
- "replay_scanner:read",
287
- "replay_scanner:write"
288
- ];
289
- /**
290
- * Extra scopes the warehouse-source program needs on top of
291
- * `WIZARD_OAUTH_SCOPES`. The agent creates data warehouse sources directly
292
- * (`external-data-sources-create`) and lists what's connected
293
- * (`external-data-sources-list`) to verify the result. Both are already within
294
- * the wizard OAuth app's scope ceiling — the self-driving program requests the
295
- * same pair.
296
- */
297
- const WAREHOUSE_SOURCE_SCOPE_ADDITIONS = ["external_data_source:read", "external_data_source:write"];
298
- /**
299
- * Extra scope the Connect-Slack step needs on top of `WIZARD_OAUTH_SCOPES`.
300
- *
301
- * The step polls `/api/projects/:id/integrations/` (`fetchSlackConnected`)
302
- * to render the already-connected variant and to flip live once the user
303
- * completes the Slack OAuth step in the browser. Without `integration:read`
304
- * the first poll 403s, the screen stops polling, and an already-connected
305
- * project is nagged with the connect nudge. Used by the default integration
306
- * run (the step ends the run) and by the standalone `wizard slack` flow
307
- * (the step is the whole program).
308
- */
309
- const CONNECT_SLACK_SCOPE_ADDITIONS = ["integration:read"];
310
- /**
311
- * Extra scopes the replay-vision program needs on top of `WIZARD_OAUTH_SCOPES`.
312
- * The same set self-driving's step 6c uses, narrowed to just this flow:
313
- * • replay_scanner:read / replay_scanner:write — the scanner tasks list the
314
- * team's existing scanners and create the ones scoped to the product's key
315
- * flows (`vision-scanners-list` / `-create`, plus the advisory
316
- * `vision-scanners-estimate-create` / `vision-quota-retrieve`). The scope
317
- * OBJECT is `replay_scanner`; `vision-scanners-*` are MCP tool names.
318
- * • session_recording:read — the scanner API pairs it with
319
- * `replay_scanner:*`, since a scanner's config indirectly exposes
320
- * recording contents. Configuring a scanner fails without it.
321
- * • product_enablement:write — the enable-replay task's server half turns on
322
- * Session Replay (`products-enable`) so there are recordings to scan.
323
- *
324
- * Without these the PostHog MCP omits the tools from the catalog it serves
325
- * this token, every scanner task takes its "tool unknown" skip path, and the
326
- * run reports success having created nothing (run 69afc6f8).
327
- *
328
- * No OAuth-ceiling edit needed — all are unprivileged public scope objects
329
- * covered by the apps' `@default` sentinel, and self-driving already requests
330
- * every one of them.
331
- */
332
- const REPLAY_VISION_SCOPE_ADDITIONS = [
333
- "session_recording:read",
334
- "product_enablement:write",
335
- "replay_scanner:read",
336
- "replay_scanner:write"
337
- ];
338
- /**
339
- * Per-program scope additions, layered on top of `WIZARD_OAUTH_SCOPES`.
340
- *
341
- * Programs not listed here request the unchanged base set. Use this
342
- * map only for programs that need *more* than the base — never for
343
- * narrowing, since narrowing risks breaking shared infrastructure
344
- * (e.g. dropping `llm_gateway:read` would 401 every agent call).
345
- *
346
- * Keyed by `ProgramId` so TypeScript catches stale entries when a
347
- * program is renamed or removed.
348
- */
349
- const PROGRAM_SCOPE_ADDITIONS = {
350
- "mcp-tutorial": MCP_TUTORIAL_SCOPE_ADDITIONS,
351
- "agent-skill": AGENT_SKILL_SCOPE_ADDITIONS,
352
- "self-driving": SELF_DRIVING_SCOPE_ADDITIONS,
353
- "warehouse-source": WAREHOUSE_SOURCE_SCOPE_ADDITIONS,
354
- "posthog-integration": [...CONNECT_SLACK_SCOPE_ADDITIONS, ...WAREHOUSE_SOURCE_SCOPE_ADDITIONS],
355
- slack: CONNECT_SLACK_SCOPE_ADDITIONS,
356
- "replay-vision": REPLAY_VISION_SCOPE_ADDITIONS
357
- };
358
- /**
359
- * Resolve the OAuth scope list to request for a given program. Returns
360
- * `WIZARD_OAUTH_SCOPES` for programs without an addition entry; for
361
- * programs that do have one, returns the union of base + additions
362
- * with duplicates dropped (declaration order preserved, base first).
363
- *
364
- * `null` / `undefined` programId falls through to the default — same
365
- * behavior as the historical hardcoded `WIZARD_OAUTH_SCOPES` reference
366
- * in `askForWizardLogin`, so call sites that haven't been updated to
367
- * pass a programId continue to work unchanged.
368
- */
369
- function getOAuthScopesForProgram(programId) {
370
- const additions = programId && PROGRAM_SCOPE_ADDITIONS[programId] || [];
371
- if (additions.length === 0) return WIZARD_OAUTH_SCOPES;
372
- const seen = /* @__PURE__ */ new Set();
373
- const merged = [];
374
- for (const s of [...WIZARD_OAUTH_SCOPES, ...additions]) {
375
- if (seen.has(s)) continue;
376
- seen.add(s);
377
- merged.push(s);
378
- }
379
- return merged;
380
- }
381
- /**
382
- * Resolve the scope list for the signup provisioning path. Same
383
- * base-plus-additions shape as `getOAuthScopesForProgram`, but layered on
384
- * `WIZARD_PROVISIONING_SCOPES` so a program's extra scopes only reach
385
- * tokens provisioned for that program.
386
- */
387
- function getProvisioningScopesForProgram(programId) {
388
- const additions = programId && PROGRAM_SCOPE_ADDITIONS[programId] || [];
389
- if (additions.length === 0) return WIZARD_PROVISIONING_SCOPES;
390
- const seen = /* @__PURE__ */ new Set();
391
- const merged = [];
392
- for (const s of [...WIZARD_PROVISIONING_SCOPES, ...additions]) {
393
- if (seen.has(s)) continue;
394
- seen.add(s);
395
- merged.push(s);
396
- }
397
- return merged;
398
- }
399
- //#endregion
400
- //#region src/shared/host-resolution.ts
401
- /**
402
- * HostResolution — the single, immutable snapshot of where the wizard talks to
403
- * PostHog for one run.
404
- *
405
- * One cloud region (or a pinned `--base-url`) implies a whole family of hosts:
406
- * the event-ingestion/API host, the user-facing web app host, the CDN asset
407
- * host, the LLM gateway, and the MCP server. Rather than re-deriving each of
408
- * these at every call site and threading `region` + `baseUrl` around as loose
409
- * params, resolve once at auth time and pass this frozen object around — read
410
- * the property you need.
411
- *
412
- * The actual region→URL math (and the `--base-url` override) lives in
413
- * `@utils/urls`; this class is a thin, immutable façade over those resolvers so
414
- * the override flows through every field without callers having to know about
415
- * it. The OAuth-server URL stays in `@utils/urls` (`getOAuthUrl`) because it is
416
- * needed *before* a region is known, so it can't come from this post-auth object.
417
- */
418
- const MCP_PROD_URL = "https://mcp.posthog.com/mcp";
419
- function assetHostFor(region, baseUrl) {
420
- const override = resolveBaseUrl(baseUrl);
421
- if (override) return override;
422
- return region === "eu" ? "https://eu-assets.i.posthog.com" : "https://us-assets.i.posthog.com";
423
- }
424
- function assetHostFromApiHost(apiHost) {
425
- if (apiHost.includes("us.i.posthog.com")) return "https://us-assets.i.posthog.com";
426
- if (apiHost.includes("eu.i.posthog.com")) return "https://eu-assets.i.posthog.com";
427
- return apiHost;
428
- }
429
- /**
430
- * Dev/CI only: the env override (see env.ts) wins even under --local-mcp;
431
- * published builds strip the read. Don't name that env var in comments here —
432
- * smoke-test.sh greps dist/*.js for it, and JSDoc survives bundling.
433
- */
434
- function mcpUrlFor(localMcp) {
435
- return localMcp ? MCP_LOCAL_URL : MCP_PROD_URL;
436
- }
437
- var HostResolution = class HostResolution {
438
- /** The resolved cloud region. `'us'` when a base URL is pinned. */
439
- region;
440
- /**
441
- * Event-ingestion / REST API host (e.g. `https://us.i.posthog.com`, or the
442
- * pinned `--base-url`). The SDK `host` written into the user's `.env`, the
443
- * base for the wizard-session REST calls, and the host shown to the agent.
444
- */
445
- apiHost;
446
- /**
447
- * User-facing web app host (e.g. `https://us.posthog.com`). Use for any link
448
- * we hand to the user or open in their browser (dashboards, settings, inbox,
449
- * deep-link base).
450
- */
451
- appHost;
452
- /** CDN asset host (e.g. `https://us-assets.i.posthog.com`). */
453
- assetHost;
454
- /**
455
- * PostHog MCP server URL the agent connects to. Region-independent — the
456
- * server resolves the user's region from the bearer token — so this is driven
457
- * only by `--local-mcp` / `--local-dev` and the dev env override, not by
458
- * region/base-url.
459
- */
460
- mcpUrl;
461
- constructor(fields) {
462
- this.region = fields.region;
463
- this.apiHost = fields.apiHost;
464
- this.appHost = fields.appHost;
465
- this.assetHost = fields.assetHost;
466
- this.mcpUrl = fields.mcpUrl;
467
- Object.freeze(this);
468
- }
469
- /**
470
- * Canonical path: build the host family from a resolved region. A pinned
471
- * `--base-url` (via `opts.baseUrl`) wins for every origin; otherwise the
472
- * region's standard hosts are used. Honors IS_DEV through `resolveBaseUrl`.
473
- */
474
- static fromRegion(region, opts = {}) {
475
- return new HostResolution({
476
- region,
477
- apiHost: getHost(region, opts.baseUrl),
478
- appHost: getCloudUrl(region, opts.baseUrl),
479
- assetHost: assetHostFor(region, opts.baseUrl),
480
- mcpUrl: mcpUrlFor(opts.localMcp ?? false)
481
- });
482
- }
483
- /**
484
- * Build from an ingestion host string (the provisioning API returns one). The
485
- * given host is preserved verbatim as `apiHost`; the region and the derived
486
- * app/asset/gateway hosts are inferred from it.
487
- */
488
- static fromApiHost(apiHost, opts = {}) {
489
- return new HostResolution({
490
- region: apiHost.includes("eu.") ? "eu" : "us",
491
- apiHost,
492
- appHost: getUiHostFromHost(apiHost),
493
- assetHost: assetHostFromApiHost(apiHost),
494
- mcpUrl: mcpUrlFor(opts.localMcp ?? false)
495
- });
496
- }
497
- /**
498
- * Resolve the region from an access token (the us/eu probe, skipped when a
499
- * base URL is pinned), then build the host family. Used after OAuth and after
500
- * CI-mode API-key auth.
501
- */
502
- static async fromAccessToken(accessToken, opts = {}) {
503
- const region = opts.region ?? await detectRegion(accessToken, opts.baseUrl);
504
- return HostResolution.fromRegion(region, opts);
505
- }
506
- };
507
- //#endregion
508
- //#region src/shared/utils/oauth-errors.ts
509
- /**
510
- * OAuth failure presentation — the structured error the flow throws and the
511
- * user-facing messaging built from it.
512
- *
513
- * `oauth.ts` owns the flow machinery (callback server, token exchange, port
514
- * retries); this module owns what a failure *means*: the RFC 6749 error
515
- * fields (`error`, `error_description`, `error_uri`), per-code remediation
516
- * copy, and safe rendering for the browser callback page. Everything here is
517
- * pure so the copy can be unit-tested without the HTTP machinery.
518
- */
519
- /**
520
- * A structured OAuth failure (RFC 6749 §4.1.2.1 authorize errors, §5.2 token
521
- * errors). Thrown by both the authorize callback and the token exchange so
522
- * the flow's error handler keys remediation copy and analytics fingerprints
523
- * off `code` instead of re-parsing `message`.
524
- *
525
- * The message stays exactly `OAuth error: <code>` — the analytics fingerprint
526
- * scheme (`wizard_oauth_<code>`) and the legacy message-prefix parsing both
527
- * depend on that shape. The description/uri ride along as properties.
528
- *
529
- * NAMING: never bind an instance to a variable or property whose name
530
- * contains "oauth" (use `flowError`, `callbackError`, ...). CodeQL's
531
- * clear-text-logging heuristic classifies any `*oauth*`-named variable read
532
- * as password data, and these errors are deliberately shown to the user, so
533
- * such a binding flags every log statement downstream of it (CWE-312).
534
- */
535
- var OAuthError = class extends Error {
536
- code;
537
- /** The server's human-readable explanation (`error_description`), if sent. */
538
- description;
539
- /** The server's "more info" link (`error_uri`), if sent. */
540
- uri;
541
- constructor(code, description, uri) {
542
- super(`OAuth error: ${code}`);
543
- this.name = "OAuthError";
544
- this.code = code;
545
- this.description = description;
546
- this.uri = uri;
547
- }
548
- };
549
- /**
550
- * Sanitize an OAuth error param before logging or rendering it: these arrive
551
- * on a query string (or a token-endpoint body) that anything able to hit the
552
- * local callback port can populate. Strips non-printable/non-ASCII characters
553
- * and caps the length. Returns undefined when nothing printable remains.
554
- */
555
- function sanitizeOAuthParam(value, maxLength = 200) {
556
- if (!value) return void 0;
557
- return value.replace(/[^\x20-\x7e]/g, "").slice(0, maxLength).trim() || void 0;
558
- }
559
- /** Description sentences get more room than bare codes/URIs. */
560
- const MAX_DESCRIPTION_LENGTH = 500;
561
- function escapeHtml(value) {
562
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
563
- }
564
- const OAuthErrorBodySchema = z.object({
565
- error: z.string().min(1),
566
- error_description: z.string().optional(),
567
- error_uri: z.string().optional()
568
- });
569
- /**
570
- * Build an `OAuthError` from an authorize-callback's query params.
571
- * Sanitizes every field — the callback URL is attacker-reachable input.
572
- */
573
- function oauthErrorFromCallbackParams(params) {
574
- return new OAuthError(sanitizeOAuthParam(params.get("error")) ?? "unknown", sanitizeOAuthParam(params.get("error_description"), MAX_DESCRIPTION_LENGTH), sanitizeOAuthParam(params.get("error_uri")));
575
- }
576
- /**
577
- * Build an `OAuthError` from a token-endpoint JSON error body (RFC 6749
578
- * §5.2). Returns null when the body isn't an OAuth error shape (HTML error
579
- * pages, proxy bodies, network failures) — the caller rethrows the raw
580
- * error in that case.
581
- */
582
- function oauthErrorFromTokenBody(data) {
583
- const parsed = OAuthErrorBodySchema.safeParse(data);
584
- if (!parsed.success) return null;
585
- return new OAuthError(sanitizeOAuthParam(parsed.data.error) ?? "unknown", sanitizeOAuthParam(parsed.data.error_description, MAX_DESCRIPTION_LENGTH), sanitizeOAuthParam(parsed.data.error_uri));
586
- }
587
- /**
588
- * The error paragraphs for the browser callback page. The constant framing
589
- * (title, styles, "return to your terminal") stays in `oauth.ts`; this owns
590
- * the part that varies by error, with everything HTML-escaped since the
591
- * values come straight off the callback query string.
592
- */
593
- function buildCallbackErrorHtml(error) {
594
- if (error.code === "access_denied") return "<p>Authorization cancelled.</p>";
595
- const paragraphs = [`<p>Authorization failed (${escapeHtml(error.code)}).</p>`];
596
- if (error.description) paragraphs.push(`<p>${escapeHtml(error.description)}</p>`);
597
- if (error.uri) paragraphs.push(`<p>More info: ${escapeHtml(error.uri)}</p>`);
598
- return paragraphs.join("\n");
599
- }
600
- /**
601
- * Per-code headline + "what to do" remediation for the terminal failure
602
- * message. Codes not listed fall through to a generic rendering of the
603
- * error. `access_denied` and the flow timeout never reach this — they keep
604
- * their dedicated handling in `performOAuthFlow`.
605
- */
606
- function headlineAndRemediation(params) {
607
- const { error, oauthUrl, isDevStack } = params;
608
- if (!(error instanceof OAuthError)) return { headline: error.message };
609
- switch (error.code) {
610
- case "invalid_scope": return {
611
- headline: "PostHog rejected one or more of the requested scopes (invalid_scope).",
612
- whatToDo: isDevStack ? "The wizard OAuth app on your local stack allows fewer scopes than the wizard requests (its OAuthApplication.scopes ceiling). Re-run your local wizard OAuth app setup so it allows every scope listed below, or add the missing ones in Django admin, then try again." : `The wizard OAuth app's server-side scope ceiling (OAuthApplication.scopes) is missing scopes the wizard requests. This needs a fix on the PostHog side, so email ${WIZARD_CONTACT_EMAIL} with the details below (PostHog staff: the "scope-ceiling-invalid-scope" runbook in PostHog/runbooks has the fix). Re-running the wizard will not help until the ceiling is updated.`
613
- };
614
- case "invalid_client": return {
615
- headline: `PostHog at ${oauthUrl} does not recognize the wizard's OAuth client (invalid_client).`,
616
- whatToDo: "The client ID below is not registered on the target instance. If you pointed the wizard at a local or self-hosted stack (--base-url), seed its wizard OAuth app first; otherwise re-run without --base-url to use PostHog Cloud."
617
- };
618
- case "invalid_grant": return {
619
- headline: "The login code was rejected (invalid_grant): it expired or was already used.",
620
- whatToDo: "Re-run the wizard and complete the browser login promptly. Login codes expire after 5 minutes and can only be used once."
621
- };
622
- case "server_error": return {
623
- headline: "PostHog's OAuth server hit an internal error (server_error).",
624
- whatToDo: `This is usually transient. Wait a moment and re-run the wizard. If it keeps failing, check ${POSTHOG_STATUS_PAGE_URL}.`
625
- };
626
- case "temporarily_unavailable": return {
627
- headline: "PostHog's OAuth server is temporarily unavailable (temporarily_unavailable).",
628
- whatToDo: `This is usually transient. Wait a moment and re-run the wizard. If it keeps failing, check ${POSTHOG_STATUS_PAGE_URL}.`
629
- };
630
- default: return {
631
- headline: `PostHog returned an OAuth error: ${error.code}.`,
632
- whatToDo: "Re-run the wizard. If the error persists, include the details below when asking for help."
633
- };
634
- }
635
- }
636
- /**
637
- * Terminal message for a failed OAuth flow. Always ends with the request
638
- * context (target host, client ID, requested scopes) so a pasted bug report
639
- * is actionable without follow-up questions, plus how to get help: the
640
- * support email (Zendesk-backed) and the issues link.
641
- */
642
- function buildOAuthFailureMessage(params) {
643
- const { error, requestedScopes, clientId, oauthUrl } = params;
644
- const flowError = error instanceof OAuthError ? error : null;
645
- const { headline, whatToDo } = headlineAndRemediation(params);
646
- const sections = [`Authorization failed: ${headline}`];
647
- if (flowError?.description) sections.push(`The server said: ${flowError.description}`);
648
- if (flowError?.uri) sections.push(`More info: ${flowError.uri}`);
649
- if (whatToDo) sections.push(`What to do: ${whatToDo}`);
650
- sections.push([
651
- "Details for bug reports:",
652
- ` target host: ${oauthUrl}`,
653
- ` client ID: ${clientId}`,
654
- ` requested scopes: ${requestedScopes.join(" ")}`
655
- ].join("\n"));
656
- sections.push(`Need help? Email ${WIZARD_CONTACT_EMAIL} with the details above, or create an issue:\n${ISSUES_URL}`);
657
- return sections.join("\n\n");
658
- }
659
- //#endregion
660
- //#region src/shared/utils/oauth.ts
661
- const OAUTH_CALLBACK_STYLES = `
662
- <style>
663
- * {
664
- font-family: monospace;
665
- background-color: #1b0a00;
666
- color: #F7A502;
667
- font-weight: medium;
668
- font-size: 24px;
669
- margin: .25rem;
670
- }
671
-
672
- .blink {
673
- animation: blink-animation 1s steps(2, start) infinite;
674
- }
675
-
676
- @keyframes blink-animation {
677
- to {
678
- opacity: 0;
679
- }
680
- }
681
- </style>
682
- `;
683
- const OAuthTokenResponseSchema = z.object({
684
- access_token: z.string(),
685
- expires_in: z.number(),
686
- token_type: z.string(),
687
- scope: z.string(),
688
- refresh_token: z.string().optional(),
689
- scoped_teams: z.array(z.number()).optional(),
690
- scoped_organizations: z.array(z.string()).optional(),
691
- posthog_region: z.enum(["us", "eu"]).optional().catch(void 0),
692
- posthog_base_url: z.string().optional().catch(void 0)
693
- });
694
- const WIZARD_COMPLETION_SCOPE = "event_definition:write";
695
- function parseOAuthScopes(scope) {
696
- return scope.split(/\s+/).filter(Boolean);
697
- }
698
- /**
699
- * Requested scopes the grant came back without.
700
- *
701
- * A token can legitimately carry fewer scopes than the wizard asked for: the
702
- * consent screen lets the user deselect any scope the OAuth app doesn't mark
703
- * required, and anything outside the app's ceiling is clamped server-side.
704
- * Neither path is an error — `/oauth/token` just returns a narrower `scope`.
705
- * Diff it at login, where the gap is fixable, rather than letting the run
706
- * discover it as a permission failure on some API call minutes in.
707
- */
708
- function missingOAuthScopes(requested, grantedScope) {
709
- const granted = new Set(parseOAuthScopes(grantedScope));
710
- return requested.filter((scope) => !granted.has(scope));
711
- }
712
- function assertWizardCompletionScope(scope) {
713
- if (parseOAuthScopes(scope).includes("event_definition:write")) return;
714
- throw new Error(`This run was authorized without the ${WIZARD_COMPLETION_SCOPE} permission, which the wizard needs to finish setup. Please try again, approving all permissions on the PostHog authorization screen. If that screen does not reappear, revoke the existing PostHog Wizard authorization in your PostHog settings first.`);
715
- }
716
- const AUTHORIZATION_TIMEOUT_MESSAGE = "Authorization timed out";
717
- function isAuthorizationTimeout(error) {
718
- return error.message === AUTHORIZATION_TIMEOUT_MESSAGE;
719
- }
720
- /**
721
- * OAuth client ID for the current target. A pinned base URL (`--base-url`, or
722
- * IS_DEV's implicit localhost) means we're talking to a dev-seeded stack, which
723
- * registers the dev client; prod uses the proxy client.
724
- *
725
- * TODO: this assumes any pinned base URL is a dev-seeded instance that
726
- * registers POSTHOG_DEV_CLIENT_ID. If we ever point `--base-url` at a non-dev
727
- * instance with its own OAuth app, make the client ID configurable (e.g. a
728
- * `--oauth-client-id` flag) instead of always falling back to the dev client.
729
- */
730
- function getOAuthClientId(baseUrl) {
731
- return resolveBaseUrl(baseUrl) ? POSTHOG_DEV_CLIENT_ID : POSTHOG_PROXY_CLIENT_ID;
732
- }
733
- function getLocalOAuthOrigin(port) {
734
- return `http://localhost:${port}`;
735
- }
736
- function getCallbackUrl(port) {
737
- return `${getLocalOAuthOrigin(port)}/callback`;
738
- }
739
- function getLocalLoginUrl(port) {
740
- return `${getLocalOAuthOrigin(port)}/authorize`;
741
- }
742
- function getLocalSignupUrl(port) {
743
- return `${getLocalLoginUrl(port)}?signup=true`;
744
- }
745
- /**
746
- * Extract an OAuth authorization code from raw user input. Accepts either the
747
- * bare code, the full callback URL the browser was redirected to
748
- * (`http://localhost:8239/callback?code=abc123&...`), or just the query
749
- * string. Returns null when no code can be found.
750
- *
751
- * This backs the manual-entry fallback: in headless/remote environments the
752
- * browser can't reach the wizard's local callback server, so the user copies
753
- * the failed callback URL (or the code from it) back into the terminal.
754
- */
755
- function extractOAuthCode(input) {
756
- const trimmed = input.trim();
757
- if (!trimmed) return null;
758
- let looksLikeUrl = false;
759
- try {
760
- const url = new URL(trimmed);
761
- looksLikeUrl = true;
762
- const code = url.searchParams.get("code");
763
- if (code) return code;
764
- } catch {}
765
- const match = trimmed.match(/[?&]?code=([^&\s]+)/);
766
- if (match) return decodeURIComponent(match[1]);
767
- if (looksLikeUrl) return null;
768
- if (!/\s/.test(trimmed)) return trimmed;
769
- return null;
770
- }
771
- function generateCodeVerifier() {
772
- return crypto.randomBytes(32).toString("base64url");
773
- }
774
- function generateCodeChallenge(verifier) {
775
- return crypto.createHash("sha256").update(verifier).digest("base64url");
776
- }
777
- async function startCallbackServer(authUrl, signupUrl, port) {
778
- return new Promise((resolve, reject) => {
779
- let callbackResolve;
780
- let callbackReject;
781
- const waitForCallback = () => new Promise((res, rej) => {
782
- callbackResolve = res;
783
- callbackReject = rej;
784
- });
785
- const server = http.createServer((req, res) => {
786
- if (!req.url) {
787
- res.writeHead(400);
788
- res.end();
789
- return;
790
- }
791
- const url = new URL(req.url, getLocalOAuthOrigin(port));
792
- if (url.pathname === "/authorize") {
793
- const redirectUrl = url.searchParams.get("signup") === "true" ? signupUrl : authUrl;
794
- res.writeHead(302, { Location: redirectUrl });
795
- res.end();
796
- return;
797
- }
798
- const code = url.searchParams.get("code");
799
- if (url.searchParams.get("error")) {
800
- const callbackError = oauthErrorFromCallbackParams(url.searchParams);
801
- const isAccessDenied = callbackError.code === "access_denied";
802
- logToFile(`[oauth] callback received with error: ${callbackError.code}` + (callbackError.description ? ` (${callbackError.description})` : ""));
803
- res.writeHead(isAccessDenied ? 200 : 400, { "Content-Type": "text/html; charset=utf-8" });
804
- res.end(`
805
- <html>
806
- <head>
807
- <meta charset="UTF-8">
808
- <title>PostHog wizard - Authorization ${isAccessDenied ? "cancelled" : "failed"}</title>
809
- ${OAUTH_CALLBACK_STYLES}
810
- </head>
811
- <body>
812
- ${buildCallbackErrorHtml(callbackError)}
813
- <p>Return to your terminal. This window will close automatically.</p>
814
- <script>window.close();<\/script>
815
- </body>
816
- </html>
817
- `);
818
- callbackReject(callbackError);
819
- return;
820
- }
821
- if (code) {
822
- logToFile("[oauth] callback received with authorization code");
823
- res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
824
- res.end(`
825
- <html>
826
- <head>
827
- <meta charset="UTF-8">
828
- <title>PostHog wizard is ready</title>
829
- ${OAUTH_CALLBACK_STYLES}
830
- </head>
831
- <body>
832
- <p>PostHog login complete!</p>
833
- <p>Return to your terminal: the wizard is hard at work on your project<span class="blink">█</span></p>
834
- <script>window.close();<\/script>
835
- </body>
836
- </html>
837
- `);
838
- callbackResolve(code);
839
- } else {
840
- res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
841
- res.end(`
842
- <html>
843
- <head>
844
- <meta charset="UTF-8">
845
- <title>PostHog wizard - Invalid request</title>
846
- ${OAUTH_CALLBACK_STYLES}
847
- </head>
848
- <body>
849
- <p>Invalid request - no authorization code received.</p>
850
- <p>You can close this window.</p>
851
- </body>
852
- </html>
853
- `);
854
- }
855
- });
856
- server.on("clientError", (error, socket) => {
857
- if (socket.destroyed || socket.writableEnded) return;
858
- if (error.code === "ECONNRESET" || !socket.writable) {
859
- socket.destroy();
860
- return;
861
- }
862
- logToFile(`[oauth] local HTTP request rejected: ${error.code ?? "unknown"}`);
863
- const overflow = error.code === "HPE_HEADER_OVERFLOW";
864
- let status = "400 Bad Request";
865
- switch (error.code) {
866
- case "HPE_HEADER_OVERFLOW":
867
- status = "431 Request Header Fields Too Large";
868
- break;
869
- case "HPE_CHUNK_EXTENSIONS_OVERFLOW":
870
- status = "413 Payload Too Large";
871
- break;
872
- case "ERR_HTTP_REQUEST_TIMEOUT":
873
- status = "408 Request Timeout";
874
- break;
875
- }
876
- const body = overflow ? `<!doctype html>
877
- <html lang="en">
878
- <head>
879
- <meta charset="UTF-8">
880
- <title>PostHog wizard - Browser request too large</title>
881
- ${OAUTH_CALLBACK_STYLES}
882
- </head>
883
- <body>
884
- <p>Your browser sent more than ${http.maxHeaderSize / 1024} KiB of request headers.</p>
885
- <p>This can happen when cookies from other localhost apps accumulate.</p>
886
- <p>Clear cookies for localhost and retry, or open the login link from your terminal in a private/incognito window.</p>
887
- </body>
888
- </html>` : "";
889
- socket.end(`HTTP/1.1 ${status}\r\nContent-Type: text/html; charset=utf-8\r
890
- Content-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r
891
- Cache-Control: no-store\r
892
- \r
893
- ` + body);
894
- });
895
- server.listen(port, () => {
896
- resolve({
897
- port,
898
- server,
899
- waitForCallback
900
- });
901
- });
902
- server.on("error", reject);
903
- });
904
- }
905
- function getPortProcessInfo(port) {
906
- try {
907
- const lines = execSync(`lsof -i :${port} -sTCP:LISTEN 2>/dev/null`, {
908
- encoding: "utf-8",
909
- timeout: 3e3
910
- }).trim().split("\n");
911
- if (lines.length < 2) return {
912
- command: "unknown",
913
- pid: "unknown",
914
- port,
915
- user: "unknown"
916
- };
917
- const fields = lines[1].split(/\s+/);
918
- return {
919
- command: fields[0] ?? "unknown",
920
- pid: fields[1] ?? "unknown",
921
- port,
922
- user: fields[2] ?? "unknown"
923
- };
924
- } catch {
925
- return {
926
- command: "unknown",
927
- pid: "unknown",
928
- port,
929
- user: "unknown"
930
- };
931
- }
932
- }
933
- function isPortInUseError(error) {
934
- return error instanceof Error && "code" in error && error.code === "EADDRINUSE";
935
- }
936
- async function exchangeCodeForToken(code, codeVerifier, callbackUrl, baseUrl) {
937
- const clientId = getOAuthClientId(baseUrl);
938
- const oauthUrl = getOAuthUrl(baseUrl);
939
- logToFile(`[oauth] exchanging code for token at ${oauthUrl}/oauth/token`);
940
- let response;
941
- try {
942
- response = await axios.post(`${oauthUrl}/oauth/token`, {
943
- grant_type: "authorization_code",
944
- code,
945
- redirect_uri: callbackUrl,
946
- client_id: clientId,
947
- code_verifier: codeVerifier
948
- }, { headers: {
949
- "Content-Type": "application/json",
950
- "User-Agent": WIZARD_USER_AGENT
951
- } });
952
- } catch (e) {
953
- const status = axios.isAxiosError(e) ? e.response?.status : void 0;
954
- logToFile(`[oauth] token exchange failed${status ? ` (HTTP ${status})` : ""}:`, e instanceof Error ? e.message : e);
955
- const exchangeError = axios.isAxiosError(e) ? oauthErrorFromTokenBody(e.response?.data) : null;
956
- if (exchangeError) {
957
- logToFile(`[oauth] token endpoint error: ${exchangeError.code}` + (exchangeError.description ? ` (${exchangeError.description})` : ""));
958
- throw exchangeError;
959
- }
960
- throw e;
961
- }
962
- const token = OAuthTokenResponseSchema.parse(response.data);
963
- logToFile(`[oauth] token exchange succeeded, granted scopes: ${token.scope}${token.posthog_region ? `, region: ${token.posthog_region}` : ""}${token.scoped_teams ? `, scoped_teams: [${token.scoped_teams.join(", ")}]` : ""}${token.scoped_organizations ? `, scoped_organizations: ${token.scoped_organizations.length}` : ""}`);
964
- return token;
965
- }
966
- async function refreshAccessToken(refreshToken, baseUrl, clientId) {
967
- const oauthUrl = getOAuthUrl(baseUrl);
968
- logToFile(`[oauth] refreshing access token at ${oauthUrl}/oauth/token`);
969
- try {
970
- const response = await axios.post(`${oauthUrl}/oauth/token`, {
971
- grant_type: "refresh_token",
972
- refresh_token: refreshToken,
973
- client_id: clientId ?? getOAuthClientId(baseUrl)
974
- }, {
975
- headers: {
976
- "Content-Type": "application/json",
977
- "User-Agent": WIZARD_USER_AGENT
978
- },
979
- timeout: 3e4
980
- });
981
- const token = OAuthTokenResponseSchema.parse(response.data);
982
- logToFile("[oauth] access token refreshed");
983
- return token;
984
- } catch (e) {
985
- logToFile("[oauth] token refresh failed:", e instanceof Error ? e.message : e);
986
- throw (axios.isAxiosError(e) ? oauthErrorFromTokenBody(e.response?.data) : null) ?? e;
987
- }
988
- }
989
- /**
990
- * Warn — at login, while the user is still watching — when the grant came back
991
- * narrower than the request, and record the gap so narrowed runs are countable.
992
- * Non-fatal by design: deselecting an optional scope is the user's call, and
993
- * most flows survive it. The one scope the wizard cannot run without has its
994
- * own hard check (`assertWizardCompletionScope`).
995
- */
996
- function reportNarrowedGrant(requestedScopes, grantedScope) {
997
- const missing = missingOAuthScopes(requestedScopes, grantedScope);
998
- if (missing.length === 0) return;
999
- logToFile(`[oauth] grant narrower than request, missing: ${missing.join(" ")}`);
1000
- analytics.wizardCapture("oauth grant narrowed", {
1001
- requested_scopes: [...requestedScopes].sort().join(" "),
1002
- granted_scopes: parseOAuthScopes(grantedScope).sort().join(" "),
1003
- missing_scopes: missing.join(" "),
1004
- missing_scope_count: missing.length
1005
- });
1006
- const plural = missing.length > 1;
1007
- getUI().log.warn(`Your PostHog authorization is missing ${plural ? `${missing.length} permissions` : "a permission"} the wizard asked for: ${missing.join(", ")}. Setup will continue, but steps that need ${plural ? "them" : "it"} may fail. To grant ${plural ? "them" : "it"}, re-run the wizard and approve all permissions on the authorization screen. If that screen does not reappear, revoke the existing PostHog Wizard authorization in your PostHog settings first.`);
1008
- }
1009
- async function performOAuthFlow(config) {
1010
- const clientId = getOAuthClientId(config.baseUrl);
1011
- const oauthUrl = getOAuthUrl(config.baseUrl);
1012
- const codeVerifier = generateCodeVerifier();
1013
- const codeChallenge = generateCodeChallenge(codeVerifier);
1014
- let shouldRetry = false;
1015
- logToFile(`[oauth] starting flow against ${oauthUrl}, requested scopes: ${config.scopes.join(" ")}`);
1016
- do {
1017
- shouldRetry = false;
1018
- let lastProcessInfo = null;
1019
- for (const port of OAUTH_PORTS) {
1020
- const callbackUrl = getCallbackUrl(port);
1021
- const authUrl = new URL(`${oauthUrl}/oauth/authorize`);
1022
- authUrl.searchParams.set("client_id", clientId);
1023
- authUrl.searchParams.set("redirect_uri", callbackUrl);
1024
- authUrl.searchParams.set("response_type", "code");
1025
- authUrl.searchParams.set("code_challenge", codeChallenge);
1026
- authUrl.searchParams.set("code_challenge_method", "S256");
1027
- authUrl.searchParams.set("scope", config.scopes.join(" "));
1028
- authUrl.searchParams.set("required_access_level", "project");
1029
- if (config.projectId !== void 0) authUrl.searchParams.set("team_id", String(config.projectId));
1030
- const taggedAuthUrl = withUtm(authUrl.toString(), "oauth-authorize");
1031
- const signupUrl = new URL(withUtm(`${oauthUrl}/signup?next=${encodeURIComponent(taggedAuthUrl)}`, "oauth-signup"));
1032
- const localSignupUrl = getLocalSignupUrl(port);
1033
- const localLoginUrl = getLocalLoginUrl(port);
1034
- const urlToOpen = config.signup ? localSignupUrl : localLoginUrl;
1035
- logToFile(`[oauth] attempting callback server on port ${port}`);
1036
- let server;
1037
- let waitForCallback;
1038
- try {
1039
- ({server, waitForCallback} = await startCallbackServer(taggedAuthUrl, signupUrl.toString(), port));
1040
- } catch (e) {
1041
- if (!isPortInUseError(e)) throw e;
1042
- lastProcessInfo = getPortProcessInfo(port);
1043
- continue;
1044
- }
1045
- logToFile("[oauth] callback server ready, showing login URL");
1046
- getUI().setLoginUrl(urlToOpen);
1047
- getUI().setAuthorizeUrl(config.signup ? signupUrl.toString() : taggedAuthUrl);
1048
- openTrackedLink(urlToOpen, "oauth", {
1049
- auto: true,
1050
- skipUtm: true
1051
- });
1052
- const loginSpinner = getUI().spinner();
1053
- loginSpinner.start("Waiting for authorization...");
1054
- try {
1055
- const token = await exchangeCodeForToken(await Promise.race([
1056
- waitForCallback(),
1057
- getUI().waitForManualAuthCode(),
1058
- new Promise((_, reject) => setTimeout(() => reject(new Error(AUTHORIZATION_TIMEOUT_MESSAGE)), OAUTH_TIMEOUT_MS))
1059
- ]), codeVerifier, callbackUrl, config.baseUrl);
1060
- server.close();
1061
- getUI().setLoginUrl(null);
1062
- getUI().setAuthorizeUrl(null);
1063
- loginSpinner.stop("Authorization complete!");
1064
- reportNarrowedGrant(config.scopes, token.scope);
1065
- return token;
1066
- } catch (e) {
1067
- const error = e instanceof Error ? e : /* @__PURE__ */ new Error("Unknown error");
1068
- const timedOut = isAuthorizationTimeout(error);
1069
- const flowError = error instanceof OAuthError ? error : null;
1070
- loginSpinner.stop(timedOut ? "Session timed out." : "Authorization failed.");
1071
- server.close();
1072
- logToFile("[oauth] flow failed:", error);
1073
- if (flowError?.description) logToFile(`[oauth] server error_description: ${flowError.description}`);
1074
- const accessDenied = flowError ? flowError.code === "access_denied" : error.message.includes("access_denied");
1075
- if (timedOut) getUI().showSessionTimeout();
1076
- else if (accessDenied) getUI().log.info(`Authorization was cancelled.\n\nYou denied access to PostHog. To use the wizard, you need to authorize access to your PostHog account.\n\nYou can try again by re-running the wizard.`);
1077
- else getUI().log.error(buildOAuthFailureMessage({
1078
- error,
1079
- requestedScopes: config.scopes,
1080
- clientId,
1081
- oauthUrl,
1082
- isDevStack: resolveBaseUrl(config.baseUrl) !== void 0
1083
- }));
1084
- const oauthErrorCode = flowError ? flowError.code : error.message.startsWith("OAuth error: ") ? error.message.slice(13) : timedOut ? "timeout" : "unknown";
1085
- analytics.captureException(error, {
1086
- step: "oauth_flow",
1087
- oauth_error_code: oauthErrorCode,
1088
- oauth_error_description: flowError?.description,
1089
- client_id: clientId,
1090
- requested_scopes: config.scopes.join(" "),
1091
- $exception_fingerprint: `wizard_oauth_${oauthErrorCode}`
1092
- });
1093
- await abort();
1094
- throw error;
1095
- }
1096
- }
1097
- if (!lastProcessInfo) throw new Error("No OAuth callback ports configured");
1098
- await getUI().showPortConflict(lastProcessInfo);
1099
- shouldRetry = true;
1100
- } while (shouldRetry);
1101
- throw new Error("OAuth port retry loop exited unexpectedly");
1102
- }
1103
- //#endregion
1104
- //#region src/shared/utils/project-resolution.ts
1105
- /**
1106
- * Decide which project to use after OAuth. `--project-id` (when passed) is authoritative,
1107
- * but only when the user granted access to it on the consent screen; a different grant is a
1108
- * mismatch the caller must surface. With no `--project-id` this returns the granted project
1109
- * (`scopedTeams[0]`), preserving the pre-flag behavior for every wizard program (the main
1110
- * integration flow included).
1111
- */
1112
- function resolveGrantedProject(requestedProjectId, scopedTeams) {
1113
- if (requestedProjectId === void 0) return {
1114
- ok: true,
1115
- projectId: scopedTeams?.[0]
1116
- };
1117
- if (scopedTeams?.includes(requestedProjectId)) return {
1118
- ok: true,
1119
- projectId: requestedProjectId
1120
- };
1121
- if (scopedTeams && scopedTeams.length > 0) return {
1122
- ok: false,
1123
- requested: requestedProjectId,
1124
- granted: scopedTeams[0]
1125
- };
1126
- return {
1127
- ok: true,
1128
- projectId: void 0
1129
- };
1130
- }
1131
- //#endregion
1132
- //#region src/shared/utils/semver.ts
1133
- /**
1134
- * Version strings from package.json that are not semver ranges.
1135
- * URLs, git refs, dist-tags, local paths, workspace protocol, npm aliases, etc.
1136
- * These should be rejected early — we can't determine a clear version from them.
1137
- */
1138
- function isNonSemverVersion(version) {
1139
- const v = version.trim();
1140
- return v === "" || v.startsWith("http://") || v.startsWith("https://") || v.startsWith("git+") || v.startsWith("git://") || v.startsWith("file:") || v.startsWith("npm:") || v.startsWith("workspace:") || v.startsWith("/") || v.includes("/");
1141
- }
1142
- /**
1143
- * Creates a version bucket function for analytics.
1144
- * Converts versions like "1.2.3" to "1.x" for grouping in analytics.
1145
- *
1146
- * @param minMajorVersion - Optional minimum major version threshold.
1147
- * Versions below this will be bucketed as "<{min}.0.0"
1148
- *
1149
- * @example
1150
- * const getVersionBucket = createVersionBucket(); // no minimum
1151
- * getVersionBucket("1.2.3") // "1.x"
1152
- *
1153
- * const getVersionBucket = createVersionBucket(11);
1154
- * getVersionBucket("15.3.0") // "15.x"
1155
- * getVersionBucket("10.0.0") // "<11.0.0"
1156
- */
1157
- function createVersionBucket(minMajorVersion) {
1158
- return (version) => {
1159
- if (!version) return "none";
1160
- if (isNonSemverVersion(version)) return "unknown";
1161
- try {
1162
- const minVer = minVersion(version);
1163
- if (!minVer) return "invalid";
1164
- const majorVersion = major(minVer);
1165
- if (minMajorVersion !== void 0 && majorVersion < minMajorVersion) return `<${minMajorVersion}.0.0`;
1166
- return `${majorVersion}.x`;
1167
- } catch {
1168
- return "unknown";
1169
- }
1170
- };
1171
- }
1172
- //#endregion
1173
- //#region src/shared/utils/setup-utils.ts
1174
- /** @deprecated Use wizardAbort() directly for new code. */
1175
- async function abort(message, status) {
1176
- return wizardAbort({
1177
- message,
1178
- exitCode: status
1179
- });
1180
- }
1181
- const FREEMAIL_DOMAINS = new Set([
1182
- "gmail.com",
1183
- "googlemail.com",
1184
- "hotmail.com",
1185
- "outlook.com",
1186
- "yahoo.com",
1187
- "icloud.com",
1188
- "me.com",
1189
- "mail.com",
1190
- "protonmail.com",
1191
- "proton.me",
1192
- "live.com",
1193
- "aol.com",
1194
- "yandex.com",
1195
- "zoho.com",
1196
- "gmx.com",
1197
- "fastmail.com"
1198
- ]);
1199
- function parseGitRemote() {
1200
- try {
1201
- const match = childProcess.execSync("git remote get-url origin", { stdio: [
1202
- "ignore",
1203
- "pipe",
1204
- "ignore"
1205
- ] }).toString().trim().match(/[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
1206
- if (match) return {
1207
- org: match[1],
1208
- repo: match[2]
1209
- };
1210
- } catch {}
1211
- return null;
1212
- }
1213
- function detectOrgAndProject(email) {
1214
- const remote = parseGitRemote();
1215
- const projectName = remote?.repo || basename(process.cwd()) || void 0;
1216
- let orgName;
1217
- if (remote?.org) orgName = remote.org;
1218
- else {
1219
- const domain = email.split("@")[1]?.toLowerCase();
1220
- if (domain && !FREEMAIL_DOMAINS.has(domain)) orgName = domain.split(".")[0];
1221
- }
1222
- return {
1223
- orgName,
1224
- projectName
1225
- };
1226
- }
1227
- /**
1228
- * Get package.json or abort the wizard if not found.
1229
- * Only use where package.json is required (e.g., package install, overrides).
1230
- * For detection/version-checks, use tryGetPackageJson() instead.
1231
- */
1232
- async function getPackageDotJson({ installDir }) {
1233
- const pkgPath = join$1(installDir, "package.json");
1234
- let raw;
1235
- try {
1236
- raw = await fs$1.promises.readFile(pkgPath, "utf8");
1237
- } catch {
1238
- getUI().log.error("Could not find package.json. Make sure to run the wizard in the root of your app!");
1239
- await abort();
1240
- return {};
1241
- }
1242
- try {
1243
- return JSON.parse(raw) ?? {};
1244
- } catch {
1245
- getUI().log.error(`Unable to parse your package.json. Make sure it has a valid format!`);
1246
- await abort();
1247
- return {};
1248
- }
1249
- }
1250
- /**
1251
- * Try to get package.json, returning null if it doesn't exist.
1252
- * Use this for detection purposes where missing package.json is expected (e.g., Python projects).
1253
- */
1254
- async function tryGetPackageJson({ installDir }) {
1255
- try {
1256
- const packageJsonFileContents = await fs$1.promises.readFile(join$1(installDir, "package.json"), "utf8");
1257
- return JSON.parse(packageJsonFileContents);
1258
- } catch {
1259
- return null;
1260
- }
1261
- }
1262
- async function updatePackageDotJson(packageDotJson, { installDir }) {
1263
- const pkgPath = join$1(installDir, "package.json");
1264
- const serialized = JSON.stringify(packageDotJson, null, 2);
1265
- try {
1266
- await fs$1.promises.writeFile(pkgPath, serialized, {
1267
- encoding: "utf8",
1268
- flag: "w"
1269
- });
1270
- return;
1271
- } catch {
1272
- getUI().log.error(`Unable to update your package.json.`);
1273
- await abort();
1274
- }
1275
- }
1276
- function isUsingTypeScript({ installDir }) {
1277
- try {
1278
- fs$1.accessSync(join$1(installDir, "tsconfig.json"));
1279
- return true;
1280
- } catch {
1281
- return false;
1282
- }
1283
- }
1284
- /**
1285
- * Get project data for the wizard via OAuth or CI API key.
1286
- */
1287
- async function getOrAskForProjectData(_options) {
1288
- if (_options.ci && _options.apiKey) {
1289
- getUI().log.info("Using provided API key (CI mode - OAuth bypassed)");
1290
- const host = await HostResolution.fromAccessToken(_options.apiKey, {
1291
- region: _options.region,
1292
- localMcp: _options.localMcp,
1293
- baseUrl: _options.baseUrl
1294
- });
1295
- const cloudUrl = host.appHost;
1296
- const projectData = _options.projectId != null ? await fetchProjectDataById(_options.apiKey, _options.projectId, cloudUrl) : await fetchProjectDataWithApiKey(_options.apiKey, cloudUrl);
1297
- let user = null;
1298
- let roleAtOrganization = null;
1299
- try {
1300
- user = await fetchUserData(_options.apiKey, cloudUrl);
1301
- roleAtOrganization = user.role_at_organization ?? null;
1302
- } catch (err) {
1303
- logToFile("[ci-auth] user lookup failed:", err instanceof Error ? err.message : String(err));
1304
- }
1305
- if (user) {
1306
- analytics.identifyUser(user);
1307
- logToFile("[ci-auth] identified via API key; flags evaluate as the key owner");
1308
- } else getUI().log.warn("Could not resolve the API key user (key needs user:read scope) — feature flags evaluate anonymously; user-targeted flags will not match.");
1309
- return {
1310
- host,
1311
- projectApiKey: projectData.api_token,
1312
- accessToken: _options.apiKey,
1313
- projectId: projectData.id,
1314
- roleAtOrganization,
1315
- user,
1316
- project: projectData.project,
1317
- missingScopes: []
1318
- };
1319
- }
1320
- const { host, projectApiKey, accessToken, refreshToken, expiresAt, oauthClientId, projectId, roleAtOrganization, user, project, missingScopes } = await withProgress("login", () => askForWizardLogin({
1321
- signup: _options.signup,
1322
- email: _options.email,
1323
- region: _options.region,
1324
- baseUrl: _options.baseUrl,
1325
- programId: _options.programId,
1326
- projectId: _options.projectId,
1327
- localMcp: _options.localMcp
1328
- }));
1329
- if (!projectApiKey) {
1330
- const cloudUrl = host.appHost;
1331
- getUI().log.error(`Didn't receive a project token. This shouldn't happen :(
1332
-
1333
- Please let us know if you think this is a bug in the wizard:
1334
- ${ISSUES_URL}`);
1335
- getUI().log.info(`In the meantime, we'll add a dummy project token ("${DUMMY_PROJECT_API_KEY}") for you to replace later.
1336
- You can find your project token here:
1337
- ${cloudUrl}/settings/project#variables`);
1338
- }
1339
- return {
1340
- accessToken,
1341
- refreshToken,
1342
- expiresAt,
1343
- oauthClientId,
1344
- host,
1345
- projectApiKey: projectApiKey || "_YOUR_POSTHOG_PROJECT_TOKEN_",
1346
- projectId,
1347
- roleAtOrganization: roleAtOrganization ?? null,
1348
- user: user ?? null,
1349
- project: project ?? null,
1350
- missingScopes: missingScopes ?? []
1351
- };
1352
- }
1353
- async function fetchProjectDataWithApiKey(apiKey, cloudUrl) {
1354
- const projectId = (await fetchUserData(apiKey, cloudUrl)).team?.id;
1355
- if (!projectId) throw new Error("Could not determine project ID from API key. Please ensure your API key has access to a project in this cloud region.");
1356
- const projectData = await fetchProjectData(apiKey, projectId, cloudUrl);
1357
- return {
1358
- api_token: projectData.api_token,
1359
- id: projectId,
1360
- project: projectData
1361
- };
1362
- }
1363
- async function fetchProjectDataById(apiKey, projectId, cloudUrl) {
1364
- const projectData = await fetchProjectData(apiKey, projectId, cloudUrl);
1365
- return {
1366
- api_token: projectData.api_token,
1367
- id: projectId,
1368
- project: projectData
1369
- };
1370
- }
1371
- async function askForWizardLogin(options) {
1372
- if (options.signup) return askForProvisioningSignup(options.email, options.region, options.baseUrl, options.localMcp, options.programId);
1373
- const requestedScopes = [...getOAuthScopesForProgram(options.programId)];
1374
- const tokenResponse = await performOAuthFlow({
1375
- scopes: requestedScopes,
1376
- signup: false,
1377
- projectId: options.projectId,
1378
- baseUrl: options.baseUrl
1379
- });
1380
- try {
1381
- assertWizardCompletionScope(tokenResponse.scope);
1382
- } catch (error) {
1383
- const scopeError = error instanceof Error ? error : /* @__PURE__ */ new Error("OAuth scope check failed");
1384
- const missing = missingOAuthScopes(requestedScopes, tokenResponse.scope);
1385
- analytics.captureException(scopeError, {
1386
- step: "wizard_login",
1387
- missing_scope: "event_definition:write"
1388
- });
1389
- await wizardAbort({
1390
- message: scopeError.message,
1391
- outroData: {
1392
- kind: "error",
1393
- message: "Setup needs permissions that were not granted",
1394
- body: [
1395
- "Missing permissions:",
1396
- ...missing.map((scope) => ` • ${scope}`),
1397
- "",
1398
- "Re-run the wizard and approve all permissions on the PostHog authorization screen.",
1399
- "If that screen does not reappear, revoke the existing PostHog Wizard authorization in your PostHog settings first."
1400
- ].join("\n")
1401
- }
1402
- });
1403
- }
1404
- const resolution = resolveGrantedProject(options.projectId, tokenResponse.scoped_teams);
1405
- if (!resolution.ok) {
1406
- const error = /* @__PURE__ */ new Error(`You authorized project ${resolution.granted}, but setup is targeting project ${resolution.requested} (from --project-id). If ${resolution.requested} is not a project you own — a copy-pasted example value, say — re-run without --project-id, or with the id shown in your PostHog project settings. If it is yours, re-run and grant access to project ${resolution.requested} on the authorization screen.`);
1407
- analytics.captureException(error, {
1408
- step: "wizard_login",
1409
- requested_project_id: resolution.requested,
1410
- granted_project_id: resolution.granted
1411
- });
1412
- getUI().log.error(error.message);
1413
- await abort(error.message);
1414
- }
1415
- const projectId = resolution.ok ? resolution.projectId : void 0;
1416
- if (projectId === void 0) {
1417
- const error = /* @__PURE__ */ new Error("No project access granted. Please authorize with project-level access.");
1418
- analytics.captureException(error, {
1419
- step: "wizard_login",
1420
- has_scoped_teams: !!tokenResponse.scoped_teams
1421
- });
1422
- getUI().log.error(error.message);
1423
- await abort(error.message);
1424
- }
1425
- const host = await HostResolution.fromAccessToken(tokenResponse.access_token, {
1426
- region: tokenResponse.posthog_region,
1427
- localMcp: options.localMcp,
1428
- baseUrl: options.baseUrl
1429
- });
1430
- const cloudUrl = host.appHost;
1431
- const projectData = await fetchProjectData(tokenResponse.access_token, projectId, cloudUrl);
1432
- const userData = await fetchUserData(tokenResponse.access_token, cloudUrl);
1433
- const data = {
1434
- accessToken: tokenResponse.access_token,
1435
- refreshToken: tokenResponse.refresh_token,
1436
- expiresAt: Date.now() + tokenResponse.expires_in * 1e3,
1437
- projectApiKey: projectData.api_token,
1438
- host,
1439
- distinctId: userData.distinct_id,
1440
- projectId,
1441
- roleAtOrganization: userData.role_at_organization ?? null,
1442
- user: userData,
1443
- project: projectData,
1444
- missingScopes: missingOAuthScopes(requestedScopes, tokenResponse.scope)
1445
- };
1446
- getUI().log.success("Login complete.");
1447
- analytics.setTag("opened-wizard-link", true);
1448
- analytics.identifyUser(userData);
1449
- return data;
1450
- }
1451
- async function askForProvisioningSignup(email, region, baseUrl, localMcp, programId) {
1452
- if (!email || !email.includes("@")) {
1453
- getUI().log.error("Email is required for signup. Use --email your@email.com with --signup.");
1454
- await abort();
1455
- throw new Error("unreachable");
1456
- }
1457
- const spinner = getUI().spinner();
1458
- spinner.start("Creating your PostHog account...");
1459
- try {
1460
- const provisionRegion = (region ?? "us").toUpperCase();
1461
- const { orgName, projectName } = detectOrgAndProject(email);
1462
- const result = await provisionNewAccount(email, "", provisionRegion, {
1463
- orgName,
1464
- projectName,
1465
- baseUrl,
1466
- scopes: getProvisioningScopesForProgram(programId)
1467
- });
1468
- spinner.stop("Account created!");
1469
- getUI().log.success("Welcome to PostHog!");
1470
- const host = HostResolution.fromApiHost(result.host, { localMcp });
1471
- analytics.setTag("provisioning-signup", true);
1472
- return {
1473
- accessToken: result.accessToken,
1474
- refreshToken: result.refreshToken,
1475
- expiresAt: result.expiresAt,
1476
- oauthClientId: result.oauthClientId,
1477
- projectApiKey: result.projectApiKey,
1478
- host,
1479
- distinctId: email,
1480
- projectId: parseInt(result.projectId, 10) || 0
1481
- };
1482
- } catch (error) {
1483
- const message = error instanceof Error ? error.message : "Unknown error";
1484
- if (error instanceof ProvisionedAccountUnreadableError) {
1485
- spinner.stop("Account created, but the project could not be read back.");
1486
- getUI().log.warn(message);
1487
- getUI().log.info("Signing you in to your new account instead...");
1488
- return askForWizardLogin({
1489
- signup: false,
1490
- baseUrl,
1491
- localMcp
1492
- });
1493
- }
1494
- spinner.stop("Account creation failed.");
1495
- if (message.includes("already associated")) {
1496
- getUI().log.info("This email already has a PostHog account. Switching to login flow...");
1497
- return askForWizardLogin({
1498
- signup: false,
1499
- baseUrl,
1500
- localMcp
1501
- });
1502
- }
1503
- getUI().log.error(`Failed to create account: ${message}`);
1504
- analytics.captureException(error instanceof Error ? error : new Error(message), { step: "provisioning_signup" });
1505
- await abort();
1506
- throw error;
1507
- }
1508
- }
1509
- //#endregion
1510
- export { isUsingTypeScript as a, createVersionBucket as c, refreshAccessToken as d, OAuthError as f, detectNodePackageManagers as g, detectAllPackageManagers as h, getPackageDotJson as i, extractOAuthCode as l, mcpUrlFor as m, detectOrgAndProject as n, tryGetPackageJson as o, HostResolution as p, getOrAskForProjectData as r, updatePackageDotJson as s, abort as t, missingOAuthScopes as u };
1511
-
1512
- //# sourceMappingURL=setup-utils-B26Lf2yF.js.map