splithub 0.2.0 → 0.2.2

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 (104) hide show
  1. package/README.md +20 -1
  2. package/dist/chunk-5VFCW4FI.js +75 -0
  3. package/dist/chunk-5VFCW4FI.js.map +1 -0
  4. package/dist/{chunk-3VY5CP3E.js → chunk-6OXCLYOI.js} +3 -2
  5. package/dist/chunk-6OXCLYOI.js.map +1 -0
  6. package/dist/{chunk-HSH4ZI2V.js → chunk-7EB5WOYE.js} +4 -4
  7. package/dist/{chunk-3VACHXWE.js → chunk-AZJEZFOB.js} +14 -7
  8. package/dist/chunk-AZJEZFOB.js.map +1 -0
  9. package/dist/{chunk-3DUWIEHB.js → chunk-BQAWJPIK.js} +10 -4
  10. package/dist/chunk-BQAWJPIK.js.map +1 -0
  11. package/dist/{chunk-PWSRKABE.js → chunk-BSWCWCYP.js} +3 -3
  12. package/dist/{chunk-GVARYUL3.js → chunk-D7KVM4L7.js} +2 -2
  13. package/dist/{chunk-C5S7RPYM.js → chunk-ECV5QR6H.js} +5 -5
  14. package/dist/{chunk-V3DLUVOE.js → chunk-EJC4E3VD.js} +7 -2
  15. package/dist/{chunk-V3DLUVOE.js.map → chunk-EJC4E3VD.js.map} +1 -1
  16. package/dist/chunk-IFCSJYXN.js +264 -0
  17. package/dist/chunk-IFCSJYXN.js.map +1 -0
  18. package/dist/{chunk-YSXW2HN6.js → chunk-IGYK7N2F.js} +21 -6
  19. package/dist/chunk-IGYK7N2F.js.map +1 -0
  20. package/dist/{chunk-QOXGIB3R.js → chunk-LK3NRAHA.js} +14 -13
  21. package/dist/chunk-LK3NRAHA.js.map +1 -0
  22. package/dist/{chunk-EYYLDI5J.js → chunk-NTAIRQP6.js} +3 -3
  23. package/dist/{chunk-PLXDG4B5.js → chunk-PLZRB3VX.js} +2 -2
  24. package/dist/{chunk-UUTLLC54.js → chunk-VKLZJRYW.js} +57 -56
  25. package/dist/chunk-VKLZJRYW.js.map +1 -0
  26. package/dist/{chunk-AJO3C4BS.js → chunk-X5AV7YBR.js} +27 -10
  27. package/dist/chunk-X5AV7YBR.js.map +1 -0
  28. package/dist/{chunk-A2RCSPG6.js → chunk-XVWJZJSF.js} +6 -5
  29. package/dist/chunk-XVWJZJSF.js.map +1 -0
  30. package/dist/{chunk-EUF75FUC.js → chunk-ZND3T67D.js} +31 -10
  31. package/dist/chunk-ZND3T67D.js.map +1 -0
  32. package/dist/{ci-ZQZ6RBUJ.js → ci-4OC23DTI.js} +4 -4
  33. package/dist/create-NCBDS2YG.js +18 -0
  34. package/dist/dev-7FXVGFL6.js +11 -0
  35. package/dist/doctor-E4KLPZZI.js +14 -0
  36. package/dist/{holdout-PECSNGAD.js → holdout-OKHR2CKW.js} +4 -4
  37. package/dist/index.js +37 -28
  38. package/dist/index.js.map +1 -1
  39. package/dist/init-PFNPS6XO.js +15 -0
  40. package/dist/lifecycle-G7OAC4ZZ.js +12 -0
  41. package/dist/{login-TTWSQ7XS.js → login-ZEIH7KIH.js} +4 -4
  42. package/dist/{menu-UQX3K5QR.js → menu-4X5S37OK.js} +23 -22
  43. package/dist/{menu-UQX3K5QR.js.map → menu-4X5S37OK.js.map} +1 -1
  44. package/dist/plan-QLYHRYCV.js +71 -0
  45. package/dist/plan-QLYHRYCV.js.map +1 -0
  46. package/dist/push-3NDLL7US.js +16 -0
  47. package/dist/{refs-ZDNH6NRK.js → refs-IWZ5GP7Q.js} +5 -5
  48. package/dist/{remove-KFQUK367.js → remove-YDJ7JTPR.js} +6 -6
  49. package/dist/report-JS7Z42FD.js +58 -0
  50. package/dist/report-JS7Z42FD.js.map +1 -0
  51. package/dist/results-HCXQH7IY.js +17 -0
  52. package/dist/{review-EIZDOGDC.js → review-BGGNVL6L.js} +3 -3
  53. package/dist/{ship-4YX2WCBP.js → ship-C22SGFUD.js} +6 -6
  54. package/dist/skills-UBPQOTDQ.js +18 -0
  55. package/dist/status-6IODQYHV.js +12 -0
  56. package/dist/update-SAHMBHIZ.js +37 -0
  57. package/dist/update-SAHMBHIZ.js.map +1 -0
  58. package/package.json +4 -5
  59. package/dist/chunk-3DUWIEHB.js.map +0 -1
  60. package/dist/chunk-3VACHXWE.js.map +0 -1
  61. package/dist/chunk-3VY5CP3E.js.map +0 -1
  62. package/dist/chunk-74NI7BED.js +0 -58
  63. package/dist/chunk-74NI7BED.js.map +0 -1
  64. package/dist/chunk-A2RCSPG6.js.map +0 -1
  65. package/dist/chunk-AJO3C4BS.js.map +0 -1
  66. package/dist/chunk-EUF75FUC.js.map +0 -1
  67. package/dist/chunk-QOXGIB3R.js.map +0 -1
  68. package/dist/chunk-UUTLLC54.js.map +0 -1
  69. package/dist/chunk-YSXW2HN6.js.map +0 -1
  70. package/dist/create-K75OY6XK.js +0 -18
  71. package/dist/dev-WQWFEA6I.js +0 -11
  72. package/dist/doctor-MFYBZUKO.js +0 -13
  73. package/dist/init-QAAM2GQ7.js +0 -15
  74. package/dist/lifecycle-56HM7ITG.js +0 -12
  75. package/dist/plan-BSFSMKTU.js +0 -135
  76. package/dist/plan-BSFSMKTU.js.map +0 -1
  77. package/dist/push-YVS25VVD.js +0 -16
  78. package/dist/report-TF2BLJMC.js +0 -64
  79. package/dist/report-TF2BLJMC.js.map +0 -1
  80. package/dist/results-TLV5KJWO.js +0 -17
  81. package/dist/skills-HWQT3DTJ.js +0 -13
  82. package/dist/status-CWI7ZCYJ.js +0 -11
  83. /package/dist/{chunk-HSH4ZI2V.js.map → chunk-7EB5WOYE.js.map} +0 -0
  84. /package/dist/{chunk-PWSRKABE.js.map → chunk-BSWCWCYP.js.map} +0 -0
  85. /package/dist/{chunk-GVARYUL3.js.map → chunk-D7KVM4L7.js.map} +0 -0
  86. /package/dist/{chunk-C5S7RPYM.js.map → chunk-ECV5QR6H.js.map} +0 -0
  87. /package/dist/{chunk-EYYLDI5J.js.map → chunk-NTAIRQP6.js.map} +0 -0
  88. /package/dist/{chunk-PLXDG4B5.js.map → chunk-PLZRB3VX.js.map} +0 -0
  89. /package/dist/{ci-ZQZ6RBUJ.js.map → ci-4OC23DTI.js.map} +0 -0
  90. /package/dist/{create-K75OY6XK.js.map → create-NCBDS2YG.js.map} +0 -0
  91. /package/dist/{dev-WQWFEA6I.js.map → dev-7FXVGFL6.js.map} +0 -0
  92. /package/dist/{doctor-MFYBZUKO.js.map → doctor-E4KLPZZI.js.map} +0 -0
  93. /package/dist/{holdout-PECSNGAD.js.map → holdout-OKHR2CKW.js.map} +0 -0
  94. /package/dist/{init-QAAM2GQ7.js.map → init-PFNPS6XO.js.map} +0 -0
  95. /package/dist/{lifecycle-56HM7ITG.js.map → lifecycle-G7OAC4ZZ.js.map} +0 -0
  96. /package/dist/{login-TTWSQ7XS.js.map → login-ZEIH7KIH.js.map} +0 -0
  97. /package/dist/{push-YVS25VVD.js.map → push-3NDLL7US.js.map} +0 -0
  98. /package/dist/{refs-ZDNH6NRK.js.map → refs-IWZ5GP7Q.js.map} +0 -0
  99. /package/dist/{remove-KFQUK367.js.map → remove-YDJ7JTPR.js.map} +0 -0
  100. /package/dist/{results-TLV5KJWO.js.map → results-HCXQH7IY.js.map} +0 -0
  101. /package/dist/{review-EIZDOGDC.js.map → review-BGGNVL6L.js.map} +0 -0
  102. /package/dist/{ship-4YX2WCBP.js.map → ship-C22SGFUD.js.map} +0 -0
  103. /package/dist/{skills-HWQT3DTJ.js.map → skills-UBPQOTDQ.js.map} +0 -0
  104. /package/dist/{status-CWI7ZCYJ.js.map → status-6IODQYHV.js.map} +0 -0
@@ -4,18 +4,18 @@ import {
4
4
  readSource,
5
5
  setExperimentStatus,
6
6
  writeConfigChecked
7
- } from "./chunk-3VY5CP3E.js";
7
+ } from "./chunk-6OXCLYOI.js";
8
8
  import {
9
9
  applyLiveStatus
10
- } from "./chunk-EUF75FUC.js";
10
+ } from "./chunk-ZND3T67D.js";
11
11
  import {
12
12
  requireConfig
13
- } from "./chunk-PLXDG4B5.js";
13
+ } from "./chunk-PLZRB3VX.js";
14
14
  import {
15
15
  c,
16
16
  fail,
17
17
  printJson
18
- } from "./chunk-V3DLUVOE.js";
18
+ } from "./chunk-EJC4E3VD.js";
19
19
 
20
20
  // src/commands/lifecycle.ts
21
21
  import { relative } from "path";
@@ -51,4 +51,4 @@ async function lifecycle(command, id, flags) {
51
51
  export {
52
52
  lifecycle
53
53
  };
54
- //# sourceMappingURL=chunk-C5S7RPYM.js.map
54
+ //# sourceMappingURL=chunk-ECV5QR6H.js.map
@@ -95,6 +95,10 @@ function verdictColor(status, text) {
95
95
  return c.dim(text);
96
96
  }
97
97
  }
