splithub 0.2.2 → 0.3.0

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 (93) hide show
  1. package/dist/{chunk-PLZRB3VX.js → chunk-4LE4SCWY.js} +2 -2
  2. package/dist/{chunk-7EB5WOYE.js → chunk-4PUFNQ5F.js} +4 -4
  3. package/dist/{chunk-ZND3T67D.js → chunk-4YXB73AZ.js} +2 -2
  4. package/dist/{chunk-IFCSJYXN.js → chunk-A3FYDTIP.js} +2 -2
  5. package/dist/{chunk-AZJEZFOB.js → chunk-BNZFC2DQ.js} +16 -13
  6. package/dist/chunk-BNZFC2DQ.js.map +1 -0
  7. package/dist/{chunk-LK3NRAHA.js → chunk-C3ZJEZDE.js} +8 -8
  8. package/dist/{chunk-5VFCW4FI.js → chunk-EQCMCULO.js} +5 -5
  9. package/dist/{chunk-BQAWJPIK.js → chunk-HK267YK2.js} +5 -1
  10. package/dist/chunk-HK267YK2.js.map +1 -0
  11. package/dist/{chunk-6OXCLYOI.js → chunk-J5ZUSS43.js} +3 -2
  12. package/dist/chunk-J5ZUSS43.js.map +1 -0
  13. package/dist/{chunk-XVWJZJSF.js → chunk-JBPVGBLN.js} +19 -6
  14. package/dist/chunk-JBPVGBLN.js.map +1 -0
  15. package/dist/{chunk-ECV5QR6H.js → chunk-NHRWXNB5.js} +5 -5
  16. package/dist/{chunk-NTAIRQP6.js → chunk-PMER7I7F.js} +3 -3
  17. package/dist/{chunk-EJC4E3VD.js → chunk-PP3RLIJP.js} +1 -1
  18. package/dist/chunk-PP3RLIJP.js.map +1 -0
  19. package/dist/{chunk-IGYK7N2F.js → chunk-QKOATM5G.js} +7 -7
  20. package/dist/{chunk-D7KVM4L7.js → chunk-TIL2VQX4.js} +2 -2
  21. package/dist/{chunk-BSWCWCYP.js → chunk-U3QRNSLM.js} +3 -3
  22. package/dist/{chunk-VKLZJRYW.js → chunk-VSMWYVJ2.js} +4 -4
  23. package/dist/{chunk-X5AV7YBR.js → chunk-WTUZFXXJ.js} +5 -5
  24. package/dist/{ci-4OC23DTI.js → ci-KFSOM2AF.js} +4 -4
  25. package/dist/create-POZWP6JT.js +18 -0
  26. package/dist/dev-3SPMTW3T.js +11 -0
  27. package/dist/doctor-OHZEXUGO.js +14 -0
  28. package/dist/{holdout-OKHR2CKW.js → holdout-OYKY6UIE.js} +4 -4
  29. package/dist/index.js +31 -27
  30. package/dist/index.js.map +1 -1
  31. package/dist/init-4PNOZUIZ.js +15 -0
  32. package/dist/lifecycle-3QVRQRHM.js +12 -0
  33. package/dist/{login-ZEIH7KIH.js → login-AETAL2DO.js} +4 -4
  34. package/dist/{menu-4X5S37OK.js → menu-PBZVBCGA.js} +19 -19
  35. package/dist/{plan-QLYHRYCV.js → plan-Q2EZSSAO.js} +4 -4
  36. package/dist/push-7EELDSKG.js +16 -0
  37. package/dist/{refs-IWZ5GP7Q.js → refs-VPQ7WIRJ.js} +5 -5
  38. package/dist/{remove-YDJ7JTPR.js → remove-IPLTQIFK.js} +6 -6
  39. package/dist/{report-JS7Z42FD.js → report-TOWSAQYM.js} +4 -4
  40. package/dist/results-SMBCREVI.js +17 -0
  41. package/dist/{review-BGGNVL6L.js → review-HMBIZ6V2.js} +3 -3
  42. package/dist/{ship-C22SGFUD.js → ship-LKSCUDAE.js} +6 -6
  43. package/dist/skills-5ZAMIVP3.js +18 -0
  44. package/dist/status-7LDIKVX7.js +12 -0
  45. package/dist/{update-SAHMBHIZ.js → update-R4L7ZP5G.js} +3 -3
  46. package/package.json +3 -3
  47. package/dist/chunk-6OXCLYOI.js.map +0 -1
  48. package/dist/chunk-AZJEZFOB.js.map +0 -1
  49. package/dist/chunk-BQAWJPIK.js.map +0 -1
  50. package/dist/chunk-EJC4E3VD.js.map +0 -1
  51. package/dist/chunk-XVWJZJSF.js.map +0 -1
  52. package/dist/create-NCBDS2YG.js +0 -18
  53. package/dist/dev-7FXVGFL6.js +0 -11
  54. package/dist/doctor-E4KLPZZI.js +0 -14
  55. package/dist/init-PFNPS6XO.js +0 -15
  56. package/dist/lifecycle-G7OAC4ZZ.js +0 -12
  57. package/dist/push-3NDLL7US.js +0 -16
  58. package/dist/results-HCXQH7IY.js +0 -17
  59. package/dist/skills-UBPQOTDQ.js +0 -18
  60. package/dist/status-6IODQYHV.js +0 -12
  61. /package/dist/{chunk-PLZRB3VX.js.map → chunk-4LE4SCWY.js.map} +0 -0
  62. /package/dist/{chunk-7EB5WOYE.js.map → chunk-4PUFNQ5F.js.map} +0 -0
  63. /package/dist/{chunk-ZND3T67D.js.map → chunk-4YXB73AZ.js.map} +0 -0
  64. /package/dist/{chunk-IFCSJYXN.js.map → chunk-A3FYDTIP.js.map} +0 -0
  65. /package/dist/{chunk-LK3NRAHA.js.map → chunk-C3ZJEZDE.js.map} +0 -0
  66. /package/dist/{chunk-5VFCW4FI.js.map → chunk-EQCMCULO.js.map} +0 -0
  67. /package/dist/{chunk-ECV5QR6H.js.map → chunk-NHRWXNB5.js.map} +0 -0
  68. /package/dist/{chunk-NTAIRQP6.js.map → chunk-PMER7I7F.js.map} +0 -0
  69. /package/dist/{chunk-IGYK7N2F.js.map → chunk-QKOATM5G.js.map} +0 -0
  70. /package/dist/{chunk-D7KVM4L7.js.map → chunk-TIL2VQX4.js.map} +0 -0
  71. /package/dist/{chunk-BSWCWCYP.js.map → chunk-U3QRNSLM.js.map} +0 -0
  72. /package/dist/{chunk-VKLZJRYW.js.map → chunk-VSMWYVJ2.js.map} +0 -0
  73. /package/dist/{chunk-X5AV7YBR.js.map → chunk-WTUZFXXJ.js.map} +0 -0
  74. /package/dist/{ci-4OC23DTI.js.map → ci-KFSOM2AF.js.map} +0 -0
  75. /package/dist/{create-NCBDS2YG.js.map → create-POZWP6JT.js.map} +0 -0
  76. /package/dist/{dev-7FXVGFL6.js.map → dev-3SPMTW3T.js.map} +0 -0
  77. /package/dist/{doctor-E4KLPZZI.js.map → doctor-OHZEXUGO.js.map} +0 -0
  78. /package/dist/{holdout-OKHR2CKW.js.map → holdout-OYKY6UIE.js.map} +0 -0
  79. /package/dist/{init-PFNPS6XO.js.map → init-4PNOZUIZ.js.map} +0 -0
  80. /package/dist/{lifecycle-G7OAC4ZZ.js.map → lifecycle-3QVRQRHM.js.map} +0 -0
  81. /package/dist/{login-ZEIH7KIH.js.map → login-AETAL2DO.js.map} +0 -0
  82. /package/dist/{menu-4X5S37OK.js.map → menu-PBZVBCGA.js.map} +0 -0
  83. /package/dist/{plan-QLYHRYCV.js.map → plan-Q2EZSSAO.js.map} +0 -0
  84. /package/dist/{push-3NDLL7US.js.map → push-7EELDSKG.js.map} +0 -0
  85. /package/dist/{refs-IWZ5GP7Q.js.map → refs-VPQ7WIRJ.js.map} +0 -0
  86. /package/dist/{remove-YDJ7JTPR.js.map → remove-IPLTQIFK.js.map} +0 -0
  87. /package/dist/{report-JS7Z42FD.js.map → report-TOWSAQYM.js.map} +0 -0
  88. /package/dist/{results-HCXQH7IY.js.map → results-SMBCREVI.js.map} +0 -0
  89. /package/dist/{review-BGGNVL6L.js.map → review-HMBIZ6V2.js.map} +0 -0
  90. /package/dist/{ship-C22SGFUD.js.map → ship-LKSCUDAE.js.map} +0 -0
  91. /package/dist/{skills-UBPQOTDQ.js.map → skills-5ZAMIVP3.js.map} +0 -0
  92. /package/dist/{status-6IODQYHV.js.map → status-7LDIKVX7.js.map} +0 -0
  93. /package/dist/{update-SAHMBHIZ.js.map → update-R4L7ZP5G.js.map} +0 -0
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  fail
4
- } from "./chunk-EJC4E3VD.js";
4
+ } from "./chunk-PP3RLIJP.js";
5
5
 
6
6
  // src/project.ts
7
7
  import { existsSync, readFileSync, readdirSync, statSync } from "fs";
@@ -131,4 +131,4 @@ export {
131
131
  grepLines,
132
132
  grepFiles
133
133
  };
134
- //# sourceMappingURL=chunk-PLZRB3VX.js.map
134
+ //# sourceMappingURL=chunk-4LE4SCWY.js.map
@@ -2,13 +2,13 @@
2
2
  import {
3
3
  fetchStatus,
4
4
  resolveTarget
5
- } from "./chunk-ZND3T67D.js";
5
+ } from "./chunk-4YXB73AZ.js";
6
6
  import {
7
7
  detectProject
8
- } from "./chunk-PLZRB3VX.js";
8
+ } from "./chunk-4LE4SCWY.js";
9
9
  import {
10
10
  c
11
- } from "./chunk-EJC4E3VD.js";
11
+ } from "./chunk-PP3RLIJP.js";
12
12
 
13
13
  // src/commands/dev.ts
14
14
  import { spawn } from "child_process";
@@ -69,4 +69,4 @@ async function dev(flags) {
69
69
  export {
70
70
  dev
71
71
  };
72
- //# sourceMappingURL=chunk-7EB5WOYE.js.map
72
+ //# sourceMappingURL=chunk-4PUFNQ5F.js.map
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  CliError,
4
4
  fail
5
- } from "./chunk-EJC4E3VD.js";
5
+ } from "./chunk-PP3RLIJP.js";
6
6
 
7
7
  // src/credentials.ts
8
8
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
@@ -178,4 +178,4 @@ export {
178
178
  fetchPlan,
179
179
  fetchSkills
180
180
  };
181
- //# sourceMappingURL=chunk-ZND3T67D.js.map
181
+ //# sourceMappingURL=chunk-4YXB73AZ.js.map
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  c
4
- } from "./chunk-EJC4E3VD.js";
4
+ } from "./chunk-PP3RLIJP.js";
5
5
 
6
6
  // src/update.ts
7
7
  import { execSync, spawn } from "child_process";
@@ -261,4 +261,4 @@ export {
261
261
  updateFlow,
262
262
  versionReport
263
263
  };
264
- //# sourceMappingURL=chunk-IFCSJYXN.js.map
264
+ //# sourceMappingURL=chunk-A3FYDTIP.js.map
@@ -6,18 +6,18 @@ import {
6
6
  loadConfig,
7
7
  readSource,
8
8
  writeConfigChecked
9
- } from "./chunk-6OXCLYOI.js";
9
+ } from "./chunk-J5ZUSS43.js";
10
10
  import {
11
11
  componentVariantTemplate
12
- } from "./chunk-BQAWJPIK.js";
12
+ } from "./chunk-HK267YK2.js";
13
13
  import {
14
14
  requireConfig
15
- } from "./chunk-PLZRB3VX.js";
15
+ } from "./chunk-4LE4SCWY.js";
16
16
  import {
17
17
  c,
18
18
  fail,
19
19
  printJson
20
- } from "./chunk-EJC4E3VD.js";
20
+ } from "./chunk-PP3RLIJP.js";
21
21
 
22
22
  // src/commands/create.ts
23
23
  import * as p from "@clack/prompts";
