splithub 0.1.9 → 0.2.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 (80) hide show
  1. package/README.md +11 -0
  2. package/dist/chunk-3RVNT2HA.js +54 -0
  3. package/dist/chunk-3RVNT2HA.js.map +1 -0
  4. package/dist/chunk-5C24F2ZN.js +113 -0
  5. package/dist/chunk-5C24F2ZN.js.map +1 -0
  6. package/dist/chunk-B6FITBWN.js +384 -0
  7. package/dist/chunk-B6FITBWN.js.map +1 -0
  8. package/dist/chunk-BJQJGLOB.js +160 -0
  9. package/dist/chunk-BJQJGLOB.js.map +1 -0
  10. package/dist/chunk-DDWYTOX4.js +565 -0
  11. package/dist/chunk-DDWYTOX4.js.map +1 -0
  12. package/dist/chunk-DUIJ5DTV.js +170 -0
  13. package/dist/chunk-DUIJ5DTV.js.map +1 -0
  14. package/dist/chunk-E5VH4BQX.js +326 -0
  15. package/dist/chunk-E5VH4BQX.js.map +1 -0
  16. package/dist/chunk-EYYLDI5J.js +195 -0
  17. package/dist/chunk-EYYLDI5J.js.map +1 -0
  18. package/dist/chunk-GVARYUL3.js +28 -0
  19. package/dist/chunk-GVARYUL3.js.map +1 -0
  20. package/dist/chunk-KMO5GGGC.js +185 -0
  21. package/dist/chunk-KMO5GGGC.js.map +1 -0
  22. package/dist/chunk-LT4JP3IF.js +119 -0
  23. package/dist/chunk-LT4JP3IF.js.map +1 -0
  24. package/dist/chunk-NMN5YGNP.js +72 -0
  25. package/dist/chunk-NMN5YGNP.js.map +1 -0
  26. package/dist/chunk-OHA2M7QR.js +264 -0
  27. package/dist/chunk-OHA2M7QR.js.map +1 -0
  28. package/dist/chunk-OYM64FMD.js +63 -0
  29. package/dist/chunk-OYM64FMD.js.map +1 -0
  30. package/dist/chunk-PLXDG4B5.js +134 -0
  31. package/dist/chunk-PLXDG4B5.js.map +1 -0
  32. package/dist/chunk-PNPOOAHF.js +393 -0
  33. package/dist/chunk-PNPOOAHF.js.map +1 -0
  34. package/dist/chunk-RYDA7PQF.js +97 -0
  35. package/dist/chunk-RYDA7PQF.js.map +1 -0
  36. package/dist/chunk-V3DLUVOE.js +112 -0
  37. package/dist/chunk-V3DLUVOE.js.map +1 -0
  38. package/dist/ci-ZQZ6RBUJ.js +16 -0
  39. package/dist/ci-ZQZ6RBUJ.js.map +1 -0
  40. package/dist/create-AEJVXN25.js +18 -0
  41. package/dist/create-AEJVXN25.js.map +1 -0
  42. package/dist/dev-W2JGUV2A.js +11 -0
  43. package/dist/dev-W2JGUV2A.js.map +1 -0
  44. package/dist/doctor-D3KOGOX6.js +14 -0
  45. package/dist/doctor-D3KOGOX6.js.map +1 -0
  46. package/dist/holdout-BWVTTLEY.js +44 -0
  47. package/dist/holdout-BWVTTLEY.js.map +1 -0
  48. package/dist/index.js +94 -2240
  49. package/dist/index.js.map +1 -1
  50. package/dist/init-UBUDSJBD.js +15 -0
  51. package/dist/init-UBUDSJBD.js.map +1 -0
  52. package/dist/lifecycle-ZLZUTASA.js +12 -0
  53. package/dist/lifecycle-ZLZUTASA.js.map +1 -0
  54. package/dist/login-TIIX5V4O.js +18 -0
  55. package/dist/login-TIIX5V4O.js.map +1 -0
  56. package/dist/menu-S3WDS4JY.js +163 -0
  57. package/dist/menu-S3WDS4JY.js.map +1 -0
  58. package/dist/plan-G2A55FR7.js +135 -0
  59. package/dist/plan-G2A55FR7.js.map +1 -0
  60. package/dist/push-OJX4F2BH.js +16 -0
  61. package/dist/push-OJX4F2BH.js.map +1 -0
  62. package/dist/refs-RY7H3J7L.js +44 -0
  63. package/dist/refs-RY7H3J7L.js.map +1 -0
  64. package/dist/remove-EQQCDJRU.js +54 -0
  65. package/dist/remove-EQQCDJRU.js.map +1 -0
  66. package/dist/report-6WNO576N.js +69 -0
  67. package/dist/report-6WNO576N.js.map +1 -0
  68. package/dist/results-ZDOCWN6U.js +21 -0
  69. package/dist/results-ZDOCWN6U.js.map +1 -0
  70. package/dist/review-7E7JVMMV.js +34 -0
  71. package/dist/review-7E7JVMMV.js.map +1 -0
  72. package/dist/ship-MRBHWFZR.js +450 -0
  73. package/dist/ship-MRBHWFZR.js.map +1 -0
  74. package/dist/skills-JJOKGNO5.js +13 -0
  75. package/dist/skills-JJOKGNO5.js.map +1 -0
  76. package/dist/status-SATP23WK.js +12 -0
  77. package/dist/status-SATP23WK.js.map +1 -0
  78. package/dist/update-67QDJ6GF.js +37 -0
  79. package/dist/update-67QDJ6GF.js.map +1 -0
  80. package/package.json +22 -5
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ fail
4
+ } from "./chunk-V3DLUVOE.js";
5
+
6
+ // src/project.ts
7
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs";
8
+ import { join, relative, resolve } from "path";
9
+ var CONFIG_NAMES = ["splithub.config.ts", "splithub.config.mts", "splithub.config.js", "splithub.config.mjs"];
10
+ function findConfigFile(root) {
11
+ for (const name of CONFIG_NAMES) {
12
+ const p = join(root, name);
13
+ if (existsSync(p)) return p;
14
+ }
15
+ return null;
16
+ }
17
+ function detectProject(cwd = process.cwd()) {
18
+ const root = resolve(cwd);
19
+ let name = "my-app";
20
+ let deps = {};
21
+ try {
22
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
23
+ name = pkg.name ?? name;
24
+ deps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
25
+ } catch {
26
+ }
27
+ const has = (file) => existsSync(join(root, file));
28
+ const framework = deps.next || has("next.config.js") || has("next.config.mjs") || has("next.config.ts") ? "next" : deps.vite || has("vite.config.ts") || has("vite.config.js") || has("vite.config.mjs") ? "vite" : "unknown";
29
+ const packageManager = has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("bun.lockb") || has("bun.lock") ? "bun" : "npm";
30
+ const appDir = has("src/app") ? "src/app" : has("app") ? "app" : null;
31
+ return {
32
+ root,
33
+ name: name.replace(/^@[^/]+\//, ""),
34
+ framework,
35
+ packageManager,
36
+ appDir,
37
+ hasSrc: has("src"),
38
+ configFile: findConfigFile(root),
39
+ typescript: has("tsconfig.json")
40
+ };
41
+ }
42
+ function requireConfig(cwd = process.cwd()) {
43
+ const project = detectProject(cwd);
44
+ if (!project.configFile) fail("NO_CONFIG", "There's no splithub.config.ts here.", "Run npx splithub init first, or run the command in your app folder.");
45
+ return project;
46
+ }
47
+ function installCommand(pm, packages, dev = false) {
48
+ const flag = dev ? pm === "npm" ? " -D" : " -D" : "";
49
+ switch (pm) {
50
+ case "pnpm":
51
+ return `pnpm add${flag} ${packages.join(" ")}`;
52
+ case "yarn":
53
+ return `yarn add${flag} ${packages.join(" ")}`;
54
+ case "bun":
55
+ return `bun add${dev ? " -d" : ""} ${packages.join(" ")}`;
56
+ default:
57
+ return `npm install${flag} ${packages.join(" ")}`;
58
+ }
59
+ }
60
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".next", "dist", "build", ".git", "coverage", "out", ".turbo"]);
61
+ var CODE_EXT = /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;
62
+ function listSourceFiles(root, maxFiles = 5e3) {
63
+ const out = [];
64
+ const walk = (dir, depth) => {
65
+ if (out.length >= maxFiles || depth > 8) return;
66
+ let entries;
67
+ try {
68
+ entries = readdirSync(dir);
69
+ } catch {
70
+ return;
71
+ }
72
+ for (const entry of entries) {
73
+ if (SKIP_DIRS.has(entry)) continue;
74
+ const full = join(dir, entry);
75
+ let st;
76
+ try {
77
+ st = statSync(full);
78
+ } catch {
79
+ continue;
80
+ }
81
+ if (st.isDirectory()) walk(full, depth + 1);
82
+ else if (CODE_EXT.test(entry)) out.push(full);
83
+ }
84
+ };
85
+ walk(root, 0);
86
+ return out;
87
+ }
88
+ function quoted(key) {
89
+ return [`'${key}'`, `"${key}"`, `\`${key}\``];
90
+ }
91
+ function grepLines(root, files, needles) {
92
+ const hits = [];
93
+ for (const f of files) {
94
+ let src;
95
+ try {
96
+ src = readFileSync(f, "utf8");
97
+ } catch {
98
+ continue;
99
+ }
100
+ if (!needles.some((n) => src.includes(n))) continue;
101
+ const lines = src.split(/\r?\n/);
102
+ lines.forEach((text, i) => {
103
+ for (const needle of needles) {
104
+ const col = text.indexOf(needle);
105
+ if (col >= 0) {
106
+ hits.push({ file: relative(root, f).replace(/\\/g, "/"), line: i + 1, column: col + 1, text: text.trim().slice(0, 200), needle });
107
+ break;
108
+ }
109
+ }
110
+ });
111
+ }
112
+ return hits;
113
+ }
114
+ function grepFiles(files, needle) {
115
+ const hits = [];
116
+ for (const f of files) {
117
+ try {
118
+ if (readFileSync(f, "utf8").includes(needle)) hits.push(f);
119
+ } catch {
120
+ }
121
+ }
122
+ return hits;
123
+ }
124
+
125
+ export {
126
+ detectProject,
127
+ requireConfig,
128
+ installCommand,
129
+ listSourceFiles,
130
+ quoted,
131
+ grepLines,
132
+ grepFiles
133
+ };
134
+ //# sourceMappingURL=chunk-PLXDG4B5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport { fail } from './errors';\n\nexport type Framework = 'next' | 'vite' | 'unknown';\nexport type PackageManager = 'pnpm' | 'yarn' | 'bun' | 'npm';\n\nexport interface ProjectInfo {\n root: string;\n name: string;\n framework: Framework;\n packageManager: PackageManager;\n /** Next.js app directory (`app` or `src/app`), when present. */\n appDir: string | null;\n /** Whether sources live under `src/`. */\n hasSrc: boolean;\n configFile: string | null;\n typescript: boolean;\n}\n\nconst CONFIG_NAMES = ['splithub.config.ts', 'splithub.config.mts', 'splithub.config.js', 'splithub.config.mjs'];\n\nexport function findConfigFile(root: string): string | null {\n for (const name of CONFIG_NAMES) {\n const p = join(root, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nexport function detectProject(cwd = process.cwd()): ProjectInfo {\n const root = resolve(cwd);\n let name = 'my-app';\n let deps: Record<string, string> = {};\n try {\n const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n name = pkg.name ?? name;\n deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n } catch {\n // no package.json: still usable\n }\n const has = (file: string) => existsSync(join(root, file));\n const framework: Framework = deps.next || has('next.config.js') || has('next.config.mjs') || has('next.config.ts')\n ? 'next'\n : deps.vite || has('vite.config.ts') || has('vite.config.js') || has('vite.config.mjs')\n ? 'vite'\n : 'unknown';\n const packageManager: PackageManager = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : 'npm';\n const appDir = has('src/app') ? 'src/app' : has('app') ? 'app' : null;\n return {\n root,\n name: name.replace(/^@[^/]+\\//, ''),\n framework,\n packageManager,\n appDir,\n hasSrc: has('src'),\n configFile: findConfigFile(root),\n typescript: has('tsconfig.json'),\n };\n}\n\n/** The project and its config file; NO_CONFIG when there is none. */\nexport function requireConfig(cwd = process.cwd()): ProjectInfo & { configFile: string } {\n const project = detectProject(cwd);\n if (!project.configFile) fail('NO_CONFIG', \"There's no splithub.config.ts here.\", 'Run npx splithub init first, or run the command in your app folder.');\n return project as ProjectInfo & { configFile: string };\n}\n\nexport function installCommand(pm: PackageManager, packages: string[], dev = false): string {\n const flag = dev ? (pm === 'npm' ? ' -D' : ' -D') : '';\n switch (pm) {\n case 'pnpm':\n return `pnpm add${flag} ${packages.join(' ')}`;\n case 'yarn':\n return `yarn add${flag} ${packages.join(' ')}`;\n case 'bun':\n return `bun add${dev ? ' -d' : ''} ${packages.join(' ')}`;\n default:\n return `npm install${flag} ${packages.join(' ')}`;\n }\n}\n\nconst SKIP_DIRS = new Set(['node_modules', '.next', 'dist', 'build', '.git', 'coverage', 'out', '.turbo']);\nconst CODE_EXT = /\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;\n\n/** Source files of the project (shallow enough for a doctor run). */\nexport function listSourceFiles(root: string, maxFiles = 5000): string[] {\n const out: string[] = [];\n const walk = (dir: string, depth: number) => {\n if (out.length >= maxFiles || depth > 8) return;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (SKIP_DIRS.has(entry)) continue;\n const full = join(dir, entry);\n let st;\n try {\n st = statSync(full);\n } catch {\n continue;\n }\n if (st.isDirectory()) walk(full, depth + 1);\n else if (CODE_EXT.test(entry)) out.push(full);\n }\n };\n walk(root, 0);\n return out;\n}\n\nexport interface LineHit {\n /** Path relative to the project root, forward slashes. */\n file: string;\n line: number;\n column: number;\n text: string;\n /** Which needle matched. */\n needle: string;\n}\n\n/** Quoted forms of a key as it appears in code: 'k', \"k\", `k`. */\nexport function quoted(key: string): string[] {\n return [`'${key}'`, `\"${key}\"`, `\\`${key}\\``];\n}\n\n/** Every line of `files` that contains one of `needles`, with its position. */\nexport function grepLines(root: string, files: string[], needles: string[]): LineHit[] {\n const hits: LineHit[] = [];\n for (const f of files) {\n let src: string;\n try {\n src = readFileSync(f, 'utf8');\n } catch {\n continue;\n }\n if (!needles.some((n) => src.includes(n))) continue;\n const lines = src.split(/\\r?\\n/);\n lines.forEach((text, i) => {\n for (const needle of needles) {\n const col = text.indexOf(needle);\n if (col >= 0) {\n hits.push({ file: relative(root, f).replace(/\\\\/g, '/'), line: i + 1, column: col + 1, text: text.trim().slice(0, 200), needle });\n break;\n }\n }\n });\n }\n return hits;\n}\n\nexport function grepFiles(files: string[], needle: string): string[] {\n const hits: string[] = [];\n for (const f of files) {\n try {\n if (readFileSync(f, 'utf8').includes(needle)) hits.push(f);\n } catch {\n // unreadable file\n }\n }\n return hits;\n}\n"],"mappings":";;;;;;AAAA,SAAS,YAAY,cAAc,aAAa,gBAAgB;AAChE,SAAS,MAAM,UAAU,eAAe;AAmBxC,IAAM,eAAe,CAAC,sBAAsB,uBAAuB,sBAAsB,qBAAqB;AAEvG,SAAS,eAAe,MAA6B;AAC1D,aAAW,QAA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AGO,SAAS,UAAU,MAAc,OAAiB,SAA8B;AACrF,QAAM,OAAkB,CAAC;AACzB,aAAW,KAAK,OAAO;AACrB,QAAI;AACJ,QAAI;AACF,YAAM,aAAa,GAAG,MAAM;AAAA,IAC9B,QAAQ;AACN;AAAA,IACF;AACA,QAAI,CAAC,QAAQ,KAAK,CAAC,MAAM,IAAI,SAAS,CAAC,CAAC,EAAG;AAC3C,UAAM,QAAQ,IAAI,MAAM,OAAO;AAC/B,UAAM,QAAQ,CAAC,MAAM,MAAM;AACzB,iBAAW,UAAU,SAAS;AAC5B,cAAM,MAAM,KAAK,QAAQ,MAAM;AAC/B,YAAI,OAAO,GAAG;AACZ,eAAK,KAAK,EAAE,MAAM,SAAS,MAAM,CAAC,EAAE,QAAQ,OAAO,GAAG,GAAG,MAAM,IAAI,GAAG,QAAQ,MAAM,GAAG,MAAM,KAAK,KAAK,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,CAAC;AAChI;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAEO,SAAS,UAAU,OAAiB,QAA0B;AACnE,QAAM,OAAiB,CAAC;AACxB,aAAW,KAAK,OAAO;AACrB,QAAI;AACF,UAAI,aAAa,GAAG,MAAM,EAAE,SAAS,MAAM,EAAG,MAAK,KAAK,CAAC;AAAA,IAC3D,QAAQ;AAAA,IAER;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,393 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ deviceLogin
4
+ } from "./chunk-5C24F2ZN.js";
5
+ import {
6
+ cloudTarget,
7
+ loadCredential
8
+ } from "./chunk-BJQJGLOB.js";
9
+ import {
10
+ installSkills
11
+ } from "./chunk-RYDA7PQF.js";
12
+ import {
13
+ configTemplate,
14
+ nextMiddlewareTemplate,
15
+ nextRouteTemplate
16
+ } from "./chunk-DDWYTOX4.js";
17
+ import {
18
+ writeWorkflow
19
+ } from "./chunk-EYYLDI5J.js";
20
+ import {
21
+ detectProject,
22
+ installCommand
23
+ } from "./chunk-PLXDG4B5.js";
24
+ import {
25
+ c
26
+ } from "./chunk-V3DLUVOE.js";
27
+
28
+ // src/commands/init.ts
29
+ import * as p from "@clack/prompts";
30
+ import { execSync } from "child_process";
31
+ import { existsSync, mkdirSync, writeFileSync } from "fs";
32
+ import { dirname, join, relative } from "path";
33
+
34
+ // src/templates-store.ts
35
+ var DB_KINDS = ["sqlite", "postgres", "mysql", "custom"];
36
+ var PG_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';
37
+ import { Pool } from 'pg';
38
+
39
+ // SplitHub events in your Postgres. Run once (or add to your migrations):
40
+ export const SCHEMA_SQL = \`
41
+ CREATE TABLE IF NOT EXISTS splithub_events (
42
+ id text PRIMARY KEY,
43
+ type text NOT NULL, -- exposure | goal
44
+ experiment text,
45
+ variant text,
46
+ goal text,
47
+ visitor_id text NOT NULL,
48
+ session_id text NOT NULL,
49
+ ts bigint NOT NULL, -- client clock, unix ms
50
+ url text,
51
+ props jsonb,
52
+ received_at bigint NOT NULL, -- server clock, unix ms
53
+ host text,
54
+ country text,
55
+ device text,
56
+ browser text
57
+ );
58
+ CREATE INDEX IF NOT EXISTS splithub_events_exp ON splithub_events (type, experiment, visitor_id, ts);
59
+ CREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal, visitor_id, ts);
60
+ \`;
61
+
62
+ // The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).
63
+ const counts = variantCountsSql({ dialect: 'postgres', table: 'splithub_events' });
64
+
65
+ export function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {
66
+ return {
67
+ async insertEvents(events: StoredEvent[]) {
68
+ if (events.length === 0) return 0;
69
+ const cols = 15;
70
+ const values: unknown[] = [];
71
+ const rows = events.map((e, i) => {
72
+ values.push(e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null);
73
+ return '(' + Array.from({ length: cols }, (_, j) => '$' + (i * cols + j + 1)).join(', ') + ')';
74
+ });
75
+ const r = await pool.query(
76
+ 'INSERT INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ' + rows.join(', ') + ' ON CONFLICT (id) DO NOTHING',
77
+ values
78
+ );
79
+ return r.rowCount ?? 0;
80
+ },
81
+ async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {
82
+ const r = await pool.query(counts.sql, counts.bind({ experiment, goal }));
83
+ return r.rows.map(countsFromRow);
84
+ },
85
+ async summaries(): Promise<ExperimentSummary[]> {
86
+ const r = await pool.query(
87
+ \`SELECT experiment, COUNT(*)::int AS exposures, COUNT(DISTINCT visitor_id)::int AS visitors, MIN(ts)::bigint AS first_ts, MAX(ts)::bigint AS last_ts
88
+ FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\`
89
+ );
90
+ return r.rows.map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));
91
+ },
92
+ close: () => pool.end(),
93
+ };
94
+ }
95
+ `;
96
+ var MYSQL_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';
97
+ import mysql, { type Pool } from 'mysql2/promise';
98
+
99
+ // SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):
100
+ export const SCHEMA_SQL = \`
101
+ CREATE TABLE IF NOT EXISTS splithub_events (
102
+ id VARCHAR(64) PRIMARY KEY,
103
+ type VARCHAR(16) NOT NULL,
104
+ experiment VARCHAR(64) NULL,
105
+ variant VARCHAR(64) NULL,
106
+ goal VARCHAR(64) NULL,
107
+ visitor_id VARCHAR(64) NOT NULL,
108
+ session_id VARCHAR(64) NOT NULL,
109
+ ts BIGINT NOT NULL,
110
+ url VARCHAR(512) NULL,
111
+ props JSON NULL,
112
+ received_at BIGINT NOT NULL,
113
+ host VARCHAR(255) NULL,
114
+ country VARCHAR(8) NULL,
115
+ device VARCHAR(16) NULL,
116
+ browser VARCHAR(32) NULL,
117
+ INDEX splithub_events_exp (type, experiment, visitor_id, ts),
118
+ INDEX splithub_events_goal (type, goal, visitor_id, ts)
119
+ );
120
+ \`;
121
+
122
+ // The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).
123
+ const counts = variantCountsSql({ dialect: 'mysql', table: 'splithub_events' });
124
+
125
+ export function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {
126
+ return {
127
+ async insertEvents(events: StoredEvent[]) {
128
+ if (events.length === 0) return 0;
129
+ const values = events.map((e) => [e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null]);
130
+ const [r] = await pool.query(
131
+ 'INSERT IGNORE INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ?',
132
+ [values]
133
+ );
134
+ return (r as { affectedRows: number }).affectedRows;
135
+ },
136
+ async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {
137
+ const [rows] = await pool.query(counts.sql, counts.bind({ experiment, goal }));
138
+ return (rows as Array<Record<string, unknown>>).map(countsFromRow);
139
+ },
140
+ async summaries(): Promise<ExperimentSummary[]> {
141
+ const [rows] = await pool.query(
142
+ \`SELECT experiment, COUNT(*) AS exposures, COUNT(DISTINCT visitor_id) AS visitors, MIN(ts) AS first_ts, MAX(ts) AS last_ts
143
+ FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\`
144
+ );
145
+ return (rows as Array<Record<string, unknown>>).map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));
146
+ },
147
+ close: () => pool.end(),
148
+ };
149
+ }
150
+ `;
151
+ var CUSTOM_STORE = `import { attributeVariants, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';
152
+
153
+ /**
154
+ * Your own store (Prisma, Drizzle, Supabase, Mongo, anything). Three methods.
155
+ * Attribution rule (keep it, so results match the dashboard):
156
+ * a visitor counts once per experiment, in the variant of their earliest
157
+ * exposure (same ts: smallest variant key), and converts when they sent the
158
+ * goal at or after that exposure (60 s of clock skew allowed); only the first
159
+ * 50 events of one goal per visitor and UTC day count; count unique visitors.
160
+ * SQL database: run variantCountsSql({ dialect }) from @splithub/node.
161
+ * Anything else: load the experiment's exposures and the goal's events and
162
+ * return attributeVariants(events, experiment, goal).
163
+ * Columns worth keeping: id (unique, dedupe on it), type, experiment, variant,
164
+ * goal, visitor_id, session_id, ts, url, props (json), received_at, host,
165
+ * country, device, browser.
166
+ */
167
+ export function customStore(): Store {
168
+ return {
169
+ async insertEvents(events: StoredEvent[]): Promise<number> {
170
+ // Insert, skipping ids that already exist. Return how many were inserted.
171
+ throw new Error('implement insertEvents ' + events.length);
172
+ },
173
+ async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {
174
+ // Per variant: exposures, conversions, revenueSum and revenueSumSq (per-visitor revenue).
175
+ // Load the exposures of this experiment and the events of this goal, then apply the shared rule.
176
+ const events: StoredEvent[] = [];
177
+ if (events.length === 0) throw new Error('implement variantCounts ' + experiment + ' ' + goal);
178
+ return attributeVariants(events, experiment, goal);
179
+ },
180
+ async summaries(): Promise<ExperimentSummary[]> {
181
+ // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).
182
+ throw new Error('implement summaries');
183
+ },
184
+ };
185
+ }
186
+ `;
187
+ function storeTemplate(db) {
188
+ return db === "postgres" ? PG_STORE : db === "mysql" ? MYSQL_STORE : db === "custom" ? CUSTOM_STORE : null;
189
+ }
190
+ function storeUsage(db, storeImport) {
191
+ switch (db) {
192
+ case "postgres":
193
+ return { imports: `import { pgStore } from '${storeImport}';`, factory: "pgStore()" };
194
+ case "mysql":
195
+ return { imports: `import { mysqlStore } from '${storeImport}';`, factory: "mysqlStore()" };
196
+ case "custom":
197
+ return { imports: `import { customStore } from '${storeImport}';`, factory: "customStore()" };
198
+ default:
199
+ return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };
200
+ }
201
+ }
202
+ function runtimePackages(db) {
203
+ return db === "postgres" ? ["pg"] : db === "mysql" ? ["mysql2"] : db === "sqlite" ? ["@splithub/adapter-sqlite"] : [];
204
+ }
205
+
206
+ // src/commands/init.ts
207
+ function str(v) {
208
+ return typeof v === "string" ? v : void 0;
209
+ }
210
+ function writeIfMissing(file, content, created, skipped) {
211
+ if (existsSync(file)) {
212
+ skipped.push(file);
213
+ return;
214
+ }
215
+ mkdirSync(dirname(file), { recursive: true });
216
+ writeFileSync(file, content, "utf8");
217
+ created.push(file);
218
+ }
219
+ function importPath(fromFile, toFile) {
220
+ let rel = relative(dirname(fromFile), toFile).replace(/\\/g, "/").replace(/\.(ts|mts|js|mjs)$/, "");
221
+ if (!rel.startsWith(".")) rel = `./${rel}`;
222
+ return rel;
223
+ }
224
+ var VITE_PLUGIN_HINT = `// vite.config.ts
225
+ import { splithub } from '@splithub/core/vite';
226
+
227
+ export default defineConfig({ plugins: [react(), splithub()] });`;
228
+ async function init(flags) {
229
+ const yes = Boolean(flags.yes);
230
+ const json = Boolean(flags.json);
231
+ const project = detectProject();
232
+ const created = [];
233
+ const skipped = [];
234
+ if (!json) p.intro(c.bold("splithub init"));
235
+ let mode = str(flags.mode);
236
+ if (!mode) {
237
+ if (yes) mode = "self";
238
+ else {
239
+ const picked = await p.select({
240
+ message: "Where should events be stored?",
241
+ options: [
242
+ { value: "self", label: "My own database (self-hosted)", hint: "free forever, nothing leaves your infra" },
243
+ { value: "cloud", label: "SplitHub Cloud", hint: "hosted dashboard, no server code" }
244
+ ]
245
+ });
246
+ if (p.isCancel(picked)) return cancel2();
247
+ mode = picked;
248
+ }
249
+ }
250
+ let db = DB_KINDS.includes(str(flags.db) ?? "") ? str(flags.db) : "sqlite";
251
+ if (mode === "self" && !flags.db && !yes) {
252
+ const picked = await p.select({
253
+ message: "Where should events be stored?",
254
+ options: [
255
+ { value: "sqlite", label: "SQLite file (zero setup)", hint: "./splithub.db via node:sqlite" },
256
+ { value: "postgres", label: "Postgres", hint: "pg + DATABASE_URL, table splithub_events" },
257
+ { value: "mysql", label: "MySQL / MariaDB / PlanetScale", hint: "mysql2 + DATABASE_URL" },
258
+ { value: "custom", label: "My own store (Prisma, Drizzle, Supabase, Mongo\u2026)", hint: "a stub with the three methods to fill in" }
259
+ ]
260
+ });
261
+ if (p.isCancel(picked)) return cancel2();
262
+ db = picked;
263
+ }
264
+ let key = str(flags.key);
265
+ let connected = null;
266
+ if (mode === "cloud") {
267
+ const api = cloudTarget(flags).url;
268
+ const saved = loadCredential(api, project.root);
269
+ if (saved) {
270
+ key ??= saved.publicKey ?? void 0;
271
+ connected = { projectName: saved.projectName, projectId: saved.projectId };
272
+ } else if (!process.env.SPLITHUB_API_KEY && !flags["no-login"]) {
273
+ if (!json) p.log.step("Connect to SplitHub Cloud");
274
+ try {
275
+ const cred = await deviceLogin({
276
+ api,
277
+ root: project.root,
278
+ json,
279
+ onCode: json ? (s) => console.log(JSON.stringify({ step: "approve", verifyUrl: s.verifyUrl, userCode: s.userCode, expiresIn: s.expiresIn, hint: "Show this link to the user and wait; init continues once approved." })) : (s) => p.note(`${c.cyan(s.verifyUrl)}
280
+
281
+ Code ${c.green(s.userCode)} \xB7 sign in, pick or create the project, approve.`, "Open this link")
282
+ });
283
+ key ??= cred.publicKey ?? void 0;
284
+ connected = { projectName: cred.projectName, projectId: cred.projectId };
285
+ if (!json) p.log.success(`connected to ${c.cyan(cred.projectName ?? cred.projectId ?? "project")}`);
286
+ } catch (error) {
287
+ if (!json) p.log.warn(`not connected: ${error instanceof Error ? error.message : String(error)}. Run ${c.cyan("npx splithub login")} later.`);
288
+ }
289
+ }
290
+ if (!key && process.env.SPLITHUB_API_KEY) {
291
+ try {
292
+ const res = await fetch(`${api}/config`, { headers: { authorization: `Bearer ${process.env.SPLITHUB_API_KEY}` } });
293
+ const body = await res.json().catch(() => ({}));
294
+ if (typeof body.publicKey === "string" && body.publicKey.startsWith("pk_")) {
295
+ key = body.publicKey;
296
+ connected ??= { projectName: null, projectId: null };
297
+ }
298
+ } catch {
299
+ }
300
+ }
301
+ if (!key && !yes) {
302
+ const k = await p.text({ message: "Cloud public key (pk_...), leave empty to set later via NEXT_PUBLIC_SPLITHUB_KEY", placeholder: "pk_" });
303
+ if (p.isCancel(k)) return cancel2();
304
+ key = k || void 0;
305
+ }
306
+ }
307
+ const configFile = project.configFile ?? join(project.root, "splithub.config.ts");
308
+ writeIfMissing(configFile, configTemplate(project.name, mode, key), created, skipped);
309
+ const storeBody = mode === "self" ? storeTemplate(db) : null;
310
+ const storeFile = storeBody ? join(project.root, "splithub", "store.ts") : null;
311
+ if (storeFile && storeBody) writeIfMissing(storeFile, storeBody, created, skipped);
312
+ if (project.framework === "next") {
313
+ const mwFile = join(project.root, project.hasSrc ? "src/middleware.ts" : "middleware.ts");
314
+ writeIfMissing(mwFile, nextMiddlewareTemplate(importPath(mwFile, configFile)), created, skipped);
315
+ if (mode === "self" && project.appDir) {
316
+ const routeFile = join(project.root, project.appDir, "api/splithub/[[...path]]/route.ts");
317
+ writeIfMissing(routeFile, nextRouteTemplate(importPath(routeFile, configFile), storeUsage(db, storeFile ? importPath(routeFile, storeFile) : "")), created, skipped);
318
+ }
319
+ }
320
+ let mcp = !flags["no-mcp"];
321
+ if (!yes && !json && mcp) {
322
+ const want = await p.confirm({ message: "Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?", initialValue: true });
323
+ if (p.isCancel(want)) return cancel2();
324
+ mcp = want;
325
+ }
326
+ const skillsResult = installSkills(project.root, { mcp });
327
+ created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));
328
+ skipped.push(...skillsResult.skipped);
329
+ if (flags["github-action"]) {
330
+ const wf = writeWorkflow(project.root, Boolean(flags.force));
331
+ (wf.written ? created : skipped).push(join(project.root, wf.file));
332
+ }
333
+ const runtime = ["@splithub/react", "@splithub/core"];
334
+ if (project.framework === "next") runtime.push("@splithub/next");
335
+ if (mode === "self") runtime.push("@splithub/node", ...runtimePackages(db));
336
+ const installRuntime = installCommand(project.packageManager, runtime);
337
+ const installDev = installCommand(project.packageManager, ["splithub"], true);
338
+ let installed = false;
339
+ if (!flags["no-install"]) {
340
+ const go = yes ? true : await p.confirm({ message: `Install packages now? (${installRuntime})` });
341
+ if (p.isCancel(go)) return cancel2();
342
+ if (go) {
343
+ const s = json ? null : p.spinner();
344
+ s?.start("Installing");
345
+ try {
346
+ execSync(installRuntime, { cwd: project.root, stdio: json ? "ignore" : "inherit" });
347
+ execSync(installDev, { cwd: project.root, stdio: json ? "ignore" : "inherit" });
348
+ installed = true;
349
+ s?.stop("Installed");
350
+ } catch (error) {
351
+ s?.stop("Install failed; run it manually");
352
+ if (!json) p.log.error(error instanceof Error ? error.message : String(error));
353
+ }
354
+ }
355
+ }
356
+ const providerHint = project.framework === "next" ? `// ${project.appDir ?? "app"}/layout.tsx
357
+ import { SplitHubNextProvider } from '@splithub/next/client';
358
+ import { getSplitHub } from '@splithub/next/server';
359
+ import config from '${importPath(join(project.root, project.appDir ?? "app", "layout.tsx"), configFile)}';
360
+
361
+ export default async function RootLayout({ children }) {
362
+ const sh = await getSplitHub(config);
363
+ return <html><body><SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider></body></html>;
364
+ }` : `// main.tsx
365
+ import { SplitHubProvider } from '@splithub/react';
366
+ import config from './splithub.config';
367
+
368
+ <SplitHubProvider config={config}><App /></SplitHubProvider>`;
369
+ const warning = mode === "cloud" && !key ? "No public key yet: storage.key falls back to process.env.NEXT_PUBLIC_SPLITHUB_KEY. It is written into the config by the first `npx splithub push`, by `npx splithub login` (saved with the credentials), or pass --key pk_\u2026 (dashboard \u2192 Setup); SPLITHUB_API_KEY in the environment also resolves it." : null;
370
+ const summary = { project: project.name, framework: project.framework, mode, db: mode === "self" ? db : null, connected, publicKey: key ?? null, warning, created, skipped, installed, installCommands: installed ? [] : [installRuntime, installDev], nextStep: providerHint, ...project.framework === "vite" ? { vitePlugin: VITE_PLUGIN_HINT } : {} };
371
+ if (json) {
372
+ console.log(JSON.stringify(summary));
373
+ return;
374
+ }
375
+ if (warning) p.log.warn(warning);
376
+ if (mode === "self" && db !== "sqlite") p.note(db === "custom" ? "Fill in the three methods in splithub/store.ts (the comments say what each must return)." : `Set DATABASE_URL and run the SCHEMA_SQL from splithub/store.ts once (or add it to your migrations).`, `Database: ${db}`);
377
+ if (created.length) p.note(created.map((f) => relative(project.root, f) || f).join("\n"), "Created");
378
+ if (skipped.length) p.note(skipped.map((f) => relative(project.root, f)).join("\n"), "Already present, left untouched");
379
+ if (!installed) p.note(`${installRuntime}
380
+ ${installDev}`, "Install");
381
+ p.note(providerHint, "Wrap your app once");
382
+ if (project.framework === "vite") p.note(VITE_PLUGIN_HINT, "Notes in your dev terminal");
383
+ p.outro(`Next: ${c.cyan("npx splithub create")} to add your first experiment, ${c.cyan("npx splithub push")} to sync it, ${c.cyan("npx splithub doctor")} to verify.`);
384
+ }
385
+ function cancel2() {
386
+ p.cancel("Cancelled.");
387
+ process.exit(0);
388
+ }
389
+
390
+ export {
391
+ init
392
+ };
393
+ //# sourceMappingURL=chunk-PNPOOAHF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/init.ts","../src/templates-store.ts"],"sourcesContent":["import * as p from '@clack/prompts';\nimport { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { cloudTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject, installCommand } from '../project';\nimport { deviceLogin } from './login';\nimport { configTemplate, nextMiddlewareTemplate, nextRouteTemplate } from '../templates';\nimport { DB_KINDS, runtimePackages, storeTemplate, storeUsage, type DbKind } from '../templates-store';\nimport { installSkills } from './skills';\nimport { writeWorkflow } from './ci';\nimport { c } from '../ui';\n\nexport type Flags = Record<string, string | boolean | string[] | undefined>;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction writeIfMissing(file: string, content: string, created: string[], skipped: string[]): void {\n if (existsSync(file)) {\n skipped.push(file);\n return;\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n created.push(file);\n}\n\nfunction importPath(fromFile: string, toFile: string): string {\n let rel = relative(dirname(fromFile), toFile).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');\n if (!rel.startsWith('.')) rel = `./${rel}`;\n return rel;\n}\n\n// Vite apps run the SDK in the browser; this plugin prints what each experiment does in the dev server's terminal.\nconst VITE_PLUGIN_HINT = `// vite.config.ts\nimport { splithub } from '@splithub/core/vite';\n\nexport default defineConfig({ plugins: [react(), splithub()] });`;\n\nexport async function init(flags: Flags): Promise<void> {\n const yes = Boolean(flags.yes);\n const json = Boolean(flags.json);\n const project = detectProject();\n const created: string[] = [];\n const skipped: string[] = [];\n\n if (!json) p.intro(c.bold('splithub init'));\n\n let mode = str(flags.mode) as 'self' | 'cloud' | undefined;\n if (!mode) {\n if (yes) mode = 'self';\n else {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'self', label: 'My own database (self-hosted)', hint: 'free forever, nothing leaves your infra' },\n { value: 'cloud', label: 'SplitHub Cloud', hint: 'hosted dashboard, no server code' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n mode = picked as 'self' | 'cloud';\n }\n }\n\n // Cloud: connect this directory to a project. A saved login or SPLITHUB_API_KEY\n // is enough; otherwise run the device flow — print a link, the human signs in\n // and picks (or creates) the project, the CLI gets the keys. Works when an\n // agent runs init: it relays the link, the user clicks it.\n // Self mode: which database keeps the events. sqlite needs nothing; postgres / mysql\n // get a ready Store in splithub/store.ts; custom gets a documented stub.\n let db: DbKind = (DB_KINDS as string[]).includes(str(flags.db) ?? '') ? (str(flags.db) as DbKind) : 'sqlite';\n if (mode === 'self' && !flags.db && !yes) {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'sqlite', label: 'SQLite file (zero setup)', hint: './splithub.db via node:sqlite' },\n { value: 'postgres', label: 'Postgres', hint: 'pg + DATABASE_URL, table splithub_events' },\n { value: 'mysql', label: 'MySQL / MariaDB / PlanetScale', hint: 'mysql2 + DATABASE_URL' },\n { value: 'custom', label: 'My own store (Prisma, Drizzle, Supabase, Mongo…)', hint: 'a stub with the three methods to fill in' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n db = picked as DbKind;\n }\n\n let key = str(flags.key);\n let connected: { projectName: string | null; projectId: string | null } | null = null;\n if (mode === 'cloud') {\n const api = cloudTarget(flags).url;\n const saved = loadCredential(api, project.root);\n if (saved) {\n key ??= saved.publicKey ?? undefined;\n connected = { projectName: saved.projectName, projectId: saved.projectId };\n } else if (!process.env.SPLITHUB_API_KEY && !flags['no-login']) {\n if (!json) p.log.step('Connect to SplitHub Cloud');\n try {\n const cred = await deviceLogin({\n api,\n root: project.root,\n json,\n onCode: json\n ? (s) => console.log(JSON.stringify({ step: 'approve', verifyUrl: s.verifyUrl, userCode: s.userCode, expiresIn: s.expiresIn, hint: 'Show this link to the user and wait; init continues once approved.' }))\n : (s) => p.note(`${c.cyan(s.verifyUrl)}\\n\\nCode ${c.green(s.userCode)} · sign in, pick or create the project, approve.`, 'Open this link'),\n });\n key ??= cred.publicKey ?? undefined;\n connected = { projectName: cred.projectName, projectId: cred.projectId };\n if (!json) p.log.success(`connected to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n } catch (error) {\n if (!json) p.log.warn(`not connected: ${error instanceof Error ? error.message : String(error)}. Run ${c.cyan('npx splithub login')} later.`);\n }\n }\n // An API key in the environment (CI, agents) identifies the project: ask the cloud for its public key.\n if (!key && process.env.SPLITHUB_API_KEY) {\n try {\n const res = await fetch(`${api}/config`, { headers: { authorization: `Bearer ${process.env.SPLITHUB_API_KEY}` } });\n const body = (await res.json().catch(() => ({}))) as { publicKey?: string };\n if (typeof body.publicKey === 'string' && body.publicKey.startsWith('pk_')) {\n key = body.publicKey;\n connected ??= { projectName: null, projectId: null };\n }\n } catch {\n // offline: the first push writes the key into the config anyway\n }\n }\n if (!key && !yes) {\n const k = await p.text({ message: 'Cloud public key (pk_...), leave empty to set later via NEXT_PUBLIC_SPLITHUB_KEY', placeholder: 'pk_' });\n if (p.isCancel(k)) return cancel();\n key = k || undefined;\n }\n }\n\n // 1. config\n const configFile = project.configFile ?? join(project.root, 'splithub.config.ts');\n writeIfMissing(configFile, configTemplate(project.name, mode, key), created, skipped);\n\n // 2a. store for self mode (postgres / mysql / custom); sqlite needs no file.\n const storeBody = mode === 'self' ? storeTemplate(db) : null;\n const storeFile = storeBody ? join(project.root, 'splithub', 'store.ts') : null;\n if (storeFile && storeBody) writeIfMissing(storeFile, storeBody, created, skipped);\n\n // 2. framework files\n if (project.framework === 'next') {\n const mwFile = join(project.root, project.hasSrc ? 'src/middleware.ts' : 'middleware.ts');\n writeIfMissing(mwFile, nextMiddlewareTemplate(importPath(mwFile, configFile)), created, skipped);\n if (mode === 'self' && project.appDir) {\n const routeFile = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n writeIfMissing(routeFile, nextRouteTemplate(importPath(routeFile, configFile), storeUsage(db, storeFile ? importPath(routeFile, storeFile) : '')), created, skipped);\n }\n }\n\n // 3. agent skills (+ MCP server registration): the agent learns the library, how to test\n // well, the API and the MCP tools from .claude/skills/*; Cursor gets the rule file.\n let mcp = !flags['no-mcp'];\n if (!yes && !json && mcp) {\n const want = await p.confirm({ message: 'Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?', initialValue: true });\n if (p.isCancel(want)) return cancel();\n mcp = want;\n }\n const skillsResult = installSkills(project.root, { mcp });\n created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));\n skipped.push(...skillsResult.skipped);\n\n // 3b. GitHub workflow: checks on PRs, results comment on a schedule.\n if (flags['github-action']) {\n const wf = writeWorkflow(project.root, Boolean(flags.force));\n (wf.written ? created : skipped).push(join(project.root, wf.file));\n }\n\n // 4. dependencies\n const runtime = ['@splithub/react', '@splithub/core'];\n if (project.framework === 'next') runtime.push('@splithub/next');\n if (mode === 'self') runtime.push('@splithub/node', ...runtimePackages(db));\n const installRuntime = installCommand(project.packageManager, runtime);\n const installDev = installCommand(project.packageManager, ['splithub'], true);\n let installed = false;\n if (!flags['no-install']) {\n const go = yes ? true : await p.confirm({ message: `Install packages now? (${installRuntime})` });\n if (p.isCancel(go)) return cancel();\n if (go) {\n const s = json ? null : p.spinner();\n s?.start('Installing');\n try {\n execSync(installRuntime, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n execSync(installDev, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n installed = true;\n s?.stop('Installed');\n } catch (error) {\n s?.stop('Install failed; run it manually');\n if (!json) p.log.error(error instanceof Error ? error.message : String(error));\n }\n }\n }\n\n const providerHint =\n project.framework === 'next'\n ? `// ${project.appDir ?? 'app'}/layout.tsx\\nimport { SplitHubNextProvider } from '@splithub/next/client';\\nimport { getSplitHub } from '@splithub/next/server';\\nimport config from '${importPath(join(project.root, project.appDir ?? 'app', 'layout.tsx'), configFile)}';\\n\\nexport default async function RootLayout({ children }) {\\n const sh = await getSplitHub(config);\\n return <html><body><SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider></body></html>;\\n}`\n : `// main.tsx\\nimport { SplitHubProvider } from '@splithub/react';\\nimport config from './splithub.config';\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>`;\n\n const warning = mode === 'cloud' && !key ? 'No public key yet: storage.key falls back to process.env.NEXT_PUBLIC_SPLITHUB_KEY. It is written into the config by the first `npx splithub push`, by `npx splithub login` (saved with the credentials), or pass --key pk_… (dashboard → Setup); SPLITHUB_API_KEY in the environment also resolves it.' : null;\n const summary = { project: project.name, framework: project.framework, mode, db: mode === 'self' ? db : null, connected, publicKey: key ?? null, warning, created, skipped, installed, installCommands: installed ? [] : [installRuntime, installDev], nextStep: providerHint, ...(project.framework === 'vite' ? { vitePlugin: VITE_PLUGIN_HINT } : {}) };\n\n if (json) {\n console.log(JSON.stringify(summary));\n return;\n }\n if (warning) p.log.warn(warning);\n if (mode === 'self' && db !== 'sqlite') p.note(db === 'custom' ? 'Fill in the three methods in splithub/store.ts (the comments say what each must return).' : `Set DATABASE_URL and run the SCHEMA_SQL from splithub/store.ts once (or add it to your migrations).`, `Database: ${db}`);\n if (created.length) p.note(created.map((f) => relative(project.root, f) || f).join('\\n'), 'Created');\n if (skipped.length) p.note(skipped.map((f) => relative(project.root, f)).join('\\n'), 'Already present, left untouched');\n if (!installed) p.note(`${installRuntime}\\n${installDev}`, 'Install');\n p.note(providerHint, 'Wrap your app once');\n if (project.framework === 'vite') p.note(VITE_PLUGIN_HINT, 'Notes in your dev terminal');\n p.outro(`Next: ${c.cyan('npx splithub create')} to add your first experiment, ${c.cyan('npx splithub push')} to sync it, ${c.cyan('npx splithub doctor')} to verify.`);\n}\n\n\nfunction cancel(): void {\n p.cancel('Cancelled.');\n process.exit(0);\n}\n","// Store templates for self-hosted mode: `splithub init --mode self --db postgres|mysql|custom`\n// writes splithub/store.ts from one of these. Each implements the Store interface\n// from @splithub/node (insertEvents, variantCounts, summaries) with the same\n// attribution rule as the cloud, through variantCountsSql from @splithub/node.\n\nexport type DbKind = 'sqlite' | 'postgres' | 'mysql' | 'custom';\nexport const DB_KINDS: DbKind[] = ['sqlite', 'postgres', 'mysql', 'custom'];\n\nexport const PG_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\nimport { Pool } from 'pg';\n\n// SplitHub events in your Postgres. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id text PRIMARY KEY,\n type text NOT NULL, -- exposure | goal\n experiment text,\n variant text,\n goal text,\n visitor_id text NOT NULL,\n session_id text NOT NULL,\n ts bigint NOT NULL, -- client clock, unix ms\n url text,\n props jsonb,\n received_at bigint NOT NULL, -- server clock, unix ms\n host text,\n country text,\n device text,\n browser text\n);\nCREATE INDEX IF NOT EXISTS splithub_events_exp ON splithub_events (type, experiment, visitor_id, ts);\nCREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal, visitor_id, ts);\n\\`;\n\n// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).\nconst counts = variantCountsSql({ dialect: 'postgres', table: 'splithub_events' });\n\nexport function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const cols = 15;\n const values: unknown[] = [];\n const rows = events.map((e, i) => {\n values.push(e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null);\n return '(' + Array.from({ length: cols }, (_, j) => '$' + (i * cols + j + 1)).join(', ') + ')';\n });\n const r = await pool.query(\n 'INSERT INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ' + rows.join(', ') + ' ON CONFLICT (id) DO NOTHING',\n values\n );\n return r.rowCount ?? 0;\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n const r = await pool.query(counts.sql, counts.bind({ experiment, goal }));\n return r.rows.map(countsFromRow);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const r = await pool.query(\n \\`SELECT experiment, COUNT(*)::int AS exposures, COUNT(DISTINCT visitor_id)::int AS visitors, MIN(ts)::bigint AS first_ts, MAX(ts)::bigint AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return r.rows.map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const MYSQL_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\nimport mysql, { type Pool } from 'mysql2/promise';\n\n// SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id VARCHAR(64) PRIMARY KEY,\n type VARCHAR(16) NOT NULL,\n experiment VARCHAR(64) NULL,\n variant VARCHAR(64) NULL,\n goal VARCHAR(64) NULL,\n visitor_id VARCHAR(64) NOT NULL,\n session_id VARCHAR(64) NOT NULL,\n ts BIGINT NOT NULL,\n url VARCHAR(512) NULL,\n props JSON NULL,\n received_at BIGINT NOT NULL,\n host VARCHAR(255) NULL,\n country VARCHAR(8) NULL,\n device VARCHAR(16) NULL,\n browser VARCHAR(32) NULL,\n INDEX splithub_events_exp (type, experiment, visitor_id, ts),\n INDEX splithub_events_goal (type, goal, visitor_id, ts)\n);\n\\`;\n\n// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).\nconst counts = variantCountsSql({ dialect: 'mysql', table: 'splithub_events' });\n\nexport function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const values = events.map((e) => [e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null]);\n const [r] = await pool.query(\n 'INSERT IGNORE INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ?',\n [values]\n );\n return (r as { affectedRows: number }).affectedRows;\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n const [rows] = await pool.query(counts.sql, counts.bind({ experiment, goal }));\n return (rows as Array<Record<string, unknown>>).map(countsFromRow);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const [rows] = await pool.query(\n \\`SELECT experiment, COUNT(*) AS exposures, COUNT(DISTINCT visitor_id) AS visitors, MIN(ts) AS first_ts, MAX(ts) AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const CUSTOM_STORE = `import { attributeVariants, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\n\n/**\n * Your own store (Prisma, Drizzle, Supabase, Mongo, anything). Three methods.\n * Attribution rule (keep it, so results match the dashboard):\n * a visitor counts once per experiment, in the variant of their earliest\n * exposure (same ts: smallest variant key), and converts when they sent the\n * goal at or after that exposure (60 s of clock skew allowed); only the first\n * 50 events of one goal per visitor and UTC day count; count unique visitors.\n * SQL database: run variantCountsSql({ dialect }) from @splithub/node.\n * Anything else: load the experiment's exposures and the goal's events and\n * return attributeVariants(events, experiment, goal).\n * Columns worth keeping: id (unique, dedupe on it), type, experiment, variant,\n * goal, visitor_id, session_id, ts, url, props (json), received_at, host,\n * country, device, browser.\n */\nexport function customStore(): Store {\n return {\n async insertEvents(events: StoredEvent[]): Promise<number> {\n // Insert, skipping ids that already exist. Return how many were inserted.\n throw new Error('implement insertEvents ' + events.length);\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n // Per variant: exposures, conversions, revenueSum and revenueSumSq (per-visitor revenue).\n // Load the exposures of this experiment and the events of this goal, then apply the shared rule.\n const events: StoredEvent[] = [];\n if (events.length === 0) throw new Error('implement variantCounts ' + experiment + ' ' + goal);\n return attributeVariants(events, experiment, goal);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).\n throw new Error('implement summaries');\n },\n };\n}\n`;\n\nexport function storeTemplate(db: DbKind): string | null {\n return db === 'postgres' ? PG_STORE : db === 'mysql' ? MYSQL_STORE : db === 'custom' ? CUSTOM_STORE : null;\n}\n\n/** Import line + factory call used by the route template. */\nexport function storeUsage(db: DbKind, storeImport: string): { imports: string; factory: string } {\n switch (db) {\n case 'postgres':\n return { imports: `import { pgStore } from '${storeImport}';`, factory: 'pgStore()' };\n case 'mysql':\n return { imports: `import { mysqlStore } from '${storeImport}';`, factory: 'mysqlStore()' };\n case 'custom':\n return { imports: `import { customStore } from '${storeImport}';`, factory: 'customStore()' };\n default:\n return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };\n }\n}\n\nexport function runtimePackages(db: DbKind): string[] {\n return db === 'postgres' ? ['pg'] : db === 'mysql' ? ['mysql2'] : db === 'sqlite' ? ['@splithub/adapter-sqlite'] : [];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,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