98
+ function starText(stars) {
99
+ const n = Math.max(0, Math.min(5, Math.round(stars)));
100
+ return "\u2605".repeat(n) + "\u2606".repeat(5 - n);
101
+ }
98
102
 
99
103
  export {
100
104
  CliError,
@@ -107,6 +111,7 @@ export {
107
111
  statusColor,
108
112
  verdictIcon,
109
113
  bar,
110
- verdictColor
114
+ verdictColor,
115
+ starText
111
116
  };
112
- //# sourceMappingURL=chunk-V3DLUVOE.js.map
117
+ //# sourceMappingURL=chunk-EJC4E3VD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/ui.ts"],"sourcesContent":["// Errors with a stable code. With --json the CLI prints `{ error, code, hint? }` on one\n// line to stdout, so agents and the MCP server branch on `code`, never on the wording.\n\nexport const ERROR_CODES = [\n 'USAGE',\n 'INVALID_FLAG',\n 'NO_CONFIG',\n 'CONFIG_PARSE',\n 'CONFIG_WRITE',\n 'CONFIG_UNSAFE',\n 'EXPERIMENT_EXISTS',\n 'EXPERIMENT_NOT_FOUND',\n 'VARIANT_NOT_FOUND',\n 'GOAL_NOT_FOUND',\n 'NOT_CLOUD',\n 'NOT_LOGGED_IN',\n 'INSUFFICIENT_SCOPE',\n 'API_ERROR',\n 'UNREACHABLE',\n 'TYPESCRIPT_MISSING',\n 'INTERNAL',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\nexport class CliError extends Error {\n readonly code: ErrorCode;\n readonly hint?: string;\n constructor(code: ErrorCode, message: string, hint?: string) {\n super(message);\n this.name = 'CliError';\n this.code = code;\n if (hint) this.hint = hint;\n }\n}\n\nexport function fail(code: ErrorCode, message: string, hint?: string): never {\n throw new CliError(code, message, hint);\n}\n\n/** The one-line JSON body for an error (unknown errors become INTERNAL, or USAGE for parseArgs). */\nexport function errorJson(error: unknown): { error: string; code: ErrorCode; hint?: string } {\n if (error instanceof CliError) return { error: error.message, code: error.code, ...(error.hint ? { hint: error.hint } : {}) };\n const message = error instanceof Error ? error.message : String(error);\n const code: ErrorCode = (error as { code?: unknown } | null)?.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION' || (error as { code?: unknown } | null)?.code === 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE' ? 'USAGE' : 'INTERNAL';\n return { error: message, code };\n}\n\n/** Machine output: always one line. */\nexport function printJson(value: unknown): void {\n console.log(JSON.stringify(value));\n}\n","const enabled = process.stdout.isTTY && !process.env.NO_COLOR;\nconst wrap = (open: number, close: number) => (s: string) => (enabled ? `\\u001b[${open}m${s}\\u001b[${close}m` : s);\n\nexport const c = {\n bold: wrap(1, 22),\n dim: wrap(2, 22),\n red: wrap(31, 39),\n green: wrap(32, 39),\n yellow: wrap(33, 39),\n blue: wrap(34, 39),\n magenta: wrap(35, 39),\n cyan: wrap(36, 39),\n};\n\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => strip(r[i] ?? '').length)));\n const line = (cells: string[]) => cells.map((cell, i) => cell + ' '.repeat(widths[i]! - strip(cell).length)).join(' ');\n return [c.dim(line(headers)), ...rows.map(line)].join('\\n');\n}\n\nexport function strip(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\\u001b\\[\\d+m/g, '');\n}\n\nexport function pct(x: number | null | undefined, signed = false): string {\n if (x === null || x === undefined || !Number.isFinite(x)) return '–';\n const v = (x * 100).toFixed(1);\n return signed && x >= 0 ? `+${v}%` : `${v}%`;\n}\n\nexport function statusColor(status: string): string {\n switch (status) {\n case 'running':\n return c.green(status);\n case 'paused':\n return c.yellow(status);\n case 'finished':\n return c.blue(status);\n default:\n return c.dim(status);\n }\n}\n\n/** One plain glyph per verdict (no emoji: terminals and CI logs render these everywhere). */\nexport function verdictIcon(status: string | null | undefined): string {\n switch (status) {\n case 'winner_found':\n return '★';\n case 'srm_detected':\n return '!';\n case 'guardrail_breached':\n return '✖';\n case 'insufficient_sample':\n return '…';\n case 'no_significant_difference':\n return '=';\n default:\n return '·';\n }\n}\n\n/** A horizontal bar: filled blocks for value / max, dim blocks for the rest. */\nexport function bar(value: number, max: number, width = 20, paint: (s: string) => string = c.green): string {\n const n = max > 0 ? Math.max(0, Math.min(width, Math.round((value / max) * width))) : 0;\n return paint('█'.repeat(n)) + c.dim('░'.repeat(width - n));\n}\n\nexport function verdictColor(status: string | null, text: string): string {\n switch (status) {\n case 'winner_found':\n return c.green(text);\n case 'srm_detected':\n case 'guardrail_breached':\n return c.red(text);\n case 'insufficient_sample':\n return c.yellow(text);\n case 'no_significant_difference':\n return c.cyan(text);\n default:\n return c.dim(text);\n }\n}\n"],"mappings":";;;AAyBO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAGlC,YAAY,MAAiB,SAAiB,MAAe;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB;AACF;AAEO,SAAS,KAAK,MAAiB,SAAiB,MAAsB;AAC3E,QAAM,IAAI,SAAS,MAAM,SAAS,IAAI;AACxC;AAGO,SAAS,UAAU,OAAmE;AAC3F,MAAI,iBAAiB,SAAU,QAAO,EAAE,OAAO,MAAM,SAAS,MAAM,MAAM,MAAM,GAAI,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC,EAAG;AAC5H,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,QAAM,OAAmB,OAAqC,SA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../src/ui.ts"],"sourcesContent":["// Errors with a stable code. With --json the CLI prints `{ error, code, hint? }` on one\n// line to stdout, so agents and the MCP server branch on `code`, never on the wording.\n\nexport const ERROR_CODES = [\n 'USAGE',\n 'INVALID_FLAG',\n 'NO_CONFIG',\n 'CONFIG_PARSE',\n 'CONFIG_WRITE',\n 'CONFIG_UNSAFE',\n 'EXPERIMENT_EXISTS',\n 'EXPERIMENT_NOT_FOUND',\n 'VARIANT_NOT_FOUND',\n 'GOAL_NOT_FOUND',\n 'NOT_CLOUD',\n 'NOT_LOGGED_IN',\n 'INSUFFICIENT_SCOPE',\n 'API_ERROR',\n 'UNREACHABLE',\n 'TYPESCRIPT_MISSING',\n 'INTERNAL',\n] as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[number];\n\nexport class CliError extends Error {\n readonly code: ErrorCode;\n readonly hint?: string;\n constructor(code: ErrorCode, message: string, hint?: string) {\n super(message);\n this.name = 'CliError';\n this.code = code;\n if (hint) this.hint = hint;\n }\n}\n\nexport function fail(code: ErrorCode, message: string, hint?: string): never {\n throw new CliError(code, message, hint);\n}\n\n/** The one-line JSON body for an error (unknown errors become INTERNAL, or USAGE for parseArgs). */\nexport function errorJson(error: unknown): { error: string; code: ErrorCode; hint?: string } {\n if (error instanceof CliError) return { error: error.message, code: error.code, ...(error.hint ? { hint: error.hint } : {}) };\n const message = error instanceof Error ? error.message : String(error);\n const code: ErrorCode = (error as { code?: unknown } | null)?.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION' || (error as { code?: unknown } | null)?.code === 'ERR_PARSE_ARGS_INVALID_OPTION_VALUE' ? 'USAGE' : 'INTERNAL';\n return { error: message, code };\n}\n\n/** Machine output: always one line. */\nexport function printJson(value: unknown): void {\n console.log(JSON.stringify(value));\n}\n","const enabled = process.stdout.isTTY && !process.env.NO_COLOR;\nconst wrap = (open: number, close: number) => (s: string) => (enabled ? `\\u001b[${open}m${s}\\u001b[${close}m` : s);\n\nexport const c = {\n bold: wrap(1, 22),\n dim: wrap(2, 22),\n red: wrap(31, 39),\n green: wrap(32, 39),\n yellow: wrap(33, 39),\n blue: wrap(34, 39),\n magenta: wrap(35, 39),\n cyan: wrap(36, 39),\n};\n\nexport function table(headers: string[], rows: string[][]): string {\n const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => strip(r[i] ?? '').length)));\n const line = (cells: string[]) => cells.map((cell, i) => cell + ' '.repeat(widths[i]! - strip(cell).length)).join(' ');\n return [c.dim(line(headers)), ...rows.map(line)].join('\\n');\n}\n\nexport function strip(s: string): string {\n // eslint-disable-next-line no-control-regex\n return s.replace(/\\u001b\\[\\d+m/g, '');\n}\n\nexport function pct(x: number | null | undefined, signed = false): string {\n if (x === null || x === undefined || !Number.isFinite(x)) return '–';\n const v = (x * 100).toFixed(1);\n return signed && x >= 0 ? `+${v}%` : `${v}%`;\n}\n\nexport function statusColor(status: string): string {\n switch (status) {\n case 'running':\n return c.green(status);\n case 'paused':\n return c.yellow(status);\n case 'finished':\n return c.blue(status);\n default:\n return c.dim(status);\n }\n}\n\n/** One plain glyph per verdict (no emoji: terminals and CI logs render these everywhere). */\nexport function verdictIcon(status: string | null | undefined): string {\n switch (status) {\n case 'winner_found':\n return '★';\n case 'srm_detected':\n return '!';\n case 'guardrail_breached':\n return '✖';\n case 'insufficient_sample':\n return '…';\n case 'no_significant_difference':\n return '=';\n default:\n return '·';\n }\n}\n\n/** A horizontal bar: filled blocks for value / max, dim blocks for the rest. */\nexport function bar(value: number, max: number, width = 20, paint: (s: string) => string = c.green): string {\n const n = max > 0 ? Math.max(0, Math.min(width, Math.round((value / max) * width))) : 0;\n return paint('█'.repeat(n)) + c.dim('░'.repeat(width - n));\n}\n\nexport function verdictColor(status: string | null, text: string): string {\n switch (status) {\n case 'winner_found':\n return c.green(text);\n case 'srm_detected':\n case 'guardrail_breached':\n return c.red(text);\n case 'insufficient_sample':\n return c.yellow(text);\n case 'no_significant_difference':\n return c.cyan(text);\n default:\n return c.dim(text);\n }\n}\n\n/** \"★★★☆☆\" for a 0..5 score from the server. */\nexport function starText(stars: number): string {\n const n = Math.max(0, Math.min(5, Math.round(stars)));\n return '★'.repeat(n) + '☆'.repeat(5 - n);\n}\n"],"mappings":";;;AAyBO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAGlC,YAAY,MAAiB,SAAiB,MAAe;AAC3D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,QAAI,KAAM,MAAK,OAAO;AAAA,EACxB;AACF;AAEO,SAAS,KAAK,MAAiB,SAAiB,MAAsB;AAC3E,QAAM,IAAI,SAAS,MAAM,SAAS,IAAI;AACxC;AAGO,SAAS,UAAU,OAAmE;AAC3F,MAAI,iBAAiB,SAAU,QAAO,EAAE,OAAO,MAAM,SAAS,MAAM,MAAM,MAAM,GAAI,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC,EAAG;AAC5H,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,QAAM,OAAmB,OAAqC,SAAS,mCAAoC,OAAqC,SAAS,wCAAwC,UAAU;AAC3M,SAAO,EAAE,OAAO,SAAS,KAAK;AAChC;AAGO,SAAS,UAAU,OAAsB;AAC9C,UAAQ,IAAI,KAAK,UAAU,KAAK,CAAC;AACnC;;;ACnDA,IAAM,UAAU,QAAQ,OAAO,SAAS,CAAC,QAAQ,IAAI;AACrD,IAAM,OAAO,CAAC,MAAc,UAAkB,CAAC,MAAe,UAAU,QAAU,IAAI,IAAI,CAAC,QAAU,KAAK,MAAM;AAEzG,IAAM,IAAI;AAAA,EACf,MAAM,KAAK,GAAG,EAAE;AAAA,EAChB,KAAK,KAAK,GAAG,EAAE;AAAA,EACf,KAAK,KAAK,IAAI,EAAE;AAAA,EAChB,OAAO,KAAK,IAAI,EAAE;AAAA,EAClB,QAAQ,KAAK,IAAI,EAAE;AAAA,EACnB,MAAM,KAAK,IAAI,EAAE;AAAA,EACjB,SAAS,KAAK,IAAI,EA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AO;AAAA,EACX;AACF;AAGO,SAAS,IAAI,OAAe,KAAa,QAAQ,IAAI,QAA+B,EAAE,OAAe;AAC1G,QAAM,IAAI,MAAM,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,KAAK,MAAO,QAAQ,MAAO,KAAK,CAAC,CAAC,IAAI;AACtF,SAAO,MAAM,SAAI,OAAO,CAAC,CAAC,IAAI,EAAE,IAAI,SAAI,OAAO,QAAQ,CAAC,CAAC;AAC3D;AAEO,SAAS,aAAa,QAAuB,MAAsB;AACxE,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aAAO,EAAE,MAAM,IAAI;AAAA,IACrB,KAAK;AAAA,IACL,KAAK;AACH,aAAO,EAAE,IAAI,IAAI;AAAA,IACnB,KAAK;AACH,aAAO,EAAE,OAAO,IAAI;AAAA,IACtB,KAAK;AACH,aAAO,EAAE,KAAK,IAAI;AAAA,IACpB;AACE,aAAO,EAAE,IAAI,IAAI;AAAA,EACrB;AACF;AAGO,SAAS,SAAS,OAAuB;AAC9C,QAAM,IAAI,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC,CAAC;AACpD,SAAO,SAAI,OAAO,CAAC,IAAI,SAAI,OAAO,IAAI,CAAC;AACzC;","names":[]}
@@ -0,0 +1,264 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ c
4
+ } from "./chunk-EJC4E3VD.js";
5
+
6
+ // src/update.ts
7
+ import { execSync, spawn } from "child_process";
8
+ import { existsSync, readFileSync, realpathSync } from "fs";
9
+ import { createRequire } from "module";
10
+ import { dirname, join, resolve } from "path";
11
+ var REGISTRY = "https://registry.npmjs.org";
12
+ var CHECK_TIMEOUT_MS = 1500;
13
+ function currentVersion() {
14
+ return createRequire(import.meta.url)("../package.json").version;
15
+ }
16
+ function parse(v) {
17
+ const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(v.trim());
18
+ if (!m) return null;
19
+ return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split(".") : [] };
20
+ }
21
+ function compareSemver(a, b) {
22
+ const x = parse(a);
23
+ const y = parse(b);
24
+ if (!x || !y) return (x ? 1 : 0) - (y ? 1 : 0);
25
+ for (let i = 0; i < 3; i++) if (x.nums[i] !== y.nums[i]) return x.nums[i] - y.nums[i];
26
+ if (!x.pre.length || !y.pre.length) return (x.pre.length ? 0 : 1) - (y.pre.length ? 0 : 1);
27
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
28
+ const p = x.pre[i];
29
+ const q = y.pre[i];
30
+ if (p === void 0) return -1;
31
+ if (q === void 0) return 1;
32
+ if (p === q) continue;
33
+ const pn = /^\d+$/.test(p);
34
+ const qn = /^\d+$/.test(q);
35
+ if (pn && qn) return Number(p) - Number(q);
36
+ if (pn !== qn) return pn ? -1 : 1;
37
+ return p < q ? -1 : 1;
38
+ }
39
+ return 0;
40
+ }
41
+ function isNewer(latest, current) {
42
+ const l = parse(latest);
43
+ const cur = parse(current);
44
+ if (!l || !cur) return false;
45
+ if (l.pre.length && !cur.pre.length) return false;
46
+ return compareSemver(latest, current) > 0;
47
+ }
48
+ async function fetchLatest(name, opts = {}) {
49
+ const fetchImpl = opts.fetchImpl ?? fetch;
50
+ const signal = opts.signal ?? AbortSignal.timeout(opts.timeoutMs ?? CHECK_TIMEOUT_MS);
51
+ try {
52
+ const res = await fetchImpl(`${REGISTRY}/${name.replace("/", "%2f")}/latest`, { signal, headers: { accept: "application/json" } });
53
+ if (!res.ok) return null;
54
+ const body = await res.json();
55
+ return typeof body?.version === "string" && parse(body.version) ? body.version : null;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+ var CI_VARS = ["CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "CIRCLECI", "TRAVIS", "JENKINS_URL", "TEAMCITY_VERSION", "TF_BUILD", "BITBUCKET_BUILD_NUMBER", "CODEBUILD_BUILD_ID", "BUILD_NUMBER", "RUN_ID"];
61
+ function isCi(env) {
62
+ return CI_VARS.some((k) => {
63
+ const v = env[k];
64
+ return v !== void 0 && v !== "" && v !== "0" && v.toLowerCase() !== "false";
65
+ });
66
+ }
67
+ function shouldCheckForUpdates({ argv, env, stdinTTY, stdoutTTY }) {
68
+ if (!stdinTTY || !stdoutTTY) return false;
69
+ if (argv.includes("--json")) return false;
70
+ if (env.SPLITHUB_NO_UPDATE_CHECK === "1" || env.SPLITHUB_MCP === "1") return false;
71
+ if (isCi(env)) return false;
72
+ const command = argv.find((a) => !a.startsWith("-"));
73
+ return command !== "update" && command !== "dev";
74
+ }
75
+ var isOurs = (name) => name === "splithub" || name.startsWith("@splithub/");
76
+ function readPkg(file) {
77
+ try {
78
+ return JSON.parse(readFileSync(file, "utf8"));
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ function findProjectRoot(cwd) {
84
+ let dir = resolve(cwd);
85
+ for (; ; ) {
86
+ if (existsSync(join(dir, "package.json"))) return dir;
87
+ const up = dirname(dir);
88
+ if (up === dir) return null;
89
+ dir = up;
90
+ }
91
+ }
92
+ function detectPackageManager(root) {
93
+ let dir = resolve(root);
94
+ for (; ; ) {
95
+ const has = (f) => existsSync(join(dir, f));
96
+ if (has("pnpm-lock.yaml")) return "pnpm";
97
+ if (has("yarn.lock")) return "yarn";
98
+ if (has("bun.lockb") || has("bun.lock")) return "bun";
99
+ if (has("package-lock.json")) return "npm";
100
+ const up = dirname(dir);
101
+ if (up === dir) return "npm";
102
+ dir = up;
103
+ }
104
+ }
105
+ function projectPackages(root) {
106
+ const pkg = readPkg(join(root, "package.json"));
107
+ if (!pkg) return [];
108
+ const prod = Object.keys(pkg.dependencies ?? {}).filter(isOurs).map((name) => ({ name, dev: false }));
109
+ const dev = Object.keys(pkg.devDependencies ?? {}).filter((n) => isOurs(n) && !prod.some((p) => p.name === n)).map((name) => ({ name, dev: true }));
110
+ return [...prod, ...dev];
111
+ }
112
+ function npmGlobalPrefix() {
113
+ if (process.env.npm_config_prefix) return process.env.npm_config_prefix;
114
+ try {
115
+ return execSync("npm prefix -g", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3e3 }).trim() || null;
116
+ } catch {
117
+ return null;
118
+ }
119
+ }
120
+ var norm = (p) => p.replace(/[\\/]+/g, "/").toLowerCase();
121
+ function detectInstall({ scriptPath, cwd, globalPrefix = npmGlobalPrefix }) {
122
+ let real = scriptPath;
123
+ try {
124
+ real = realpathSync(scriptPath);
125
+ } catch {
126
+ }
127
+ const script = norm(real);
128
+ if (/\/_npx\//.test(script) || /\/dlx-[^/]*\//.test(script)) return { mode: "npx" };
129
+ const root = findProjectRoot(cwd);
130
+ const packages = root ? projectPackages(root) : [];
131
+ const local = root !== null && (() => {
132
+ let dir = root;
133
+ for (; ; ) {
134
+ if (script.startsWith(norm(join(dir, "node_modules")) + "/")) return true;
135
+ const up = dirname(dir);
136
+ if (up === dir) return false;
137
+ dir = up;
138
+ }
139
+ })();
140
+ if (root && local && packages.length) return { mode: "project", root, pm: detectPackageManager(root), packages };
141
+ const prefix = globalPrefix();
142
+ if (prefix) {
143
+ const p = norm(prefix);
144
+ if (script.startsWith(`${p}/lib/node_modules/`) || script.startsWith(`${p}/node_modules/`)) return { mode: "global" };
145
+ }
146
+ if (root && packages.length) return { mode: "project", root, pm: detectPackageManager(root), packages };
147
+ return { mode: "unknown" };
148
+ }
149
+ var commandText = (x) => [x.cmd, ...x.args].join(" ");
150
+ function buildUpdateCommands(install) {
151
+ if (install.mode === "npx") return [];
152
+ if (install.mode !== "project") return [{ cmd: "npm", args: ["install", "-g", "splithub@latest"] }];
153
+ const list = install.packages.some((p) => p.name === "splithub") ? install.packages : [...install.packages, { name: "splithub", dev: true }];
154
+ const add = { pnpm: ["add"], yarn: ["add"], bun: ["add"], npm: ["install"] }[install.pm];
155
+ const devFlag = { pnpm: "-D", yarn: "--dev", bun: "--dev", npm: "-D" }[install.pm];
156
+ const out = [];
157
+ for (const dev of [false, true]) {
158
+ const names = list.filter((p) => p.dev === dev).map((p) => `${p.name}@latest`);
159
+ if (names.length) out.push({ cmd: install.pm, args: [...add, ...dev ? [devFlag] : [], ...names], cwd: install.root });
160
+ }
161
+ return out;
162
+ }
163
+ function run(x) {
164
+ return new Promise((done) => {
165
+ const child = spawn(x.cmd, x.args, { cwd: x.cwd, stdio: "inherit", shell: process.platform === "win32" });
166
+ child.on("error", () => done(false));
167
+ child.on("exit", (code) => done(code === 0));
168
+ });
169
+ }
170
+ function startUpdateCheck(input, fetchImpl) {
171
+ if (!shouldCheckForUpdates(input)) return null;
172
+ const ctrl = new AbortController();
173
+ const timer = setTimeout(() => ctrl.abort(), CHECK_TIMEOUT_MS);
174
+ timer.unref?.();
175
+ let latest;
176
+ void fetchLatest("splithub", { signal: ctrl.signal, ...fetchImpl ? { fetchImpl } : {} }).then((v) => {
177
+ latest = v;
178
+ });
179
+ return {
180
+ settled: () => latest,
181
+ stop: () => {
182
+ clearTimeout(timer);
183
+ ctrl.abort();
184
+ }
185
+ };
186
+ }
187
+ async function offerUpdateAfterCommand(check) {
188
+ if (!check) return;
189
+ const latest = check.settled();
190
+ check.stop();
191
+ const current = currentVersion();
192
+ if (!latest || !isNewer(latest, current)) return;
193
+ try {
194
+ console.log();
195
+ await updateFlow({ current, latest, yes: false, install: detectInstall({ scriptPath: process.argv[1] ?? "", cwd: process.cwd() }) });
196
+ } catch {
197
+ }
198
+ }
199
+ async function updateFlow({ current, latest, yes, install }) {
200
+ const news = `splithub ${latest} is out (you have ${current}).`;
201
+ if (install.mode === "npx") {
202
+ console.log(`${c.cyan(news)} Run npx splithub@latest next time to get it.`);
203
+ return;
204
+ }
205
+ const commands = buildUpdateCommands(install);
206
+ const text = commands.map(commandText).join(" && ");
207
+ if (!yes) {
208
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
209
+ console.log(`${news} Update with: ${text}`);
210
+ return;
211
+ }
212
+ const p = await import("@clack/prompts");
213
+ const go = await p.confirm({ message: `${news} Update now?`, initialValue: true });
214
+ if (p.isCancel(go) || !go) return;
215
+ }
216
+ for (const x of commands) {
217
+ console.log(c.dim(`$ ${commandText(x)}`));
218
+ if (!await run(x)) {
219
+ console.log(c.red("The update didn't finish."), `Run it by hand: ${text}`);
220
+ process.exitCode = 1;
221
+ return;
222
+ }
223
+ }
224
+ console.log(c.green(`Updated to splithub ${latest}.`));
225
+ }
226
+ function installedVersion(root, name) {
227
+ let dir = resolve(root);
228
+ for (; ; ) {
229
+ const pkg = readPkg(join(dir, "node_modules", ...name.split("/"), "package.json"));
230
+ if (pkg?.version) return pkg.version;
231
+ const up = dirname(dir);
232
+ if (up === dir) return null;
233
+ dir = up;
234
+ }
235
+ }
236
+ async function versionReport(root, opts = {}) {
237
+ const listed = projectPackages(root);
238
+ const names = listed.map((p) => p.name);
239
+ if (!names.includes("splithub")) names.push("splithub");
240
+ const latest = await Promise.all(names.map((n) => fetchLatest(n, { timeoutMs: opts.timeoutMs ?? 2500, ...opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {} })));
241
+ const cli = opts.cliVersion ?? currentVersion();
242
+ const rows = names.map((name, i) => ({ name, installed: installedVersion(root, name) ?? (name === "splithub" ? cli : null), latest: latest[i] ?? null }));
243
+ const offline = latest.every((v) => v === null);
244
+ const installed = new Set(rows.map((r) => r.installed).filter((v) => v !== null));
245
+ const outdated = rows.filter((r) => r.installed && r.latest && isNewer(r.latest, r.installed)).map((r) => r.name);
246
+ const install = listed.length ? { mode: "project", root, pm: detectPackageManager(root), packages: listed } : { mode: "global" };
247
+ const mismatch = installed.size > 1;
248
+ const command = mismatch || outdated.length ? buildUpdateCommands(install).map(commandText).join(" && ") : null;
249
+ return { rows, offline, mismatch, outdated, command };
250
+ }
251
+
252
+ export {
253
+ currentVersion,
254
+ isNewer,
255
+ fetchLatest,
256
+ detectInstall,
257
+ commandText,
258
+ buildUpdateCommands,
259
+ startUpdateCheck,
260
+ offerUpdateAfterCommand,
261
+ updateFlow,
262
+ versionReport
263
+ };
264
+ //# sourceMappingURL=chunk-IFCSJYXN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/update.ts"],"sourcesContent":["// Update check and self-update. One GET to the npm registry per run, started at\n// startup in parallel with the command; the answer is used only if it arrived\n// before the command finished, so a slow network never delays anything. Nothing\n// is written to disk.\nimport { execSync, spawn } from 'node:child_process';\nimport { existsSync, readFileSync, realpathSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport { c } from './ui';\n\nexport const REGISTRY = 'https://registry.npmjs.org';\nconst CHECK_TIMEOUT_MS = 1500;\n\ntype FetchLike = (url: string, init?: { signal?: AbortSignal; headers?: Record<string, string> }) => Promise<{ ok: boolean; json(): Promise<unknown> }>;\n\nexport function currentVersion(): string {\n // From src/ and from dist/ alike, ../package.json is the CLI's own.\n return (createRequire(import.meta.url)('../package.json') as { version: string }).version;\n}\n\n// ---------- semver ----------\n\ninterface Semver {\n nums: [number, number, number];\n pre: string[];\n}\n\nfunction parse(v: string): Semver | null {\n const m = /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+.*)?$/.exec(v.trim());\n if (!m) return null;\n return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ? m[4].split('.') : [] };\n}\n\n/** Negative when a < b, 0 when equal, positive when a > b (semver precedence). Unparseable sorts lowest. */\nexport function compareSemver(a: string, b: string): number {\n const x = parse(a);\n const y = parse(b);\n if (!x || !y) return (x ? 1 : 0) - (y ? 1 : 0);\n for (let i = 0; i < 3; i++) if (x.nums[i] !== y.nums[i]) return x.nums[i]! - y.nums[i]!;\n if (!x.pre.length || !y.pre.length) return (x.pre.length ? 0 : 1) - (y.pre.length ? 0 : 1);\n for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {\n const p = x.pre[i];\n const q = y.pre[i];\n if (p === undefined) return -1;\n if (q === undefined) return 1;\n if (p === q) continue;\n const pn = /^\\d+$/.test(p);\n const qn = /^\\d+$/.test(q);\n if (pn && qn) return Number(p) - Number(q);\n if (pn !== qn) return pn ? -1 : 1;\n return p < q ? -1 : 1;\n }\n return 0;\n}\n\n/** Whether `latest` is worth offering: newer, and not a prerelease unless the user already runs one. */\nexport function isNewer(latest: string, current: string): boolean {\n const l = parse(latest);\n const cur = parse(current);\n if (!l || !cur) return false;\n if (l.pre.length && !cur.pre.length) return false;\n return compareSemver(latest, current) > 0;\n}\n\n// ---------- registry ----------\n\n/** The `latest` dist-tag of a package, or null on any error or timeout. */\nexport async function fetchLatest(name: string, opts: { signal?: AbortSignal; timeoutMs?: number; fetchImpl?: FetchLike } = {}): Promise<string | null> {\n const fetchImpl = opts.fetchImpl ?? (fetch as unknown as FetchLike);\n const signal = opts.signal ?? AbortSignal.timeout(opts.timeoutMs ?? CHECK_TIMEOUT_MS);\n try {\n const res = await fetchImpl(`${REGISTRY}/${name.replace('/', '%2f')}/latest`, { signal, headers: { accept: 'application/json' } });\n if (!res.ok) return null;\n const body = (await res.json()) as { version?: unknown } | null;\n return typeof body?.version === 'string' && parse(body.version) ? body.version : null;\n } catch {\n return null;\n }\n}\n\n// ---------- gating ----------\n\nconst CI_VARS = ['CI', 'CONTINUOUS_INTEGRATION', 'GITHUB_ACTIONS', 'GITLAB_CI', 'BUILDKITE', 'CIRCLECI', 'TRAVIS', 'JENKINS_URL', 'TEAMCITY_VERSION', 'TF_BUILD', 'BITBUCKET_BUILD_NUMBER', 'CODEBUILD_BUILD_ID', 'BUILD_NUMBER', 'RUN_ID'];\n\nexport function isCi(env: NodeJS.ProcessEnv): boolean {\n return CI_VARS.some((k) => {\n const v = env[k];\n return v !== undefined && v !== '' && v !== '0' && v.toLowerCase() !== 'false';\n });\n}\n\nexport interface GateInput {\n argv: string[];\n env: NodeJS.ProcessEnv;\n stdinTTY: boolean | undefined;\n stdoutTTY: boolean | undefined;\n}\n\n/** The automatic check runs only for a person at a terminal: never for agents, CI, the MCP server or pipes. */\nexport function shouldCheckForUpdates({ argv, env, stdinTTY, stdoutTTY }: GateInput): boolean {\n if (!stdinTTY || !stdoutTTY) return false;\n if (argv.includes('--json')) return false;\n if (env.SPLITHUB_NO_UPDATE_CHECK === '1' || env.SPLITHUB_MCP === '1') return false;\n if (isCi(env)) return false;\n // `update` checks on its own; `dev` never finishes, so there is no \"after\" to ask in.\n const command = argv.find((a) => !a.startsWith('-'));\n return command !== 'update' && command !== 'dev';\n}\n\n// ---------- install mode ----------\n\nexport type PackageManager = 'pnpm' | 'yarn' | 'bun' | 'npm';\n\nexport type InstallMode =\n | { mode: 'project'; root: string; pm: PackageManager; packages: { name: string; dev: boolean }[] }\n | { mode: 'global' }\n | { mode: 'npx' }\n | { mode: 'unknown' };\n\ninterface PackageJson {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\nconst isOurs = (name: string) => name === 'splithub' || name.startsWith('@splithub/');\n\nfunction readPkg(file: string): PackageJson | null {\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as PackageJson;\n } catch {\n return null;\n }\n}\n\n/** Nearest directory at or above `cwd` with a package.json. */\nexport function findProjectRoot(cwd: string): string | null {\n let dir = resolve(cwd);\n for (;;) {\n if (existsSync(join(dir, 'package.json'))) return dir;\n const up = dirname(dir);\n if (up === dir) return null;\n dir = up;\n }\n}\n\n/** Package manager from the nearest lockfile at or above `root` (workspaces keep it at the top). */\nexport function detectPackageManager(root: string): PackageManager {\n let dir = resolve(root);\n for (;;) {\n const has = (f: string) => existsSync(join(dir, f));\n if (has('pnpm-lock.yaml')) return 'pnpm';\n if (has('yarn.lock')) return 'yarn';\n if (has('bun.lockb') || has('bun.lock')) return 'bun';\n if (has('package-lock.json')) return 'npm';\n const up = dirname(dir);\n if (up === dir) return 'npm';\n dir = up;\n }\n}\n\n/** splithub and every @splithub/* package the project lists, with its section. */\nexport function projectPackages(root: string): { name: string; dev: boolean }[] {\n const pkg = readPkg(join(root, 'package.json'));\n if (!pkg) return [];\n const prod = Object.keys(pkg.dependencies ?? {}).filter(isOurs).map((name) => ({ name, dev: false }));\n const dev = Object.keys(pkg.devDependencies ?? {})\n .filter((n) => isOurs(n) && !prod.some((p) => p.name === n))\n .map((name) => ({ name, dev: true }));\n return [...prod, ...dev];\n}\n\nfunction npmGlobalPrefix(): string | null {\n if (process.env.npm_config_prefix) return process.env.npm_config_prefix;\n try {\n return execSync('npm prefix -g', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000 }).trim() || null;\n } catch {\n return null;\n }\n}\n\nconst norm = (p: string) => p.replace(/[\\\\/]+/g, '/').toLowerCase();\n\nexport interface DetectInput {\n /** Path of the running CLI (process.argv[1]). */\n scriptPath: string;\n cwd: string;\n /** npm's global prefix; looked up lazily when omitted. */\n globalPrefix?: () => string | null;\n}\n\nexport function detectInstall({ scriptPath, cwd, globalPrefix = npmGlobalPrefix }: DetectInput): InstallMode {\n let real = scriptPath;\n try {\n real = realpathSync(scriptPath);\n } catch {\n // keep the path as given\n }\n const script = norm(real);\n if (/\\/_npx\\//.test(script) || /\\/dlx-[^/]*\\//.test(script)) return { mode: 'npx' };\n\n const root = findProjectRoot(cwd);\n const packages = root ? projectPackages(root) : [];\n // Running from node_modules of this project (or a workspace root above it).\n const local = root !== null && (() => {\n let dir = root;\n for (;;) {\n if (script.startsWith(norm(join(dir, 'node_modules')) + '/')) return true;\n const up = dirname(dir);\n if (up === dir) return false;\n dir = up;\n }\n })();\n if (root && local && packages.length) return { mode: 'project', root, pm: detectPackageManager(root), packages };\n\n const prefix = globalPrefix();\n if (prefix) {\n const p = norm(prefix);\n if (script.startsWith(`${p}/lib/node_modules/`) || script.startsWith(`${p}/node_modules/`)) return { mode: 'global' };\n }\n if (root && packages.length) return { mode: 'project', root, pm: detectPackageManager(root), packages };\n return { mode: 'unknown' };\n}\n\n// ---------- commands ----------\n\nexport interface Command {\n cmd: string;\n args: string[];\n cwd?: string;\n}\n\nexport const commandText = (x: Command): string => [x.cmd, ...x.args].join(' ');\n\n/** Commands that move this install to the latest release (empty for npx: nothing to install). */\nexport function buildUpdateCommands(install: InstallMode): Command[] {\n if (install.mode === 'npx') return [];\n if (install.mode !== 'project') return [{ cmd: 'npm', args: ['install', '-g', 'splithub@latest'] }];\n const list = install.packages.some((p) => p.name === 'splithub') ? install.packages : [...install.packages, { name: 'splithub', dev: true }];\n const add = { pnpm: ['add'], yarn: ['add'], bun: ['add'], npm: ['install'] }[install.pm];\n const devFlag = { pnpm: '-D', yarn: '--dev', bun: '--dev', npm: '-D' }[install.pm];\n const out: Command[] = [];\n for (const dev of [false, true]) {\n const names = list.filter((p) => p.dev === dev).map((p) => `${p.name}@latest`);\n if (names.length) out.push({ cmd: install.pm, args: [...add, ...(dev ? [devFlag] : []), ...names], cwd: install.root });\n }\n return out;\n}\n\nfunction run(x: Command): Promise<boolean> {\n return new Promise((done) => {\n // npm, pnpm and yarn are .cmd shims on Windows; the arguments are package names only.\n const child = spawn(x.cmd, x.args, { cwd: x.cwd, stdio: 'inherit', shell: process.platform === 'win32' });\n child.on('error', () => done(false));\n child.on('exit', (code) => done(code === 0));\n });\n}\n\n// ---------- flows ----------\n\n/** The update check started at launch: read its answer without waiting, then stop it. */\nexport interface StartedCheck {\n settled(): string | null | undefined;\n stop(): void;\n}\n\nexport function startUpdateCheck(input: GateInput, fetchImpl?: FetchLike): StartedCheck | null {\n if (!shouldCheckForUpdates(input)) return null;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), CHECK_TIMEOUT_MS);\n timer.unref?.();\n let latest: string | null | undefined;\n void fetchLatest('splithub', { signal: ctrl.signal, ...(fetchImpl ? { fetchImpl } : {}) }).then((v) => {\n latest = v;\n });\n return {\n settled: () => latest,\n stop: () => {\n clearTimeout(timer);\n ctrl.abort();\n },\n };\n}\n\n/** After the command: if the registry answered in time with a newer version, offer it. */\nexport async function offerUpdateAfterCommand(check: StartedCheck | null): Promise<void> {\n if (!check) return;\n const latest = check.settled();\n check.stop();\n const current = currentVersion();\n if (!latest || !isNewer(latest, current)) return;\n try {\n console.log();\n await updateFlow({ current, latest, yes: false, install: detectInstall({ scriptPath: process.argv[1] ?? '', cwd: process.cwd() }) });\n } catch {\n // An update offer must never turn a finished command into a failure.\n }\n}\n\nexport async function updateFlow({ current, latest, yes, install }: { current: string; latest: string; yes: boolean; install: InstallMode }): Promise<void> {\n const news = `splithub ${latest} is out (you have ${current}).`;\n if (install.mode === 'npx') {\n console.log(`${c.cyan(news)} Run npx splithub@latest next time to get it.`);\n return;\n }\n const commands = buildUpdateCommands(install);\n const text = commands.map(commandText).join(' && ');\n if (!yes) {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n console.log(`${news} Update with: ${text}`);\n return;\n }\n const p = await import('@clack/prompts');\n const go = await p.confirm({ message: `${news} Update now?`, initialValue: true });\n if (p.isCancel(go) || !go) return;\n }\n for (const x of commands) {\n console.log(c.dim(`$ ${commandText(x)}`));\n if (!(await run(x))) {\n console.log(c.red(\"The update didn't finish.\"), `Run it by hand: ${text}`);\n process.exitCode = 1;\n return;\n }\n }\n console.log(c.green(`Updated to splithub ${latest}.`));\n}\n\n// ---------- doctor ----------\n\n/** Installed version of a package, from the nearest node_modules at or above `root`. */\nexport function installedVersion(root: string, name: string): string | null {\n let dir = resolve(root);\n for (;;) {\n const pkg = readPkg(join(dir, 'node_modules', ...name.split('/'), 'package.json')) as { version?: string } | null;\n if (pkg?.version) return pkg.version;\n const up = dirname(dir);\n if (up === dir) return null;\n dir = up;\n }\n}\n\nexport interface VersionRow {\n name: string;\n installed: string | null;\n latest: string | null;\n}\n\nexport interface VersionReport {\n rows: VersionRow[];\n offline: boolean;\n /** Installed SDK packages and the CLI disagree. */\n mismatch: boolean;\n outdated: string[];\n command: string | null;\n}\n\n/** Versions of splithub and @splithub/* in the project vs npm, for `splithub doctor`. */\nexport async function versionReport(root: string, opts: { fetchImpl?: FetchLike; cliVersion?: string; timeoutMs?: number } = {}): Promise<VersionReport> {\n const listed = projectPackages(root);\n const names = listed.map((p) => p.name);\n if (!names.includes('splithub')) names.push('splithub');\n const latest = await Promise.all(names.map((n) => fetchLatest(n, { timeoutMs: opts.timeoutMs ?? 2500, ...(opts.fetchImpl ? { fetchImpl: opts.fetchImpl } : {}) })));\n const cli = opts.cliVersion ?? currentVersion();\n const rows = names.map((name, i) => ({ name, installed: installedVersion(root, name) ?? (name === 'splithub' ? cli : null), latest: latest[i] ?? null }));\n const offline = latest.every((v) => v === null);\n const installed = new Set(rows.map((r) => r.installed).filter((v): v is string => v !== null));\n const outdated = rows.filter((r) => r.installed && r.latest && isNewer(r.latest, r.installed)).map((r) => r.name);\n const install: InstallMode = listed.length ? { mode: 'project', root, pm: detectPackageManager(root), packages: listed } : { mode: 'global' };\n const mismatch = installed.size > 1;\n const command = mismatch || outdated.length ? buildUpdateCommands(install).map(commandText).join(' && ') : null;\n return { rows, offline, mismatch, outdated, command };\n}\n"],"mappings":";;;;;;AAIA,SAAS,UAAU,aAAa;AAChC,SAAS,YAAY,cAAc,oBAAoB;AACvD,SAAS,qBAAqB;AAC9B,SAAS,SAAS,MAAM,eAAoB;AAGrC,IAAM,WAAW;AACxB,IAAM,mBAAmB;AAIlB,SAAS,iBAAyB;AAEvC,SAAQ,cAAc,YAAY,GAAG,EAAE,iBAAiB,EAA0B;AACpF;AASA,SAAS,MAAM,GAA0B;AACvC,QAAM,IAAI,yDAAyD,KAAK,EAAE,KAAK,CAAC;AAChF,MAAI,CAAC,EAAG,QAAO;AACf,SAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,GAAG,KAAK,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC,EAAE;AAC9F;AAGO,SAAS,cAAc,GAAW,GAAmB;AAC1D,QAAM,IAAI,MAAM,CAAC;AACjB,QAAM,IAAI,MAAM,CAAC;AAC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KAAK,UAAU,IAAI,CAAC,EAAG,CAAC,CAAC,CAAC;AAClK,QAAM,MAAM,KAAK,cAAc,eAAe;AAC9C,QAAM,OAAO,MAAM,IAAI,CAAC,MAAM,OAAO,EAAE,MAAM,WAAW,iBAAiB,MAAM,IAAI,MAAM,SAAS,aAAa,MAAM,OAAO,QAAQ,OAAO,CAAC,KAAK,KAAK,EAAE;AACxJ,QAAM,UAAU,OAAO,MAAM,CAAC,MAAM,MAAM,IAAI;AAC9C,QAAM,YAAY,IAAI,IAAI,KAAK,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,MAAmB,MAAM,IAAI,CAAC;AAC7F,QAAM,WAAW,KAAK,OAAO,CAAC,MAAM,EAAE,aAAa,EAAE,UAAU,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI;AAChH,QAAM,UAAuB,OAAO,SAAS,EAAE,MAAM,WAAW,MAAM,IAAI,qBAAqB,IAAI,GAAG,UAAU,OAAO,IAAI,EAAE,MAAM,SAAS;AAC5I,QAAM,WAAW,UAAU,OAAO;AAClC,QAAM,UAAU,YAAY,SAAS,SAAS,oBAAoB,OAAO,EAAE,IAAI,WAAW,EAAE,KAAK,MAAM,IAAI;AAC3G,SAAO,EAAE,MAAM,SAAS,UAAU,UAAU,QAAQ;AACtD;","names":[]}
@@ -1,22 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  findRefs
4
- } from "./chunk-GVARYUL3.js";
4
+ } from "./chunk-D7KVM4L7.js";
5
+ import {
6
+ versionReport
7
+ } from "./chunk-IFCSJYXN.js";
5
8
  import {
6
9
  loadConfig
7
- } from "./chunk-3VY5CP3E.js";
10
+ } from "./chunk-6OXCLYOI.js";
8
11
  import {
9
12
  resolveTarget
10
- } from "./chunk-EUF75FUC.js";
13
+ } from "./chunk-ZND3T67D.js";
11
14
  import {
12
15
  detectProject,
13
16
  grepFiles,
14
17
  listSourceFiles
15
- } from "./chunk-PLXDG4B5.js";
18
+ } from "./chunk-PLZRB3VX.js";
16
19
  import {
17
20
  c,
18
21
  printJson
19
- } from "./chunk-V3DLUVOE.js";
22
+ } from "./chunk-EJC4E3VD.js";
20
23
 