@@ -95,7 +95,7 @@ async function create(flags) {
95
95
  for (const raw of list(flags.factor)) {
96
96
  const eq = raw.indexOf("=");
97
97
  if (eq <= 0) fail("INVALID_FLAG", `--factor expects name=level:value,level:value, got "${raw}".`);
98
- const name = raw.slice(0, eq).trim();
98
+ const name2 = raw.slice(0, eq).trim();
99
99
  const levels = {};
100
100
  for (const part of raw.slice(eq + 1).split(",")) {
101
101
  const colon = part.indexOf(":");
@@ -103,18 +103,18 @@ async function create(flags) {
103
103
  if (!level) continue;
104
104
  levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;
105
105
  }
106
- factors[name] = levels;
106
+ factors[name2] = levels;
107
107
  }
108
108
  while (interactive && Object.keys(factors).length === 0) {
109
- const name = await ask(p.text({ message: "Factor name (what changes), e.g. headline", validate: (v) => !KEY.test(v) ? "lowercase a-z 0-9 - _ only" : void 0 }));
110
- const levelsRaw = await ask(p.text({ message: `Levels of "${name}" as key:value, comma separated (first = control)`, placeholder: "old:Old headline, new:New headline" }));
109
+ const name2 = await ask(p.text({ message: "Factor name (what changes), e.g. headline", validate: (v) => !KEY.test(v) ? "lowercase a-z 0-9 - _ only" : void 0 }));
110
+ const levelsRaw = await ask(p.text({ message: `Levels of "${name2}" as key:value, comma separated (first = control)`, placeholder: "old:Old headline, new:New headline" }));
111
111
  const levels = {};
112
112
  for (const part of levelsRaw.split(",")) {
113
113
  const colon = part.indexOf(":");
114
114
  const level = (colon >= 0 ? part.slice(0, colon) : part).trim();
115
115
  if (level) levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;
116
116
  }
117
- factors[name] = levels;
117
+ factors[name2] = levels;
118
118
  while (await ask(p.confirm({ message: "Add another factor?", initialValue: false }))) {
119
119
  const more = await ask(p.text({ message: "Factor name", validate: (v) => !KEY.test(v) ? "lowercase a-z 0-9 - _ only" : void 0 }));
120
120
  const moreRaw = await ask(p.text({ message: `Levels of "${more}" as key:value, comma separated`, placeholder: "blue:#2563eb, green:#16a34a" }));
@@ -187,12 +187,15 @@ async function create(flags) {
187
187
  const status = str(flags.status) ?? "running";
188
188
  if (!["draft", "running", "paused"].includes(status)) fail("INVALID_FLAG", `A new experiment can't be "${status}".`, "Use --status running or --status draft.");
189
189
  const description = str(flags.description);
190
+ const name = str(flags.name)?.trim() || void 0;
191
+ if (name && name.length > 80) fail("INVALID_FLAG", "The name is longer than 80 characters.", "Use a shorter --name; the key stays the id.");
190
192
  const experiment = {
191
193
  key: id,
192
194
  kind,
193
195
  status,
194
196
  goal,
195
197
  match,
198
+ name,
196
199
  description,
197
200
  variants: mvt ? mvt.variants.map((v) => ({ key: v.key, weight: v.weight })) : variantKeys.map((k, i) => ({ key: k, weight: weights[i], value: values[k], to: tos[k] })),
198
201
  ...mvt ? { factors } : {},
@@ -213,11 +216,11 @@ async function create(flags) {
213
216
  const dir = join(project.root, project.hasSrc ? "src/splithub" : "splithub", id);
214
217
  mkdirSync(dir, { recursive: true });
215
218
  for (const k of variantKeys) {
216
- const name = `${pascal(id)}${pascal(k)}`;
217
- componentNames[k] = name;
219
+ const name2 = `${pascal(id)}${pascal(k)}`;
220
+ componentNames[k] = name2;
218
221
  const file = join(dir, `${pascal(k)}.tsx`);
219
222
  if (!existsSync(file)) {
220
- writeFileSync(file, componentVariantTemplate(name, id, k), "utf8");
223
+ writeFileSync(file, componentVariantTemplate(name2, id, k), "utf8");
221
224
  files.push(relative(project.root, file));
222
225
  }
223
226
  }
@@ -323,4 +326,4 @@ export {
323
326
  parseLimits,
324
327
  parseExtras
325
328
  };
326
- //# sourceMappingURL=chunk-AZJEZFOB.js.map
329
+ //# sourceMappingURL=chunk-BNZFC2DQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/create.ts"],"sourcesContent":["import * as p from '@clack/prompts';\nimport { mvtVariants, type ExperimentKind, type ExperimentStatus } from '@splithub/core';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { ensureLayer, hasExperiment, insertExperiment, loadConfig, readSource, writeConfigChecked, type NewExperiment } from '../config-file';\nimport { fail, printJson } from '../errors';\nimport { requireConfig } from '../project';\nimport { componentVariantTemplate } from '../templates';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\nfunction list(v: unknown): string[] {\n if (Array.isArray(v)) return v.map(String);\n if (typeof v === 'string') return [v];\n return [];\n}\nfunction parsePairs(items: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of items) {\n const i = item.indexOf('=');\n if (i > 0) out[item.slice(0, i).trim()] = item.slice(i + 1);\n }\n return out;\n}\nfunction pascal(s: string): string {\n return s.replace(/(^|[-_])([a-z0-9])/g, (_, __, ch: string) => ch.toUpperCase());\n}\n\nasync function ask<T>(promise: Promise<T | symbol>): Promise<T> {\n const v = await promise;\n if (p.isCancel(v)) {\n p.cancel('Cancelled.');\n process.exit(0);\n }\n return v as T;\n}\n\nexport async function create(flags: Flags): Promise<void> {\n const json = Boolean(flags.json);\n const yes = Boolean(flags.yes);\n const project = requireConfig();\n const config = await loadConfig(project.configFile);\n const source = readSource(project.configFile);\n const interactive = !yes && !json;\n\n if (interactive) p.intro(c.bold('splithub create'));\n\n let kind = str(flags.kind) as ExperimentKind | undefined;\n if (!kind) {\n if (!interactive) fail('USAGE', 'Which kind? Pass --kind value|component|redirect|mvt.');\n kind = await ask(\n p.select<ExperimentKind>({\n message: 'What changes between variants?',\n options: [\n { value: 'value', label: 'Text, image URL, number', hint: 'no new components' },\n { value: 'component', label: 'Layout / structure', hint: 'one component per variant' },\n { value: 'redirect', label: 'A whole page', hint: 'needs @splithub/next middleware' },\n { value: 'mvt', label: 'Several things at once', hint: 'multivariate: every combination, each factor read on its own' },\n ],\n })\n );\n }\n\n let id = str(flags.id);\n if (!id) {\n if (!interactive) fail('USAGE', 'Which id? Pass --id <key>, e.g. --id hero-title.');\n id = await ask(\n p.text({\n message: 'Experiment id',\n placeholder: 'hero-title',\n validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : hasExperiment(source, v) ? 'already exists' : undefined),\n })\n );\n }\n if (!['value', 'component', 'redirect', 'mvt'].includes(kind)) fail('INVALID_FLAG', `Unknown kind \"${kind}\".`, 'Use --kind value, component, redirect or mvt.');\n if (!KEY.test(id)) fail('INVALID_FLAG', `\"${id}\" isn't a valid id.`, 'Use lowercase a-z, 0-9, - and _, at most 64 characters.');\n if (hasExperiment(source, id) || config.experiments.some((e) => e.key === id)) fail('EXPERIMENT_EXISTS', `There's already an experiment \"${id}\".`, 'Pick another id: an old id keeps its history.');\n const limits = parseLimits(flags);\n\n // Multivariate: --factor headline=old:Old,new:New (repeatable); the variants are the combinations.\n const factors: Record<string, Record<string, string>> = {};\n if (kind === 'mvt') {\n for (const raw of list(flags.factor)) {\n const eq = raw.indexOf('=');\n if (eq <= 0) fail('INVALID_FLAG', `--factor expects name=level:value,level:value, got \"${raw}\".`);\n const name = raw.slice(0, eq).trim();\n const levels: Record<string, string> = {};\n for (const part of raw.slice(eq + 1).split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (!level) continue;\n levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n }\n while (interactive && Object.keys(factors).length === 0) {\n const name = await ask(p.text({ message: 'Factor name (what changes), e.g. headline', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const levelsRaw = await ask(p.text({ message: `Levels of \"${name}\" as key:value, comma separated (first = control)`, placeholder: 'old:Old headline, new:New headline' }));\n const levels: Record<string, string> = {};\n for (const part of levelsRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) levels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[name] = levels;\n while (await ask(p.confirm({ message: 'Add another factor?', initialValue: false }))) {\n const more = await ask(p.text({ message: 'Factor name', validate: (v) => (!KEY.test(v) ? 'lowercase a-z 0-9 - _ only' : undefined) }));\n const moreRaw = await ask(p.text({ message: `Levels of \"${more}\" as key:value, comma separated`, placeholder: 'blue:#2563eb, green:#16a34a' }));\n const moreLevels: Record<string, string> = {};\n for (const part of moreRaw.split(',')) {\n const colon = part.indexOf(':');\n const level = (colon >= 0 ? part.slice(0, colon) : part).trim();\n if (level) moreLevels[level] = colon >= 0 ? part.slice(colon + 1).trim() : level;\n }\n factors[more] = moreLevels;\n }\n }\n if (Object.keys(factors).length === 0) fail('USAGE', 'An mvt experiment needs factors.', 'Pass --factor name=level:value,level:value once per factor.');\n if (flags.variants || flags.weights) fail('INVALID_FLAG', 'An mvt experiment takes --factor, not --variants or --weights.', 'Its variants are every combination of the factor levels, split equally.');\n }\n let mvt: ReturnType<typeof mvtVariants> | null = null;\n try {\n mvt = kind === 'mvt' ? mvtVariants(id, factors) : null;\n } catch (error) {\n fail('INVALID_FLAG', error instanceof Error ? error.message : String(error), 'At most 4 factors × 4 levels, 16 combinations.');\n }\n\n let variantKeys = mvt ? mvt.variants.map((v) => v.key) : str(flags.variants)?.split(',').map((s) => s.trim()).filter(Boolean);\n if (!variantKeys || variantKeys.length < 2) {\n if (!interactive) variantKeys = ['control', 'b'];\n else {\n const v = await ask(p.text({ message: 'Variant keys, comma separated (first = control)', initialValue: 'control, b' }));\n variantKeys = v.split(',').map((s) => s.trim()).filter(Boolean);\n }\n }\n for (const k of variantKeys) if (!KEY.test(k)) fail('INVALID_FLAG', `\"${k}\" isn't a valid variant key.`, 'Use lowercase a-z, 0-9, - and _.');\n if (variantKeys.length < 2) fail('INVALID_FLAG', 'An experiment needs at least 2 variants.', 'Pass --variants control,b.');\n if (new Set(variantKeys).size !== variantKeys.length) fail('INVALID_FLAG', 'Two variants have the same key.');\n\n const weights = mvt ? variantKeys.map(() => 1) : parseWeights(str(flags.weights), variantKeys.length);\n\n const values = parsePairs(list(flags.value));\n const tos = parsePairs(list(flags.to));\n if (kind === 'value' && interactive) {\n for (const k of variantKeys) {\n if (values[k] === undefined) values[k] = await ask(p.text({ message: `Value for \"${k}\"`, placeholder: k === variantKeys[0] ? 'current text' : 'new text' }));\n }\n }\n let match = str(flags.match);\n if (kind === 'redirect') {\n if (!match) {\n if (!interactive) fail('USAGE', 'A redirect experiment needs the path it runs on.', 'Pass --match /path.');\n match = await ask(p.text({ message: 'Path to run the redirect test on', initialValue: '/' }));\n }\n for (const k of variantKeys) {\n if (tos[k] === undefined) {\n if (!interactive) tos[k] = k === variantKeys[0] ? match : `${match.replace(/\\/$/, '')}/${k}`;\n else tos[k] = await ask(p.text({ message: `URL for \"${k}\"`, initialValue: k === variantKeys[0] ? match : '' }));\n }\n }\n }\n\n let goal = str(flags.goal);\n const goals = config.goals.map((g) => g.key);\n if (!goal) {\n if (!interactive) goal = goals[0];\n else if (goals.length > 0) {\n goal = await ask(\n p.select<string>({\n message: 'Goal (conversion) to optimise',\n options: [...goals.map((g) => ({ value: g, label: g })), { value: '', label: 'none yet (add later)' }],\n })\n );\n if (!goal) goal = undefined;\n }\n }\n if (goal && !goals.includes(goal)) fail('GOAL_NOT_FOUND', `There's no goal \"${goal}\" in the config.`, `Declared goals: ${goals.join(', ') || 'none'}. Add it to goals first.`);\n const extras = parseExtras(flags, goals, goal);\n\n // Running by default: the test goes live with the deploy that ships its code, first page views included.\n const status = (str(flags.status) as ExperimentStatus | undefined) ?? 'running';\n if (!['draft', 'running', 'paused'].includes(status)) fail('INVALID_FLAG', `A new experiment can't be \"${status}\".`, 'Use --status running or --status draft.');\n const description = str(flags.description);\n const name = str(flags.name)?.trim() || undefined;\n if (name && name.length > 80) fail('INVALID_FLAG', 'The name is longer than 80 characters.', 'Use a shorter --name; the key stays the id.');\n\n const experiment: NewExperiment = {\n key: id,\n kind,\n status,\n goal,\n match,\n name,\n description,\n variants: mvt ? mvt.variants.map((v) => ({ key: v.key, weight: v.weight })) : variantKeys.map((k, i) => ({ key: k, weight: weights[i]!, value: values[k], to: tos[k] })),\n ...(mvt ? { factors } : {}),\n ...limits,\n ...extras,\n };\n\n await writeConfigChecked(project.configFile, source, insertExperiment(extras.layer ? ensureLayer(source, extras.layer.key) : source, experiment), (loaded) => {\n const e = loaded.experiments.find((x) => x.key === id);\n if (!e) return `\"${id}\" is not in the file after the write`;\n if (e.status !== status) return `\"${id}\" loads as ${e.status}, not ${status}`;\n if (limits.minDays !== undefined && e.minDays !== limits.minDays) return `\"${id}\" loads with minDays ${e.minDays ?? 'unset'}, not ${limits.minDays}`;\n if (limits.goodSample !== undefined && e.goodSample !== limits.goodSample) return `\"${id}\" loads with goodSample ${e.goodSample ?? 'unset'}, not ${limits.goodSample}`;\n return null;\n });\n\n const files: string[] = [];\n const componentNames: Record<string, string> = {};\n if (kind === 'component') {\n const dir = join(project.root, project.hasSrc ? 'src/splithub' : 'splithub', id);\n mkdirSync(dir, { recursive: true });\n for (const k of variantKeys) {\n const name = `${pascal(id)}${pascal(k)}`;\n componentNames[k] = name;\n const file = join(dir, `${pascal(k)}.tsx`);\n if (!existsSync(file)) {\n writeFileSync(file, componentVariantTemplate(name, id, k), 'utf8');\n files.push(relative(project.root, file));\n }\n }\n }\n\n const snippet =\n kind === 'mvt'\n ? `const { ${Object.keys(factors).join(', ')} } = useValue<{ ${Object.keys(factors).map((f) => `${f}: string`).join('; ')} }>('${id}');`\n : kind === 'value'\n ? `const value = useValue<string>('${id}');`\n : kind === 'component'\n ? `<Experiment id=\"${id}\">\\n${variantKeys.map((k) => ` <Variant name=\"${k}\"><${componentNames[k]} /></Variant>`).join('\\n')}\\n</Experiment>`\n : `// handled by @splithub/next middleware on ${match}; no code needed`;\n\n const result = { experiment: id, kind, status, variants: experiment.variants, goal: goal ?? null, traffic: limits.traffic ?? 1, maxVisitors: limits.maxExposures ?? null, minDays: limits.minDays ?? null, goodSample: limits.goodSample ?? null, schedule: limits.schedule ?? null, configFile: relative(project.root, project.configFile), files, snippet };\n if (json) {\n const cloudMode = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n // Agents read this JSON: the hand-off line makes sure the human learns the test is not live yet.\n const handoff =\n status === 'draft'\n ? `${id} is a draft: visitors do not see it and nothing is recorded until it is started. Tell the user and ask whether to start it now (npx splithub start ${id}).`\n : `${id} is running in the config: it goes live for visitors when this code is deployed${cloudMode ? ' and pushed; local development never sends events to the cloud' : ''}. Tell the user, and that npx splithub pause ${id} or Pause in the dashboard holds it.`;\n const nextStep = cloudMode ? `npx splithub push # the cloud does not know about ${id} until you push` : status === 'draft' ? `npx splithub start ${id}` : 'deploy the app';\n printJson({ ...result, nextStep, handoff });\n return;\n }\n p.note(snippet, kind === 'redirect' ? 'Nothing to wire' : 'Wire it in your code');\n if (files.length) p.note(files.join('\\n'), 'Scaffolded');\n const cloud = /mode\\s*:\\s*['\"]cloud['\"]/.test(readSource(project.configFile));\n if (cloud) p.log.warn(`Cloud mode: the cloud does not know about it until you run ${c.cyan('npx splithub push')}.`);\n if (status === 'draft') p.log.warn(`${c.bold(id)} is a draft: visitors do not see it and nothing is recorded until you start it.`);\n if (status === 'running') p.log.info(`${c.bold(id)} goes live when you deploy this code. Check it first with ${c.cyan(`?sh_force=${id}:<variant>`)}; ${c.cyan(`npx splithub pause ${id}`)} holds it.`);\n if (status === 'draft') p.log.info(`See it before you start it: ${c.cyan('runDraftsInDev: true')} in the config serves drafts in development, ${c.cyan(`?sh_force=${id}:<variant>`)} shows one variant anywhere.`);\n p.outro(`Added ${c.bold(id)} (${status}) to ${relative(project.root, project.configFile)}. ${status === 'running' ? '' : `Start it with ${c.cyan(`npx splithub start ${id}`)}. `}${cloud ? `Then ${c.cyan('npx splithub push')}.` : ''}`);\n}\n\n/** --weights 50,50: one non-negative number per variant, not all zero. Equal weights when absent. */\nexport function parseWeights(raw: string | undefined, count: number): number[] {\n if (!raw) return Array.from({ length: count }, () => 1);\n const weights = raw.split(',').map((w) => Number(w.trim()));\n if (weights.length !== count) fail('INVALID_FLAG', `--weights has ${weights.length} numbers for ${count} variants.`, 'Give one weight per variant, in the same order: --weights 50,50.');\n if (weights.some((w) => !Number.isFinite(w) || w < 0)) fail('INVALID_FLAG', `--weights \"${raw}\" has a value that isn't a number of 0 or more.`);\n if (weights.every((w) => w === 0)) fail('INVALID_FLAG', 'All weights are 0, so nobody would see the test.');\n return weights;\n}\n\nexport interface Limits {\n traffic?: number;\n maxExposures?: number;\n minDays?: number;\n goodSample?: number;\n schedule?: { startAt: string | null; endAt: string | null };\n}\n\n/** --traffic (percent, 0 < t <= 100), --max-visitors (whole number > 0), --min-days (whole number 0..30), --good-sample (whole number 100..10,000,000), --start / --end (dates, start before end). */\nexport function parseLimits(flags: Flags): Limits {\n const out: Limits = {};\n const traffic = str(flags.traffic);\n if (traffic !== undefined) {\n const t = Number(traffic.replace(/%$/, ''));\n if (!Number.isFinite(t) || t <= 0 || t > 100) fail('INVALID_FLAG', `--traffic \"${traffic}\" must be a percent between 0 and 100.`, 'For example --traffic 50 puts half of the visitors in the test.');\n if (t !== 100) out.traffic = Math.round(t * 100) / 10000;\n }\n const max = str(flags['max-visitors']);\n if (max !== undefined) {\n const m = Number(max);\n if (!Number.isInteger(m) || m <= 0) fail('INVALID_FLAG', `--max-visitors \"${max}\" must be a whole number above 0.`);\n out.maxExposures = m;\n }\n const minDays = str(flags['min-days']);\n if (minDays !== undefined) {\n const d = Number(minDays);\n if (!Number.isInteger(d) || d < 0 || d > 30) fail('INVALID_FLAG', `--min-days \"${minDays}\" must be a whole number from 0 to 30.`, 'It is the fewest days before a verdict; 0 means none, the default.');\n out.minDays = d;\n }\n const good = str(flags['good-sample']);\n if (good !== undefined) {\n const g = Number(good);\n if (!Number.isInteger(g) || g < 100 || g > 10_000_000) fail('INVALID_FLAG', `--good-sample \"${good}\" must be a whole number from 100 to 10,000,000.`, 'It is the total visitors at which the sample counts as good; the default is 5000.');\n out.goodSample = g;\n }\n const date = (name: 'start' | 'end'): string | null => {\n const v = str(flags[name]);\n if (v === undefined) return null;\n const ms = Date.parse(v);\n if (Number.isNaN(ms)) fail('INVALID_FLAG', `--${name} \"${v}\" isn't a date.`, 'Use an ISO date like 2026-11-01 or 2026-11-01T09:00:00Z.');\n return new Date(ms).toISOString();\n };\n const startAt = date('start');\n const endAt = date('end');\n if (startAt && endAt && Date.parse(endAt) <= Date.parse(startAt)) fail('INVALID_FLAG', '--end must be after --start.');\n if (startAt || endAt) out.schedule = { startAt, endAt };\n return out;\n}\n\n/**\n * --secondary a,b (goals to watch) · --guardrail refunds:higher,errors (goals that must not get worse;\n * :higher when a rise is bad, default :lower) · --layer key:0-50 (mutual exclusion, buckets [start, end)).\n */\nexport function parseExtras(flags: Flags, goals: string[], primary: string | undefined): Pick<NewExperiment, 'metrics' | 'layer'> {\n const out: Pick<NewExperiment, 'metrics' | 'layer'> = {};\n const split = (v: unknown) => list(v).flatMap((x) => x.split(',')).map((x) => x.trim()).filter(Boolean);\n const secondary = split(flags.secondary);\n const guardrails = split(flags.guardrail).map((g) => {\n const [goal = '', worse] = g.split(':');\n if (worse !== undefined && worse !== 'lower' && worse !== 'higher') fail('INVALID_FLAG', `--guardrail \"${g}\": after the colon comes lower or higher.`, 'refunds:higher means more refunds is worse; signups (or signups:lower) means fewer is worse.');\n return worse === 'higher' ? { goal, worse: 'higher' as const } : goal;\n });\n const named = [...secondary, ...guardrails.map((g) => (typeof g === 'string' ? g : g.goal))];\n if (named.length) {\n if (!primary) fail('USAGE', 'Secondary metrics and guardrails need a primary goal.', 'Pass --goal too.');\n for (const g of named) if (!goals.includes(g)) fail('GOAL_NOT_FOUND', `There's no goal \"${g}\" in the config.`, `Declared goals: ${goals.join(', ') || 'none'}. Add it to goals first.`);\n const all = [primary, ...named];\n if (new Set(all).size !== all.length) fail('INVALID_FLAG', 'A goal is listed twice across --goal, --secondary and --guardrail.');\n out.metrics = { ...(secondary.length ? { secondary } : {}), ...(guardrails.length ? { guardrails } : {}) };\n }\n const layer = str(flags.layer);\n if (layer) {\n const m = /^([a-z0-9][a-z0-9_-]{0,63}):(\\d{1,3})-(\\d{1,3})$/.exec(layer);\n const start = Number(m?.[2]);\n const end = Number(m?.[3]);\n if (!m || !(start < end) || end > 100) fail('INVALID_FLAG', `--layer \"${layer}\" must look like key:start-end with 0 <= start < end <= 100.`, 'For example --layer checkout:0-50; another test in checkout:50-100 never shares a visitor.');\n out.layer = { key: m[1]!, range: [start, end] };\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,OAAO;AACnB,SAAS,mBAA+D;AACxE,SAAS,YAAY,WAAW,qBAAqB;AACrD,SAAS,MAAM,gBAAgB;AAQ/B,IAAM,MAAM;AAEZ,SAAS,IAAI,GAAgC;AAC3C,SAAO,OAAO,MAAM,YAAY,EAAE,SAAS,IAAI,IAAI;AACrD;AACA,SAAS,KAAK,GAAsB;AAClC,MAAI,MAAM,QAAQ,CAAC,EAAG,QAAO,EAAE,IAAI,MAAM;AACzC,MAAI,OAAO,MAAM,SAAU,QAAO,CAAC,CAAC;AACpC,SAAO,CAAC;AACV;AACA,SAAS,WAAW,OAAyC;AAC3D,QAAM,MAA8B,CAAC;AACrC,aAAW,QAAQ,OAAO;AACxB,UAAM,IAAI,KAAK,QAAQ,GAAG;AAC1B,QAAI,IAAI,EAAG,KAAI,KAAK,MAAM,GAAG,CAAC,EAAE,KAAK,CAAC,IAAI,KAAK,MAAM,IAAI,CAAC;AAAA,EAC5D;AACA,SAAO;AACT;AACA,SAAS,OAAO,GAAmB;AACjC,SAAO,EAAE,QAAQ,uBA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AO;AACT;","names":["name"]}
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  deviceLogin
4
- } from "./chunk-BSWCWCYP.js";
4
+ } from "./chunk-U3QRNSLM.js";
5
5
  import {
6
6
  installSkills,
7
7
  loadSkillFiles
8
- } from "./chunk-X5AV7YBR.js";
8
+ } from "./chunk-WTUZFXXJ.js";
9
9
  import {
10
10
  configTemplate,
11
11
  nextMiddlewareTemplate,
12
12
  nextRouteTemplate
13
- } from "./chunk-BQAWJPIK.js";
13
+ } from "./chunk-HK267YK2.js";
14
14
  import {
15
15
  cloudTarget,
16
16
  loadCredential
17
- } from "./chunk-ZND3T67D.js";
17
+ } from "./chunk-4YXB73AZ.js";
18
18
  import {
19
19
  writeWorkflow
20
- } from "./chunk-NTAIRQP6.js";
20
+ } from "./chunk-PMER7I7F.js";
21
21
  import {
22
22
  detectProject,
23
23
  installCommand
24
- } from "./chunk-PLZRB3VX.js";
24
+ } from "./chunk-4LE4SCWY.js";
25
25
  import {
26
26
  c
27
- } from "./chunk-EJC4E3VD.js";
27
+ } from "./chunk-PP3RLIJP.js";
28
28
 
