@posthog/wizard 2.13.1 → 2.14.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 (87) hide show
  1. package/LICENSE +0 -26
  2. package/README.md +1 -1
  3. package/dist/TextBlock-B3cm43YY.js +244 -0
  4. package/dist/TextBlock-B3cm43YY.js.map +1 -0
  5. package/dist/{add-mcp-server-to-clients-D1IyBa9u.js → add-mcp-server-to-clients-DVdyI6SQ.js} +7 -7
  6. package/dist/{add-mcp-server-to-clients-D1IyBa9u.js.map → add-mcp-server-to-clients-DVdyI6SQ.js.map} +1 -1
  7. package/dist/{agent-interface-D9DeIikl.js → agent-interface-BJoqBI04.js} +533 -255
  8. package/dist/agent-interface-BJoqBI04.js.map +1 -0
  9. package/dist/{agent-runner-B41-Iig3.js → agent-runner-oJ7Wyhl7.js} +102 -20
  10. package/dist/agent-runner-oJ7Wyhl7.js.map +1 -0
  11. package/dist/analytics-Cz_p0Xus.js +2 -0
  12. package/dist/{analytics-Cek5hIwm.js → analytics-kUCNQQJm.js} +2 -2
  13. package/dist/{analytics-Cek5hIwm.js.map → analytics-kUCNQQJm.js.map} +1 -1
  14. package/dist/bin.js +951 -141
  15. package/dist/bin.js.map +1 -1
  16. package/dist/{debug-B2BH87dh.js → debug-BH8HMBNX.js} +26 -21
  17. package/dist/debug-BH8HMBNX.js.map +1 -0
  18. package/dist/{debug-BNWsxaDm.js → debug-CgsJTJOO.js} +1 -1
  19. package/dist/{defaults-GbLPuHxj.js → defaults-DgKAzsD1.js} +1 -1
  20. package/dist/{defaults-GbLPuHxj.js.map → defaults-DgKAzsD1.js.map} +1 -1
  21. package/dist/{detection-BFl2AYV6.js → detection-DWNUEyek.js} +4 -4
  22. package/dist/detection-DWNUEyek.js.map +1 -0
  23. package/dist/{file-8iNrXHkG.js → file-BKbKreWF.js} +1 -1
  24. package/dist/{file-8iNrXHkG.js.map → file-BKbKreWF.js.map} +1 -1
  25. package/dist/{file-utils-DnTSiTJw.js → file-utils-DPmgn9Vm.js} +1 -1
  26. package/dist/{file-utils-DnTSiTJw.js.map → file-utils-DPmgn9Vm.js.map} +1 -1
  27. package/dist/{package-json-F_7oktsp.js → package-json-DZpnf6vU.js} +8 -10
  28. package/dist/package-json-DZpnf6vU.js.map +1 -0
  29. package/dist/package-json-_4PEss19.js +2 -0
  30. package/dist/{package-manager-BBTvHn9i.js → package-manager-DmDoOiaW.js} +2 -2
  31. package/dist/{package-manager-BBTvHn9i.js.map → package-manager-DmDoOiaW.js.map} +1 -1
  32. package/dist/{posthog-vm0k9PKS.js → posthog-BbQf_Hzq.js} +1 -1
  33. package/dist/{posthog-vm0k9PKS.js.map → posthog-BbQf_Hzq.js.map} +1 -1
  34. package/dist/posthog-integration-DZgP-ysj.js +1012 -0
  35. package/dist/posthog-integration-DZgP-ysj.js.map +1 -0
  36. package/dist/{provisioning-DRwH4skH.js → provisioning-Buqple4U.js} +3 -3
  37. package/dist/{provisioning-DRwH4skH.js.map → provisioning-Buqple4U.js.map} +1 -1
  38. package/dist/provisioning-CAf6fMWM.js +2 -0
  39. package/dist/{registry-CZjMhhsK.js → registry-PGYX7928.js} +5 -5
  40. package/dist/{registry-CZjMhhsK.js.map → registry-PGYX7928.js.map} +1 -1
  41. package/dist/setup-utils-LGtFkuI1.js +2 -0
  42. package/dist/{setup-utils-DGUR4Djo.js → setup-utils-xt6Z8gik.js} +77 -107
  43. package/dist/setup-utils-xt6Z8gik.js.map +1 -0
  44. package/dist/{AuditChecksViewer-CjBCZjxG.js → slides-0xga1duy.js} +626 -1058
  45. package/dist/slides-0xga1duy.js.map +1 -0
  46. package/dist/smoke-test-ci.sh +4 -4
  47. package/dist/{start-playground-DPYl5WR-.js → start-playground-DYElnFW1.js} +259 -10
  48. package/dist/start-playground-DYElnFW1.js.map +1 -0
  49. package/dist/{start-tui-Cj_4BhK8.js → start-tui-BBhG-LSW.js} +288 -446
  50. package/dist/start-tui-BBhG-LSW.js.map +1 -0
  51. package/dist/{steps-BFD76-MP.js → steps-B9mb9qRe.js} +7 -7
  52. package/dist/{steps-BFD76-MP.js.map → steps-B9mb9qRe.js.map} +1 -1
  53. package/dist/{task-stream-CX7Uf6EM.js → task-stream-DUpUZmFQ.js} +8 -8
  54. package/dist/task-stream-DUpUZmFQ.js.map +1 -0
  55. package/dist/telemetry-BFwKBgCJ.js +13 -0
  56. package/dist/telemetry-BFwKBgCJ.js.map +1 -0
  57. package/dist/{wizard-abort-54DpTnUi.js → wizard-abort-DWwOHzHR.js} +3 -3
  58. package/dist/{wizard-abort-54DpTnUi.js.map → wizard-abort-DWwOHzHR.js.map} +1 -1
  59. package/dist/{wizard-abort-CZH03nD0.js → wizard-abort-Djz2J6p9.js} +1 -1
  60. package/dist/wizard-session-CPhhll4P.js +2 -0
  61. package/dist/{wizard-session-BcNJTl2I.js → wizard-session-CsI33S4_.js} +6 -3
  62. package/dist/wizard-session-CsI33S4_.js.map +1 -0
  63. package/dist/wizard-ui-YdGFRyu_.js.map +1 -1
  64. package/package.json +3 -2
  65. package/dist/AuditChecksViewer-CjBCZjxG.js.map +0 -1
  66. package/dist/agent-interface-D9DeIikl.js.map +0 -1
  67. package/dist/agent-runner-B41-Iig3.js.map +0 -1
  68. package/dist/analytics-CpbY05Lf.js +0 -2
  69. package/dist/debug-B2BH87dh.js.map +0 -1
  70. package/dist/detection-BFl2AYV6.js.map +0 -1
  71. package/dist/package-json-BzVey4Bd.js +0 -2
  72. package/dist/package-json-F_7oktsp.js.map +0 -1
  73. package/dist/posthog-integration-vFBuSN5U.js +0 -259
  74. package/dist/posthog-integration-vFBuSN5U.js.map +0 -1
  75. package/dist/provisioning--RCv39tI.js +0 -2
  76. package/dist/router-COhhuIW3.js +0 -135
  77. package/dist/router-COhhuIW3.js.map +0 -1
  78. package/dist/setup-utils-DGUR4Djo.js.map +0 -1
  79. package/dist/setup-utils-eh1450iu.js +0 -2
  80. package/dist/start-playground-DPYl5WR-.js.map +0 -1
  81. package/dist/start-tui-Cj_4BhK8.js.map +0 -1
  82. package/dist/task-stream-CX7Uf6EM.js.map +0 -1
  83. package/dist/telemetry-DCyjsXhw.js +0 -13
  84. package/dist/telemetry-DCyjsXhw.js.map +0 -1
  85. package/dist/wizard-session-BQC9vy9Z.js +0 -2
  86. package/dist/wizard-session-BcNJTl2I.js.map +0 -1
  87. package/npm-shrinkwrap.json +0 -2931