21
24
  // src/commands/doctor.ts
22
25
  import { existsSync, readFileSync } from "fs";
@@ -26,6 +29,7 @@ async function doctor(flags) {
26
29
  const add = (level, message) => checks.push({ level, message });
27
30
  const project = detectProject();
28
31
  add("ok", `project "${project.name}" \xB7 ${project.framework} \xB7 ${project.packageManager}`);
32
+ await versionChecks(project.root, add);
29
33
  if (!project.configFile) {
30
34
  add("error", "splithub.config.ts not found. Run `npx splithub init`.");
31
35
  return report(checks, flags);
@@ -83,6 +87,17 @@ async function doctor(flags) {
83
87
  }
84
88
  return report(checks, flags);
85
89
  }
90
+ async function versionChecks(root, add) {
91
+ const v = await versionReport(root);
92
+ const list = v.rows.map((r) => `${r.name} ${r.installed ?? "not installed"}`).join(", ");
93
+ if (v.mismatch) add("warn", `versions differ: ${list}. Update them together: ${v.command}`);
94
+ else add("ok", `versions: ${list}`);
95
+ if (v.offline) add("warn", "couldn't reach npm, so the latest versions weren't checked");
96
+ else if (v.outdated.length) {
97
+ const what = v.rows.filter((r) => v.outdated.includes(r.name)).map((r) => `${r.name} ${r.installed} \u2192 ${r.latest}`).join(", ");
98
+ add("warn", `updates available: ${what}` + (v.mismatch ? "" : `. Run ${v.command}`));
99
+ }
100
+ }
86
101
  function report(checks, flags) {
87
102
  const errors = checks.filter((x) => x.level === "error").length;
88
103
  if (flags.json) {
@@ -101,4 +116,4 @@ function report(checks, flags) {
101
116
  export {
102
117
  doctor
103
118
  };
104
- //# sourceMappingURL=chunk-YSXW2HN6.js.map
119
+ //# sourceMappingURL=chunk-IGYK7N2F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/doctor.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport { resolveTarget } from '../api';\nimport { loadConfig } from '../config-file';\nimport { printJson } from '../errors';\nimport { detectProject, grepFiles, listSourceFiles } from '../project';\nimport { findRefs } from '../refs';\nimport { c } from '../ui';\nimport { versionReport } from '../update';\nimport type { Flags } from './init';\n\ntype Level = 'ok' | 'warn' | 'error';\ninterface Check {\n level: Level;\n message: string;\n}\n\nexport async function doctor(flags: Flags): Promise<void> {\n const checks: Check[] = [];\n const add = (level: Level, message: string) => checks.push({ level, message });\n const project = detectProject();\n\n add('ok', `project \"${project.name}\" · ${project.framework} · ${project.packageManager}`);\n await versionChecks(project.root, add);\n\n if (!project.configFile) {\n add('error', 'splithub.config.ts not found. Run `npx splithub init`.');\n return report(checks, flags);\n }\n add('ok', `config: ${relative(project.root, project.configFile)}`);\n\n let config;\n try {\n config = await loadConfig(project.configFile);\n add('ok', `config loads · ${config.experiments.length} experiment(s) · storage ${config.storage.mode}`);\n } catch (error) {\n add('error', `config does not load: ${error instanceof Error ? error.message : String(error)}`);\n return report(checks, flags);\n }\n\n const files = listSourceFiles(project.root);\n const providerHits = grepFiles(files, 'SplitHubProvider').concat(grepFiles(files, 'SplitHubNextProvider'));\n if (providerHits.length === 0) add('error', 'no <SplitHubProvider> found in source. Wrap your app once.');\n else add('ok', `provider in ${relative(project.root, providerHits[0]!)}`);\n\n if (project.framework === 'next') {\n const mw = ['middleware.ts', 'src/middleware.ts', 'middleware.js', 'src/middleware.js'].map((f) => join(project.root, f)).find((f) => existsSync(f));\n const hasRedirects = config.experiments.some((e) => e.kind === 'redirect');\n if (!mw) add(hasRedirects ? 'error' : 'warn', 'no middleware.ts: visitor cookie is not set on the server (SSR may flicker)' + (hasRedirects ? '; redirect experiments will not run' : ''));\n else if (!readFileSync(mw, 'utf8').includes('splithubMiddleware')) add('warn', `${relative(project.root, mw)} does not call splithubMiddleware()`);\n else add('ok', `middleware: ${relative(project.root, mw)}`);\n if (config.storage.mode === 'self' && project.appDir) {\n const catchAll = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n const plain = join(project.root, project.appDir, 'api/splithub/route.ts');\n if (existsSync(catchAll)) add('ok', `ingest route: ${relative(project.root, catchAll)}`);\n else if (existsSync(plain)) add('error', `${relative(project.root, plain)} only serves POST /api/splithub; move it to api/splithub/[[...path]]/route.ts so /status and /results work`);\n else add('error', `self mode but ${relative(project.root, catchAll)} is missing (ingest endpoint)`);\n }\n }\n\n for (const exp of config.experiments) {\n const label = `${exp.key} (${exp.kind}, ${exp.status})`;\n if (!exp.goal) add(exp.status === 'running' ? 'error' : 'warn', `${label}: no goal; the verdict cannot be computed`);\n if (exp.kind !== 'redirect') {\n const used = findRefs(project.root, config, exp.key, files).refs.filter((r) => r.match === 'experiment').length;\n if (used === 0) add(exp.status === 'running' ? 'error' : 'warn', `${label}: not referenced in code (useValue/useVariant/<Experiment id>)`);\n }\n if (exp.status === 'running' && exp.variants.every((v) => v.weight === 0)) add('error', `${label}: all weights are 0`);\n }\n for (const goal of config.goals) {\n if (goal.type === 'event' && grepFiles(files, `'${goal.key}'`).length + grepFiles(files, `\"${goal.key}\"`).length === 0) {\n add('warn', `goal \"${goal.key}\": track('${goal.key}') is never called`);\n }\n }\n\n const target = resolveTarget(flags, project);\n try {\n const ctrl = new AbortController();\n const t = setTimeout(() => ctrl.abort(), 2500);\n const res = await fetch(`${target.url}/health`, { signal: ctrl.signal });\n clearTimeout(t);\n add(res.ok ? 'ok' : 'warn', `endpoint ${target.url}/health → ${res.status}`);\n } catch {\n add('warn', `endpoint ${target.url} not reachable (is the dev server running?)`);\n }\n\n return report(checks, flags);\n}\n\nasync function versionChecks(root: string, add: (level: Level, message: string) => void): Promise<void> {\n const v = await versionReport(root);\n const list = v.rows.map((r) => `${r.name} ${r.installed ?? 'not installed'}`).join(', ');\n if (v.mismatch) add('warn', `versions differ: ${list}. Update them together: ${v.command}`);\n else add('ok', `versions: ${list}`);\n if (v.offline) add('warn', \"couldn't reach npm, so the latest versions weren't checked\");\n else if (v.outdated.length) {\n const what = v.rows.filter((r) => v.outdated.includes(r.name)).map((r) => `${r.name} ${r.installed} → ${r.latest}`).join(', ');\n add('warn', `updates available: ${what}` + (v.mismatch ? '' : `. Run ${v.command}`));\n }\n}\n\nfunction report(checks: Check[], flags: Flags): void {\n const errors = checks.filter((x) => x.level === 'error').length;\n if (flags.json) {\n printJson({ ok: errors === 0, errors, warnings: checks.filter((x) => x.level === 'warn').length, checks });\n } else {\n for (const x of checks) {\n const icon = x.level === 'ok' ? c.green('✔') : x.level === 'warn' ? c.yellow('!') : c.red('✖');\n console.log(`${icon} ${x.message}`);\n }\n console.log();\n console.log(errors === 0 ? c.green('All good.') : c.red(`${errors} problem(s) to fix.`));\n }\n if (errors > 0) process.exitCode = 1;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,oBAAoB;AACzC,SAAS,MAAM,gBAAgB;AAgB/B,eAAsB,OAAO,OAA6B;AACxD,QAAM,SAAkB,CAAC;AACzB,QAAM,MAAM,CAAC,OAAc,YAAoB,OAAO,KAAK,EAAE,OAAO,QAAQ,CAAC;AAC7E,QAAM,UAAU,cAAc;AAE9B,MAAI,MAAM,YAAY,QAAQ,IAAI,UAAO,QAAQ,SAAS,SAAM,QAAQ,cAAc,EAAE;AACxF,QAAM,cAAc,QAAQ,MAAM,GAAG;AAErC,MAAI,CAAC,QAAQ,YAAY;AACvB,QAAI,SAAS,wDAAwD;AACrE,WAAO,OAAO,QAAQ,KAAK;AAAA,EAC7B;AACA,MAAI,MAAM,WAAW,SAAS,QAAQ,MAAM,QAAQ,UAAU,CAAC,EAAE;AAEjE,MAAI;AACJ,MAAI;AACF,aAAS,MAAM,WAAW,QAAQ,UAAU;AAC5C,QAAI,MAAM,qBAAkB,OAAO,YAAY,MAAM,+BAA4B,OAAO,QAAQ,IAAI,EAAE;AAAA,EACxG,SAAS,OAAO;AACd,QAAI,SAAS,yBAAyB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAC9F,WAAO,O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AAM,WAAW,IAAI,EAAE,IAAI,GAAG,MAAM,qBAAqB,CAAC;AAAA,EACzF;AACA,MAAI,SAAS,EAAG,SAAQ,WAAW;AACrC;","names":[]}
@@ -1,29 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  deviceLogin
4
- } from "./chunk-PWSRKABE.js";
4
+ } from "./chunk-BSWCWCYP.js";
5
5
  import {
6
- cloudTarget,
7
- loadCredential
8
- } from "./chunk-EUF75FUC.js";
9
- import {
10
- installSkills
11
- } from "./chunk-AJO3C4BS.js";
6
+ installSkills,
7
+ loadSkillFiles
8
+ } from "./chunk-X5AV7YBR.js";
12
9
  import {
13
10
  configTemplate,
14
11
  nextMiddlewareTemplate,
15
12
  nextRouteTemplate
16
- } from "./chunk-3DUWIEHB.js";
13
+ } from "./chunk-BQAWJPIK.js";
14
+ import {
15
+ cloudTarget,
16
+ loadCredential
17
+ } from "./chunk-ZND3T67D.js";
17
18
  import {
18
19
  writeWorkflow
19
- } from "./chunk-EYYLDI5J.js";
20
+ } from "./chunk-NTAIRQP6.js";
20
21
  import {
21
22
  detectProject,
22
23
  installCommand
23
- } from "./chunk-PLXDG4B5.js";
24
+ } from "./chunk-PLZRB3VX.js";
24
25
  import {
25
26
  c
26
- } from "./chunk-V3DLUVOE.js";
27
+ } from "./chunk-EJC4E3VD.js";
27
28
 