29
29
  // src/commands/init.ts
30
30
  import * as p from "@clack/prompts";
@@ -391,4 +391,4 @@ function cancel2() {
391
391
  export {
392
392
  init
393
393
  };
394
- //# sourceMappingURL=chunk-LK3NRAHA.js.map
394
+ //# sourceMappingURL=chunk-C3ZJEZDE.js.map
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  analysisLine
4
- } from "./chunk-VKLZJRYW.js";
4
+ } from "./chunk-VSMWYVJ2.js";
5
5
  import {
6
6
  fetchStatus,
7
7
  resolveTarget
8
- } from "./chunk-ZND3T67D.js";
8
+ } from "./chunk-4YXB73AZ.js";
9
9
  import {
10
10
  detectProject
11
- } from "./chunk-PLZRB3VX.js";
11
+ } from "./chunk-4LE4SCWY.js";
12
12
  import {
13
13
  bar,
14
14
  c,
@@ -18,7 +18,7 @@ import {
18
18
  table,
19
19
  verdictColor,
20
20
  verdictIcon
21
- } from "./chunk-EJC4E3VD.js";
21
+ } from "./chunk-PP3RLIJP.js";
22
22
 
23
23
  // src/commands/status.ts
24
24
  async function status(flags) {
@@ -72,4 +72,4 @@ ${c.dim(next)}`);
72
72
  export {
73
73
  status
74
74
  };
75
- //# sourceMappingURL=chunk-5VFCW4FI.js.map
75
+ //# sourceMappingURL=chunk-EQCMCULO.js.map
@@ -209,6 +209,10 @@ combinations and, below them, each factor summed over its combinations). With li
209
209
  ## Create an experiment
210
210
 
211
211
  1. \`npx splithub create --kind <value|component|redirect|mvt> --id <key> \u2026 --goal <goal> --yes --json\` (see the table).
212
+ The key is the test's id for good: never reuse one from an earlier test. \`--name "Signup button"\` adds a human
213
+ name (dashboard, CLI) that can change any time. \`push\` fails with \`KEY_CONFLICT\` when a key already belongs to
214
+ another test: ask the user, then rename the key, or push with \`--replace <key>\` (new test, old numbers cleared)
215
+ or \`--same <key>\` (same test). \`KEY_DELETED\`: a deleted test used the key; pick a new one.
212
216
  2. Goal: pick an existing key or add one to \`goals\`:
213
217
  \`{ type: 'event' }\` + \`track('<goal>')\` where the conversion happens; \`{ type: 'pageview', path: '/thanks' }\`;
214
218
  \`{ type: 'click', selector: '#buy' }\` (tracked automatically by the SDK and the script).
@@ -564,4 +568,4 @@ export {
564
568
  AGENTS_SECTION,
565
569
  CURSOR_RULE
566
570
  };
567
- //# sourceMappingURL=chunk-BQAWJPIK.js.map
571
+ //# sourceMappingURL=chunk-HK267YK2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/skills-self-hosted.ts","../src/skills-ship.ts","../src/skills.ts","../src/templates.ts"],"sourcesContent":["// Skill: SplitHub with the user's own database (self mode) and reporting from the cloud.\n// Bundled fallback; SplitHub Cloud serves the current text at GET /v1/skills.\nexport const SKILL_SELF_HOSTED = `---\nname: splithub-self-hosted\ndescription: Keep SplitHub events in your own database (self mode): which tables, how to write a Store for Postgres, MySQL, Prisma, Drizzle, Supabase or anything else, where the ingest route lives, how the CLI reads results from it, and how to get cloud data into your own database for reports. Use when the user wants data in their infra or asks about tables, schema or reporting.\n---\n\n# SplitHub with your own database\n\nTwo ways to own the data:\n\n1. **Self mode** — the app hosts the ingest route and the store; nothing leaves your infra.\n \\`splithub.config.ts\\`: \\`storage: { mode: 'self', endpoint: '/api/splithub' }\\`.\n2. **Cloud + export** — events go to SplitHub Cloud; you pull summaries into your warehouse for reports.\n\n## Self mode: the pieces\n\n- Route: \\`app/api/splithub/[[...path]]/route.ts\\` (Next.js) or any fetch-style handler from\n \\`createSplitHubHandler({ config, store, adminToken })\\` in \\`@splithub/node\\`. It accepts\n \\`POST /events\\` from the SDK and answers \\`GET /status\\`, \\`GET /results/<id>\\` for the CLI\n (\\`npx splithub status\\` talks to the local dev server, or \\`--url https://your.app/api/splithub\\`).\n Self-hosted reads are raw numbers per variant (\\`variants[]\\`: visitors, conversions, rate, revenue)\n with \\`analysis: { available: false }\\`. Verdicts, data-quality stars and recommendations come with SplitHub Cloud.\n- Store: an object with three methods (below). Ready-made: \\`@splithub/adapter-sqlite\\`\n (Node 22.13+, \\`node:sqlite\\`, zero setup) and \\`@splithub/adapter-d1\\` (Cloudflare D1).\n \\`npx splithub init --mode self --db postgres|mysql|custom\\` writes \\`splithub/store.ts\\` with a\n working Postgres (pg) or MySQL (mysql2) store, or a documented stub for anything else.\n- Admin token: set \\`SPLITHUB_ADMIN_TOKEN\\` in the app and \\`--token\\` / \\`SPLITHUB_ADMIN_TOKEN\\` for\n the CLI, so results are not public.\n\n## The events table\n\nOne table, one row per event. Column names are yours; the templates use these:\n\n| column | type | meaning |\n|---|---|---|\n| id | text, primary key | client-generated, unique; dedupe on it (retries resend batches) |\n| type | text | \\`exposure\\` or \\`goal\\` |\n| experiment, variant | text | for exposures |\n| goal | text | for goals |\n| visitor_id, session_id | text | \\`sh_vid\\` cookie / session |\n| ts | bigint | client time, unix ms |\n| url | text | page |\n| props | json | goal payload, e.g. \\`{ \"revenue\": 49 }\\` |\n| received_at | bigint | server time, unix ms |\n| host, country, device, browser | text | request metadata (fill from headers if you want breakdowns) |\n\nIndexes: \\`(type, experiment, visitor_id, ts)\\` and \\`(type, goal, visitor_id, ts)\\`.\n\n## The Store interface (\\`@splithub/node\\`)\n\n\\`\\`\\`ts\ninterface Store {\n insertEvents(events: StoredEvent[]): Promise<number>; // skip existing ids, return inserted count\n variantCounts(experiment: string, goal: string): Promise<VariantCounts[]>; // per variant: exposures, conversions, revenue\n summaries(): Promise<ExperimentSummary[]>; // per experiment: exposures, visitors, first/last ts\n close?(): Promise<void> | void;\n}\n\\`\\`\\`\n\nAttribution rule — keep it exactly, so self-hosted results equal the cloud's:\n**a visitor converts for a variant when they sent the goal at or after their first exposure to\nthat variant; exposures and conversions count unique visitors.** The SQL in the generated\n\\`splithub/store.ts\\` implements it (CTE \\`first_exposure\\`, then goals joined with \\`ts >= first_ts\\`).\n\nPrisma / Drizzle: map the table in your schema and write the three methods with the ORM, or run the\none raw query for \\`variantCounts\\`. Supabase: the same SQL as a Postgres function called through\n\\`rpc\\`. Mongo: \\`$group\\` by variant and visitor with \\`$min ts\\`, then \\`$lookup\\` goals.\n\n## Reports from the cloud into your database\n\n- CSV: dashboard → experiment → Export (summary, daily timeline, raw events up to 50k rows).\n- Webhook channel for alerts and the digest: POST JSON to your endpoint when something happens.\n- Scheduled pull: a cron in your app calls \\`GET /v1/status\\` and \\`GET /v1/results/<id>\\` with the\n API key (\\`sk_…\\`) and stores the verdicts. Raw events live 30–90 days in the cloud (plan dependent),\n aggregates a year: pull summaries, not raw rows, for long-term reporting.\n- Need every raw event forever in your infra? Use self mode; one store per project.\n\n## Do not\n\n- Put database credentials in \\`splithub.config.ts\\` (it ships to the browser). They belong in the route's env.\n- Call a winner from raw rates: a higher rate is often noise. Say the numbers as they are; verdicts come with SplitHub Cloud.\n`;\n","// Skills: ship the winner (`splithub ship`) and the full agent loop. Installed next\n// to the other skills by `splithub init` / `splithub skills`.\n\nexport const SKILL_SHIP = `---\nname: splithub-ship\ndescription: Ship the winner of an A/B test and remove the test from the code: keep only the winning value, component or page, delete the losing variants, finish the experiment and clean splithub.config.ts. Use when a test has a verdict and the user says ship it, roll out the winner, remove the test, or clean up; and whenever a test shows status finished and the user agreed on which variant to keep.\n---\n\n# Shipping the winner\n\nGoal: the app behaves exactly as the kept variant did, with no experiment left in the code or in the config.\n\n## 1. Decide\n\n\\`npx splithub results <id> --json\\` (MCP: \\`splithub_results\\`). Act on \\`verdict.status\\`:\n- \\`winner_found\\`: keep \\`verdict.winner\\`.\n- \\`no_significant_difference\\`: keep the control, or the simpler variant if the user agrees.\n- \\`insufficient_sample\\`: do not ship. Say when to look again: \\`daysToVerdict\\` days at the current traffic.\n- \\`srm_detected\\`: do not ship. The split is broken; fix the setup first.\n- \\`guardrail_breached\\`: do not ship the variant in \\`verdict.guardrailBreached\\`; it made a guardrail worse. Say what broke.\nAsk the user which variant to keep before going on. Never pick from raw rates.\n\n## 2. Preview, then ship\n\n\\`\\`\\`bash\nnpx splithub ship <id> --keep <variant> --dry-run --json # diff + leftovers, nothing written\nnpx splithub ship <id> --keep <variant> --json # apply\n\\`\\`\\`\nMCP: \\`splithub_ship\\` with \\`dryRun: true\\`, then without. It archives the test in the cloud (numbers stay readable), removes it from\n\\`splithub.config.ts\\` (checked by reloading the file) and rewrites the code:\n- \\`<Experiment id>\\` → the kept \\`<Variant>\\`'s children; the other variants are dropped.\n- \\`useValue('<id>')\\` / \\`sh.value('<id>')\\` → the kept value as a literal.\n- \\`useVariant('<id>')\\` comparisons, ternaries, \\`&&\\`, \\`if\\` and \\`switch\\` → the kept branch.\n- Unused \\`Experiment\\`, \\`Variant\\`, \\`useVariant\\`, \\`useValue\\` imports go.\n\n## 3. Finish by hand\n\n- \\`leftovers[]\\`: each \\`{ file, line, text, reason }\\` still mentions the experiment; rewrite those yourself.\n- component kind: delete components and files only the losing variants used (e.g. \\`splithub/<id>/\\`).\n- redirect kind: make the kept URL the real page (move the route or add a permanent redirect), delete the other page.\n- Goal: keep \\`track('<goal>')\\` when another test measures it (\\`next\\` says so); otherwise ask before removing it.\n- Cloud mode: \\`npx splithub push\\`. Then \\`npx splithub doctor\\` and the project's typecheck and tests.\n- \\`npx splithub refs <id> --json\\` must return \\`count: 0\\` for the experiment.\n\nReport what changed (files, the kept content) and the verdict in one line with its numbers. Never reuse the id.\n`;\n\nexport const SKILL_LOOP = `---\nname: splithub-loop\ndescription: The whole A/B test loop for an agent with SplitHub, step by step with the MCP tools and CLI --json fields: plan, create, implement, check, push, read results, finish, ship. Use when the user asks to run an A/B test end to end, or to pick up a test where it stands.\n---\n\n# The full loop\n\nEach step: MCP tool, or the CLI with \\`--json\\` (one line of JSON; errors are \\`{ error, code, hint }\\`, exit 1).\n\n| step | MCP tool | CLI | read |\n|---|---|---|---|\n| 0. size it | \\`splithub_plan\\` | \\`plan --baseline 0.05 --mde 0.1 [<id>]\\` | \\`perVariant\\`, \\`total\\`, \\`traffic.daysLeft\\` |\n| 1. create | \\`splithub_create_experiment\\` | \\`create --kind … --id … --goal … --yes\\` | \\`snippet\\`, \\`files\\`, \\`nextStep\\`, \\`handoff\\` |\n| 2. implement | (edit code) | | wire \\`snippet\\`; \\`track('<goal>')\\` where it converts |\n| 3. check | \\`splithub_doctor\\`, \\`splithub_refs\\` | \\`doctor\\`, \\`refs <id>\\` | \\`ok\\`, \\`checks[]\\`; \\`refs[]\\` shows the wiring |\n| 4. push (cloud) | \\`splithub_push\\` | \\`push\\` (\\`--dry-run\\` to preview) | \\`adopted\\`, \\`diff\\` |\n| 5. results | \\`splithub_status\\`, \\`splithub_results\\` | \\`status\\`, \\`results <id>\\` | \\`verdict.status\\`, \\`verdict.message\\`, \\`verdict.notes[]\\`, \\`daysToVerdict\\` |\n| 6. finish | \\`splithub_set_status\\` | \\`finish <id>\\` | \\`live\\`, \\`next\\` |\n| 7. ship | \\`splithub_ship\\` | \\`ship <id> --keep <v> [--dry-run]\\` | \\`diff\\`, \\`leftovers[]\\`, \\`next\\` |\n\nRules that keep the answer honest:\n- Plan before creating: if \\`traffic.daysLeft\\` is months, test a bigger change or a busier page.\n- \\`create\\` writes a running test; it goes live when the code is deployed (and pushed in cloud mode). Tell the user.\n- Verdicts are sequential (always-valid): checking any day is safe. Quote \\`verdict.message\\` and the always-valid\n \\`comparisons[].sequential.pValue\\`, not the fixed-horizon \\`pValue\\` (p = 0.01 there can still be not significant).\n Relay \\`verdict.notes[]\\`. Verdicts depend on sample size, not days. Say \\`verdict.sample.quality\\` (small | ok | good;\n good = every variant has its share of \\`goodSample\\`, default 5000 visitors, \\`create --good-sample\\`) next to the verdict.\n- \\`daysToVerdict\\` is the re-check date: schedule (or tell the user) a look in that many days instead of polling.\n- \\`srm_detected\\`: the split is broken; fix the setup, do not read the numbers.\n- \\`guardrail_breached\\`: don't ship. A variant made a guardrail worse (\\`verdict.guardrailBreached[]\\`), e.g. \"bold wins on\n signups but raises refunds\". \\`verdict.metrics[]\\` has the secondary metrics and guardrails, read like the main table.\n- Guard what matters when creating: \\`--secondary pricing_view --guardrail refunds:higher\\` (MCP: \\`secondary\\`, \\`guardrails\\`).\n Tests that could clash on one page go in one layer: \\`--layer checkout:0-50\\` and \\`checkout:50-100\\` never share a visitor.\n- \\`splithub holdout set 5\\` keeps 5% of visitors out of every test; the \\`__holdout\\` row (\"Holdout: long-term impact\")\n compares them with everyone else.\n- Ask the user which variant to keep before \\`ship\\`; preview with \\`dryRun\\` and show them the diff.\n- Error \\`code\\` → action: \\`NOT_LOGGED_IN\\` → \\`splithub_login\\`, show the link, wait, retry · \\`INSUFFICIENT_SCOPE\\` → the key\n can only read; ask for a key with write scope · \\`NO_CONFIG\\` → \\`splithub_init\\` ·\n \\`EXPERIMENT_NOT_FOUND\\` → \\`splithub_status\\` for ids · \\`CONFIG_UNSAFE\\` → edit the config by hand where the experiment is\n defined · \\`CONFIG_WRITE\\` → the file was restored; edit by hand, then \\`doctor\\`.\n`;\n","// Agent skills installed by `splithub init` / `splithub skills`. One folder per\n// topic under .claude/skills/, so an agent loads only what the task needs:\n// splithub — the library, the config file, the CLI, where things live\n// ab-testing — what a good test is, metrics, sample size, when to stop\n// splithub-api — the HTTP API (keys, endpoints, payloads) for scripts and servers\n// splithub-mcp — the MCP server: tools, how to register it in Claude Code / Cursor\n// splithub-ship — keep a variant and take the test out (`splithub ship`)\n// splithub-loop — the whole loop for an agent, tool by tool\n// Same text goes to .cursor/rules and the AGENTS.md section points here.\n\nexport interface Skill {\n dir: string;\n body: string;\n}\n\nexport const SKILL_SPLITHUB = `---\nname: splithub\ndescription: Add, change, run or read A/B experiments in an app that uses SplitHub (@splithub/react, splithub.config.ts, the splithub CLI, SplitHub Cloud). Use when the user asks to A/B test a component, headline, image, price, CTA or page, asks which variant is winning, or wants to start, pause or finish a test.\n---\n\n# SplitHub for coding agents\n\nThree pieces: \\`splithub.config.ts\\` (the experiments; source of truth when it exists),\n\\`@splithub/react\\` (renders variants), the \\`splithub\\` CLI (creates, pushes, reads results).\nEvents go to the app's own database (self mode) or to SplitHub Cloud (cloud mode).\n\n## Where things live\n\n- Config: \\`splithub.config.ts\\` in the project root. Experiments and goals. Ships to the browser: never put secrets in it.\n- Credentials: \\`npx splithub login\\` (or \\`init --mode cloud\\`) prints a link; the human approves it in the browser; the CLI\n stores a project API key for this folder. Never ask the user to paste keys. CI uses \\`SPLITHUB_API_KEY\\`.\n- The public key (\\`pk_\\`) ends up in \\`storage.key\\` of the config from any of: \\`login\\` (saved credentials), the first\n \\`push\\`, \\`init --key\\`, or \\`SPLITHUB_API_KEY\\` in the environment (init asks the cloud). Missing key = events go nowhere.\n- Cloud: \\`npx splithub push\\` uploads the config; \\`npx splithub pull\\` writes dashboard-created experiments into the file.\n- Results: \\`npx splithub status --json\\`, \\`npx splithub results <id> --json\\`. Sizing: \\`npx splithub plan --baseline 0.05 --mde 0.1\\`.\n- Code that uses a test: \\`npx splithub refs <id> --json\\`. Keep a variant and remove the test: \\`npx splithub ship <id> --keep <v>\\`.\n- \\`--json\\` prints one line; errors are \\`{ error, code, hint }\\` with exit code 1. The \\`splithub-loop\\` skill has the whole flow.\n- Everything interactive: \\`npx splithub\\` (menu). Everything scriptable: subcommands + \\`--json\\`.\n\n## Pick the kind\n\n| kind | use it when | create | read in code |\n|---|---|---|---|\n| \\`value\\` | only data changes: text, number, image URL, price, JSON. The default choice: no new components. | \\`--variants control,bold --value control=\"Old text\" --value bold=\"New text\"\\` | \\`const text = useValue<string>('<id>')\\`; server components: \\`getValue\\` from \\`@splithub/next\\`; no SDK: \\`sh.value('<id>')\\` |\n| \\`component\\` | structure changes: a layout, a section, a flow, a different component per variant | \\`--variants control,bold\\` (the CLI scaffolds \\`splithub/<id>/<Variant>.tsx\\` stubs) | \\`<Experiment id=\"<id>\"><Variant name=\"control\">…</Variant><Variant name=\"bold\">…</Variant></Experiment>\\`, or \\`useVariant('<id>')\\` in a switch |\n| \\`redirect\\` | a whole page changes: another URL per variant | \\`--match / --to control=/ --to v2=/home-v2\\` | nothing: \\`@splithub/next\\` middleware or the drop-in script \\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_…\">\\` sends visitors there |\n| \\`mvt\\` | several things change at once (headline × button × image) and the user wants to know which of them matters; every combination is tested and each factor is read on its own | \\`--factor headline=old:\"Old text\",new:\"New text\" --factor button=blue:#2563eb,green:#16a34a\\` (no \\`--variants\\`; first level = control; at most 4 factors × 4 levels, 16 combinations) | \\`const { headline, button } = useValue<{ headline: string; button: string }>('<id>')\\` |\n\nmvt needs more visitors than an A/B test: every combination must reach the minimum on its own (the results show the\ncombinations and, below them, each factor summed over its combinations). With little traffic, test one thing with \\`value\\`.\n\n## Create an experiment\n\n1. \\`npx splithub create --kind <value|component|redirect|mvt> --id <key> … --goal <goal> --yes --json\\` (see the table).\n The key is the test's id for good: never reuse one from an earlier test. \\`--name \"Signup button\"\\` adds a human\n name (dashboard, CLI) that can change any time. \\`push\\` fails with \\`KEY_CONFLICT\\` when a key already belongs to\n another test: ask the user, then rename the key, or push with \\`--replace <key>\\` (new test, old numbers cleared)\n or \\`--same <key>\\` (same test). \\`KEY_DELETED\\`: a deleted test used the key; pick a new one.\n2. Goal: pick an existing key or add one to \\`goals\\`:\n \\`{ type: 'event' }\\` + \\`track('<goal>')\\` where the conversion happens; \\`{ type: 'pageview', path: '/thanks' }\\`;\n \\`{ type: 'click', selector: '#buy' }\\` (tracked automatically by the SDK and the script).\n3. Wire it in code. \\`create\\` writes \\`status: 'running'\\`: the test goes live for every visitor, first page view\n included, as soon as this code is deployed. Use \\`--status draft\\` only when the user asks to hold it.\n4. Cloud mode: \\`npx splithub push\\` after any config change.\n5. Hand-off, always: end your reply by saying the test is **running in the config** and goes live when the user deploys\n this code; nothing is recorded before that, and local development never sends events to the cloud. Tell them how to\n check it locally (\\`?sh_force=<id>:<variant>\\`) and that Pause in the dashboard or \\`npx splithub pause <id>\\` holds it.\n In cloud mode a status set in the dashboard wins over the file for every visitor, first page included.\n For a draft (only if asked): say visitors do not see it and nothing is recorded until \\`npx splithub start <id>\\`.\n\nA draft is invisible to visitors. To check one before starting: \\`runDraftsInDev: true\\` at the top level of the config\nserves drafts like running tests in development only (\\`NODE_ENV=development\\`: \\`next dev\\`, \\`vite\\`);\n\\`?sh_force=<id>:<variant>\\` shows one variant on any page, draft or not, without recording an exposure;\n\\`?sh_debug=1\\` (or \\`npx splithub dev\\`) logs every decision and opens a panel to switch variants.\nIn development the SDK explains drafts, paused tests and held-back events in one line each. Vite apps: add \\`splithub()\\`\nfrom \\`@splithub/core/vite\\` to the plugins in vite.config so these lines and a summary of every experiment appear in the\nterminal that runs \\`vite\\`; Next.js server code prints them in its terminal anyway.\n\nKeys: lowercase a-z 0-9 - _, max 64 chars. First variant = control. Weights are relative (50/50, 1/1, 90/10).\nTargeting (country, device, UTM, cookie, time) is a \\`flow\\` graph on the experiment, edited in the dashboard; \\`pull\\` brings it into the file.\n\n## Read results\n\n\\`verdict.status\\` ∈ no_data | insufficient_sample | srm_detected | winner_found | no_significant_difference.\nReport \\`verdict.message\\` verbatim and the numbers behind it (visitors per variant, lift, the always-valid\n\\`comparisons[].sequential.pValue\\` and \\`sequential.ci\\`; the plain \\`pValue\\` is fixed-horizon, for display only) and relay\n\\`verdict.notes[]\\`. Verdicts are sequential and depend on sample size, not days: safe to check any time. \\`verdict.sample.quality\\` is\nsmall (below 100 visitors per variant or 50 conversions), ok, or good (every variant has its share of \\`goodSample\\`, default 5000\nvisitors; \\`create --good-sample\\`); say it next to the verdict. \\`verdict.sample.stars\\` (0..5) scores data quality from\n\\`verdict.sample.checks[]\\`: report the stars and the unmet labels; they never override the verdict. \\`daysToVerdict\\` says when to look again.\nNever declare a winner from raw rates. \\`srm_detected\\` means the split is broken: fix the setup before anything else.\n\n## Finish, and what to do when a test is finished\n\n\\`npx splithub finish <id>\\` stops the test (live within a minute in cloud mode). A finished test keeps its numbers for as long\nas it stays in the config; the code still contains every variant until someone removes it.\n\nWhenever you see a test with \\`status: finished\\` (in \\`status\\`, \\`results\\`, the MCP tools, or right after you finished it):\n1. Read \\`npx splithub results <id> --json\\` and tell the user the verdict in one line with its numbers.\n2. Ask two questions, do not assume: **which variant to keep** (recommend \\`verdict.winner\\`; with no significant\n difference, the control or the simpler one) and **whether to remove the test from the code now**.\n3. On yes, follow the \\`splithub-ship\\` skill: \\`npx splithub ship <id> --keep <variant> --dry-run\\`, show the diff, then run it\n without \\`--dry-run\\`; fix the \\`leftovers\\`, \\`push\\` in cloud mode, run \\`doctor\\` and the project's checks.\n4. On no, leave everything: a finished test costs nothing and the user may come back to it.\n\nA \\`paused\\` test is not over: say so and ask whether to resume (\\`start\\`) or finish it.\n\n## Do not\n\n- Nest an \\`<Experiment>\\` inside a \\`<Variant>\\` of the same id; call hooks conditionally.\n- Change \\`seed\\`, weights or variants of a running experiment (reshuffles visitors). Create a new experiment instead.\n- Edit in the dashboard what the config file owns: file experiments are read-only there (pause/finish still work).\n- Run more than 2-3 experiments on one page of a low-traffic site.\n- Put secrets, API keys or database credentials in the config or in the browser. \\`pk_\\` is public, \\`sk_\\` is not.\n`;\n\nexport const SKILL_AB_TESTING = `---\nname: ab-testing\ndescription: How to design, run and read an A/B test correctly: hypothesis, control, primary metric, sample size, significance, SRM, peeking, when to stop. Use before creating an experiment or when interpreting results, with any tool.\n---\n\n# A/B testing, the parts that matter\n\nAn A/B test splits visitors at random into variants and compares one metric. It answers one question:\n\"does this change move this metric?\" Everything below exists to keep that answer honest.\n\n## Before creating a test\n\n1. **One hypothesis, one primary metric.** \"A shorter signup form raises signup completion.\" The metric is a goal\n (event, page visit or click) that happens after the exposure. Pick it before looking at data.\n2. **Control first.** The first variant is what exists today. Change one thing per variant; several unrelated changes\n in one variant cannot be attributed.\n3. **Traffic reality.** Rough rule: to detect a relative lift L on a baseline rate p you need about\n \\`16 · p(1-p) / (p·L)²\\` visitors per variant (95% confidence, 80% power).\n Examples: baseline 5%, lift 20% → ~7,600 per variant; baseline 2%, lift 10% → ~78,000 per variant.\n If the site cannot reach that in 2-4 weeks, test a bigger change or a higher-traffic page.\n4. **Few tests per page.** Interactions between simultaneous tests on the same page muddy both.\n\n## While it runs\n\n- **Do not peek and stop early.** Checking daily and stopping at the first \"significant\" moment inflates false\n positives several times. Decide the sample or the duration up front; run whole weeks (weekday/weekend cycles).\n- **SRM (sample ratio mismatch).** If the split is 50/50 and you see 60/40, the assignment or the tracking is broken\n (bots, caching, redirect loops, a variant that errors). Fix first; results from an SRM run are meaningless.\n- **Keep variants frozen.** Changing copy, weights or targeting mid-run reshuffles who saw what. Start a new test.\n- **Watch the guardrails.** A variant that wins the primary metric but breaks revenue, errors or latency is not a win.\n\n## Reading results\n\n- Significance (p < 0.05 after correction for several variants) says the difference is unlikely to be noise;\n the confidence interval says how big it plausibly is. A \"winner\" with a CI that touches 0 is a weak win.\n- \"No significant difference\" with a sample smaller than needed means **keep running**, not \"no effect\".\n With enough sample it means the change does not matter: ship whichever is cheaper or cleaner.\n- Relative lift is on the baseline rate: 5% → 6% is +20% relative, +1 point absolute. Report both.\n- Attribution: conversions count only after the visitor's first exposure, per unique visitor.\n- Segments (country, device) are for hypotheses, not verdicts: slicing after the fact finds noise.\n\n## When to stop\n\n- Winner found with the planned sample → ship it, finish the test, remove the losing code.\n- Planned sample reached, no difference → ship the simpler variant, finish.\n- SRM or broken tracking → stop, fix, restart as a new test.\n- The business moved on → finish; do not leave tests running forever (they cost events and split traffic).\n\n## Vocabulary\n\nexposure = a visitor saw a variant · conversion = the goal happened after exposure · lift = relative change in rate ·\np-value = chance of seeing this difference by luck · CI = range the true difference likely lies in ·\nSRM = the split differs from the configured weights · guardrail = a metric that must not get worse.\n`;\n\nexport const SKILL_SPLITHUB_API = `---\nname: splithub-api\ndescription: Use the SplitHub Cloud HTTP API directly: public key event ingest, API-key endpoints for config, status, results and overrides, hosted experiments. Use when writing a server, a script, a non-JS client, or when the CLI is not available.\n---\n\n# SplitHub Cloud API\n\nBase URL: \\`https://go.splithub.io\\`. JSON in, JSON out (no envelope under \\`/v1/*\\`). Two credentials:\n\n- **Public key \\`pk_…\\`**: identifies the project to browsers and SDKs. Safe to ship. Can only send events and read\n the public overrides JSON.\n- **API key \\`sk_…\\`**: project-scoped secret for servers, CI and the CLI (\\`npx splithub login\\` mints one through a\n browser approval; or Settings → API keys in the dashboard). Never in client code.\n\n## Send events (public key)\n\n\\`\\`\\`http\nPOST /v1/events\nAuthorization: Bearer pk_live_…\nContent-Type: application/json\n\n{ \"project\": \"my-app\", \"sdk\": \"custom/1.0\", \"events\": [\n { \"id\": \"e_01h…\", \"type\": \"exposure\", \"exp\": \"hero-cta\", \"var\": \"bold\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000000000, \"url\": \"/\" },\n { \"id\": \"g_01h…\", \"type\": \"goal\", \"goal\": \"signup\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000010000, \"props\": { \"revenue\": 49 } }\n] }\n\\`\\`\\`\n\n- \\`id\\`: unique per event (8-64 chars, [a-z0-9_-]); duplicates are ignored. \\`vid\\`: stable visitor id (cookie \\`sh_vid\\`).\n- Reply \\`202 { ok, received, inserted, dropped }\\`. A project with nothing running or no config yet answers\n \\`202 { ok, inserted: 0, idle: 'no_running' | 'no_config' }\\`: nothing stored, not an error. \\`429\\` with \\`code\\` ∈\n quota_exceeded | deleted: back off for \\`Retry-After\\` seconds; nothing was stored. \\`403 origin_not_allowed\\` when the project restricts domains.\n- Exposures for experiments that are not running are dropped and not billed. Goals are never billed.\n\n## Live config for clients (public key)\n\n\\`GET /v1/overrides/<pk>.json\\` → \\`{ version, experiments: { <id>: { status?, traffic?, weights?, values? } }, added: [ …hosted experiments… ], goals: [...], ctx: { country, region, city } }\\`.\nPoll it at most once a minute; the SDK caches it in localStorage. \\`ctx\\` is the visitor's geo for targeting.\n\n## Project endpoints (API key)\n\n\\`\\`\\`http\nGET /v1/status every experiment: status, visitors, days, verdict headline\nGET /v1/results/<experiment> full verdict: sample, comparisons (lift, p-value, CI, P(beat)), srm, winner\nGET /v1/config the config stored in the cloud (file + dashboard experiments)\nPUT /v1/config { config } push a normalized config (what defineConfig returns); answers cloudOnly experiments to adopt\nGET /v1/overrides live overrides\nPUT /v1/overrides/<experiment> { status | traffic | weights | values } pause / resume / reweight without a deploy\nDELETE /v1/overrides/<experiment>\n\\`\\`\\`\n\n\\`Authorization: Bearer sk_live_…\\` on each. Status values: draft | running | paused | finished.\n\n## Dashboard-scope endpoints (session, same shapes the dashboard uses)\n\nUnder \\`/v1/projects/<projectId>/…\\` with a user session: \\`experiments\\` (hosted experiments CRUD incl. \\`flow\\` targeting),\n\\`goals\\`, \\`timeline\\`, \\`breakdown\\`, \\`realtime\\`, \\`events\\`, \\`export\\`, \\`notes\\`, \\`domains\\`, \\`links\\`, \\`alerts\\`, \\`billing\\`, \\`ai\\`.\nScripts should prefer the API-key endpoints above; the session ones exist for the UI.\n\n## Drop-in script (no SDK)\n\n\\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_live_…\"></script>\\` in \\`<head>\\`: redirect experiments, page-visit and\nclick goals from the cloud config, \\`window.splithub.track('goal')\\` for custom events,\n\\`<meta name=\"splithub-experiment\" content=\"<id>\">\\` on a tested page for an instant decision.\n\n## Errors\n\n\\`400\\` validation (message in \\`error\\`), \\`401\\` bad key, \\`403\\` forbidden, \\`404\\` unknown experiment/project, \\`409\\` state\n(e.g. \\`config_not_pushed\\`, \\`file_owned\\`), \\`429\\` gate or rate limit. Bodies: \\`{ error, code? }\\`.\n`;\n\nexport const SKILL_SPLITHUB_MCP = `---\nname: splithub-mcp\ndescription: Use or set up the SplitHub MCP server (@splithub/mcp) so an agent can create experiments, read verdicts, start/pause/finish tests and push config through tools instead of shelling out. Use when the user asks to connect SplitHub to Claude Code, Cursor, Codex or another MCP client.\n---\n\n# SplitHub MCP server\n\n\\`@splithub/mcp\\` is a stdio MCP server that wraps the \\`splithub\\` CLI for the current project folder.\nSame credentials and config file as the CLI; nothing extra to configure.\n\n## Register it\n\nClaude Code (project scope, committed in \\`.mcp.json\\`):\n\n\\`\\`\\`json\n{ \"mcpServers\": { \"splithub\": { \"command\": \"npx\", \"args\": [\"-y\", \"@splithub/mcp\"] } } }\n\\`\\`\\`\n\nor \\`claude mcp add splithub -- npx -y @splithub/mcp\\`. Cursor: the same object in \\`.cursor/mcp.json\\`.\nCodex / other clients: command \\`npx\\`, args \\`-y @splithub/mcp\\`. \\`npx splithub skills --mcp\\` writes both files.\nEnv: \\`SPLITHUB_PROJECT_DIR\\` (defaults to the MCP client's working directory), \\`SPLITHUB_API\\` (staging or self-hosted cloud), \\`SPLITHUB_API_KEY\\` (CI).\n\n## Tools\n\n| tool | does | notes |\n|---|---|---|\n| \\`splithub_status\\` | all experiments with verdict headline | start here |\n| \\`splithub_results\\` | full verdict for one experiment | report \\`verdict.message\\` verbatim; \\`daysToVerdict\\` = when to check again |\n| \\`splithub_review\\` | stored AI reviews (Pro): at start, on verdict changes, on finish, on demand | quote them as the analyst's opinion, the verdict stays the source of truth |\n| \\`splithub_plan\\` | visitors per variant for a baseline and a lift; days at an experiment's traffic | before creating |\n| \\`splithub_create_experiment\\` | adds an experiment to splithub.config.ts | kind value / component / redirect / mvt, id, variants (or factors for mvt), goal, values/to, weights, traffic, maxVisitors, start/end; running by default |\n| \\`splithub_refs\\` | files and lines that use an experiment and its goal | check the wiring, find leftovers |\n| \\`splithub_ship\\` | finish, remove from the config, rewrite the code to the kept variant | \\`dryRun: true\\` first; returns \\`diff\\` and \\`leftovers\\` |\n| \\`splithub_remove\\` | removes an experiment from the config (finished in the cloud) | when the code is already clean |\n| \\`splithub_projects\\` | every folder on this machine connected to a cloud project | |\n| \\`splithub_set_status\\` | start / pause / finish | applies live in cloud mode; after \\`finished\\`, ask which variant to keep and whether to clean the code (splithub-ship skill) |\n| \\`splithub_push\\` / \\`splithub_pull\\` | sync the config with the cloud | pull adopts dashboard-created experiments |\n| \\`splithub_doctor\\` | checks the installation | run after wiring code |\n| \\`splithub_login\\` | returns a sign-in link; the human approves it in the browser | show the link, then call \\`splithub_whoami\\` |\n| \\`splithub_whoami\\` | connected project and keys | |\n\n## Working rules\n\n- Create (running by default) → wire in code → \\`doctor\\` → \\`push\\` (cloud mode) → tell the user it goes live when they\n deploy this code and that \\`set_status paused\\` or Pause in the dashboard holds it.\n- Results: never call a winner from raw rates; quote the verdict. \\`srm_detected\\` = fix the setup first.\n- Running experiments are frozen: no weight / variant / seed edits; create a new one.\n- Errors carry a \\`code\\`. \\`NOT_LOGGED_IN\\`: call \\`splithub_login\\`, show the link to the user, wait for them, then retry.\n- The whole loop (plan → create → implement → doctor → push → results → finish → ship) is in the \\`splithub-loop\\` skill.\n- A \\`finished\\` experiment in \\`splithub_status\\` or \\`splithub_results\\` means the test is over but its code is still there: report\n the verdict, ask which variant to keep and whether to remove the test from the code, then follow the \\`splithub-ship\\` skill.\n`;\n\nexport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nimport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nexport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\nimport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\n\nexport const SKILLS: Skill[] = [\n { dir: 'splithub', body: SKILL_SPLITHUB },\n { dir: 'ab-testing', body: SKILL_AB_TESTING },\n { dir: 'splithub-api', body: SKILL_SPLITHUB_API },\n { dir: 'splithub-mcp', body: SKILL_SPLITHUB_MCP },\n { dir: 'splithub-self-hosted', body: SKILL_SELF_HOSTED },\n { dir: 'splithub-ship', body: SKILL_SHIP },\n { dir: 'splithub-loop', body: SKILL_LOOP },\n];\n\nexport const MCP_SERVER_ENTRY = { command: 'npx', args: ['-y', '@splithub/mcp'] };\n","export function configTemplate(project: string, mode: 'self' | 'cloud', key?: string): string {\n const storage = mode === 'self' ? `{ mode: 'self', endpoint: '/api/splithub' }` : `{ mode: 'cloud', key: ${key ? `'${key}'` : \"process.env.NEXT_PUBLIC_SPLITHUB_KEY ?? ''\"} }`;\n return `import { defineConfig } from '@splithub/core';\n\n// SplitHub experiments. This file is the source of truth: the SDK, the CLI\n// and the dashboard all read it. Keys: lowercase a-z 0-9 - _. First variant = control.\nexport default defineConfig({\n project: '${project}',\n storage: ${storage},\n // Drafts behave like running tests while you develop (next dev, vite); production ignores them.\n runDraftsInDev: true,\n\n goals: {\n // call track('signup') where the conversion happens\n signup: { type: 'event' },\n },\n\n experiments: {\n // run \\`npx splithub create\\` or add entries here:\n //\n // 'hero-title': {\n // kind: 'value',\n // status: 'running',\n // variants: {\n // control: { weight: 50, value: 'Ship faster' },\n // direct: { weight: 50, value: 'Know which version wins' },\n // },\n // goal: 'signup',\n // },\n },\n});\n`;\n}\n\nexport function nextMiddlewareTemplate(configImport: string): string {\n return `import { splithubMiddleware } from '@splithub/next';\nimport splithub from '${configImport}';\n\n// Sets the visitor cookie, forwards it to Server Components and serves\n// redirect experiments with an invisible rewrite.\nexport default splithubMiddleware(splithub);\n\nexport const config = {\n matcher: ['/((?!_next|api|.*\\\\\\\\..*).*)'],\n};\n`;\n}\n\nexport function nextRouteTemplate(configImport: string, store: { imports: string; factory: string } = { imports: \"import { sqliteStore } from '@splithub/adapter-sqlite';\", factory: \"sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })\" }): string {\n return `import { createSplitHubHandler } from '@splithub/node';\n${store.imports}\nimport config from '${configImport}';\n\n// Self-hosted ingest + results: events stay in your database. The CLI reads\n// status / results from this route; set SPLITHUB_ADMIN_TOKEN to protect it.\nconst handler = createSplitHubHandler({\n config,\n store: ${store.factory},\n adminToken: process.env.SPLITHUB_ADMIN_TOKEN,\n});\n\nexport const POST = handler;\nexport const GET = handler;\nexport const runtime = 'nodejs';\n`;\n}\n\nexport function componentVariantTemplate(name: string, experiment: string, variant: string): string {\n return `// Variant \"${variant}\" of experiment \"${experiment}\". Edit freely.\nexport function ${name}() {\n return (\n <section>\n <h2>${experiment} · ${variant}</h2>\n </section>\n );\n}\n`;\n}\n\nexport const AGENTS_SECTION = `\n## A/B testing (SplitHub)\n\nThis project uses SplitHub (\\`@splithub/react\\`). Experiments are declared in\n\\`splithub.config.ts\\` and rendered with \\`<Experiment id>\\` / \\`useVariant(id)\\` /\n\\`useValue(id)\\`. Conversions: \\`useTrack()\\` then \\`track('<goal>')\\`.\n\n- Not connected yet? \\`npx splithub init --mode cloud\\` (or \\`npx splithub login\\`) prints a link: show it to the user, they sign in and approve, the CLI gets the keys. Never ask the user to paste keys.\n- New experiment: \\`npx splithub create --kind value|component|redirect|mvt --id <key> --variants control,<other> --goal <goal> --yes\\`\n then wire it in code (value → \\`useValue\\`, component → \\`<Experiment>\\` with one \\`<Variant>\\` per key, redirect → nothing,\n mvt → \\`--factor name=level:value,…\\` and \\`const { a, b } = useValue(id)\\`).\n- Results: \\`npx splithub results <id> --json\\`; report \\`verdict.message\\` verbatim, never call a winner from raw rates.\n- Lifecycle: \\`npx splithub start|pause|finish <id>\\`. Check setup: \\`npx splithub doctor\\`.\n- A \\`finished\\` test still has all its variants in the code: report the verdict, ask which variant to keep and whether to\n remove the test from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete test code unasked.\n- \\`create\\` writes \\`status: 'running'\\`: the test goes live when the code is deployed. Always tell the user that, and that\n \\`npx splithub pause <id>\\` or Pause in the dashboard holds it. Never change \\`seed\\` of a running experiment.\n- Config ships to the browser: no secrets in it. Full rules: .claude/skills/splithub/SKILL.md\n`;\n\nexport { SKILL_SPLITHUB as SKILL_MD } from './skills';\nimport { SKILL_SPLITHUB } from './skills';\n\nexport const CURSOR_RULE = `---\ndescription: SplitHub A/B testing conventions\nglobs: [\"splithub.config.ts\", \"splithub/**\", \"**/*.tsx\"]\nalwaysApply: false\n---\n${SKILL_SPLITHUB.replace(/^---[\\s\\S]*?---\\n/, '')}`;\n"],"mappings":";;;AAEO,IAAM,oBAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACC1B,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAS,SAAS,gDAAgD,yBAAyB,MAAM,IAAI,GAAG,MAAM,4CAA4C;AAC1K,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA,cAKK,OAAO;AAAA,aACR,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwBpB;AAEO,SAAS,uBAAuB,cAA8B;AACnE,SAAO;AAAA,wBACe,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUpC;AAEO,SAAS,kBAAkB,cAAsB,QAA8C,EAAE,SAAS,2DAA2D,SAAS,oEAAoE,GAAW;AAClQ,SAAO;AAAA,EACP,MAAM,OAAO;AAAA,sBACO,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAMvB,MAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQxB;AAEO,SAAS,yBAAyB,MAAc,YAAoB,SAAyB;AAClG,SAAO,eAAe,OAAO,oBAAoB,UAAU;AAAA,kBAC3C,IAAI;AAAA;AAAA;AAAA,YAGV,UAAU,SAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAKnC;AAEO,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBvB,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,eAAe,QAAQ,qBAAqB,EAAE,CAAC;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  CliError,
4
4
  fail
5
- } from "./chunk-EJC4E3VD.js";
5
+ } from "./chunk-PP3RLIJP.js";
6
6
 