@@ -1 +0,0 @@
1
- {"version":3,"file":"debug-B2BH87dh.js","names":["errResult"],"sources":["../src/utils/logging.ts","../src/lib/version.ts","../src/env.ts","../src/lib/constants.ts","../src/lib/health-checks/statuspage.ts","../src/lib/health-checks/incidentio.ts","../src/lib/health-checks/endpoints.ts","../src/lib/health-checks/readiness.ts","../src/ui/logging-ui.ts","../src/ui/index.ts","../src/utils/debug.ts"],"sourcesContent":["export function prepareMessage(msg: unknown): string {\n if (typeof msg === 'string') {\n return msg;\n }\n if (msg instanceof Error) {\n return `${msg.stack || ''}`;\n }\n return JSON.stringify(msg, null, '\\t');\n}\n\nexport function l(msg: string): void {\n // eslint-disable-next-line no-console\n console.log(msg);\n}\n\nexport function nl(): void {\n return l('');\n}\n\nexport function green(msg: string): void {\n return l(prepareMessage(msg));\n}\n\nexport function red(msg: string): void {\n return l(prepareMessage(msg));\n}\n\nexport function dim(msg: string): void {\n return l(prepareMessage(msg));\n}\n\nexport function yellow(msg: string): void {\n return l(prepareMessage(msg));\n}\n\nexport function cyan(msg: string): void {\n return l(prepareMessage(msg));\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function debug(msg: any): void {\n return l(prepareMessage(msg));\n}\n","// Auto-generated by scripts/generate-version.js — do not edit\nexport const VERSION = '2.13.1';\n","/**\n * Central environment variable access for the PostHog wizard.\n *\n * ── Build-time constants ────────────────────────────────────────────\n * Inlined by tsdown's `env` option at compile time. After build, the\n * runtime value of these env vars has zero effect on the wizard.\n *\n * ── Runtime variables ───────────────────────────────────────────────\n * Read through `runtimeEnv()` with a typed allowlist. This makes every\n * runtime dependency on the environment explicit and grep-able.\n *\n * ── Direct process.env access ───────────────────────────────────────\n * Reserved for subprocess environment configuration (writes) and\n * vendored code. Production source outside those cases should use\n * this module instead.\n */\n\n// ── Build-time constants ─────────────────────────────────────────────\n// tsdown replaces `process.env.NODE_ENV` with a string literal.\n// After build these are just `\"production\"`, `false`, etc.\n\nexport const NODE_ENV = process.env.NODE_ENV as string;\nexport const IS_DEV =\n process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test';\n\n// ── Runtime environment ──────────────────────────────────────────────\n\n/**\n * Exhaustive allowlist of env vars the wizard reads at runtime.\n * Add new keys here when a new runtime dependency is needed.\n */\ntype RuntimeEnvKey =\n // Wizard CLI configuration (yargs POSTHOG_WIZARD_ prefix)\n | 'POSTHOG_WIZARD_BENCHMARK_CONFIG'\n | 'POSTHOG_WIZARD_BENCHMARK_FILE'\n | 'POSTHOG_WIZARD_LOG_DIR'\n | 'POSTHOG_WIZARD_DEBUG'\n | 'DEBUG'\n // Agent / MCP\n | 'MCP_URL'\n | 'POSTHOG_API_KEY'\n // Platform: terminal detection\n | 'TERM'\n | 'TERM_PROGRAM'\n | 'TERMINAL_EMULATOR'\n | 'CI'\n | 'WT_SESSION'\n | 'TERMINUS_SUBLIME'\n | 'ConEmuTask'\n // Platform: paths\n | 'APPDATA'\n | 'XDG_CONFIG_HOME';\n\n/** Read a runtime environment variable. Only allowlisted keys compile. */\nexport function runtimeEnv(key: RuntimeEnvKey): string | undefined {\n return process.env[key];\n}\n","/**\n * Shared constants for the PostHog wizard.\n */\n\nimport { VERSION } from './version';\n\n// ── Integration / CLI ───────────────────────────────────────────────\n\n/**\n * Detection order matters: put framework-specific integrations BEFORE basic language fallbacks.\n */\nexport enum Integration {\n // Frameworks\n nextjs = 'nextjs',\n nuxt = 'nuxt',\n vue = 'vue',\n reactRouter = 'react-router',\n tanstackStart = 'tanstack-start',\n tanstackRouter = 'tanstack-router',\n reactNative = 'react-native',\n angular = 'angular',\n astro = 'astro',\n django = 'django',\n flask = 'flask',\n fastapi = 'fastapi',\n laravel = 'laravel',\n sveltekit = 'sveltekit',\n swift = 'swift',\n android = 'android',\n rails = 'rails',\n\n // Language fallbacks\n python = 'python',\n ruby = 'ruby',\n javascriptNode = 'javascript_node',\n javascript_web = 'javascript_web',\n}\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\n// ── Environment ──────────────────────────────────────────────────────\n\nimport { IS_DEV } from '@env';\nexport { IS_DEV };\nexport const DEBUG = false;\n\n// ── URLs ─────────────────────────────────────────────────────────────\n\nexport const DEFAULT_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.posthog.com';\nexport const DEFAULT_HOST_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://us.i.posthog.com';\nexport const ISSUES_URL = 'https://github.com/posthog/wizard/issues';\nexport const CONTEXT_MILL_URL = 'https://github.com/PostHog/context-mill';\nexport const POSTHOG_DOCS_URL = 'https://posthog.com/docs';\n\n/** Remote base URL for fetching the skill menu + downloading skills. */\nexport const REMOTE_SKILLS_BASE_URL =\n 'https://github.com/PostHog/context-mill/releases/latest/download';\n/** Local base URL when `--local-mcp` is set (served by context-mill dev server). */\nexport const LOCAL_SKILLS_BASE_URL = 'http://localhost:8765';\n\n/**\n * Pick the skills base URL based on the session's localMcp flag.\n * Single source of truth — do not inline this ternary anywhere.\n */\nexport function getSkillsBaseUrl(localMcp: boolean): string {\n return localMcp ? LOCAL_SKILLS_BASE_URL : REMOTE_SKILLS_BASE_URL;\n}\n\n// ── Analytics (internal) ──────────────────────────────────────────────\n\nexport const ANALYTICS_POSTHOG_PUBLIC_PROJECT_WRITE_KEY = 'sTMFPsFhdP1Ssg';\nexport const ANALYTICS_HOST_URL = 'https://internal-j.posthog.com';\nexport const ANALYTICS_TEAM_TAG = 'docs-and-wizard';\n\n// ── OAuth / Auth ────────────────────────────────────────────────────\n\nexport const POSTHOG_OAUTH_URL = IS_DEV\n ? 'http://localhost:8010'\n : 'https://oauth.posthog.com';\nexport const OAUTH_PORTS = [8239, 8238, 8240, 8237, 8236, 8235] as const;\nexport const POSTHOG_US_CLIENT_ID = 'c4Rdw8DIxgtQfA80IiSnGKlNX8QN00cFWF00QQhM';\nexport const POSTHOG_EU_CLIENT_ID = 'bx2C5sZRN03TkdjraCcetvQFPGH6N2Y9vRLkcKEy';\nexport const POSTHOG_DEV_CLIENT_ID = 'DC5uRLVbGI02YQ82grxgnK6Qn12SXWpCqdPb60oZ';\nexport const POSTHOG_PROXY_CLIENT_ID = POSTHOG_US_CLIENT_ID;\nexport const DUMMY_PROJECT_API_KEY = '_YOUR_POSTHOG_PROJECT_TOKEN_';\n\n/**\n * Scopes the wizard requests during the agentic provisioning signup flow.\n *\n * Each entry is justified by what the wizard's agent step does after signup:\n * - user:read identify the user for analytics + agent context\n * - project:read look up the freshly-provisioned project\n * - llm_gateway:read authenticate to gateway.{us,eu}.posthog.com/wizard\n * (the agent's LLM calls — without this scope, every\n * agent message returns 401)\n * - query:read run HogQL queries when the agent needs data\n * - dashboard:write create the onboarding dashboard during setup\n * - insight:write create the onboarding insights during setup\n *\n * Must be a subset of `ALLOWED_PROVISIONING_SCOPES` in\n * `ee/api/agentic_provisioning/views.py` on the backend.\n */\nexport const WIZARD_PROVISIONING_SCOPES = [\n 'user:read',\n 'project:read',\n 'llm_gateway:read',\n 'dashboard:write',\n 'insight:write',\n 'query:read',\n] as const;\n\n/**\n * Scopes the wizard requests during the OAuth login flow. Superset of\n * `WIZARD_PROVISIONING_SCOPES` with two scopes that only apply to the login\n * path and are not in the provisioning allowlist:\n * - introspection lets the wizard introspect its own token\n * - health_issue:read used by `wizard doctor`\n */\nexport const WIZARD_OAUTH_SCOPES = [\n ...WIZARD_PROVISIONING_SCOPES,\n 'introspection',\n 'health_issue:read',\n] as const;\n\n// ── Wizard run / variants ───────────────────────────────────────────\n\nexport const WIZARD_INTERACTION_EVENT_NAME = 'wizard interaction';\nexport const WIZARD_REMARK_EVENT_NAME = 'wizard remark';\n/** Feature flag key whose value selects a variant from WIZARD_VARIANTS. */\nexport const WIZARD_VARIANT_FLAG_KEY = 'wizard-variant';\n/** Feature flag key that gates the intro-screen \"Tools\" menu. */\nexport const WIZARD_TOOLS_MENU_FLAG_KEY = 'wizard-tools-menu';\n/** Variant key -> metadata for wizard run (VARIANT flag selects which entry to use). */\nexport const WIZARD_VARIANTS: Record<string, Record<string, string>> = {\n base: { VARIANT: 'base' },\n subagents: { VARIANT: 'subagents' },\n};\n/** User-Agent for wizard HTTP requests and MCP server identification. */\nexport const WIZARD_USER_AGENT = `posthog/wizard; version: ${VERSION}`;\n\n// ── HTTP headers ─────────────────────────────────────────────────────\n\n/** Header prefix for PostHog properties (e.g. X-POSTHOG-PROPERTY-VARIANT). */\nexport const POSTHOG_PROPERTY_HEADER_PREFIX = 'X-POSTHOG-PROPERTY-';\n/** Header prefix for PostHog feature flags. */\nexport const POSTHOG_FLAG_HEADER_PREFIX = 'X-POSTHOG-FLAG-';\n\n// ── Timeouts ─────────────────────────────────────────────────────────\n\n/** Timeout for framework / project detection probes (ms). */\nexport const DETECTION_TIMEOUT_MS = 10_000;\n\n/** Timeout for the OAuth authorization flow (ms). */\nexport const OAUTH_TIMEOUT_MS = 360_000;\n","import {\n ServiceHealthStatus,\n type BaseHealthResult,\n type ComponentHealthResult,\n} from './types';\n\n// ---------------------------------------------------------------------------\n// Statuspage.io v2 API helpers\n// https://metastatuspage.com/api\n//\n// status.json – page-level rollup; indicator is one of: none | minor | major | critical\n// summary.json – same rollup + component list; component status is one of:\n// operational | degraded_performance | partial_outage | major_outage | under_maintenance\n// https://support.atlassian.com/statuspage/docs/show-service-status-with-components\n// ---------------------------------------------------------------------------\n\ninterface StatuspageStatusResponse {\n status?: { indicator?: string; description?: string };\n}\n\ninterface StatuspageSummaryResponse extends StatuspageStatusResponse {\n components?: { id: string; name: string; status: string }[];\n}\n\nfunction mapIndicator(v: string | null | undefined): ServiceHealthStatus {\n switch (v) {\n case 'none':\n return ServiceHealthStatus.Healthy;\n case 'minor':\n return ServiceHealthStatus.Degraded;\n case 'major':\n case 'critical':\n return ServiceHealthStatus.Down;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction mapComponentRaw(v: string | null | undefined): ServiceHealthStatus {\n switch (v) {\n case 'operational':\n return ServiceHealthStatus.Healthy;\n case 'degraded_performance':\n case 'under_maintenance':\n return ServiceHealthStatus.Degraded;\n case 'partial_outage':\n case 'major_outage':\n return ServiceHealthStatus.Down;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction errResult(error: string): BaseHealthResult {\n return { status: ServiceHealthStatus.Degraded, error };\n}\n\nasync function fetchStatuspageIndicator(\n url: string,\n timeoutMs = 5000,\n): Promise<BaseHealthResult> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, { signal: controller.signal });\n clearTimeout(tid);\n\n if (!res.ok) return errResult(`HTTP ${res.status}`);\n\n const data = (await res.json()) as StatuspageStatusResponse;\n const indicator = data.status?.indicator ?? null;\n return {\n status: mapIndicator(indicator),\n rawIndicator: indicator ?? undefined,\n };\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError')\n return errResult('Request timed out');\n return errResult(e instanceof Error ? e.message : 'Unknown error');\n }\n}\n\nasync function fetchStatuspageSummary(\n url: string,\n timeoutMs = 5000,\n): Promise<ComponentHealthResult> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, { signal: controller.signal });\n clearTimeout(tid);\n\n if (!res.ok) return errResult(`HTTP ${res.status}`);\n\n const data = (await res.json()) as StatuspageSummaryResponse;\n const indicator = data.status?.indicator ?? null;\n const overall = mapIndicator(indicator);\n\n const affected = (data.components ?? [])\n .map((c) => ({\n name: c.name,\n status: mapComponentRaw(c.status),\n rawStatus: c.status,\n }))\n .filter((c) => c.status !== ServiceHealthStatus.Healthy);\n\n return {\n status: affected.length > 0 ? ServiceHealthStatus.Degraded : overall,\n rawIndicator: indicator ?? undefined,\n degradedOrDownComponents: affected.length > 0 ? affected : undefined,\n };\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError')\n return errResult('Request timed out');\n return errResult(e instanceof Error ? e.message : 'Unknown error');\n }\n}\n\n// ---------------------------------------------------------------------------\n// Individual statuspage-backed checks\n// ---------------------------------------------------------------------------\n\nexport const checkAnthropicHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator('https://status.claude.com/api/v2/status.json');\n\nexport const checkGithubHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator('https://www.githubstatus.com/api/v2/status.json');\n\nexport const checkNpmOverallHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator('https://status.npmjs.org/api/v2/status.json');\n\nexport const checkNpmComponentHealth = (): Promise<ComponentHealthResult> =>\n fetchStatuspageSummary('https://status.npmjs.org/api/v2/summary.json');\n\nexport const checkCloudflareOverallHealth = (): Promise<BaseHealthResult> =>\n fetchStatuspageIndicator(\n 'https://www.cloudflarestatus.com/api/v2/status.json',\n );\n\nexport const checkCloudflareComponentHealth =\n (): Promise<ComponentHealthResult> =>\n fetchStatuspageSummary(\n 'https://www.cloudflarestatus.com/api/v2/summary.json',\n );\n","import {\n ServiceHealthStatus,\n type BaseHealthResult,\n type ComponentHealthResult,\n type ComponentStatus,\n} from './types';\n\ninterface IncidentIoAffectedComponent {\n id: string;\n name: string;\n group_name?: string;\n current_status: string;\n}\n\ninterface IncidentIoIncident {\n id: string;\n name: string;\n status: string;\n current_worst_impact: string;\n affected_components: IncidentIoAffectedComponent[];\n}\n\ninterface IncidentIoSummary {\n ongoing_incidents: IncidentIoIncident[];\n in_progress_maintenances: unknown[];\n}\n\nfunction mapIncidentImpact(impact: string): ServiceHealthStatus {\n switch (impact) {\n case 'full_outage':\n return ServiceHealthStatus.Down;\n case 'partial_outage':\n case 'degraded_performance':\n return ServiceHealthStatus.Degraded;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction mapComponentStatus(status: string): ServiceHealthStatus {\n switch (status) {\n case 'operational':\n return ServiceHealthStatus.Healthy;\n case 'full_outage':\n return ServiceHealthStatus.Down;\n case 'partial_outage':\n case 'degraded_performance':\n return ServiceHealthStatus.Degraded;\n default:\n return ServiceHealthStatus.Degraded;\n }\n}\n\nfunction errResult(error: string): BaseHealthResult {\n return { status: ServiceHealthStatus.Degraded, error };\n}\n\nconst POSTHOG_STATUS_URL = 'https://www.posthogstatus.com/api/v1/summary';\n\nasync function fetchPosthogStatus(\n timeoutMs = 5000,\n): Promise<{ overall: BaseHealthResult; components: ComponentHealthResult }> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(POSTHOG_STATUS_URL, { signal: controller.signal });\n clearTimeout(tid);\n\n if (!res.ok) {\n const err = errResult(`HTTP ${res.status}`);\n return { overall: err, components: err };\n }\n\n const data = (await res.json()) as IncidentIoSummary;\n const incidents = data.ongoing_incidents ?? [];\n\n if (incidents.length === 0) {\n return {\n overall: { status: ServiceHealthStatus.Healthy },\n components: { status: ServiceHealthStatus.Healthy },\n };\n }\n\n let worstOverall = ServiceHealthStatus.Degraded;\n const affected: ComponentStatus[] = [];\n\n for (const incident of incidents) {\n const impact = mapIncidentImpact(incident.current_worst_impact);\n if (impact === ServiceHealthStatus.Down) {\n worstOverall = ServiceHealthStatus.Down;\n }\n\n for (const comp of incident.affected_components ?? []) {\n const compStatus = mapComponentStatus(comp.current_status);\n if (compStatus !== ServiceHealthStatus.Healthy) {\n affected.push({\n name: comp.group_name\n ? `${comp.group_name} — ${comp.name}`\n : comp.name,\n status: compStatus,\n rawStatus: comp.current_status,\n });\n }\n }\n }\n\n return {\n overall: { status: worstOverall },\n components: {\n status:\n affected.length > 0 ? ServiceHealthStatus.Degraded : worstOverall,\n degradedOrDownComponents: affected.length > 0 ? affected : undefined,\n },\n };\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError') {\n const err = errResult('Request timed out');\n return { overall: err, components: err };\n }\n const err = errResult(e instanceof Error ? e.message : 'Unknown error');\n return { overall: err, components: err };\n }\n}\n\nlet _cache: Promise<{\n overall: BaseHealthResult;\n components: ComponentHealthResult;\n}> | null = null;\n\nfunction getPosthogHealth() {\n if (!_cache) _cache = fetchPosthogStatus();\n return _cache;\n}\n\nexport function resetPosthogHealthCache(): void {\n _cache = null;\n}\n\nexport const checkPosthogOverallHealth = async (): Promise<BaseHealthResult> =>\n (await getPosthogHealth()).overall;\n\nexport const checkPosthogComponentHealth =\n async (): Promise<ComponentHealthResult> =>\n (await getPosthogHealth()).components;\n","import { REMOTE_SKILLS_BASE_URL } from '../constants';\nimport { ServiceHealthStatus, type BaseHealthResult } from './types';\n\n// ---------------------------------------------------------------------------\n// Direct endpoint health checks\n//\n// These ping PostHog-owned services directly (no Statuspage intermediary).\n// A non-expected HTTP status or any network error is treated as Down.\n//\n// LLM Gateway – FastAPI service\n// Source: posthog/services/llm-gateway/src/llm_gateway/api/health.py\n// GET /_liveness → 200 {\"status\":\"alive\"}\n//\n// MCP – Cloudflare Worker\n// Source: posthog/services/mcp/src/index.ts\n// GET / → 200 (HTML landing page)\n// ---------------------------------------------------------------------------\n\nfunction downResult(error: string): BaseHealthResult {\n return { status: ServiceHealthStatus.Down, error };\n}\n\nasync function fetchEndpointHealth(\n url: string,\n timeoutMs = 5000,\n expectedStatus = 200,\n): Promise<BaseHealthResult> {\n try {\n const controller = new AbortController();\n const tid = setTimeout(() => controller.abort(), timeoutMs);\n const res = await fetch(url, { signal: controller.signal });\n clearTimeout(tid);\n\n if (res.status === expectedStatus) {\n return {\n status: ServiceHealthStatus.Healthy,\n rawIndicator: `HTTP ${res.status}`,\n };\n }\n return downResult(`HTTP ${res.status}`);\n } catch (e) {\n if (e instanceof Error && e.name === 'AbortError')\n return downResult('Request timed out');\n return downResult(e instanceof Error ? e.message : 'Unknown error');\n }\n}\n\nexport const checkLlmGatewayHealth = (): Promise<BaseHealthResult> =>\n fetchEndpointHealth('https://gateway.us.posthog.com/_liveness');\n\nexport const checkMcpHealth = (): Promise<BaseHealthResult> =>\n fetchEndpointHealth('https://mcp.posthog.com/');\n\nexport const checkGithubReleasesHealth = (): Promise<BaseHealthResult> =>\n fetchEndpointHealth(`${REMOTE_SKILLS_BASE_URL}/skill-menu.json`);\n","import {\n ServiceHealthStatus,\n type AllServicesHealth,\n type BaseHealthResult,\n type ComponentHealthResult,\n type HealthCheckKey,\n} from './types';\nimport {\n checkAnthropicHealth,\n checkGithubHealth,\n checkNpmOverallHealth,\n checkNpmComponentHealth,\n checkCloudflareOverallHealth,\n checkCloudflareComponentHealth,\n} from './statuspage';\nimport {\n checkPosthogOverallHealth,\n checkPosthogComponentHealth,\n} from './incidentio';\nimport {\n checkLlmGatewayHealth,\n checkMcpHealth,\n checkGithubReleasesHealth,\n} from './endpoints';\nimport { logToFile } from '../../utils/debug';\n\n// ---------------------------------------------------------------------------\n// Service labels (used in human-readable reason strings)\n// ---------------------------------------------------------------------------\n\nexport const SERVICE_LABELS: Record<HealthCheckKey, string> = {\n anthropic: 'Anthropic',\n posthogOverall: 'PostHog',\n posthogComponents: 'PostHog (components)',\n github: 'GitHub',\n npmOverall: 'npm',\n npmComponents: 'npm (components)',\n cloudflareOverall: 'Cloudflare',\n cloudflareComponents: 'Cloudflare (components)',\n llmGateway: 'LLM Gateway',\n mcp: 'MCP',\n githubReleases: 'GitHub Releases',\n};\n\n// ---------------------------------------------------------------------------\n// Readiness config\n// ---------------------------------------------------------------------------\n\nexport interface WizardReadinessConfig {\n /** Services where status=Down blocks the run (readiness=No). */\n downBlocksRun: HealthCheckKey[];\n /** Services where status=Degraded (or worse) blocks the run (readiness=No). */\n degradedBlocksRun?: HealthCheckKey[];\n}\n\n/**\n * See README section \"Health checks\" for the full rationale.\n * Adjust these arrays to change what blocks a wizard run.\n */\nexport const DEFAULT_WIZARD_READINESS_CONFIG: WizardReadinessConfig = {\n downBlocksRun: [\n 'anthropic',\n 'npmOverall',\n 'llmGateway',\n 'mcp',\n 'githubReleases',\n ],\n degradedBlocksRun: ['anthropic'],\n};\n\n/**\n * Reduced readiness config for --signup provisioning flows.\n *\n * Provisioning only needs PostHog and the LLM Gateway - it doesn't\n * use Anthropic directly, npm, GitHub Releases, or MCP.\n */\nexport const SIGNUP_WIZARD_READINESS_CONFIG: WizardReadinessConfig = {\n downBlocksRun: ['posthogOverall', 'llmGateway'],\n};\n\n// ---------------------------------------------------------------------------\n// Aggregate check\n// ---------------------------------------------------------------------------\n\nexport async function checkAllExternalServices(): Promise<AllServicesHealth> {\n const [\n anthropic,\n posthogOverall,\n posthogComponents,\n github,\n npmOverall,\n npmComponents,\n cloudflareOverall,\n cloudflareComponents,\n llmGateway,\n mcp,\n githubReleases,\n ] = await Promise.all([\n checkAnthropicHealth(),\n checkPosthogOverallHealth(),\n checkPosthogComponentHealth(),\n checkGithubHealth(),\n checkNpmOverallHealth(),\n checkNpmComponentHealth(),\n checkCloudflareOverallHealth(),\n checkCloudflareComponentHealth(),\n checkLlmGatewayHealth(),\n checkMcpHealth(),\n checkGithubReleasesHealth(),\n ]);\n\n return {\n anthropic,\n posthogOverall,\n posthogComponents,\n github,\n npmOverall,\n npmComponents,\n cloudflareOverall,\n cloudflareComponents,\n llmGateway,\n mcp,\n githubReleases,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Wizard readiness evaluation\n// ---------------------------------------------------------------------------\n\nexport enum WizardReadiness {\n Yes = 'yes',\n No = 'no',\n YesWithWarnings = 'yes_with_warnings',\n}\n\nexport interface WizardReadinessResult {\n decision: WizardReadiness;\n health: AllServicesHealth;\n reasons: string[];\n}\n\nfunction describeResult(label: string, h: BaseHealthResult): string {\n const parts = [`${label}: ${h.status}`];\n if (h.rawIndicator) parts.push(`indicator=${h.rawIndicator}`);\n if (h.error) parts.push(h.error);\n return parts.join(' — ');\n}\n\nconst MAX_COMPONENT_NAMES = 8;\n\nfunction describeComponents(label: string, h: ComponentHealthResult): string {\n const affected = h.degradedOrDownComponents;\n if (!affected || affected.length === 0)\n return `${label} components: all operational`;\n const shown = affected\n .slice(0, MAX_COMPONENT_NAMES)\n .map((c) => `${c.name} (${c.status})`);\n const suffix =\n affected.length > MAX_COMPONENT_NAMES\n ? `, +${affected.length - MAX_COMPONENT_NAMES} more`\n : '';\n return `${label} components impacted: ${shown.join(', ')}${suffix}`;\n}\n\nconst READINESS_TIMEOUT_MS = 10_000;\n\nexport async function evaluateWizardReadiness(\n config: WizardReadinessConfig = DEFAULT_WIZARD_READINESS_CONFIG,\n): Promise<WizardReadinessResult> {\n try {\n const health = await Promise.race([\n checkAllExternalServices(),\n new Promise<AllServicesHealth>((resolve) =>\n setTimeout(\n () => resolve(allUnknown('Health check timed out')),\n READINESS_TIMEOUT_MS,\n ),\n ),\n ]);\n\n const reasons: string[] = [];\n\n for (const key of Object.keys(health) as HealthCheckKey[]) {\n const result = health[key];\n const label = SERVICE_LABELS[key];\n\n reasons.push(describeResult(label, result));\n\n if ('degradedOrDownComponents' in result) {\n reasons.push(describeComponents(label, result));\n }\n }\n\n const blockingKeys = getBlockingServiceKeys(health, config);\n if (blockingKeys.length > 0) {\n logToFile(`[health-checks] blocked by: ${blockingKeys.join(', ')}`);\n return { decision: WizardReadiness.No, health, reasons };\n }\n\n const hasWarnings = Object.values(health).some(\n (h) => h.status !== ServiceHealthStatus.Healthy,\n );\n\n if (hasWarnings) {\n return { decision: WizardReadiness.YesWithWarnings, health, reasons };\n }\n\n return { decision: WizardReadiness.Yes, health, reasons };\n } catch (err) {\n logToFile(\n `[health-checks] error: ${err instanceof Error ? err.message : err}`,\n );\n // Health checks must never block the wizard run\n return {\n decision: WizardReadiness.Yes,\n health: allUnknown('Unexpected error'),\n reasons: ['Health check failed unexpectedly — proceeding anyway'],\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Blocking service detection\n// ---------------------------------------------------------------------------\n\n/** Keys that are component-level detail, not top-level services. */\nconst COMPONENT_KEYS: HealthCheckKey[] = [\n 'posthogComponents',\n 'npmComponents',\n 'cloudflareComponents',\n];\n\n/**\n * Get the keys of services that would block a wizard run per the given config.\n */\nexport function getBlockingServiceKeys(\n health: AllServicesHealth,\n config: WizardReadinessConfig = DEFAULT_WIZARD_READINESS_CONFIG,\n): HealthCheckKey[] {\n return (Object.keys(health) as HealthCheckKey[]).filter((key) => {\n if (COMPONENT_KEYS.includes(key)) return false;\n const result = health[key];\n if (\n config.downBlocksRun.includes(key) &&\n result.status === ServiceHealthStatus.Down\n ) {\n return true;\n }\n if (\n (config.degradedBlocksRun ?? []).includes(key) &&\n result.status !== ServiceHealthStatus.Healthy\n ) {\n return true;\n }\n return false;\n });\n}\n\n/** Build an AllServicesHealth where every service is Degraded with the given error. */\nfunction allUnknown(error: string): AllServicesHealth {\n const base: BaseHealthResult = {\n status: ServiceHealthStatus.Degraded,\n error,\n };\n return {\n anthropic: base,\n posthogOverall: base,\n posthogComponents: { ...base },\n github: base,\n npmOverall: base,\n npmComponents: { ...base },\n cloudflareOverall: base,\n cloudflareComponents: { ...base },\n llmGateway: base,\n mcp: base,\n githubReleases: base,\n };\n}\n","/* eslint-disable no-console */\n/**\n * LoggingUI — Logging-only implementation for CI mode.\n * No prompts, no TUI, no interactivity. Just console output.\n */\n\nimport { TaskStatus, type WizardUI, type SpinnerHandle } from './wizard-ui';\nimport type { SettingsConflict } from '../lib/agent/agent-interface';\nimport {\n type WizardReadinessResult,\n getBlockingServiceKeys,\n SERVICE_LABELS,\n} from '../lib/health-checks/readiness.js';\nimport type { OutroData } from '../lib/wizard-session';\n\nexport class LoggingUI implements WizardUI {\n intro(message: string): void {\n console.log(`┌ ${message}`);\n }\n\n outro(message: string): void {\n console.log(`└ ${message}`);\n }\n\n outroError(data: OutroData): void {\n console.log(`✖ ${data.message ?? 'Wizard aborted'}`);\n if (data.body) console.log(`│ ${data.body}`);\n if (data.docsUrl) console.log(`│ Docs: ${data.docsUrl}`);\n }\n\n waitForOutroDismissed(): Promise<void> {\n return Promise.resolve();\n }\n\n cancel(message: string): void {\n console.log(`■ ${message}`);\n }\n\n log = {\n info(message: string): void {\n console.log(`│ ${message}`);\n },\n warn(message: string): void {\n console.log(`▲ ${message}`);\n },\n error(message: string): void {\n console.log(`✖ ${message}`);\n },\n success(message: string): void {\n console.log(`✔ ${message}`);\n },\n step(message: string): void {\n console.log(`◇ ${message}`);\n },\n };\n\n note(message: string): void {\n console.log(`│ ${message}`);\n }\n\n spinner(): SpinnerHandle {\n return {\n start(message?: string) {\n if (message) console.log(`◌ ${message}`);\n },\n stop(message?: string) {\n if (message) console.log(`● ${message}`);\n },\n message(msg?: string) {\n if (msg) console.log(`◌ ${msg}`);\n },\n };\n }\n\n pushStatus(message: string): void {\n console.log(`◇ ${message}`);\n }\n\n setDetectedFramework(label: string): void {\n console.log(`✔ Framework: ${label}`);\n }\n\n onEnterScreen(_screen: string, _fn: () => void): void {\n // No screen transitions in CI\n }\n\n setLoginUrl(url: string | null): void {\n if (url) {\n console.log(\n `│ If the browser didn't open automatically, use this link:`,\n );\n console.log(`│ ${url}`);\n }\n }\n\n showBlockingOutage(result: WizardReadinessResult): Promise<void> {\n console.log(`▲ Service health issues detected — blocking outage.`);\n const blockingKeys = getBlockingServiceKeys(result.health);\n if (blockingKeys.length > 0) {\n console.log(`│`);\n console.log(`│ Blocking services:`);\n for (const key of blockingKeys) {\n const status = result.health[key].status;\n const error = result.health[key].error;\n const label = SERVICE_LABELS[key];\n const detail = error ? ` — ${error}` : '';\n console.log(`│ ✖ ${label}: ${status}${detail}`);\n }\n console.log(`│`);\n }\n for (const reason of result.reasons) {\n console.log(`│ ${reason}`);\n }\n console.log(`│ The wizard cannot start while these services are down.`);\n return Promise.resolve();\n }\n\n setReadinessWarnings(result: WizardReadinessResult): void {\n console.log(`▲ Service health warnings detected.`);\n for (const reason of result.reasons) {\n console.log(`│ ${reason}`);\n }\n }\n\n showPortConflict(_processInfo: {\n command: string;\n pid: string;\n port: number;\n user: string;\n }): Promise<void> {\n return Promise.resolve();\n }\n\n showSettingsOverride(\n _conflicts: SettingsConflict[],\n _backupAndFix: () => boolean,\n ): Promise<void> {\n return Promise.resolve();\n }\n\n showAuthError(): void {\n console.log(`✖ Authentication failed (401)`);\n console.log(\n `│ Claude Code auth is conflicting with the wizard. Please try again after logging out:`,\n );\n console.log(`│ claude auth logout`);\n }\n\n startRun(): void {\n // No-op in CI mode\n }\n\n setCredentials(_credentials: {\n accessToken: string;\n projectApiKey: string;\n host: string;\n projectId: number;\n }): void {\n // No-op in CI mode — credentials are handled directly\n }\n\n syncTodos(\n todos: Array<{ content: string; status: string; activeForm?: string }>,\n ): void {\n const completed = todos.filter(\n (t) => t.status === TaskStatus.Completed,\n ).length;\n const inProgress = todos.find((t) => t.status === TaskStatus.InProgress);\n if (inProgress) {\n console.log(\n `◌ [${completed}/${todos.length}] ${\n inProgress.activeForm || inProgress.content\n }`,\n );\n }\n }\n\n setEventPlan(_events: Array<{ name: string; description: string }>): void {\n // No-op in CI mode\n }\n\n setFrameworkContext(_key: string, _value: unknown): void {\n // No-op in CI mode\n }\n}\n","/**\n * UI singleton — provides getUI() and setUI() for the wizard.\n * Default: LoggingUI. Swap to InkUI at startup for TUI mode.\n */\n\nimport type { WizardUI } from './wizard-ui';\nimport { LoggingUI } from './logging-ui';\n\nlet currentUI: WizardUI = new LoggingUI();\n\nexport function getUI(): WizardUI {\n return currentUI;\n}\n\nexport function setUI(ui: WizardUI): void {\n currentUI = ui;\n}\n\nexport type { WizardUI, SpinnerHandle } from './wizard-ui';\n","import { appendFileSync } from 'fs';\nimport path from 'path';\nimport { prepareMessage } from './logging';\nimport { getUI } from '../ui';\nimport { runtimeEnv } from '@env';\nimport { WIZARD_LOG_FILE } from './paths';\n\nlet debugEnabled = false;\nlet logFilePath = WIZARD_LOG_FILE;\nlet logEnabled = true;\n\nexport function getLogFilePath(): string {\n return logFilePath;\n}\n\n/**\n * Configure the log file path and enable/disable state.\n * Call before initLogFile() to override defaults.\n */\nexport function configureLogFile(opts: {\n path?: string;\n enabled?: boolean;\n}): void {\n if (opts.path !== undefined) logFilePath = opts.path;\n if (opts.enabled !== undefined) logEnabled = opts.enabled;\n}\n\n/**\n * Configure log path from environment variables.\n *\n * Uses POSTHOG_WIZARD_LOG_DIR when set, joined with posthog-wizard.log.\n */\nexport function configureLogFileFromEnvironment(): void {\n const envLogDir = runtimeEnv('POSTHOG_WIZARD_LOG_DIR');\n if (envLogDir) {\n configureLogFile({ path: path.join(envLogDir, 'posthog-wizard.log') });\n }\n}\n\n/**\n * Initialize the log file with a run header.\n * Call this at the start of each wizard run.\n * Fails silently to avoid crashing the wizard.\n */\nexport function initLogFile() {\n if (!logEnabled) return;\n try {\n const header = `\\n${'='.repeat(\n 60,\n )}\\nPostHog Wizard Run: ${new Date().toISOString()}\\n${'='.repeat(60)}\\n`;\n appendFileSync(logFilePath, header);\n } catch {\n // Silently ignore - logging is non-critical\n }\n}\n\n/**\n * Log a message to the log file.\n * Always writes regardless of debug flag (when logging is enabled).\n * Fails silently to avoid masking errors in catch blocks.\n */\nexport function logToFile(...args: unknown[]) {\n if (!logEnabled) return;\n try {\n const timestamp = new Date().toISOString();\n const msg = args.map((a) => prepareMessage(a)).join(' ');\n appendFileSync(logFilePath, `[${timestamp}] ${msg}\\n`);\n } catch {\n // Silently ignore logging failures to avoid masking original errors\n }\n}\n\nexport function debug(...args: unknown[]) {\n if (!debugEnabled) {\n return;\n }\n\n const msg = args.map((a) => prepareMessage(a)).join(' ');\n\n getUI().log.info(msg);\n}\n\nexport function enableDebugLogs() {\n debugEnabled = true;\n}\n"],"mappings":";;;;;AAAA,SAAgB,eAAe,KAAsB;AACnD,KAAI,OAAO,QAAQ,SACjB,QAAO;AAET,KAAI,eAAe,MACjB,QAAO,GAAG,IAAI,SAAS;AAEzB,QAAO,KAAK,UAAU,KAAK,MAAM,IAAK;;AAGxC,SAAgB,EAAE,KAAmB;AAEnC,SAAQ,IAAI,IAAI;;AAWlB,SAAgB,IAAI,KAAmB;AACrC,QAAO,EAAE,eAAe,IAAI,CAAC;;;;ACv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I,eAAe;AACnB,IAAI,cAAc;AAClB,IAAI,aAAa;AAEjB,SAAgB,iBAAyB;AACvC,QAAO;;;;;;AAOT,SAAgB,iBAAiB,MAGxB;AACP,KAAI,KAAK,SAAS,KAAA,EAAW,eAAc,KAAK;AAChD,KAAI,KAAK,YAAY,KAAA,EAAW,cAAa,KAAK;;;;;;;AAQpD,SAAgB,kCAAwC;CACtD,MAAM,YAAY,WAAW,yBAAyB;AACtD,KAAI,UACF,kBAAiB,EAAE,MAAM,KAAK,KAAK,WAAW,qBAAqB,EAAE,CAAC;;;;;;;AAS1E,SAAgB,cAAc;AAC5B,KAAI,CAAC,WAAY;AACjB,KAAI;EACF,MAAM,SAAS,KAAK,IAAI,OACtB,GACD,CAAC,yCAAwB,IAAI,MAAM,EAAC,aAAa,CAAC,IAAI,IAAI,OAAO,GAAG,CAAC;AACtE,iBAAe,aAAa,OAAO;SAC7B;;;;;;;AAUV,SAAgB,UAAU,GAAG,MAAiB;AAC5C,KAAI,CAAC,WAAY;AACjB,KAAI;EACF,MAAM,6BAAY,IAAI,MAAM,EAAC,aAAa;EAC1C,MAAM,MAAM,KAAK,KAAK,MAAM,eAAe,EAAE,CAAC,CAAC,KAAK,IAAI;AACxD,iBAAe,aAAa,IAAI,UAAU,IAAI,IAAI,IAAI;SAChD;;AAKV,SAAgB,MAAM,GAAG,MAAiB;AACxC,KAAI,CAAC,aACH;CAGF,MAAM,MAAM,KAAK,KAAK,MAAM,eAAe,EAAE,CAAC,CAAC,KAAK,IAAI;AAExD,QAAO,CAAC,IAAI,KAAK,IAAI;;AAGvB,SAAgB,kBAAkB;AAChC,gBAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"detection-BFl2AYV6.js","names":[],"sources":["../src/lib/detection/framework.ts","../src/lib/detection/features.ts","../src/lib/detection/context.ts","../src/lib/detection/index.ts"],"sourcesContent":["/**\n * Framework detection — identify which PostHog-supported framework\n * is present in the project directory.\n *\n * Pure function: takes an install dir, returns the detected integration\n * (or undefined). No store mutations, no UI calls.\n */\n\nimport { Integration, DETECTION_TIMEOUT_MS } from '../constants.js';\nimport { FRAMEWORK_REGISTRY } from '../registry.js';\n\n/**\n * Loop through all registered frameworks and return the first one\n * whose `detect()` predicate matches the given directory.\n * Returns undefined if no framework is detected or detection times out.\n */\nexport async function detectFramework(\n installDir: string,\n): Promise<Integration | undefined> {\n for (const integration of Object.values(Integration)) {\n const config = FRAMEWORK_REGISTRY[integration];\n try {\n const detected = await Promise.race([\n config.detection.detect({ installDir }),\n new Promise<false>((resolve) =>\n setTimeout(() => resolve(false), DETECTION_TIMEOUT_MS),\n ),\n ]);\n if (detected) {\n return integration;\n }\n } catch {\n // Skip frameworks whose detection throws\n }\n }\n}\n","/**\n * Feature discovery — scan project dependencies for known SDK patterns\n * that indicate additional PostHog workflows are relevant.\n *\n * Pure function: takes an install dir, returns a set of discovered features.\n * No store mutations, no UI calls.\n */\n\nimport { readFileSync } from 'fs';\nimport { join } from 'path';\nimport { DiscoveredFeature } from '../wizard-session.js';\n\nconst STRIPE_PACKAGES = ['stripe', '@stripe/stripe-js'];\n\nconst LLM_PACKAGES = [\n 'openai',\n '@anthropic-ai/sdk',\n 'ai',\n '@ai-sdk/openai',\n 'langchain',\n '@langchain/openai',\n '@langchain/langgraph',\n '@google/generative-ai',\n '@google/genai',\n '@instructor-ai/instructor',\n '@mastra/core',\n 'portkey-ai',\n];\n\n// PyPI normalizes `_` to `-` and is case-insensitive; compare via normalizePyName.\nconst PYTHON_LLM_PACKAGES = [\n 'openai',\n 'anthropic',\n 'langchain',\n 'langchain-openai',\n 'langchain-anthropic',\n 'langchain-google-genai',\n 'langgraph',\n 'litellm',\n 'llama-index',\n 'pydantic-ai',\n 'crewai',\n 'instructor',\n 'dspy-ai',\n 'mistralai',\n 'cohere',\n 'google-generativeai',\n 'google-genai',\n 'portkey-ai',\n];\n\nexport function discoverFeatures(installDir: string): DiscoveredFeature[] {\n const features: DiscoveredFeature[] = [];\n discoverNodeFeatures(installDir, features);\n discoverPythonFeatures(installDir, features);\n return features;\n}\n\nfunction discoverNodeFeatures(\n installDir: string,\n features: DiscoveredFeature[],\n): void {\n const packageJsonText = safeRead(installDir, 'package.json');\n if (!packageJsonText) return;\n\n let packageJson: {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n try {\n packageJson = JSON.parse(packageJsonText);\n } catch {\n return;\n }\n\n const depNames = Object.keys({\n ...packageJson.dependencies,\n ...packageJson.devDependencies,\n });\n\n if (depNames.some((depName) => STRIPE_PACKAGES.includes(depName))) {\n features.push(DiscoveredFeature.Stripe);\n }\n if (depNames.some((depName) => LLM_PACKAGES.includes(depName))) {\n features.push(DiscoveredFeature.LLM);\n }\n}\n\nfunction discoverPythonFeatures(\n installDir: string,\n features: DiscoveredFeature[],\n): void {\n if (features.includes(DiscoveredFeature.LLM)) return;\n\n const depNames: string[] = [];\n\n const requirementsTxt = safeRead(installDir, 'requirements.txt');\n if (requirementsTxt) depNames.push(...parseRequirementsTxt(requirementsTxt));\n\n const pyprojectToml = safeRead(installDir, 'pyproject.toml');\n if (pyprojectToml) depNames.push(...parsePyprojectToml(pyprojectToml));\n\n const pipfile = safeRead(installDir, 'Pipfile');\n if (pipfile) depNames.push(...parsePipfile(pipfile));\n\n if (depNames.some((depName) => PYTHON_LLM_PACKAGES.includes(depName))) {\n features.push(DiscoveredFeature.LLM);\n }\n}\n\nfunction safeRead(installDir: string, file: string): string | null {\n try {\n return readFileSync(join(installDir, file), 'utf-8');\n } catch {\n return null;\n }\n}\n\nfunction normalizePyName(name: string): string {\n return name.toLowerCase().replace(/_/g, '-');\n}\n\nexport function parseRequirementsTxt(content: string): string[] {\n return content\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line && !line.startsWith('#') && !line.startsWith('-'))\n .map((line) => line.replace(/\\[[^\\]]*\\]/, ''))\n .map((line) => line.split(/[<>=!~;\\s]/)[0])\n .filter(Boolean)\n .map(normalizePyName);\n}\n\n// Pragmatic, not a full TOML parser — only the dep shapes we care about.\nexport function parsePyprojectToml(content: string): string[] {\n const depNames: string[] = [];\n\n for (const arrayMatch of content.matchAll(\n /dependencies\\s*=\\s*\\[([^\\]]*)\\]/g,\n )) {\n const arrayBody = arrayMatch[1];\n for (const quotedMatch of arrayBody.matchAll(/[\"']([^\"']+)[\"']/g)) {\n const depSpec = quotedMatch[1];\n const name = depSpec.replace(/\\[[^\\]]*\\]/, '').split(/[<>=!~;\\s]/)[0];\n if (name) depNames.push(normalizePyName(name));\n }\n }\n\n const poetrySectionRe =\n /\\[tool\\.poetry\\.(?:dev-dependencies|dependencies|group\\.[^.\\]]+\\.dependencies)\\]([\\s\\S]*?)(?=\\n\\[|$)/g;\n for (const sectionMatch of content.matchAll(poetrySectionRe)) {\n const sectionBody = sectionMatch[1];\n depNames.push(...extractTomlSectionKeys(sectionBody, { skip: ['python'] }));\n }\n\n return depNames;\n}\n\nexport function parsePipfile(content: string): string[] {\n const depNames: string[] = [];\n const sectionRe = /\\[(packages|dev-packages)\\]([\\s\\S]*?)(?=\\n\\[|$)/g;\n for (const sectionMatch of content.matchAll(sectionRe)) {\n const sectionBody = sectionMatch[2];\n depNames.push(...extractTomlSectionKeys(sectionBody));\n }\n return depNames;\n}\n\nfunction extractTomlSectionKeys(\n sectionBody: string,\n opts: { skip?: string[] } = {},\n): string[] {\n const skipNames = new Set(opts.skip ?? []);\n const depNames: string[] = [];\n for (const line of sectionBody.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const equalsIndex = trimmed.indexOf('=');\n if (equalsIndex <= 0) continue;\n const name = trimmed.slice(0, equalsIndex).trim();\n if (!/^[a-zA-Z0-9._-]+$/.test(name)) continue;\n if (skipNames.has(name.toLowerCase())) continue;\n depNames.push(normalizePyName(name));\n }\n return depNames;\n}\n","/**\n * Framework context gathering — run gatherContext and version checks\n * for a detected framework.\n *\n * Pure functions: take a framework config and options, return results.\n * No store mutations, no UI calls.\n */\n\nimport * as semver from 'semver';\nimport { DETECTION_TIMEOUT_MS } from '../constants.js';\nimport type { FrameworkConfig } from '../framework-config.js';\nimport type { WizardOptions } from '../../utils/types.js';\n\n/**\n * Run a framework's `gatherContext()` to collect variant-specific\n * metadata (e.g., router type for Next.js, Expo vs bare for React Native).\n *\n * Returns the gathered context, or an empty object on failure/timeout.\n */\nexport async function gatherFrameworkContext(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<Record<string, unknown>> {\n if (!config.metadata.gatherContext) return {};\n\n try {\n return await Promise.race([\n config.metadata.gatherContext(options),\n new Promise<Record<string, never>>((resolve) =>\n setTimeout(() => resolve({}), DETECTION_TIMEOUT_MS),\n ),\n ]);\n } catch {\n return {};\n }\n}\n\nexport interface VersionCheckResult {\n /** Whether the installed version is supported */\n supported:\n | true\n | {\n current: string;\n minimum: string;\n docsUrl: string;\n };\n}\n\n/**\n * Check whether the installed framework version meets the minimum requirement.\n *\n * Returns `{ supported: true }` if the version is fine (or no check is needed).\n * Returns the version details if unsupported.\n */\nexport async function checkFrameworkVersion(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<VersionCheckResult> {\n if (\n !config.detection.minimumVersion ||\n !config.detection.getInstalledVersion\n ) {\n return { supported: true };\n }\n\n const version = await config.detection.getInstalledVersion(options);\n if (!version) return { supported: true };\n\n const coerced = semver.coerce(version);\n if (coerced && semver.lt(coerced, config.detection.minimumVersion)) {\n return {\n supported: {\n current: version,\n minimum: config.detection.minimumVersion,\n docsUrl:\n config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl,\n },\n };\n }\n\n return { supported: true };\n}\n","export { detectFramework } from './framework.js';\nexport { discoverFeatures } from './features.js';\nexport {\n gatherFrameworkContext,\n checkFrameworkVersion,\n type VersionCheckResult,\n} from './context.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,eAAsB,gBACpB,YACkC;AAClC,MAAK,MAAM,eAAe,OAAO,OAAO,YAAY,EAAE;EACpD,MAAM,SAAS,mBAAmB;AAClC,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tC,KAAI,WAAW,OAAO,GAAG,SAAS,OAAO,UAAU,eAAe,CAChE,QAAO,EACL,WAAW;EACT,SAAS;EACT,SAAS,OAAO,UAAU;EAC1B,SACE,OAAO,SAAS,6BAA6B,OAAO,SAAS;EAChE,EACF;AAGH,QAAO,EAAE,WAAW,MAAM"}
@@ -1,2 +0,0 @@
1
- import { r as hasPackageInstalled } from "./package-json-F_7oktsp.js";
2
- export { hasPackageInstalled };
@@ -1 +0,0 @@
1
- {"version":3,"file":"package-json-F_7oktsp.js","names":[],"sources":["../src/utils/package-json.ts"],"sourcesContent":["import { readFileSync } from 'fs';\nimport path from 'path';\n\nexport type PackageDotJson = {\n version?: string;\n scripts?: Record<string, string | undefined>;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n resolutions?: Record<string, string>;\n overrides?: Record<string, string>;\n pnpm?: {\n overrides?: Record<string, string>;\n };\n};\n\ntype NpmPackage = {\n name: string;\n version: string;\n};\n\n/**\n * Checks if @param packageJson has any of the @param packageNamesList package names\n * listed as a dependency or devDependency.\n * If so, it returns the first package name that is found, including the\n * version (range) specified in the package.json.\n */\nexport function findInstalledPackageFromList(\n packageNamesList: string[],\n packageJson: PackageDotJson,\n): NpmPackage | undefined {\n return packageNamesList\n .map((packageName) => ({\n name: packageName,\n version: getPackageVersion(packageName, packageJson),\n }))\n .find((sdkPackage): sdkPackage is NpmPackage => !!sdkPackage.version);\n}\n\nexport function hasPackageInstalled(\n packageName: string,\n packageJson: PackageDotJson,\n): boolean {\n return getPackageVersion(packageName, packageJson) !== undefined;\n}\n\n/**\n * Read the actual installed version from node_modules/[packageName]/package.json.\n * Returns the real semver (e.g. \"15.5.9\"), not the range from the project's package.json.\n */\nexport function getInstalledPackageVersion(\n packageName: string,\n installDir: string,\n): string | undefined {\n try {\n const pkgPath = path.join(\n installDir,\n 'node_modules',\n packageName,\n 'package.json',\n );\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));\n return pkg.version;\n } catch {\n return undefined;\n }\n}\n\nexport function getPackageVersion(\n packageName: string,\n packageJson: PackageDotJson,\n): string | undefined {\n return (\n packageJson?.dependencies?.[packageName] ||\n packageJson?.devDependencies?.[packageName]\n );\n}\n"],"mappings":";;;AAsCA,SAAgB,oBACd,aACA,aACS;AACT,QAAO,kBAAkB,aAAa,YAAY,KAAK,KAAA;;;;;;AAOzD,SAAgB,2BACd,aACA,YACoB;AACpB,KAAI;EACF,MAAM,UAAU,KAAK,KACnB,YACA,gBACA,aACA,eACD;AAED,SADY,KAAK,MAAM,aAAa,SAAS,QAAQ,CAAC,CAC3C;SACL;AACN;;;AAIJ,SAAgB,kBACd,aACA,aACoB;AACpB,QACE,aAAa,eAAe,gBAC5B,aAAa,kBAAkB"}
@@ -1,259 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
2
- import { P as WIZARD_INTERACTION_EVENT_NAME, c as getUI, f as SIGNUP_WIZARD_READINESS_CONFIG, m as getBlockingServiceKeys, p as evaluateWizardReadiness } from "./debug-B2BH87dh.js";
3
- import { n as analytics } from "./analytics-Cek5hIwm.js";
4
- import { a as isUsingTypeScript, d as getCloudUrlFromRegion, o as tryGetPackageJson } from "./setup-utils-DGUR4Djo.js";
5
- import { n as requestDeepLink } from "./provisioning-DRwH4skH.js";
6
- import { t as AgentSignals } from "./agent-interface-D9DeIikl.js";
7
- import { i as SPINNER_MESSAGE, t as FRAMEWORK_REGISTRY } from "./registry-CZjMhhsK.js";
8
- import { a as detectFramework, i as discoverFeatures, n as checkFrameworkVersion, r as gatherFrameworkContext } from "./detection-BFl2AYV6.js";
9
- import opn from "opn";
10
- //#region src/lib/workflows/posthog-integration/detect.ts
11
- async function detectPostHogIntegration(ctx) {
12
- const session = ctx.session;
13
- const installDir = session.installDir;
14
- const detectedIntegration = await detectFramework(installDir);
15
- if (detectedIntegration) {
16
- const config = FRAMEWORK_REGISTRY[detectedIntegration];
17
- const sessionOptions = {
18
- installDir,
19
- debug: session.debug,
20
- forceInstall: session.forceInstall,
21
- default: false,
22
- signup: session.signup,
23
- localMcp: session.localMcp,
24
- ci: session.ci,
25
- menu: session.menu,
26
- benchmark: session.benchmark,
27
- yaraReport: session.yaraReport
28
- };
29
- const context = await gatherFrameworkContext(config, sessionOptions);
30
- for (const [key, value] of Object.entries(context)) if (!(key in session.frameworkContext)) ctx.setFrameworkContext(key, value);
31
- ctx.setFrameworkConfig(detectedIntegration, config);
32
- session.skillId = detectedIntegration;
33
- if (!session.detectedFrameworkLabel) ctx.setDetectedFramework(config.metadata.name);
34
- const versionResult = await checkFrameworkVersion(config, sessionOptions);
35
- if (versionResult.supported !== true) ctx.setUnsupportedVersion(versionResult.supported);
36
- }
37
- for (const feature of discoverFeatures(installDir)) ctx.addDiscoveredFeature(feature);
38
- ctx.setDetectionComplete();
39
- }
40
- //#endregion
41
- //#region src/lib/workflows/posthog-integration/steps.ts
42
- function needsSetup(session) {
43
- const config = session.frameworkConfig;
44
- if (!config?.metadata.setup?.questions) return false;
45
- return config.metadata.setup.questions.some((q) => !(q.key in session.frameworkContext));
46
- }
47
- function healthCheckReady(session) {
48
- if (!session.readinessResult) return false;
49
- if (session.signup) {
50
- const hardBlocking = getBlockingServiceKeys(session.readinessResult.health, SIGNUP_WIZARD_READINESS_CONFIG);
51
- const defaultBlocking = getBlockingServiceKeys(session.readinessResult.health);
52
- if (hardBlocking.length === 0 && defaultBlocking.length === 0) return true;
53
- return session.outageDismissed;
54
- }
55
- if (session.readinessResult.decision === "no") return session.outageDismissed;
56
- return true;
57
- }
58
- const POSTHOG_INTEGRATION_WORKFLOW = [
59
- {
60
- id: "detect",
61
- label: "Detecting framework",
62
- onReady: (ctx) => detectPostHogIntegration(ctx)
63
- },
64
- {
65
- id: "intro",
66
- label: "Welcome",
67
- screen: "intro",
68
- gate: (session) => session.setupConfirmed
69
- },
70
- {
71
- id: "health-check",
72
- label: "Health check",
73
- screen: "health-check",
74
- gate: healthCheckReady,
75
- onInit: (ctx) => {
76
- evaluateWizardReadiness().then((readiness) => {
77
- ctx.setReadinessResult(readiness);
78
- }).catch(() => {
79
- ctx.setReadinessResult({
80
- decision: "yes",
81
- health: {},
82
- reasons: []
83
- });
84
- });
85
- }
86
- },
87
- {
88
- id: "setup",
89
- label: "Setup",
90
- screen: "setup",
91
- show: needsSetup,
92
- isComplete: (session) => !needsSetup(session)
93
- },
94
- {
95
- id: "auth",
96
- label: "Authentication",
97
- screen: "auth",
98
- isComplete: (session) => session.credentials !== null
99
- },
100
- {
101
- id: "run",
102
- label: "Integration",
103
- screen: "run",
104
- isComplete: (session) => session.runPhase === "completed" || session.runPhase === "error"
105
- },
106
- {
107
- id: "mcp",
108
- label: "MCP servers",
109
- screen: "mcp",
110
- isComplete: (session) => session.mcpComplete
111
- },
112
- {
113
- id: "outro",
114
- label: "Done",
115
- screen: "outro",
116
- isComplete: (session) => session.outroDismissed
117
- },
118
- {
119
- id: "keep-skills",
120
- label: "Keep Skills",
121
- screen: "keep-skills"
122
- }
123
- ];
124
- //#endregion
125
- //#region src/lib/workflows/posthog-integration/index.ts
126
- var posthog_integration_exports = /* @__PURE__ */ __exportAll({
127
- EVENT_PLAN_FILE: () => EVENT_PLAN_FILE,
128
- SETUP_REPORT_FILE: () => SETUP_REPORT_FILE,
129
- posthogIntegrationConfig: () => posthogIntegrationConfig
130
- });
131
- const DASHBOARD_DEEP_LINK_KEY = "dashboardDeepLink";
132
- function resolveContinueUrl(sess, cloudRegion, deepLink) {
133
- if (!sess.signup) return void 0;
134
- if (typeof deepLink === "string" && deepLink) return deepLink;
135
- if (cloudRegion) return `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`;
136
- }
137
- const SETUP_REPORT_FILE = "posthog-setup-report.md";
138
- const EVENT_PLAN_FILE = ".posthog-events.json";
139
- const posthogIntegrationConfig = {
140
- command: "integrate",
141
- description: "Set up PostHog SDK integration",
142
- flowKey: "posthog-integration",
143
- steps: POSTHOG_INTEGRATION_WORKFLOW,
144
- run: async (session) => {
145
- const config = session.frameworkConfig;
146
- const typeScriptDetected = isUsingTypeScript({ installDir: session.installDir });
147
- session.typescript = typeScriptDetected;
148
- const usesPackageJson = config.detection.usesPackageJson !== false;
149
- let frameworkVersion;
150
- if (usesPackageJson) {
151
- const packageJson = await tryGetPackageJson({ installDir: session.installDir });
152
- if (packageJson) {
153
- const { hasPackageInstalled } = await import("./package-json-BzVey4Bd.js");
154
- if (!hasPackageInstalled(config.detection.packageName, packageJson)) getUI().log.warn(`${config.detection.packageDisplayName} does not seem to be installed. Continuing anyway — the agent will handle it.`);
155
- frameworkVersion = config.detection.getVersion(packageJson);
156
- } else getUI().log.warn("Could not find package.json. Continuing anyway — the agent will handle it.");
157
- } else frameworkVersion = config.detection.getVersion(null);
158
- if (frameworkVersion && config.detection.getVersionBucket) {
159
- const versionBucket = config.detection.getVersionBucket(frameworkVersion);
160
- analytics.setTag(`${config.metadata.integration}-version`, versionBucket);
161
- }
162
- const frameworkContext = session.frameworkContext;
163
- const contextTags = config.analytics.getTags(frameworkContext);
164
- Object.entries(contextTags).forEach(([key, value]) => {
165
- analytics.setTag(key, value);
166
- });
167
- return {
168
- integrationLabel: config.metadata.integration,
169
- additionalMcpServers: config.metadata.additionalMcpServers,
170
- detectPackageManager: config.detection.detectPackageManager,
171
- spinnerMessage: SPINNER_MESSAGE,
172
- successMessage: config.ui.successMessage,
173
- estimatedDurationMinutes: config.ui.estimatedDurationMinutes,
174
- reportFile: SETUP_REPORT_FILE,
175
- docsUrl: config.metadata.docsUrl,
176
- errorMessage: "Integration failed",
177
- additionalFeatureQueue: session.additionalFeatureQueue,
178
- customPrompt: (ctx) => {
179
- const additionalLines = config.prompts.getAdditionalContextLines ? config.prompts.getAdditionalContextLines(frameworkContext) : [];
180
- const additionalContext = additionalLines.length > 0 ? "\n" + additionalLines.map((line) => `- ${line}`).join("\n") : "";
181
- return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${config.metadata.name} project.
182
-
183
- Project context:
184
- - PostHog Project ID: ${ctx.projectId}
185
- - Framework: ${config.metadata.name} ${frameworkVersion || "latest"}
186
- - TypeScript: ${typeScriptDetected ? "Yes" : "No"}
187
- - PostHog public token: ${ctx.projectApiKey}
188
- - PostHog Host: ${ctx.host}
189
- - Project type: ${config.prompts.projectTypeDetection}
190
- - Package installation: ${config.prompts.packageInstallation ?? "Use the detect_package_manager tool to determine the package manager. Do not manually edit package.json; the package manager handles it automatically."}${additionalContext}
191
-
192
- Instructions (follow these steps IN ORDER - do not skip or reorder):
193
-
194
- STEP 1: Call load_skill_menu (from the wizard-tools MCP server) to see available skills.
195
- If the tool fails, emit: ${AgentSignals.ERROR_MCP_MISSING} Could not load skill menu and halt.
196
-
197
- Choose a skill from the \`integration\` category that matches this project's framework. Do NOT pick skills from other categories (llm-analytics, error-tracking, feature-flags, omnibus, etc.) — those are handled separately.
198
- If no suitable integration skill is found, emit: ${AgentSignals.ERROR_RESOURCE_MISSING} Could not find a suitable skill for this project.
199
-
200
- STEP 2: Call install_skill (from the wizard-tools MCP server) with the chosen skill ID (e.g., "integration-nextjs-app-router").
201
- Do NOT run any shell commands to install skills.
202
-
203
- STEP 3: Load the installed skill's SKILL.md file to understand what references are available.
204
-
205
- STEP 4: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like "1.0-", "1.1-", "1.2-"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next. Never directly write PostHog tokens directly to code files; always use environment variables.
206
-
207
- STEP 5: Set up environment variables for PostHog using the wizard-tools MCP server (this runs locally — secret values never leave the machine):
208
- - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).
209
- - Use set_env_values to create or update the PostHog public token and host, using the appropriate environment variable naming convention for ${config.metadata.name}, which you'll find in example code. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.
210
- - Reference these environment variables in the code files you create instead of hardcoding the public token and host.
211
-
212
- Important: Use the detect_package_manager tool (from the wizard-tools MCP server) to determine which package manager the project uses. Do not manually search for lockfiles or config files. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.
213
-
214
-
215
- `;
216
- },
217
- postRun: async (sess, credentials) => {
218
- const envVars = config.environment.getEnvVars(credentials.projectApiKey, credentials.host);
219
- if (config.environment.uploadToHosting) {
220
- const { uploadEnvironmentVariablesStep } = await import("./steps-BFD76-MP.js");
221
- const uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {
222
- integration: config.metadata.integration,
223
- session: sess
224
- });
225
- if (uploadedEnvVars.length > 0) analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {
226
- action: "wizard_env_vars_uploaded",
227
- integration: config.metadata.integration,
228
- variable_count: uploadedEnvVars.length,
229
- variable_keys: uploadedEnvVars
230
- });
231
- }
232
- if (sess.signup) {
233
- const deepLink = await requestDeepLink(credentials.accessToken, credentials.host);
234
- if (deepLink) {
235
- sess.frameworkContext[DASHBOARD_DEEP_LINK_KEY] = deepLink;
236
- opn(deepLink, { wait: false }).catch(() => {});
237
- }
238
- }
239
- },
240
- buildOutroData: (sess, credentials, cloudRegion) => {
241
- const envVars = config.environment.getEnvVars(credentials.projectApiKey, credentials.host);
242
- const deepLink = sess.frameworkContext[DASHBOARD_DEEP_LINK_KEY];
243
- const continueUrl = resolveContinueUrl(sess, cloudRegion, deepLink);
244
- return {
245
- kind: "success",
246
- message: "Successfully installed PostHog!",
247
- reportFile: SETUP_REPORT_FILE,
248
- changes: [...config.ui.getOutroChanges(frameworkContext), Object.keys(envVars).length > 0 ? "Added environment variables to .env file" : ""].filter(Boolean),
249
- docsUrl: config.metadata.docsUrl,
250
- continueUrl
251
- };
252
- }
253
- };
254
- }
255
- };
256
- //#endregion
257
- export { posthogIntegrationConfig as n, posthog_integration_exports as r, EVENT_PLAN_FILE as t };
258
-
259
- //# sourceMappingURL=posthog-integration-vFBuSN5U.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"posthog-integration-vFBuSN5U.js","names":[],"sources":["../src/lib/workflows/posthog-integration/detect.ts","../src/lib/workflows/posthog-integration/steps.ts","../src/lib/workflows/posthog-integration/index.ts"],"sourcesContent":["/**\n * Core integration detection step.\n *\n * Runs framework detection, context gathering, version checking,\n * and feature discovery. Writes results to the store via the\n * WorkflowReadyContext so the IntroScreen can display them.\n *\n * This is the same work that bin.ts $0 handler does inline —\n * extracted here so the `integrate` subcommand can reuse it.\n */\n\nimport type { WorkflowReadyContext } from '../workflow-step.js';\nimport { FRAMEWORK_REGISTRY } from '../../registry.js';\nimport {\n detectFramework,\n discoverFeatures,\n gatherFrameworkContext,\n checkFrameworkVersion,\n} from '../../detection/index.js';\n\nexport async function detectPostHogIntegration(\n ctx: WorkflowReadyContext,\n): Promise<void> {\n const session = ctx.session;\n const installDir = session.installDir;\n\n const detectedIntegration = await detectFramework(installDir);\n\n if (detectedIntegration) {\n const config = FRAMEWORK_REGISTRY[detectedIntegration];\n\n const sessionOptions = {\n installDir,\n debug: session.debug,\n forceInstall: session.forceInstall,\n default: false,\n signup: session.signup,\n localMcp: session.localMcp,\n ci: session.ci,\n menu: session.menu,\n benchmark: session.benchmark,\n yaraReport: session.yaraReport,\n };\n\n // Gather framework-specific context (e.g., router type)\n const context = await gatherFrameworkContext(config, sessionOptions);\n for (const [key, value] of Object.entries(context)) {\n if (!(key in session.frameworkContext)) {\n ctx.setFrameworkContext(key, value);\n }\n }\n\n ctx.setFrameworkConfig(detectedIntegration, config);\n session.skillId = detectedIntegration;\n\n if (!session.detectedFrameworkLabel) {\n ctx.setDetectedFramework(config.metadata.name);\n }\n\n // Version check\n const versionResult = await checkFrameworkVersion(config, sessionOptions);\n if (versionResult.supported !== true) {\n ctx.setUnsupportedVersion(versionResult.supported);\n }\n }\n\n // Feature discovery\n for (const feature of discoverFeatures(installDir)) {\n ctx.addDiscoveredFeature(feature);\n }\n\n ctx.setDetectionComplete();\n}\n","/**\n * PostHog integration workflow — the default wizard flow.\n *\n * Steps define their own gate predicates and onInit callbacks.\n * The store derives gate promises and fires init work from these\n * definitions — no hardcoded per-flow logic in the store.\n */\n\nimport type { Workflow } from '../workflow-step.js';\nimport type { WizardSession } from '../../wizard-session.js';\nimport { RunPhase } from '../../wizard-session.js';\nimport {\n evaluateWizardReadiness,\n WizardReadiness,\n SIGNUP_WIZARD_READINESS_CONFIG,\n getBlockingServiceKeys,\n} from '../../health-checks/readiness.js';\nimport { detectPostHogIntegration } from './detect.js';\n\nfunction needsSetup(session: WizardSession): boolean {\n const config = session.frameworkConfig;\n if (!config?.metadata.setup?.questions) return false;\n\n return config.metadata.setup.questions.some(\n (q: { key: string }) => !(q.key in session.frameworkContext),\n );\n}\n\nfunction healthCheckReady(session: WizardSession): boolean {\n if (!session.readinessResult) return false;\n\n if (session.signup) {\n const hardBlocking = getBlockingServiceKeys(\n session.readinessResult.health,\n SIGNUP_WIZARD_READINESS_CONFIG,\n );\n const defaultBlocking = getBlockingServiceKeys(\n session.readinessResult.health,\n );\n if (hardBlocking.length === 0 && defaultBlocking.length === 0) return true;\n return session.outageDismissed;\n }\n\n if (session.readinessResult.decision === WizardReadiness.No) {\n return session.outageDismissed;\n }\n return true;\n}\n\nexport const POSTHOG_INTEGRATION_WORKFLOW: Workflow = [\n {\n id: 'detect',\n label: 'Detecting framework',\n // Headless step: no screen. onReady fires after bin.ts assigns the\n // session — runs framework detection, context gathering, version\n // check, and feature discovery. Results are written to the store\n // for the IntroScreen to render.\n onReady: (ctx) => detectPostHogIntegration(ctx),\n },\n {\n id: 'intro',\n label: 'Welcome',\n screen: 'intro',\n gate: (session) => session.setupConfirmed,\n },\n {\n id: 'health-check',\n label: 'Health check',\n screen: 'health-check',\n gate: healthCheckReady,\n onInit: (ctx) => {\n evaluateWizardReadiness()\n .then((readiness) => {\n ctx.setReadinessResult(readiness);\n })\n .catch(() => {\n ctx.setReadinessResult({\n decision: WizardReadiness.Yes,\n health: {} as never,\n reasons: [],\n });\n });\n },\n },\n {\n id: 'setup',\n label: 'Setup',\n screen: 'setup',\n show: needsSetup,\n isComplete: (session) => !needsSetup(session),\n },\n {\n id: 'auth',\n label: 'Authentication',\n screen: 'auth',\n isComplete: (session) => session.credentials !== null,\n },\n {\n id: 'run',\n label: 'Integration',\n screen: 'run',\n isComplete: (session) =>\n session.runPhase === RunPhase.Completed ||\n session.runPhase === RunPhase.Error,\n },\n {\n id: 'mcp',\n label: 'MCP servers',\n screen: 'mcp',\n isComplete: (session) => session.mcpComplete,\n },\n {\n id: 'outro',\n label: 'Done',\n screen: 'outro',\n isComplete: (session) => session.outroDismissed,\n },\n {\n id: 'keep-skills',\n label: 'Keep Skills',\n screen: 'keep-skills',\n },\n];\n","import opn from 'opn';\nimport type { WorkflowConfig } from '../workflow-step.js';\nimport type { WorkflowRun } from '../../agent/agent-runner.js';\nimport type { WizardSession } from '../../wizard-session.js';\nimport { OutroKind } from '../../wizard-session.js';\nimport { AgentSignals } from '../../agent/agent-interface.js';\nimport {\n DEFAULT_PACKAGE_INSTALLATION,\n SPINNER_MESSAGE,\n} from '../../framework-config.js';\nimport {\n tryGetPackageJson,\n isUsingTypeScript,\n} from '../../../utils/setup-utils.js';\nimport { analytics } from '../../../utils/analytics.js';\nimport { WIZARD_INTERACTION_EVENT_NAME } from '../../constants.js';\nimport { getUI } from '../../../ui/index.js';\nimport { getCloudUrlFromRegion } from '../../../utils/urls.js';\nimport { requestDeepLink } from '../../../utils/provisioning.js';\nimport type { CloudRegion } from '../../../utils/types.js';\nimport { POSTHOG_INTEGRATION_WORKFLOW } from './steps.js';\n\nconst DASHBOARD_DEEP_LINK_KEY = 'dashboardDeepLink';\n\nfunction resolveContinueUrl(\n sess: WizardSession,\n cloudRegion: CloudRegion | undefined,\n deepLink: unknown,\n): string | undefined {\n if (!sess.signup) return undefined;\n if (typeof deepLink === 'string' && deepLink) return deepLink;\n if (cloudRegion)\n return `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`;\n return undefined;\n}\n\nexport const SETUP_REPORT_FILE = 'posthog-setup-report.md';\nexport const EVENT_PLAN_FILE = '.posthog-events.json';\n\nexport const posthogIntegrationConfig: WorkflowConfig = {\n command: 'integrate',\n description: 'Set up PostHog SDK integration',\n flowKey: 'posthog-integration',\n steps: POSTHOG_INTEGRATION_WORKFLOW,\n\n run: async (session: WizardSession): Promise<WorkflowRun> => {\n const config = session.frameworkConfig!;\n\n const typeScriptDetected = isUsingTypeScript({\n installDir: session.installDir,\n });\n session.typescript = typeScriptDetected;\n\n // Read package.json and resolve framework version\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n const packageJson = await tryGetPackageJson({\n installDir: session.installDir,\n });\n if (packageJson) {\n const { hasPackageInstalled } = await import(\n '../../../utils/package-json.js'\n );\n if (!hasPackageInstalled(config.detection.packageName, packageJson)) {\n getUI().log.warn(\n `${config.detection.packageDisplayName} does not seem to be installed. Continuing anyway — the agent will handle it.`,\n );\n }\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n getUI().log.warn(\n 'Could not find package.json. Continuing anyway — the agent will handle it.',\n );\n }\n } else {\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Analytics tags\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n const frameworkContext = session.frameworkContext;\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n return {\n integrationLabel: config.metadata.integration,\n additionalMcpServers: config.metadata.additionalMcpServers,\n detectPackageManager: config.detection.detectPackageManager,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n reportFile: SETUP_REPORT_FILE,\n docsUrl: config.metadata.docsUrl,\n errorMessage: 'Integration failed',\n additionalFeatureQueue: session.additionalFeatureQueue,\n\n customPrompt: (ctx) => {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- PostHog Project ID: ${ctx.projectId}\n- Framework: ${config.metadata.name} ${frameworkVersion || 'latest'}\n- TypeScript: ${typeScriptDetected ? 'Yes' : 'No'}\n- PostHog public token: ${ctx.projectApiKey}\n- PostHog Host: ${ctx.host}\n- Project type: ${config.prompts.projectTypeDetection}\n- Package installation: ${\n config.prompts.packageInstallation ?? DEFAULT_PACKAGE_INSTALLATION\n }${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: Call load_skill_menu (from the wizard-tools MCP server) to see available skills.\n If the tool fails, emit: ${\n AgentSignals.ERROR_MCP_MISSING\n } Could not load skill menu and halt.\n\n Choose a skill from the \\`integration\\` category that matches this project's framework. Do NOT pick skills from other categories (llm-analytics, error-tracking, feature-flags, omnibus, etc.) — those are handled separately.\n If no suitable integration skill is found, emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Call install_skill (from the wizard-tools MCP server) with the chosen skill ID (e.g., \"integration-nextjs-app-router\").\n Do NOT run any shell commands to install skills.\n\nSTEP 3: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 4: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next. Never directly write PostHog tokens directly to code files; always use environment variables.\n\nSTEP 5: Set up environment variables for PostHog using the wizard-tools MCP server (this runs locally — secret values never leave the machine):\n - Use check_env_keys to see which keys already exist in the project's .env file (e.g. .env.local or .env).\n - Use set_env_values to create or update the PostHog public token and host, using the appropriate environment variable naming convention for ${\n config.metadata.name\n }, which you'll find in example code. The tool will also ensure .gitignore coverage. Don't assume the presence of keys means the value is up to date. Write the correct value each time.\n - Reference these environment variables in the code files you create instead of hardcoding the public token and host.\n\nImportant: Use the detect_package_manager tool (from the wizard-tools MCP server) to determine which package manager the project uses. Do not manually search for lockfiles or config files. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.\n\n\n`;\n },\n\n postRun: async (sess, credentials) => {\n const envVars = config.environment.getEnvVars(\n credentials.projectApiKey,\n credentials.host,\n );\n if (config.environment.uploadToHosting) {\n const { uploadEnvironmentVariablesStep } = await import(\n '../../../steps/index.js'\n );\n const uploadedEnvVars = await uploadEnvironmentVariablesStep(\n envVars,\n {\n integration: config.metadata.integration,\n session: sess,\n },\n );\n if (uploadedEnvVars.length > 0) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'wizard_env_vars_uploaded',\n integration: config.metadata.integration,\n variable_count: uploadedEnvVars.length,\n variable_keys: uploadedEnvVars,\n });\n }\n }\n\n if (sess.signup) {\n const deepLink = await requestDeepLink(\n credentials.accessToken,\n credentials.host,\n );\n if (deepLink) {\n sess.frameworkContext[DASHBOARD_DEEP_LINK_KEY] = deepLink;\n if (process.env.NODE_ENV !== 'test') {\n opn(deepLink, { wait: false }).catch(() => {\n // opn throws in environments without a browser\n });\n }\n }\n }\n },\n\n buildOutroData: (sess, credentials, cloudRegion) => {\n const envVars = config.environment.getEnvVars(\n credentials.projectApiKey,\n credentials.host,\n );\n const deepLink = sess.frameworkContext[DASHBOARD_DEEP_LINK_KEY];\n const continueUrl = resolveContinueUrl(sess, cloudRegion, deepLink);\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? 'Added environment variables to .env file'\n : '',\n ].filter(Boolean);\n\n return {\n kind: OutroKind.Success as const,\n message: 'Successfully installed PostHog!',\n reportFile: SET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AM,UAAU,OAAO,YAAY,WACjC,YAAY,eACZ,YAAY,KACb;IACD,MAAM,WAAW,KAAK,iBAAiB;IACvC,MAAM,cAAc,mBAAmB,MAAM,aAAa,SAAS;AASnE,WAAO;KACL,MAAA;KACA,SAAS;KACT,YAAY;KACZ,SAXc,CACd,GAAG,OAAO,GAAG,gBAAgB,iBAAiB,EAC9C,OAAO,KAAK,QAAQ,CAAC,SAAS,IAC1B,6CACA,GACL,CAAC,OAAO,QAAQ;KAOf,SAAS,OAAO,SAAS;KACzB;KACD;;GAEJ;;CAEJ"}
@@ -1,2 +0,0 @@
1
- import { t as provisionNewAccount } from "./provisioning-DRwH4skH.js";
2
- export { provisionNewAccount };
@@ -1,135 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-B_-DWIq7.js";
2
- import { a as AGENT_SKILL_STEPS, t as WORKFLOW_REGISTRY } from "./bin.js";
3
- //#region src/lib/workflows/workflow-step.ts
4
- /**
5
- * Project a Workflow into the narrower FlowEntry shape the router consumes.
6
- *
7
- * Two things happen here:
8
- * 1. Headless steps (no `screen`) are filtered out. The router walks
9
- * visible screens; gate-only steps like `detect` are store concerns.
10
- * 2. The step is narrowed to just { screen, show, isComplete } — the
11
- * router has no business touching gate, onInit, id, or label.
12
- *
13
- * This intentional separation keeps the router focused on one question:
14
- * "Which screen should be rendered right now?"
15
- */
16
- function workflowToFlowEntries(workflow) {
17
- const entries = workflow.filter((step) => step.screen != null).map((step) => ({
18
- screen: step.screen,
19
- show: step.show,
20
- isComplete: step.isComplete ?? step.gate
21
- }));
22
- entries.push({
23
- screen: "exit",
24
- show: void 0,
25
- isComplete: void 0
26
- });
27
- return entries;
28
- }
29
- //#endregion
30
- //#region src/ui/tui/flows.ts
31
- /** Named flows the router can run */
32
- let Flow = /* @__PURE__ */ function(Flow) {
33
- Flow["PostHogIntegration"] = "posthog-integration";
34
- Flow["RevenueAnalyticsSetup"] = "revenue-analytics-setup";
35
- Flow["Audit"] = "audit";
36
- Flow["Audit3000"] = "audit-3000";
37
- Flow["PosthogDoctor"] = "posthog-doctor";
38
- Flow["AgentSkill"] = "agent-skill";
39
- Flow["McpAdd"] = "mcp-add";
40
- Flow["McpRemove"] = "mcp-remove";
41
- return Flow;
42
- }({});
43
- /** Raw workflow step arrays — used by the store for gate/onInit definitions. */
44
- const WORKFLOW_STEPS = {
45
- ...Object.fromEntries(WORKFLOW_REGISTRY.map((c) => [c.flowKey, c.steps])),
46
- ["agent-skill"]: AGENT_SKILL_STEPS
47
- };
48
- /**
49
- * All flow pipelines.
50
- *
51
- * Workflow-based flows are derived from the registry.
52
- * MCP add/remove flows are standalone.
53
- */
54
- const FLOWS = {
55
- ...Object.fromEntries(WORKFLOW_REGISTRY.map((c) => [c.flowKey, workflowToFlowEntries(c.steps)])),
56
- ["agent-skill"]: workflowToFlowEntries(AGENT_SKILL_STEPS),
57
- ["mcp-add"]: [{
58
- screen: "mcp-add",
59
- isComplete: (s) => s.mcpComplete
60
- }, { screen: "exit" }],
61
- ["mcp-remove"]: [{
62
- screen: "mcp-remove",
63
- isComplete: (s) => s.mcpComplete
64
- }, { screen: "exit" }]
65
- };
66
- //#endregion
67
- //#region src/ui/tui/router.ts
68
- var router_exports = /* @__PURE__ */ __exportAll({
69
- Flow: () => Flow,
70
- WizardRouter: () => WizardRouter
71
- });
72
- var WizardRouter = class {
73
- flow;
74
- flowName;
75
- overlays = [];
76
- constructor(flowName = "posthog-integration") {
77
- this.flowName = flowName;
78
- this.flow = FLOWS[flowName];
79
- }
80
- /**
81
- * Resolve which screen should be active based on session state.
82
- * Walks the flow pipeline, skipping hidden entries and completed entries,
83
- * returns the first incomplete screen.
84
- */
85
- resolve(session) {
86
- if (this.overlays.length > 0) return this.overlays[this.overlays.length - 1];
87
- for (const entry of this.flow) {
88
- if (entry.show && !entry.show(session)) continue;
89
- if (entry.isComplete && entry.isComplete(session)) continue;
90
- return entry.screen;
91
- }
92
- return this.flow[this.flow.length - 1].screen;
93
- }
94
- /** The screen that should be rendered right now. */
95
- get activeScreen() {
96
- if (this.overlays.length > 0) return this.overlays[this.overlays.length - 1];
97
- return this.flow[0].screen;
98
- }
99
- /** The name of the active flow. */
100
- get activeFlow() {
101
- return this.flowName;
102
- }
103
- /** Whether an overlay is currently active. */
104
- get hasOverlay() {
105
- return this.overlays.length > 0;
106
- }
107
- /**
108
- * Push an overlay that interrupts the current flow.
109
- * The flow resumes when the overlay is dismissed via popOverlay().
110
- */
111
- pushOverlay(overlay) {
112
- this.overlays.push(overlay);
113
- }
114
- /**
115
- * Dismiss the topmost overlay. The flow screen underneath resumes.
116
- */
117
- popOverlay() {
118
- this.overlays.pop();
119
- }
120
- /**
121
- * Direction hint for screen transitions.
122
- */
123
- _lastDirection = null;
124
- get lastNavDirection() {
125
- return this._lastDirection;
126
- }
127
- /** @internal — called by store wrapper to track direction */
128
- _setDirection(dir) {
129
- this._lastDirection = dir;
130
- }
131
- };
132
- //#endregion
133
- export { WORKFLOW_STEPS as i, router_exports as n, Flow as r, WizardRouter as t };
134
-
135
- //# sourceMappingURL=router-COhhuIW3.js.map