28
29
  // src/commands/init.ts
29
30
  import * as p from "@clack/prompts";
@@ -323,7 +324,7 @@ Code ${c.green(s.userCode)} \xB7 sign in, pick or create the project, approve.`,
323
324
  if (p.isCancel(want)) return cancel2();
324
325
  mcp = want;
325
326
  }
326
- const skillsResult = installSkills(project.root, { mcp });
327
+ const skillsResult = installSkills(project.root, { mcp, ...await loadSkillFiles(flags) });
327
328
  created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));
328
329
  skipped.push(...skillsResult.skipped);
329
330
  if (flags["github-action"]) {
@@ -390,4 +391,4 @@ function cancel2() {
390
391
  export {
391
392
  init
392
393
  };
393
- //# sourceMappingURL=chunk-QOXGIB3R.js.map
394
+ //# sourceMappingURL=chunk-LK3NRAHA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/init.ts","../src/templates-store.ts"],"sourcesContent":["import * as p from '@clack/prompts';\nimport { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { cloudTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject, installCommand } from '../project';\nimport { deviceLogin } from './login';\nimport { configTemplate, nextMiddlewareTemplate, nextRouteTemplate } from '../templates';\nimport { DB_KINDS, runtimePackages, storeTemplate, storeUsage, type DbKind } from '../templates-store';\nimport { installSkills, loadSkillFiles } from './skills';\nimport { writeWorkflow } from './ci';\nimport { c } from '../ui';\n\nexport type Flags = Record<string, string | boolean | string[] | undefined>;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction writeIfMissing(file: string, content: string, created: string[], skipped: string[]): void {\n if (existsSync(file)) {\n skipped.push(file);\n return;\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n created.push(file);\n}\n\nfunction importPath(fromFile: string, toFile: string): string {\n let rel = relative(dirname(fromFile), toFile).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');\n if (!rel.startsWith('.')) rel = `./${rel}`;\n return rel;\n}\n\n// Vite apps run the SDK in the browser; this plugin prints what each experiment does in the dev server's terminal.\nconst VITE_PLUGIN_HINT = `// vite.config.ts\nimport { splithub } from '@splithub/core/vite';\n\nexport default defineConfig({ plugins: [react(), splithub()] });`;\n\nexport async function init(flags: Flags): Promise<void> {\n const yes = Boolean(flags.yes);\n const json = Boolean(flags.json);\n const project = detectProject();\n const created: string[] = [];\n const skipped: string[] = [];\n\n if (!json) p.intro(c.bold('splithub init'));\n\n let mode = str(flags.mode) as 'self' | 'cloud' | undefined;\n if (!mode) {\n if (yes) mode = 'self';\n else {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'self', label: 'My own database (self-hosted)', hint: 'free forever, nothing leaves your infra' },\n { value: 'cloud', label: 'SplitHub Cloud', hint: 'hosted dashboard, no server code' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n mode = picked as 'self' | 'cloud';\n }\n }\n\n // Cloud: connect this directory to a project. A saved login or SPLITHUB_API_KEY\n // is enough; otherwise run the device flow — print a link, the human signs in\n // and picks (or creates) the project, the CLI gets the keys. Works when an\n // agent runs init: it relays the link, the user clicks it.\n // Self mode: which database keeps the events. sqlite needs nothing; postgres / mysql\n // get a ready Store in splithub/store.ts; custom gets a documented stub.\n let db: DbKind = (DB_KINDS as string[]).includes(str(flags.db) ?? '') ? (str(flags.db) as DbKind) : 'sqlite';\n if (mode === 'self' && !flags.db && !yes) {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'sqlite', label: 'SQLite file (zero setup)', hint: './splithub.db via node:sqlite' },\n { value: 'postgres', label: 'Postgres', hint: 'pg + DATABASE_URL, table splithub_events' },\n { value: 'mysql', label: 'MySQL / MariaDB / PlanetScale', hint: 'mysql2 + DATABASE_URL' },\n { value: 'custom', label: 'My own store (Prisma, Drizzle, Supabase, Mongo…)', hint: 'a stub with the three methods to fill in' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n db = picked as DbKind;\n }\n\n let key = str(flags.key);\n let connected: { projectName: string | null; projectId: string | null } | null = null;\n if (mode === 'cloud') {\n const api = cloudTarget(flags).url;\n const saved = loadCredential(api, project.root);\n if (saved) {\n key ??= saved.publicKey ?? undefined;\n connected = { projectName: saved.projectName, projectId: saved.projectId };\n } else if (!process.env.SPLITHUB_API_KEY && !flags['no-login']) {\n if (!json) p.log.step('Connect to SplitHub Cloud');\n try {\n const cred = await deviceLogin({\n api,\n root: project.root,\n json,\n onCode: json\n ? (s) => console.log(JSON.stringify({ step: 'approve', verifyUrl: s.verifyUrl, userCode: s.userCode, expiresIn: s.expiresIn, hint: 'Show this link to the user and wait; init continues once approved.' }))\n : (s) => p.note(`${c.cyan(s.verifyUrl)}\\n\\nCode ${c.green(s.userCode)} · sign in, pick or create the project, approve.`, 'Open this link'),\n });\n key ??= cred.publicKey ?? undefined;\n connected = { projectName: cred.projectName, projectId: cred.projectId };\n if (!json) p.log.success(`connected to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n } catch (error) {\n if (!json) p.log.warn(`not connected: ${error instanceof Error ? error.message : String(error)}. Run ${c.cyan('npx splithub login')} later.`);\n }\n }\n // An API key in the environment (CI, agents) identifies the project: ask the cloud for its public key.\n if (!key && process.env.SPLITHUB_API_KEY) {\n try {\n const res = await fetch(`${api}/config`, { headers: { authorization: `Bearer ${process.env.SPLITHUB_API_KEY}` } });\n const body = (await res.json().catch(() => ({}))) as { publicKey?: string };\n if (typeof body.publicKey === 'string' && body.publicKey.startsWith('pk_')) {\n key = body.publicKey;\n connected ??= { projectName: null, projectId: null };\n }\n } catch {\n // offline: the first push writes the key into the config anyway\n }\n }\n if (!key && !yes) {\n const k = await p.text({ message: 'Cloud public key (pk_...), leave empty to set later via NEXT_PUBLIC_SPLITHUB_KEY', placeholder: 'pk_' });\n if (p.isCancel(k)) return cancel();\n key = k || undefined;\n }\n }\n\n // 1. config\n const configFile = project.configFile ?? join(project.root, 'splithub.config.ts');\n writeIfMissing(configFile, configTemplate(project.name, mode, key), created, skipped);\n\n // 2a. store for self mode (postgres / mysql / custom); sqlite needs no file.\n const storeBody = mode === 'self' ? storeTemplate(db) : null;\n const storeFile = storeBody ? join(project.root, 'splithub', 'store.ts') : null;\n if (storeFile && storeBody) writeIfMissing(storeFile, storeBody, created, skipped);\n\n // 2. framework files\n if (project.framework === 'next') {\n const mwFile = join(project.root, project.hasSrc ? 'src/middleware.ts' : 'middleware.ts');\n writeIfMissing(mwFile, nextMiddlewareTemplate(importPath(mwFile, configFile)), created, skipped);\n if (mode === 'self' && project.appDir) {\n const routeFile = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n writeIfMissing(routeFile, nextRouteTemplate(importPath(routeFile, configFile), storeUsage(db, storeFile ? importPath(routeFile, storeFile) : '')), created, skipped);\n }\n }\n\n // 3. agent skills (+ MCP server registration): the agent learns the library, how to test\n // well, the API and the MCP tools from .claude/skills/*; Cursor gets the rule file.\n let mcp = !flags['no-mcp'];\n if (!yes && !json && mcp) {\n const want = await p.confirm({ message: 'Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?', initialValue: true });\n if (p.isCancel(want)) return cancel();\n mcp = want;\n }\n const skillsResult = installSkills(project.root, { mcp, ...(await loadSkillFiles(flags)) });\n created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));\n skipped.push(...skillsResult.skipped);\n\n // 3b. GitHub workflow: checks on PRs, results comment on a schedule.\n if (flags['github-action']) {\n const wf = writeWorkflow(project.root, Boolean(flags.force));\n (wf.written ? created : skipped).push(join(project.root, wf.file));\n }\n\n // 4. dependencies\n const runtime = ['@splithub/react', '@splithub/core'];\n if (project.framework === 'next') runtime.push('@splithub/next');\n if (mode === 'self') runtime.push('@splithub/node', ...runtimePackages(db));\n const installRuntime = installCommand(project.packageManager, runtime);\n const installDev = installCommand(project.packageManager, ['splithub'], true);\n let installed = false;\n if (!flags['no-install']) {\n const go = yes ? true : await p.confirm({ message: `Install packages now? (${installRuntime})` });\n if (p.isCancel(go)) return cancel();\n if (go) {\n const s = json ? null : p.spinner();\n s?.start('Installing');\n try {\n execSync(installRuntime, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n execSync(installDev, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n installed = true;\n s?.stop('Installed');\n } catch (error) {\n s?.stop('Install failed; run it manually');\n if (!json) p.log.error(error instanceof Error ? error.message : String(error));\n }\n }\n }\n\n const providerHint =\n project.framework === 'next'\n ? `// ${project.appDir ?? 'app'}/layout.tsx\\nimport { SplitHubNextProvider } from '@splithub/next/client';\\nimport { getSplitHub } from '@splithub/next/server';\\nimport config from '${importPath(join(project.root, project.appDir ?? 'app', 'layout.tsx'), configFile)}';\\n\\nexport default async function RootLayout({ children }) {\\n const sh = await getSplitHub(config);\\n return <html><body><SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider></body></html>;\\n}`\n : `// main.tsx\\nimport { SplitHubProvider } from '@splithub/react';\\nimport config from './splithub.config';\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>`;\n\n const warning = mode === 'cloud' && !key ? 'No public key yet: storage.key falls back to process.env.NEXT_PUBLIC_SPLITHUB_KEY. It is written into the config by the first `npx splithub push`, by `npx splithub login` (saved with the credentials), or pass --key pk_… (dashboard → Setup); SPLITHUB_API_KEY in the environment also resolves it.' : null;\n const summary = { project: project.name, framework: project.framework, mode, db: mode === 'self' ? db : null, connected, publicKey: key ?? null, warning, created, skipped, installed, installCommands: installed ? [] : [installRuntime, installDev], nextStep: providerHint, ...(project.framework === 'vite' ? { vitePlugin: VITE_PLUGIN_HINT } : {}) };\n\n if (json) {\n console.log(JSON.stringify(summary));\n return;\n }\n if (warning) p.log.warn(warning);\n if (mode === 'self' && db !== 'sqlite') p.note(db === 'custom' ? 'Fill in the three methods in splithub/store.ts (the comments say what each must return).' : `Set DATABASE_URL and run the SCHEMA_SQL from splithub/store.ts once (or add it to your migrations).`, `Database: ${db}`);\n if (created.length) p.note(created.map((f) => relative(project.root, f) || f).join('\\n'), 'Created');\n if (skipped.length) p.note(skipped.map((f) => relative(project.root, f)).join('\\n'), 'Already present, left untouched');\n if (!installed) p.note(`${installRuntime}\\n${installDev}`, 'Install');\n p.note(providerHint, 'Wrap your app once');\n if (project.framework === 'vite') p.note(VITE_PLUGIN_HINT, 'Notes in your dev terminal');\n p.outro(`Next: ${c.cyan('npx splithub create')} to add your first experiment, ${c.cyan('npx splithub push')} to sync it, ${c.cyan('npx splithub doctor')} to verify.`);\n}\n\n\nfunction cancel(): void {\n p.cancel('Cancelled.');\n process.exit(0);\n}\n","// Store templates for self-hosted mode: `splithub init --mode self --db postgres|mysql|custom`\n// writes splithub/store.ts from one of these. Each implements the Store interface\n// from @splithub/node (insertEvents, variantCounts, summaries) with the same\n// attribution rule as the cloud, through variantCountsSql from @splithub/node.\n\nexport type DbKind = 'sqlite' | 'postgres' | 'mysql' | 'custom';\nexport const DB_KINDS: DbKind[] = ['sqlite', 'postgres', 'mysql', 'custom'];\n\nexport const PG_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\nimport { Pool } from 'pg';\n\n// SplitHub events in your Postgres. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id text PRIMARY KEY,\n type text NOT NULL, -- exposure | goal\n experiment text,\n variant text,\n goal text,\n visitor_id text NOT NULL,\n session_id text NOT NULL,\n ts bigint NOT NULL, -- client clock, unix ms\n url text,\n props jsonb,\n received_at bigint NOT NULL, -- server clock, unix ms\n host text,\n country text,\n device text,\n browser text\n);\nCREATE INDEX IF NOT EXISTS splithub_events_exp ON splithub_events (type, experiment, visitor_id, ts);\nCREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal, visitor_id, ts);\n\\`;\n\n// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).\nconst counts = variantCountsSql({ dialect: 'postgres', table: 'splithub_events' });\n\nexport function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const cols = 15;\n const values: unknown[] = [];\n const rows = events.map((e, i) => {\n values.push(e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null);\n return '(' + Array.from({ length: cols }, (_, j) => '$' + (i * cols + j + 1)).join(', ') + ')';\n });\n const r = await pool.query(\n 'INSERT INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ' + rows.join(', ') + ' ON CONFLICT (id) DO NOTHING',\n values\n );\n return r.rowCount ?? 0;\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n const r = await pool.query(counts.sql, counts.bind({ experiment, goal }));\n return r.rows.map(countsFromRow);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const r = await pool.query(\n \\`SELECT experiment, COUNT(*)::int AS exposures, COUNT(DISTINCT visitor_id)::int AS visitors, MIN(ts)::bigint AS first_ts, MAX(ts)::bigint AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return r.rows.map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const MYSQL_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\nimport mysql, { type Pool } from 'mysql2/promise';\n\n// SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id VARCHAR(64) PRIMARY KEY,\n type VARCHAR(16) NOT NULL,\n experiment VARCHAR(64) NULL,\n variant VARCHAR(64) NULL,\n goal VARCHAR(64) NULL,\n visitor_id VARCHAR(64) NOT NULL,\n session_id VARCHAR(64) NOT NULL,\n ts BIGINT NOT NULL,\n url VARCHAR(512) NULL,\n props JSON NULL,\n received_at BIGINT NOT NULL,\n host VARCHAR(255) NULL,\n country VARCHAR(8) NULL,\n device VARCHAR(16) NULL,\n browser VARCHAR(32) NULL,\n INDEX splithub_events_exp (type, experiment, visitor_id, ts),\n INDEX splithub_events_goal (type, goal, visitor_id, ts)\n);\n\\`;\n\n// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).\nconst counts = variantCountsSql({ dialect: 'mysql', table: 'splithub_events' });\n\nexport function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const values = events.map((e) => [e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null]);\n const [r] = await pool.query(\n 'INSERT IGNORE INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ?',\n [values]\n );\n return (r as { affectedRows: number }).affectedRows;\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n const [rows] = await pool.query(counts.sql, counts.bind({ experiment, goal }));\n return (rows as Array<Record<string, unknown>>).map(countsFromRow);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const [rows] = await pool.query(\n \\`SELECT experiment, COUNT(*) AS exposures, COUNT(DISTINCT visitor_id) AS visitors, MIN(ts) AS first_ts, MAX(ts) AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const CUSTOM_STORE = `import { attributeVariants, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\n\n/**\n * Your own store (Prisma, Drizzle, Supabase, Mongo, anything). Three methods.\n * Attribution rule (keep it, so results match the dashboard):\n * a visitor counts once per experiment, in the variant of their earliest\n * exposure (same ts: smallest variant key), and converts when they sent the\n * goal at or after that exposure (60 s of clock skew allowed); only the first\n * 50 events of one goal per visitor and UTC day count; count unique visitors.\n * SQL database: run variantCountsSql({ dialect }) from @splithub/node.\n * Anything else: load the experiment's exposures and the goal's events and\n * return attributeVariants(events, experiment, goal).\n * Columns worth keeping: id (unique, dedupe on it), type, experiment, variant,\n * goal, visitor_id, session_id, ts, url, props (json), received_at, host,\n * country, device, browser.\n */\nexport function customStore(): Store {\n return {\n async insertEvents(events: StoredEvent[]): Promise<number> {\n // Insert, skipping ids that already exist. Return how many were inserted.\n throw new Error('implement insertEvents ' + events.length);\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n // Per variant: exposures, conversions, revenueSum and revenueSumSq (per-visitor revenue).\n // Load the exposures of this experiment and the events of this goal, then apply the shared rule.\n const events: StoredEvent[] = [];\n if (events.length === 0) throw new Error('implement variantCounts ' + experiment + ' ' + goal);\n return attributeVariants(events, experiment, goal);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).\n throw new Error('implement summaries');\n },\n };\n}\n`;\n\nexport function storeTemplate(db: DbKind): string | null {\n return db === 'postgres' ? PG_STORE : db === 'mysql' ? MYSQL_STORE : db === 'custom' ? CUSTOM_STORE : null;\n}\n\n/** Import line + factory call used by the route template. */\nexport function storeUsage(db: DbKind, storeImport: string): { imports: string; factory: string } {\n switch (db) {\n case 'postgres':\n return { imports: `import { pgStore } from '${storeImport}';`, factory: 'pgStore()' };\n case 'mysql':\n return { imports: `import { mysqlStore } from '${storeImport}';`, factory: 'mysqlStore()' };\n case 'custom':\n return { imports: `import { customStore } from '${storeImport}';`, factory: 'customStore()' };\n default:\n return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };\n }\n}\n\nexport function runtimePackages(db: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