7
7
  // src/config-file.ts
8
8
  import { isSplitHubConfig } from "@splithub/core";
@@ -284,6 +284,7 @@ function renderExperiment(e, indent = " ") {
284
284
  lines.push(`${i2}metrics: { ${parts.join(", ")} },`);
285
285
  }
286
286
  if (e.layer) lines.push(`${i2}layer: { key: ${q(e.layer.key)}, range: [${e.layer.range[0]}, ${e.layer.range[1]}] },`);
287
+ if (e.name) lines.push(`${i2}name: ${q(e.name)},`);
287
288
  if (e.description) lines.push(`${i2}description: ${q(e.description)},`);
288
289
  if (e.flow) {
289
290
  const json = JSON.stringify(e.flow, null, 2).split("\n");
@@ -381,4 +382,4 @@ export {
381
382
  readSource,
382
383
  writeConfigChecked
383
384
  };
384
- //# sourceMappingURL=chunk-6OXCLYOI.js.map
385
+ //# sourceMappingURL=chunk-J5ZUSS43.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config-file.ts"],"sourcesContent":["import { isSplitHubConfig, type ExperimentKind, type ExperimentStatus, type SplitHubConfig } from '@splithub/core';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { basename } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { CliError, fail } from './errors';\n\n/** Load splithub.config.ts (TypeScript or JS) through jiti. CONFIG_PARSE when it does not load. */\nexport async function loadConfig(file: string): Promise<SplitHubConfig> {\n let mod: unknown;\n try {\n const { createJiti } = await import('jiti');\n const jiti = createJiti(pathToFileURL(file).href, { fsCache: false, moduleCache: false });\n mod = await jiti.import(file, { default: true });\n } catch (error) {\n fail('CONFIG_PARSE', `${basename(file)} doesn't load: ${error instanceof Error ? error.message.split('\\n')[0] : String(error)}`, 'Fix the error in the file, then run npx splithub doctor.');\n }\n if (!isSplitHubConfig(mod)) {\n fail('CONFIG_PARSE', `${basename(file)} must \\`export default defineConfig({...})\\` from @splithub/core.`);\n }\n return mod;\n}\n\n// ---------------------------------------------------------------------------\n// Source scanning. Edits work on a \"masked\" copy of the file where string\n// contents, template literals, regex literals and comments are blanked out\n// (same length, newlines kept), so braces and quotes inside them never count.\n// ---------------------------------------------------------------------------\n\nconst REGEX_BEFORE = new Set(['', '(', ',', '=', ':', '[', '!', '&', '|', '?', '{', '}', ';', '+', '-', '*', '%', '<', '>', '~', '^']);\n\n/** Copy of `source` with strings (contents), templates, regexes and comments blanked. */\nexport function maskSource(source: string): string {\n const out = source.split('');\n const blank = (from: number, to: number) => {\n for (let j = from; j < to && j < out.length; j++) if (out[j] !== '\\n' && out[j] !== '\\r') out[j] = ' ';\n };\n let lastCode = '';\n let i = 0;\n while (i < source.length) {\n const ch = source[i]!;\n const next = source[i + 1];\n if (ch === '/' && next === '/') {\n const end = source.indexOf('\\n', i);\n const stop = end < 0 ? source.length : end;\n blank(i, stop);\n i = stop;\n continue;\n }\n if (ch === '/' && next === '*') {\n const end = source.indexOf('*/', i + 2);\n const stop = end < 0 ? source.length : end + 2;\n blank(i, stop);\n i = stop;\n continue;\n }\n if (ch === \"'\" || ch === '\"') {\n let j = i + 1;\n while (j < source.length && source[j] !== ch && source[j] !== '\\n') j += source[j] === '\\\\' ? 2 : 1;\n blank(i + 1, j);\n i = j + 1;\n lastCode = ch;\n continue;\n }\n if (ch === '`') {\n let j = i + 1;\n let depth = 0;\n while (j < source.length) {\n const c = source[j]!;\n if (c === '\\\\') {\n j += 2;\n continue;\n }\n if (depth === 0 && c === '`') break;\n if (c === '$' && source[j + 1] === '{') {\n depth++;\n j += 2;\n continue;\n }\n if (depth > 0 && c === '{') depth++;\n else if (depth > 0 && c === '}') depth--;\n j++;\n }\n blank(i + 1, j);\n i = j + 1;\n lastCode = '`';\n continue;\n }\n if (ch === '/' && REGEX_BEFORE.has(lastCode)) {\n let j = i + 1;\n let inClass = false;\n while (j < source.length && source[j] !== '\\n') {\n const c = source[j]!;\n if (c === '\\\\') {\n j += 2;\n continue;\n }\n if (c === '[') inClass = true;\n else if (c === ']') inClass = false;\n else if (c === '/' && !inClass) break;\n j++;\n }\n blank(i + 1, j);\n i = j + 1;\n lastCode = '/';\n continue;\n }\n if (!/\\s/.test(ch)) lastCode = /[\\w$)\\]]/.test(ch) ? 'x' : ch;\n i++;\n }\n return out.join('');\n}\n\n/** Index of the bracket closing the one at `open` in masked text, or null. */\nfunction matchingClose(masked: string, open: number): number | null {\n let depth = 0;\n for (let i = open; i < masked.length; i++) {\n const ch = masked[i]!;\n if (ch === '{' || ch === '(' || ch === '[') depth++;\n else if (ch === '}' || ch === ')' || ch === ']') {\n depth--;\n if (depth === 0) return i;\n }\n }\n return null;\n}\n\nexport interface Entry {\n /** Property name; null for spreads and computed keys. */\n key: string | null;\n /** object: `key: { ... }` · expr: any other value (identifier, call, shorthand) · spread: `...x` · computed: `[k]: v`. */\n kind: 'object' | 'expr' | 'spread' | 'computed';\n start: number;\n valueStart: number;\n /** Exclusive end of the value (trailing whitespace excluded). */\n valueEnd: number;\n /** After the trailing comma when there is one, else `valueEnd`. */\n end: number;\n}\n\n/** Top-level properties of the object literal between `open` and `close` (its braces). */\nexport function objectEntries(source: string, masked: string, open: number, close: number): Entry[] {\n const entries: Entry[] = [];\n let i = open + 1;\n const ws = () => {\n while (i < close && /[\\s,]/.test(masked[i]!)) i++;\n };\n // A value runs to the next comma at depth 0 (or the closing brace).\n const valueTo = (from: number): number => {\n let j = from;\n while (j < close) {\n const ch = masked[j]!;\n if (ch === ',') break;\n if (ch === '{' || ch === '(' || ch === '[') {\n const m = matchingClose(masked, j);\n j = m === null ? close : m + 1;\n continue;\n }\n j++;\n }\n return j;\n };\n for (;;) {\n ws();\n if (i >= close) break;\n const start = i;\n let key: string | null = null;\n let kind: Entry['kind'] = 'expr';\n if (masked.startsWith('...', i)) {\n kind = 'spread';\n i += 3;\n } else {\n const ch = masked[i]!;\n if (ch === \"'\" || ch === '\"') {\n const end = masked.indexOf(ch, i + 1);\n key = source.slice(i + 1, end).replace(/\\\\(.)/g, '$1');\n i = end + 1;\n } else if (ch === '[') {\n kind = 'computed';\n const m = matchingClose(masked, i);\n i = m === null ? close : m + 1;\n } else {\n const m = /^[\\w$-]+/.exec(masked.slice(i, close));\n if (!m) break;\n key = m[0];\n i += m[0].length;\n }\n while (i < close && /\\s/.test(masked[i]!)) i++;\n if (masked[i] === ':') i++;\n }\n while (i < close && /\\s/.test(masked[i]!)) i++;\n const valueStart = i;\n const stop = valueTo(i);\n let valueEnd = stop;\n while (valueEnd > valueStart && /\\s/.test(masked[valueEnd - 1]!)) valueEnd--;\n if (kind === 'expr' && masked[valueStart] === '{' && matchingClose(masked, valueStart) === valueEnd - 1) kind = 'object';\n const end = masked[stop] === ',' ? stop + 1 : valueEnd;\n entries.push({ key, kind, start, valueStart, valueEnd, end });\n i = stop;\n }\n return entries;\n}\n\ninterface Located {\n masked: string;\n open: number;\n close: number;\n entries: Entry[];\n}\n\n/** The `experiments: { ... }` object of the config, with its entries. */\nfunction locateExperiments(source: string): Located {\n const masked = maskSource(source);\n let open = -1;\n // Prefer the object passed to defineConfig({ ... }) / export default { ... }.\n const root = /defineConfig\\s*\\(\\s*\\{|export\\s+default\\s+\\{/.exec(masked);\n if (root) {\n const rootOpen = root.index + root[0].length - 1;\n const rootClose = matchingClose(masked, rootOpen);\n if (rootClose !== null) {\n const exp = objectEntries(source, masked, rootOpen, rootClose).find((e) => e.key === 'experiments');\n if (exp && exp.kind !== 'object') {\n fail('CONFIG_UNSAFE', '`experiments` in the config is not written inline, so the CLI cannot edit it safely.', 'Edit the experiments where they are defined, or write them inline as experiments: { ... }.');\n }\n if (exp) open = exp.valueStart;\n }\n }\n if (open < 0) {\n const m = /\\bexperiments\\s*:\\s*\\{/.exec(masked);\n if (!m) fail('CONFIG_UNSAFE', \"Couldn't find `experiments: {` in the config file.\", 'Add experiments: {} to defineConfig({...}) and retry.');\n open = m.index + m[0].length - 1;\n }\n const close = matchingClose(masked, open);\n if (close === null) fail('CONFIG_PARSE', 'The braces after `experiments: {` are not balanced.');\n return { masked, open, close, entries: objectEntries(source, masked, open, close) };\n}\n\nfunction unsafeHint(key: string): string {\n return `Edit \"${key}\" where it is defined (it comes from a spread or an imported constant), then run npx splithub doctor.`;\n}\n\n/** The literal `key: { ... }` entry of an experiment. Throws when it can't be edited safely. */\nfunction experimentEntry(source: string, key: string): Located & { entry: Entry } {\n const loc = locateExperiments(source);\n const entry = loc.entries.find((e) => e.key === key);\n if (!entry) {\n if (loc.entries.some((e) => e.kind === 'spread' || e.kind === 'computed')) {\n fail('CONFIG_UNSAFE', `\"${key}\" isn't written inline in the config (the experiments use a spread), so the CLI can't edit it safely.`, unsafeHint(key));\n }\n fail('EXPERIMENT_NOT_FOUND', `There's no experiment \"${key}\" in the config.`, 'See the ids with npx splithub status.');\n }\n return { ...loc, entry };\n}\n\nexport function hasExperiment(source: string, key: string): boolean {\n try {\n return locateExperiments(source).entries.some((e) => e.key === key);\n } catch {\n return false;\n }\n}\n\n/** Indentation of the line holding `index`. */\nfunction indentAt(source: string, index: number): string {\n const lineStart = source.lastIndexOf('\\n', index - 1) + 1;\n return /^[ \\t]*/.exec(source.slice(lineStart))?.[0] ?? '';\n}\n\n/**\n * Append `render(indent)` as the last property of the object `open..close`,\n * adding the comma the previous property may be missing.\n */\nfunction appendProperty(source: string, masked: string, open: number, close: number, render: (indent: string) => string): string {\n const outerIndent = indentAt(source, open);\n const indent = outerIndent + ' ';\n let last = close - 1;\n while (last > open && /\\s/.test(masked[last]!)) last--;\n const needsComma = last > open && masked[last] !== ',';\n const lineStart = source.lastIndexOf('\\n', close - 1) + 1;\n const closeOnOwnLine = source.slice(lineStart, close).trim() === '';\n const block = `${indent}${render(indent)},\\n`;\n const at = closeOnOwnLine && lineStart > last ? lineStart : close;\n const text = at === close ? `\\n${block}${outerIndent}` : block;\n const comma = needsComma ? ',' : '';\n // Inline object (`{ a: 1 }`): the whitespace before `}` gives way to the new line.\n const head = at === close ? source.slice(0, last + 1) + comma : source.slice(0, last + 1) + comma + source.slice(last + 1, at);\n return head + text + source.slice(at);\n}\n\nexport interface NewExperiment {\n key: string;\n kind: ExperimentKind;\n status: ExperimentStatus;\n variants: Array<{ key: string; weight: number; value?: string; to?: string }>;\n /** Multivariate: factor → level → value; the variants are derived and not written. */\n factors?: Record<string, Record<string, string>>;\n goal?: string;\n match?: string;\n /** Human name shown instead of the key. */\n name?: string;\n description?: string;\n /** Targeting graph from the dashboard, written verbatim as JSON. */\n flow?: unknown;\n traffic?: number;\n maxExposures?: number;\n /** Days before a verdict (0..30); absent means the default of 0 (none). */\n minDays?: number;\n /** Total visitors for a good sample (100..10,000,000); absent means the default of 5000. */\n goodSample?: number;\n schedule?: { startAt?: string | null; endAt?: string | null };\n /** Secondary goals to watch, and guardrails that must not get worse. */\n metrics?: { secondary?: string[]; guardrails?: Array<string | { goal: string; worse: 'lower' | 'higher' }> };\n /** Mutual exclusion layer and its bucket range [start, end). */\n layer?: { key: string; range: [number, number] };\n}\n\n/** Single-quoted string literal. */\nfunction q(s: string): string {\n return `'${s.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n')}'`;\n}\n\n/** Object key: bare when it is a valid identifier, quoted otherwise. */\nfunction k(s: string): string {\n return /^[a-z_$][\\w$]*$/i.test(s) ? s : q(s);\n}\n\n/** Render an experiment entry. Every line after the first carries its own indentation. */\nexport function renderExperiment(e: NewExperiment, indent = ' '): string {\n const i2 = indent + ' ';\n const i3 = i2 + ' ';\n const lines: string[] = [`${k(e.key)}: {`];\n lines.push(`${i2}kind: ${q(e.kind)},`);\n lines.push(`${i2}status: ${q(e.status)},`);\n if (e.match) lines.push(`${i2}match: ${q(e.match)},`);\n if (e.kind === 'mvt') {\n lines.push(`${i2}factors: {`);\n for (const [factor, levels] of Object.entries(e.factors ?? {})) {\n lines.push(`${i3}${k(factor)}: { ${Object.entries(levels).map(([l, v]) => `${k(l)}: ${q(v)}`).join(', ')} },`);\n }\n lines.push(`${i2}},`);\n } else if (e.kind === 'component') {\n lines.push(`${i2}variants: { ${e.variants.map((v) => `${k(v.key)}: ${v.weight}`).join(', ')} },`);\n } else {\n lines.push(`${i2}variants: {`);\n for (const v of e.variants) {\n const extra = e.kind === 'value' ? `value: ${q(v.value ?? '')}` : `to: ${q(v.to ?? '/')}`;\n lines.push(`${i3}${k(v.key)}: { weight: ${v.weight}, ${extra} },`);\n }\n lines.push(`${i2}},`);\n }\n if (e.goal) lines.push(`${i2}goal: ${q(e.goal)},`);\n if (e.traffic !== undefined && e.traffic !== 1) lines.push(`${i2}traffic: ${e.traffic},`);\n if (e.maxExposures) lines.push(`${i2}maxExposures: ${e.maxExposures},`);\n if (e.minDays !== undefined) lines.push(`${i2}minDays: ${e.minDays},`);\n if (e.goodSample !== undefined) lines.push(`${i2}goodSample: ${e.goodSample},`);\n if (e.schedule && (e.schedule.startAt || e.schedule.endAt)) lines.push(`${i2}schedule: { ${[e.schedule.startAt ? `startAt: ${q(e.schedule.startAt)}` : null, e.schedule.endAt ? `endAt: ${q(e.schedule.endAt)}` : null].filter(Boolean).join(', ')} },`);\n if (e.metrics && (e.metrics.secondary?.length || e.metrics.guardrails?.length)) {\n const parts: string[] = [];\n if (e.metrics.secondary?.length) parts.push(`secondary: [${e.metrics.secondary.map(q).join(', ')}]`);\n if (e.metrics.guardrails?.length) parts.push(`guardrails: [${e.metrics.guardrails.map((g) => (typeof g === 'string' ? q(g) : `{ goal: ${q(g.goal)}, worse: ${q(g.worse)} }`)).join(', ')}]`);\n lines.push(`${i2}metrics: { ${parts.join(', ')} },`);\n }\n if (e.layer) lines.push(`${i2}layer: { key: ${q(e.layer.key)}, range: [${e.layer.range[0]}, ${e.layer.range[1]}] },`);\n if (e.name) lines.push(`${i2}name: ${q(e.name)},`);\n if (e.description) lines.push(`${i2}description: ${q(e.description)},`);\n if (e.flow) {\n const json = JSON.stringify(e.flow, null, 2).split('\\n');\n lines.push(`${i2}// targeting graph from the dashboard; edit it there or by hand\\n${i2}flow: ${json.map((l, n) => (n === 0 ? l : i2 + l)).join('\\n')},`);\n }\n lines.push(`${indent}}`);\n return lines.join('\\n');\n}\n\n/** Append a new experiment at the end of the `experiments: { ... }` object. */\nexport function insertExperiment(source: string, e: NewExperiment): string {\n const { masked, open, close, entries } = locateExperiments(source);\n if (entries.some((x) => x.key === e.key)) fail('EXPERIMENT_EXISTS', `There's already an experiment \"${e.key}\".`, 'Pick another id: an old id keeps its history.');\n return appendProperty(source, masked, open, close, (indent) => renderExperiment(e, indent));\n}\n\nexport function setExperimentStatus(source: string, key: string, status: ExperimentStatus): string {\n const { masked, entry } = experimentEntry(source, key);\n if (entry.kind !== 'object') fail('CONFIG_UNSAFE', `\"${key}\" points to a value defined elsewhere, so the CLI can't edit it safely.`, unsafeHint(key));\n const inner = objectEntries(source, masked, entry.valueStart, entry.valueEnd - 1);\n const field = inner.filter((x) => x.key === 'status').pop();\n if (field) {\n const raw = masked.slice(field.valueStart, field.valueEnd);\n if (!/^(['\"])\\s*\\1$/.test(raw)) fail('CONFIG_UNSAFE', `The status of \"${key}\" isn't a plain string, so the CLI can't change it safely.`, `Set status: '${status}' by hand.`);\n const quote = raw[0]!;\n return source.slice(0, field.valueStart) + `${quote}${status}${quote}` + source.slice(field.valueEnd);\n }\n // No status written (or only through a spread): append one, so it wins over any spread.\n return appendProperty(source, masked, entry.valueStart, entry.valueEnd - 1, () => `status: ${q(status)}`);\n}\n\n/** Remove an experiment's entry (and its line) from the config source. */\nexport function removeExperiment(source: string, key: string): string {\n return removeEntry(source, experimentEntry(source, key).entry);\n}\n\n/** Remove a property, its whole line when it stands alone. */\nfunction removeEntry(source: string, entry: Entry): string {\n const lineStart = source.lastIndexOf('\\n', entry.start - 1) + 1;\n const from = source.slice(lineStart, entry.start).trim() === '' ? lineStart : entry.start;\n let to = entry.end;\n const lineEnd = source.indexOf('\\n', to);\n const rest = source.slice(to, lineEnd < 0 ? source.length : lineEnd);\n if (rest.trim() === '' && from === lineStart) to = lineEnd < 0 ? source.length : lineEnd + 1;\n return source.slice(0, from) + source.slice(to);\n}\n\n/** The object passed to defineConfig({ ... }) / export default { ... }. */\nfunction locateRoot(source: string): Located {\n const masked = maskSource(source);\n const root = /defineConfig\\s*\\(\\s*\\{|export\\s+default\\s+\\{/.exec(masked);\n if (!root) fail('CONFIG_UNSAFE', \"Couldn't find defineConfig({ ... }) in the config file.\", 'Make the change by hand in splithub.config.ts.');\n const open = root.index + root[0].length - 1;\n const close = matchingClose(masked, open);\n if (close === null) fail('CONFIG_PARSE', 'The braces of defineConfig({ ... }) are not balanced.');\n return { masked, open, close, entries: objectEntries(source, masked, open, close) };\n}\n\n/** Set a top-level config property (`holdout: { ... }`), replacing it when it is there. */\nexport function setTopLevel(source: string, name: string, valueText: string | null): string {\n const { masked, open, close, entries } = locateRoot(source);\n const entry = entries.find((e) => e.key === name);\n if (valueText === null) return entry ? removeEntry(source, entry) : source;\n if (entry) return source.slice(0, entry.valueStart) + valueText + source.slice(entry.valueEnd);\n return appendProperty(source, masked, open, close, () => `${k(name)}: ${valueText}`);\n}\n\n/** Make sure `layers: { <key>: {} }` declares a layer. */\nexport function ensureLayer(source: string, key: string): string {\n const { masked, open, close, entries } = locateRoot(source);\n const layers = entries.find((e) => e.key === 'layers');\n if (!layers) return appendProperty(source, masked, open, close, () => `layers: { ${k(key)}: {} }`);\n if (layers.kind !== 'object') fail('CONFIG_UNSAFE', '`layers` in the config is not written inline.', `Add ${key}: {} to layers by hand.`);\n if (objectEntries(source, masked, layers.valueStart, layers.valueEnd - 1).some((e) => e.key === key)) return source;\n return appendProperty(source, masked, layers.valueStart, layers.valueEnd - 1, () => `${k(key)}: {}`);\n}\n\nexport function readSource(file: string): string {\n return readFileSync(file, 'utf8');\n}\n\nexport function writeSource(file: string, source: string): void {\n writeFileSync(file, source, 'utf8');\n}\n\n/**\n * Write the config, load it back and check the change landed. On any problem the\n * original file is restored and CONFIG_WRITE is thrown: the CLI never leaves a broken config.\n */\nexport async function writeConfigChecked(file: string, original: string, updated: string, verify: (config: SplitHubConfig) => string | null): Promise<SplitHubConfig> {\n writeSource(file, updated);\n let problem: string | null = null;\n let config: SplitHubConfig | null = null;\n try {\n config = await loadConfig(file);\n problem = verify(config);\n } catch (error) {\n problem = error instanceof CliError || error instanceof Error ? error.message : String(error);\n }\n if (problem || !config) {\n writeSource(file, original);\n fail('CONFIG_WRITE', `Couldn't update ${basename(file)}: ${problem ?? 'it did not load'}. The file is back as it was.`, 'Make the change by hand in the config, then run npx splithub doctor.');\n }\n return config;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,wBAAyF;AAClG,SAAS,cAAc,qBAAqB;AAC5C,SAAS,gBAAgB;AACzB,SAAS,qBAAqB;AAI9B,eAAsB,WAAW,MAAuC;AACtE,MAAI;AACJ,MAAI;AACF,UAAM,EAAE,WAAW,IAAI,MAAM,OAAO,MAAM;AAC1C,UAAM,OAAO,WAAW,cAAc,IAAI,EAAE,MAAM,EAAE,SAAS,OAAO,aAAa,MAAM,CAAC;AACxF,UAAM,MAAM,KAAK,OAAO,MAAM,EAAE,SAAS,KAAK,CAAC;AAAA,EACjD,SAAS,OAAO;AACd,SAAK,gBAAgB,GAAG,SAAS,IAAI,CAAC,kBAAkB,iBAAiB,QAAQ,MAAM,QAAQ,MAAM,IAAI,EAAE,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,0DAA0D;AAAA,EAC7L;AACA,MAAI,CAAC,iBAAiB,GAAG,GAAG;AAC1B,SAAK,gBAAgB,GAAG,SAAS,IAAI,CAAC,mEAAmE;AAAA,EAC3G;AACA,SAAO;AACT;AAQA,IAAM,eAAe,oBAAI,IAAI,CAAC,IAAI,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAG9H,SAAS,WAAW,QAAwB;AACjD,QAAM,MAAM,OAAO,MAAM,EAAE;AAC3B,QAAM,QAAQ,CAAC,MAAc,OAAe;AAC1C,aAAS,IAAI,MAAM,IAAI,MAAM,IAAI,IAAI,QAAQ,IAAK,KAAI,IAAI,CAAC,MAAM,QAAQ,IAAI,CAAC,MAAM,KAAM,KAAI,CAAC,IAAI;AAAA,EACrG;AACA,MAAI,WAAW;AACf,MAAI,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BAAiB,iDAAiD,OAAO,GAAG,yBAAyB;AACxI,MAAI,cAAc,QAAQ,QAAQ,OAAO,YAAY,OAAO,WAAW,CAAC,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,GAAG,EAAG,QAAO;AAC7G,SAAO,eAAe,QAAQ,QAAQ,OAAO,YAAY,OAAO,WAAW,GAAG,MAAM,GAAG,EAAE,GAAG,CAAC,MAAM;AACrG;AAEO,SAAS,WAAW,MAAsB;AAC/C,SAAO,aAAa,MAAM,MAAM;AAClC;AAEO,SAAS,YAAY,MAAc,QAAsB;AAC9D,gBAAc,MAAM,QAAQ,MAAM;AACpC;AAMA,eAAsB,mBAAmB,MAAc,UAAkB,SAAiB,QAA4E;AACpK,cAAY,MAAM,OAAO;AACzB,MAAI,UAAyB;AAC7B,MAAI,SAAgC;AACpC,MAAI;AACF,aAAS,MAAM,WAAW,IAAI;AAC9B,cAAU,OAAO,MAAM;AAAA,EACzB,SAAS,OAAO;AACd,cAAU,iBAAiB,YAAY,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,EAC9F;AACA,MAAI,WAAW,CAAC,QAAQ;AACtB,gBAAY,MAAM,QAAQ;AAC1B,SAAK,gBAAgB,mBAAmB,SAAS,IAAI,CAAC,KAAK,WAAW,iBAAiB,iCAAiC,sEAAsE;AAAA,EAChM;AACA,SAAO;AACT;","names":["end"]}
@@ -5,21 +5,21 @@ import {
5
5
  loadConfig,
6
6
  readSource,
7
7
  writeConfigChecked
8
- } from "./chunk-6OXCLYOI.js";
8
+ } from "./chunk-J5ZUSS43.js";
9
9
  import {
10
10
  apiError,
11
11
  cloudTarget,
12
12
  requireCloudToken
13
- } from "./chunk-ZND3T67D.js";
13
+ } from "./chunk-4YXB73AZ.js";
14
14
  import {
15
15
  detectProject,
16
16
  requireConfig
17
- } from "./chunk-PLZRB3VX.js";
17
+ } from "./chunk-4LE4SCWY.js";
18
18
  import {
19
19
  c,
20
20
  fail,
21
21
  printJson
22
- } from "./chunk-EJC4E3VD.js";
22
+ } from "./chunk-PP3RLIJP.js";
23
23
 
24
24
  // src/commands/push.ts
25
25
  import { relative } from "path";
@@ -49,6 +49,7 @@ async function adoptCloudExperiments(file, cloudOnly) {
49
49
  status: e.status,
50
50
  goal: e.goal ?? void 0,
51
51
  match: e.match ?? void 0,
52
+ name: e.name,
52
53
  description: e.description ?? void 0,
53
54
  flow: e.flow ?? void 0,
54
55
  traffic: e.traffic,
@@ -86,6 +87,16 @@ function configDiff(local, cloud) {
86
87
  }
87
88
  return { added, removed, changed };
88
89
  }
90
+ var keyList = (v) => typeof v === "string" ? v.split(",").map((k) => k.trim()).filter(Boolean) : [];
91
+ function keyConflict(conflicts) {
92
+ const why = conflicts.map((k) => k.reason === "dashboard" ? `${k.key} (a different test made in the dashboard)` : `${k.key} (an earlier test, ${(k.exposures ?? 0).toLocaleString("en-US")} visitors)`);
93
+ const keys = conflicts.map((k) => k.key).join(",");
94
+ fail(
95
+ "KEY_CONFLICT",
96
+ `These keys already belong to another test in the cloud: ${why.join("; ")}. Nothing was pushed.`,
97
+ `New test: rename its key, or run npx splithub push --replace ${keys} (the old numbers are cleared). Same test: npx splithub push --same ${keys}.`
98
+ );
99
+ }
89
100
  async function cloudFetch(url, init) {
90
101
  try {
91
102
  return await fetch(url, init);
@@ -104,9 +115,11 @@ async function push(flags) {
104
115
  const res = await cloudFetch(`${target.url}/config`, {
105
116
  method: "PUT",
106
117
  headers: { authorization: `Bearer ${target.token}`, "content-type": "application/json" },
107
- body: JSON.stringify({ config })
118
+ body: JSON.stringify({ config, replace: keyList(flags.replace), same: keyList(flags.same) })
108
119
  });
109
120
  const body = await res.json().catch(() => ({}));
121
+ if (res.status === 409 && body.code === "key_conflict" && body.conflicts?.length) keyConflict(body.conflicts);
122
+ if (res.status === 409 && body.code === "key_deleted") fail("KEY_DELETED", `${body.error ?? "A deleted test used one of these keys"}. Nothing was pushed.`, "Give the test a new key in splithub.config.ts and push again.");
110
123
  if (!res.ok) throw apiError(res.status, body, `${target.url}/config responded ${res.status}`);
111
124
  let keyWritten = false;
112
125
  if (body.publicKey && !config.storage.key) {
@@ -182,4 +195,4 @@ export {
182
195
  push,
183
196
  pull
184
197
  };
185
- //# sourceMappingURL=chunk-XVWJZJSF.js.map
198
+ //# sourceMappingURL=chunk-JBPVGBLN.js.map