splithub 0.6.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/{alerts-WOWJ3MZV.js → alerts-B7LKEY3J.js} +4 -4
- package/dist/{analytics-ZGLVQDIL.js → analytics-YY3O3HGL.js} +5 -5
- package/dist/{chunk-4DPMTGNP.js → chunk-3H7W4UIT.js} +3 -3
- package/dist/chunk-3H7W4UIT.js.map +1 -0
- package/dist/{chunk-4AZ2EOIY.js → chunk-4K2CNZYY.js} +3 -3
- package/dist/chunk-4K2CNZYY.js.map +1 -0
- package/dist/{chunk-PWLTCKEC.js → chunk-57IKDCOM.js} +6 -6
- package/dist/chunk-57IKDCOM.js.map +1 -0
- package/dist/{chunk-3V6SD74H.js → chunk-5UN2NKIF.js} +9 -9
- package/dist/chunk-5UN2NKIF.js.map +1 -0
- package/dist/{chunk-LF4ZI43E.js → chunk-BWYRU47V.js} +2 -2
- package/dist/{chunk-I5YYG3NU.js → chunk-DBGNAB2J.js} +3 -3
- package/dist/chunk-DBGNAB2J.js.map +1 -0
- package/dist/{chunk-Q5LYYWYC.js → chunk-FSMUHH4G.js} +15 -15
- package/dist/chunk-FSMUHH4G.js.map +1 -0
- package/dist/{chunk-XT7Z5GY2.js → chunk-H2OU4PJA.js} +2 -2
- package/dist/{chunk-JQA3WWEQ.js → chunk-K7KLCGYY.js} +4 -4
- package/dist/chunk-K7KLCGYY.js.map +1 -0
- package/dist/{chunk-5R6543RT.js → chunk-KXER4ZZ3.js} +6 -6
- package/dist/chunk-KXER4ZZ3.js.map +1 -0
- package/dist/{chunk-NZ4RSQ56.js → chunk-LFEVNQ75.js} +3 -3
- package/dist/{chunk-NZ4RSQ56.js.map → chunk-LFEVNQ75.js.map} +1 -1
- package/dist/{chunk-DOPSOUUT.js → chunk-LGL7JY6Y.js} +7 -7
- package/dist/chunk-LGL7JY6Y.js.map +1 -0
- package/dist/{chunk-BDCKWKJB.js → chunk-LOYPA5WN.js} +32 -32
- package/dist/chunk-LOYPA5WN.js.map +1 -0
- package/dist/{chunk-IIX2EISO.js → chunk-NQDGMBRF.js} +4 -4
- package/dist/chunk-NQDGMBRF.js.map +1 -0
- package/dist/{chunk-GWWJHAH4.js → chunk-OH735OOS.js} +4 -4
- package/dist/chunk-OH735OOS.js.map +1 -0
- package/dist/{chunk-BLEJ5DOY.js → chunk-OTK6B4QC.js} +2 -2
- package/dist/chunk-OTK6B4QC.js.map +1 -0
- package/dist/{chunk-KWL6EUML.js → chunk-Q6JPYA4Y.js} +3 -3
- package/dist/chunk-Q6JPYA4Y.js.map +1 -0
- package/dist/{chunk-VMYL36BP.js → chunk-QJQKARDO.js} +2 -2
- package/dist/{chunk-7ADMC5F3.js → chunk-RZGKAVA6.js} +3 -3
- package/dist/chunk-RZGKAVA6.js.map +1 -0
- package/dist/{chunk-ISEVDVKJ.js → chunk-SAH2BATZ.js} +3 -3
- package/dist/chunk-SAH2BATZ.js.map +1 -0
- package/dist/{chunk-H5GMGCOT.js → chunk-W66MJG3R.js} +2 -2
- package/dist/chunk-W66MJG3R.js.map +1 -0
- package/dist/{chunk-JFRRGBZU.js → chunk-X2ICUB5B.js} +5 -5
- package/dist/chunk-X2ICUB5B.js.map +1 -0
- package/dist/{ci-G4IQPM5K.js → ci-W72GPWEB.js} +2 -2
- package/dist/{connect-BICSF6XG.js → connect-5TIWPEIS.js} +11 -11
- package/dist/connect-5TIWPEIS.js.map +1 -0
- package/dist/{create-7VLV2H67.js → create-J2WN55LX.js} +3 -3
- package/dist/{dev-3CPW4LTF.js → dev-4UQ6KKB7.js} +3 -3
- package/dist/{doctor-L7NTDL2E.js → doctor-HYTPYAEW.js} +4 -4
- package/dist/domains-YIY7HXOS.js +10 -0
- package/dist/{experiment-reports-AN4S7PYS.js → experiment-reports-WCMLX34L.js} +5 -5
- package/dist/index.js +31 -31
- package/dist/index.js.map +1 -1
- package/dist/init-PTDL6EON.js +19 -0
- package/dist/{lifecycle-RROP7JMK.js → lifecycle-NKPKM76H.js} +3 -3
- package/dist/{links-DYSFIVRV.js → links-YD6QLNKY.js} +4 -4
- package/dist/{login-JIH5576K.js → login-4OQI2Q45.js} +3 -3
- package/dist/{menu-TCO6OVKR.js → menu-APVGU6TP.js} +26 -26
- package/dist/menu-APVGU6TP.js.map +1 -0
- package/dist/{notes-KHLQUNEF.js → notes-NSWGMP2V.js} +4 -4
- package/dist/{plan-BYRG2YK6.js → plan-DZGPGSIE.js} +3 -3
- package/dist/plan-DZGPGSIE.js.map +1 -0
- package/dist/{push-6MOHROGS.js → push-AI2M56OS.js} +3 -3
- package/dist/{remove-C65D4VDA.js → remove-R3AS4XYY.js} +2 -2
- package/dist/{report-Z5XHK5D6.js → report-VTJZEITT.js} +4 -4
- package/dist/report-VTJZEITT.js.map +1 -0
- package/dist/{results-3UYAU4OP.js → results-PZERL5HO.js} +6 -6
- package/dist/{review-FOE4IIXA.js → review-IB7Y2OIF.js} +2 -2
- package/dist/{ship-6HWSIA2E.js → ship-CFM5M6N3.js} +2 -2
- package/dist/{skills-RBRC7UWI.js → skills-GJGOA4HL.js} +4 -4
- package/dist/status-SOOLWHLW.js +17 -0
- package/package.json +3 -3
- package/dist/chunk-3V6SD74H.js.map +0 -1
- package/dist/chunk-4AZ2EOIY.js.map +0 -1
- package/dist/chunk-4DPMTGNP.js.map +0 -1
- package/dist/chunk-5R6543RT.js.map +0 -1
- package/dist/chunk-7ADMC5F3.js.map +0 -1
- package/dist/chunk-BDCKWKJB.js.map +0 -1
- package/dist/chunk-BLEJ5DOY.js.map +0 -1
- package/dist/chunk-DOPSOUUT.js.map +0 -1
- package/dist/chunk-GWWJHAH4.js.map +0 -1
- package/dist/chunk-H5GMGCOT.js.map +0 -1
- package/dist/chunk-I5YYG3NU.js.map +0 -1
- package/dist/chunk-IIX2EISO.js.map +0 -1
- package/dist/chunk-ISEVDVKJ.js.map +0 -1
- package/dist/chunk-JFRRGBZU.js.map +0 -1
- package/dist/chunk-JQA3WWEQ.js.map +0 -1
- package/dist/chunk-KWL6EUML.js.map +0 -1
- package/dist/chunk-PWLTCKEC.js.map +0 -1
- package/dist/chunk-Q5LYYWYC.js.map +0 -1
- package/dist/connect-BICSF6XG.js.map +0 -1
- package/dist/domains-J5SKVM6S.js +0 -10
- package/dist/init-Q234CCOT.js +0 -19
- package/dist/menu-TCO6OVKR.js.map +0 -1
- package/dist/plan-BYRG2YK6.js.map +0 -1
- package/dist/report-Z5XHK5D6.js.map +0 -1
- package/dist/status-RLKOX6NA.js +0 -17
- /package/dist/{alerts-WOWJ3MZV.js.map → alerts-B7LKEY3J.js.map} +0 -0
- /package/dist/{analytics-ZGLVQDIL.js.map → analytics-YY3O3HGL.js.map} +0 -0
- /package/dist/{chunk-LF4ZI43E.js.map → chunk-BWYRU47V.js.map} +0 -0
- /package/dist/{chunk-XT7Z5GY2.js.map → chunk-H2OU4PJA.js.map} +0 -0
- /package/dist/{chunk-VMYL36BP.js.map → chunk-QJQKARDO.js.map} +0 -0
- /package/dist/{ci-G4IQPM5K.js.map → ci-W72GPWEB.js.map} +0 -0
- /package/dist/{create-7VLV2H67.js.map → create-J2WN55LX.js.map} +0 -0
- /package/dist/{dev-3CPW4LTF.js.map → dev-4UQ6KKB7.js.map} +0 -0
- /package/dist/{doctor-L7NTDL2E.js.map → doctor-HYTPYAEW.js.map} +0 -0
- /package/dist/{domains-J5SKVM6S.js.map → domains-YIY7HXOS.js.map} +0 -0
- /package/dist/{experiment-reports-AN4S7PYS.js.map → experiment-reports-WCMLX34L.js.map} +0 -0
- /package/dist/{init-Q234CCOT.js.map → init-PTDL6EON.js.map} +0 -0
- /package/dist/{lifecycle-RROP7JMK.js.map → lifecycle-NKPKM76H.js.map} +0 -0
- /package/dist/{links-DYSFIVRV.js.map → links-YD6QLNKY.js.map} +0 -0
- /package/dist/{login-JIH5576K.js.map → login-4OQI2Q45.js.map} +0 -0
- /package/dist/{notes-KHLQUNEF.js.map → notes-NSWGMP2V.js.map} +0 -0
- /package/dist/{push-6MOHROGS.js.map → push-AI2M56OS.js.map} +0 -0
- /package/dist/{remove-C65D4VDA.js.map → remove-R3AS4XYY.js.map} +0 -0
- /package/dist/{results-3UYAU4OP.js.map → results-PZERL5HO.js.map} +0 -0
- /package/dist/{review-FOE4IIXA.js.map → review-IB7Y2OIF.js.map} +0 -0
- /package/dist/{ship-6HWSIA2E.js.map → ship-CFM5M6N3.js.map} +0 -0
- /package/dist/{skills-RBRC7UWI.js.map → skills-GJGOA4HL.js.map} +0 -0
- /package/dist/{status-RLKOX6NA.js.map → status-SOOLWHLW.js.map} +0 -0
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-CB2SJFHK.js";
|
|
5
5
|
import {
|
|
6
6
|
writeWorkflow
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-5UN2NKIF.js";
|
|
8
8
|
import {
|
|
9
9
|
appPackages,
|
|
10
10
|
appProviderSnippet,
|
|
@@ -14,19 +14,19 @@ import {
|
|
|
14
14
|
nativeSetup,
|
|
15
15
|
patchAppEntry,
|
|
16
16
|
screenTracking
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-LFEVNQ75.js";
|
|
18
18
|
import {
|
|
19
19
|
deviceLogin
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-H2OU4PJA.js";
|
|
21
21
|
import {
|
|
22
22
|
installSkills,
|
|
23
23
|
loadSkillFiles
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-LGL7JY6Y.js";
|
|
25
25
|
import {
|
|
26
26
|
configTemplate,
|
|
27
27
|
nextMiddlewareTemplate,
|
|
28
28
|
nextRouteTemplate
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-LOYPA5WN.js";
|
|
30
30
|
import {
|
|
31
31
|
detectProject,
|
|
32
32
|
installCommand
|
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
import {
|
|
35
35
|
cloudTarget,
|
|
36
36
|
loadCredential
|
|
37
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-W66MJG3R.js";
|
|
38
38
|
import {
|
|
39
39
|
c
|
|
40
40
|
} from "./chunk-ZISCJRR5.js";
|
|
@@ -50,7 +50,7 @@ var DB_KINDS = ["sqlite", "postgres", "mysql", "custom"];
|
|
|
50
50
|
var PG_STORE = `import { countsFromRow, propertyCountsFromRows, propertyCountsSql, storedEventFromRow, variantCountsSql, type ExperimentSummary, type PropertyCounts, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';
|
|
51
51
|
import { Pool } from 'pg';
|
|
52
52
|
|
|
53
|
-
//
|
|
53
|
+
// SplitHub events in your Postgres. Run once (or add to your migrations):
|
|
54
54
|
export const SCHEMA_SQL = \`
|
|
55
55
|
CREATE TABLE IF NOT EXISTS splithub_events (
|
|
56
56
|
id text PRIMARY KEY,
|
|
@@ -77,7 +77,7 @@ CREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal,
|
|
|
77
77
|
ALTER TABLE splithub_events ADD COLUMN IF NOT EXISTS platform text, ADD COLUMN IF NOT EXISTS app_version text;
|
|
78
78
|
\`;
|
|
79
79
|
|
|
80
|
-
// The attribution rule shared by every
|
|
80
|
+
// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).
|
|
81
81
|
const counts = variantCountsSql({ dialect: 'postgres', table: 'splithub_events' });
|
|
82
82
|
// Analytics properties: pageviews, events, engagement and identify rows share the table; raw counts
|
|
83
83
|
// only (users = distinct ids sent with identify).
|
|
@@ -137,7 +137,7 @@ export function pgStore(pool: Pool = new Pool({ connectionString: process.env.DA
|
|
|
137
137
|
var MYSQL_STORE = `import { countsFromRow, propertyCountsFromRows, propertyCountsSql, storedEventFromRow, variantCountsSql, type ExperimentSummary, type PropertyCounts, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';
|
|
138
138
|
import mysql, { type Pool } from 'mysql2/promise';
|
|
139
139
|
|
|
140
|
-
//
|
|
140
|
+
// SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):
|
|
141
141
|
export const SCHEMA_SQL = \`
|
|
142
142
|
CREATE TABLE IF NOT EXISTS splithub_events (
|
|
143
143
|
id VARCHAR(64) PRIMARY KEY,
|
|
@@ -162,7 +162,7 @@ CREATE TABLE IF NOT EXISTS splithub_events (
|
|
|
162
162
|
);
|
|
163
163
|
\`;
|
|
164
164
|
|
|
165
|
-
// The attribution rule shared by every
|
|
165
|
+
// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).
|
|
166
166
|
const counts = variantCountsSql({ dialect: 'mysql', table: 'splithub_events' });
|
|
167
167
|
// Analytics properties: pageviews, events, engagement and identify rows share the table; raw counts
|
|
168
168
|
// only (users = distinct ids sent with identify).
|
|
@@ -311,14 +311,14 @@ async function init(flags) {
|
|
|
311
311
|
const notes = [];
|
|
312
312
|
let mode = str(flags.mode);
|
|
313
313
|
if (native && mode === "self") {
|
|
314
|
-
notes.push("Native apps read their experiments from
|
|
314
|
+
notes.push("Native apps read their experiments from SplitHub Cloud, so this project is set up for the cloud.");
|
|
315
315
|
mode = "cloud";
|
|
316
316
|
}
|
|
317
317
|
if (!mode) {
|
|
318
318
|
if (yes || native) mode = project.app ? "cloud" : "self";
|
|
319
319
|
else {
|
|
320
320
|
const self = { value: "self", label: "My own database (self-hosted)", hint: rn ? "your server keeps the events; experiments ship with each release" : "free forever, nothing leaves your infra" };
|
|
321
|
-
const cloud = { value: "cloud", label: "
|
|
321
|
+
const cloud = { value: "cloud", label: "SplitHub Cloud", hint: rn ? "start and change experiments without a store release" : "hosted dashboard, no server code" };
|
|
322
322
|
const picked = await p.select({ message: "Where should events be stored?", options: rn ? [cloud, self] : [self, cloud] });
|
|
323
323
|
if (p.isCancel(picked)) return cancel2();
|
|
324
324
|
mode = picked;
|
|
@@ -347,7 +347,7 @@ async function init(flags) {
|
|
|
347
347
|
key ??= saved.publicKey ?? void 0;
|
|
348
348
|
connected = { projectName: saved.projectName, projectId: saved.projectId };
|
|
349
349
|
} else if (!process.env.SPLITHUB_API_KEY && !flags["no-login"]) {
|
|
350
|
-
if (!json) p.log.step("Connect to
|
|
350
|
+
if (!json) p.log.step("Connect to SplitHub Cloud");
|
|
351
351
|
try {
|
|
352
352
|
const cred = await deviceLogin({
|
|
353
353
|
api,
|
|
@@ -410,7 +410,7 @@ Code ${c.green(s.userCode)} \xB7 sign in, pick or create the project, approve.`,
|
|
|
410
410
|
}
|
|
411
411
|
let mcp = !flags["no-mcp"];
|
|
412
412
|
if (!yes && !json && mcp) {
|
|
413
|
-
const want = await p.confirm({ message: "Register the
|
|
413
|
+
const want = await p.confirm({ message: "Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?", initialValue: true });
|
|
414
414
|
if (p.isCancel(want)) return cancel2();
|
|
415
415
|
mcp = want;
|
|
416
416
|
}
|
|
@@ -507,4 +507,4 @@ export {
|
|
|
507
507
|
importPath,
|
|
508
508
|
init
|
|
509
509
|
};
|
|
510
|
-
//# sourceMappingURL=chunk-
|
|
510
|
+
//# sourceMappingURL=chunk-FSMUHH4G.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, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { cloudTarget } from '../api';\nimport { appPackages, appProviderSnippet, findAppEntry, isNativeApp, isReactNativeApp, nativeSetup, patchAppEntry, screenTracking, type EntryPatch } from '../app-setup';\nimport { findTypeScript } from '../typescript';\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\nexport function 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 // Apps: React Native / Expo get the npm package and a wrapped entry; native iOS / Android get install lines.\n const rn = isReactNativeApp(project.app);\n const native = isNativeApp(project.app);\n const notes: string[] = [];\n\n let mode = str(flags.mode) as 'self' | 'cloud' | undefined;\n if (native && mode === 'self') {\n notes.push('Native apps read their experiments from SplitHub Cloud, so this project is set up for the cloud.');\n mode = 'cloud';\n }\n if (!mode) {\n // An app cannot reach a self-hosted endpoint without a server URL, and only the cloud starts experiments without a release.\n if (yes || native) mode = project.app ? 'cloud' : 'self';\n else {\n const self = { value: 'self', label: 'My own database (self-hosted)', hint: rn ? 'your server keeps the events; experiments ship with each release' : 'free forever, nothing leaves your infra' };\n const cloud = { value: 'cloud', label: 'SplitHub Cloud', hint: rn ? 'start and change experiments without a store release' : 'hosted dashboard, no server code' };\n const picked = await p.select({ message: 'Where should events be stored?', options: rn ? [cloud, self] : [self, cloud] });\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' && !project.app && !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 // Native apps never read the file (the SDK gets experiments from the cloud), so they get none.\n const configFile = project.configFile ?? join(project.root, 'splithub.config.ts');\n if (!native) writeIfMissing(configFile, configTemplate(project.name, mode, key, { app: rn }), created, skipped);\n\n // 2a. store for self mode (postgres / mysql / custom); sqlite needs no file. An app's events go to a server set up on its own.\n const storeBody = mode === 'self' && !project.app ? storeTemplate(db) : null;\n if (rn && mode === 'self') notes.push('Self-hosted: the app sends to storage.endpoint in the config. Point it at your server, and run npx splithub init --mode self there for the ingest route.');\n\n // 2b. app entry: wrap it in <SplitHubProvider>, with screen tracking.\n const screens = screenTracking(project);\n let entry: { file: string | null; patch: EntryPatch } | null = null;\n if (rn) {\n const file = findAppEntry(project.root, project.expoRouter);\n const ts = file ? await findTypeScript(project.root) : null;\n if (!file) entry = { file: null, patch: { source: null, status: 'manual', screens: false, reason: project.expoRouter ? 'no app/_layout.tsx' : 'no App.tsx' } };\n else if (!ts) entry = { file, patch: { source: null, status: 'manual', screens: false, reason: 'TypeScript is not installed, so the entry was left as it is' } };\n else {\n const patch = patchAppEntry(ts, file, readFileSync(file, 'utf8'), { configImport: importPath(file, configFile), screens });\n if (patch.source !== null) writeFileSync(file, patch.source, 'utf8');\n entry = { file, patch };\n }\n }\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 pkgs = rn ? appPackages(project) : null;\n const runtime = pkgs ? pkgs.runtime : ['@splithub/react', '@splithub/core'];\n if (project.framework === 'next' && !rn) runtime.push('@splithub/next');\n if (mode === 'self' && !project.app) runtime.push('@splithub/node', ...runtimePackages(db));\n const installRuntime = installCommand(project.packageManager, runtime);\n // Expo picks the native module version that matches the app's SDK.\n const installExpo = pkgs?.expo.length ? `npx expo install ${pkgs.expo.join(' ')}` : null;\n const installDev = installCommand(project.packageManager, ['splithub'], true);\n const commands = native ? [] : [installRuntime, ...(installExpo ? [installExpo] : []), installDev];\n let installed = false;\n if (!flags['no-install'] && commands.length) {\n const go = yes ? true : await p.confirm({ message: `Install packages now? (${commands.slice(0, -1).join(' && ')})` });\n if (p.isCancel(go)) return cancel();\n if (go) {\n const s = json ? null : p.spinner();\n s?.start('Installing');\n try {\n for (const cmd of commands) execSync(cmd, { 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 entryFile = entry?.file ?? join(project.root, project.expoRouter ? 'app/_layout.tsx' : 'App.tsx');\n const nativeKit = native ? nativeSetup(project.app as 'ios' | 'android', key ?? null) : null;\n const providerHint = nativeKit\n ? `${nativeKit.install}\\n\\n${nativeKit.quickStart}`\n : rn\n ? appProviderSnippet(importPath(entryFile, configFile), screens)\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 =\n mode === 'cloud' && !key\n ? native\n ? 'No public key yet: run `npx splithub login` (or pass --key pk_…, dashboard → Setup) and put it in SplitHub.start.'\n : `No public key yet: storage.key falls back to process.env.${rn ? 'EXPO_PUBLIC_SPLITHUB_KEY' : '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.`\n : null;\n if (rn && entry?.file && entry.patch.status === 'added') created.push(`${entry.file} (wrapped in <SplitHubProvider>${entry.patch.screens && screens ? ', screens tracked' : ''})`);\n if (rn && entry?.patch.status === 'added' && !entry.patch.screens && screens) notes.push(`Screens: add <NavigationScreens /> inside your <NavigationContainer> (from @splithub/react-native).`);\n if (rn && !screens) notes.push(\"Screens: call useScreen('Home') in each screen (from @splithub/react-native).\");\n if (project.app) notes.push('Experiments in splithub.config.ts ship inside the app binary. Create them in the dashboard to start them without a store release.');\n const app = project.app\n ? {\n kind: project.app,\n screens: rn ? screens ?? 'useScreen' : null,\n entry: entry ? { file: entry.file ? relative(project.root, entry.file).replace(/\\\\/g, '/') : null, status: entry.patch.status, screens: entry.patch.screens, ...(entry.patch.reason ? { reason: entry.patch.reason } : {}) } : null,\n ...(nativeKit ? { install: nativeKit.install, quickStart: nativeKit.quickStart } : {}),\n }\n : null;\n const providerDone = entry?.patch.status === 'added' || entry?.patch.status === 'already';\n const summary = { project: project.name, framework: project.framework, app, mode, db: mode === 'self' && !project.app ? db : null, connected, publicKey: key ?? null, warning, notes, created, skipped, installed, installCommands: installed ? [] : commands, nextStep: providerDone ? null : providerHint, ...(project.framework === 'vite' && !rn ? { 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 for (const note of notes) p.log.info(note);\n if (mode === 'self' && !project.app && 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 && commands.length) p.note(commands.join('\\n'), 'Install');\n if (nativeKit) {\n p.note(nativeKit.install, project.app === 'ios' ? 'Add the Swift package' : 'Add the Gradle dependency');\n p.note(nativeKit.quickStart, 'Quick start');\n p.outro(`Next: create an experiment in the dashboard, then ${c.cyan('npx splithub status')} and ${c.cyan('npx splithub results <id>')} read it here.`);\n return;\n }\n if (rn && entry?.patch.status === 'manual') p.log.warn(`Left ${entry.file ? relative(project.root, entry.file) : 'the entry'} as it is: ${entry.patch.reason}. Add the provider by hand.`);\n if (!providerDone) p.note(providerHint, 'Wrap your app once');\n if (project.framework === 'vite' && !rn) p.note(VITE_PLUGIN_HINT, 'Notes in your dev terminal');\n const analyticsNext = rn ? `, ${c.cyan('npx splithub analytics connect')} for screens and retention` : '';\n p.outro(`Next: ${c.cyan('npx splithub create')} to add your first experiment, ${c.cyan('npx splithub push')} to sync it${analyticsNext}, ${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, and the raw analytics\n// reads propertyCounts / propertyEvents) 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, propertyCountsFromRows, propertyCountsSql, storedEventFromRow, variantCountsSql, type ExperimentSummary, type PropertyCounts, 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 | page | event | engage | identify (analytics rows: experiment = property, goal = event name)\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 platform text, -- web | ios | android | macos | windows | linux\n app_version text -- the app's version; null on websites\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-- Tables from before the app columns (the store also adds them on its first insert):\nALTER TABLE splithub_events ADD COLUMN IF NOT EXISTS platform text, ADD COLUMN IF NOT EXISTS app_version text;\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// Analytics properties: pageviews, events, engagement and identify rows share the table; raw counts\n// only (users = distinct ids sent with identify).\nconst prop = propertyCountsSql({ dialect: 'postgres', table: 'splithub_events' });\n\nexport function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {\n // A table made before the app columns gets them on the first insert. Without ALTER rights they are left out.\n let appColumns: Promise<boolean> | null = null;\n const ensureAppColumns = (): Promise<boolean> =>\n (appColumns ??= (async () => {\n const have = async () =>\n (await pool.query(\"SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = 'splithub_events' AND column_name IN ('platform', 'app_version')\")).rows.length === 2;\n if (await have()) return true;\n await pool.query('ALTER TABLE splithub_events ADD COLUMN IF NOT EXISTS platform text, ADD COLUMN IF NOT EXISTS app_version text').catch(() => undefined);\n return have();\n })().catch(() => false));\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const app = await ensureAppColumns();\n const cols = app ? 17 : 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 if (app) values.push(e.platform ?? null, e.app_version ?? 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' + (app ? ', platform, app_version' : '') + ') 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 async propertyCounts(property: string, since: number, until?: number): Promise<PropertyCounts> {\n const [totals, events] = await Promise.all([pool.query(prop.totals.sql, prop.totals.bind({ property, since, until })), pool.query(prop.events.sql, prop.events.bind({ property, since, until }))]);\n return propertyCountsFromRows(totals.rows[0], events.rows);\n },\n async propertyEvents(property: string, { before, limit }: { before: number; limit: number }): Promise<StoredEvent[]> {\n const r = await pool.query(prop.rows.sql, prop.rows.bind({ property, before, limit }));\n return r.rows.map(storedEventFromRow);\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const MYSQL_STORE = `import { countsFromRow, propertyCountsFromRows, propertyCountsSql, storedEventFromRow, variantCountsSql, type ExperimentSummary, type PropertyCounts, 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, -- exposure | goal | page | event | engage | identify\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 platform VARCHAR(16) NULL, -- web | ios | android | macos | windows | linux\n app_version VARCHAR(32) NULL, -- the app's version; null on websites\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// Analytics properties: pageviews, events, engagement and identify rows share the table; raw counts\n// only (users = distinct ids sent with identify).\nconst prop = propertyCountsSql({ dialect: 'mysql', table: 'splithub_events' });\n\nexport function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {\n // A table made before the app columns gets them on the first insert. Without ALTER rights they are left out.\n let appColumns: Promise<boolean> | null = null;\n const ensureAppColumns = (): Promise<boolean> =>\n (appColumns ??= (async () => {\n const have = async () => {\n const [rows] = await pool.query(\"SELECT COLUMN_NAME AS name FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'splithub_events' AND COLUMN_NAME IN ('platform', 'app_version')\");\n return new Set((rows as Array<{ name: string }>).map((r) => r.name));\n };\n const found = await have();\n if (!found.has('platform')) await pool.query('ALTER TABLE splithub_events ADD COLUMN platform VARCHAR(16) NULL').catch(() => undefined);\n if (!found.has('app_version')) await pool.query('ALTER TABLE splithub_events ADD COLUMN app_version VARCHAR(32) NULL').catch(() => undefined);\n return (await have()).size === 2;\n })().catch(() => false));\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const app = await ensureAppColumns();\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, ...(app ? [e.platform ?? null, e.app_version ?? 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' + (app ? ', platform, app_version' : '') + ') 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 async propertyCounts(property: string, since: number, until?: number): Promise<PropertyCounts> {\n const [[totals], [events]] = await Promise.all([pool.query(prop.totals.sql, prop.totals.bind({ property, since, until })), pool.query(prop.events.sql, prop.events.bind({ property, since, until }))]);\n return propertyCountsFromRows((totals as Array<Record<string, unknown>>)[0], events as Array<Record<string, unknown>>);\n },\n async propertyEvents(property: string, { before, limit }: { before: number; limit: number }): Promise<StoredEvent[]> {\n const [rows] = await pool.query(prop.rows.sql, prop.rows.bind({ property, before, limit }));\n return (rows as Array<Record<string, unknown>>).map(storedEventFromRow);\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, platform (web | ios | android | macos | windows | linux)\n * and app_version (apps only).\n * Analytics (optional): \\`page\\`, \\`event\\`, \\`engage\\` and \\`identify\\` rows carry the\n * property key in \\`experiment\\` (and the event name in \\`goal\\`); engage props are\n * { ms, scroll }, identify props { uid, traits }. Store them like the others and add\n * propertyCounts(property, since, until?) (or run propertyCountsSql, which also counts users)\n * to read them with \\`splithub analytics\\`.\n */\nexport function customStore(): Store {\n return {\n async insertEvents(events: StoredEvent[]): Promise<number> {\n // Insert, skipping ids that already exist. Return how many were inserted.\n throw new Error('implement insertEvents ' + events.length);\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n // Per variant: exposures, conversions, revenueSum and revenueSumSq (per-visitor revenue).\n // Load the exposures of this experiment and the events of this goal, then apply the shared rule.\n const events: StoredEvent[] = [];\n if (events.length === 0) throw new Error('implement variantCounts ' + experiment + ' ' + goal);\n return attributeVariants(events, experiment, goal);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).\n throw new Error('implement summaries');\n },\n };\n}\n`;\n\nexport function storeTemplate(db: DbKind): string | null {\n return db === 'postgres' ? PG_STORE : db === 'mysql' ? MYSQL_STORE : db === 'custom' ? CUSTOM_STORE : null;\n}\n\n/** Import line + factory call used by the route template. */\nexport function storeUsage(db: DbKind, storeImport: string): { imports: string; factory: string } {\n switch (db) {\n case 'postgres':\n return { imports: `import { pgStore } from '${storeImport}';`, factory: 'pgStore()' };\n case 'mysql':\n return { imports: `import { mysqlStore } from '${storeImport}';`, factory: 'mysqlStore()' };\n case 'custom':\n return { imports: `import { customStore } from '${storeImport}';`, factory: 'customStore()' };\n default:\n return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };\n }\n}\n\nexport function runtimePackages(db: DbKind): string[] {\n return db === 'postgres' ? ['pg'] : db === 'mysql' ? ['mysql2'] : db === 'sqlite' ? ['@splithub/adapter-sqlite'] : [];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,OAAO;AACnB,SAAS,gBAAgB;AACzB,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,MAAM,gBAAgB;;;ACIjC,IAAM,WAAqB,CAAC,UAAU,YAAY,SAAS,QAAQ;AAEnE,IAAM,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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IAAI,CAAC,MAAM,SAAS,QAAQ,MAAM,CAAC,CAAC,EAAE,KAAK,IAAI,GAAG,iCAAiC;AACtH,MAAI,CAAC,aAAa,SAAS,OAAQ,CAAE,OAAK,SAAS,KAAK,IAAI,GAAG,SAAS;AACxE,MAAI,WAAW;AACb,IAAE,OAAK,UAAU,SAAS,QAAQ,QAAQ,QAAQ,0BAA0B,2BAA2B;AACvG,IAAE,OAAK,UAAU,YAAY,aAAa;AAC1C,IAAE,QAAM,qDAAqD,EAAE,KAAK,qBAAqB,CAAC,QAAQ,EAAE,KAAK,2BAA2B,CAAC,gBAAgB;AACrJ;AAAA,EACF;AACA,MAAI,MAAM,OAAO,MAAM,WAAW,SAAU,CAAE,MAAI,KAAK,QAAQ,MAAM,OAAO,SAAS,QAAQ,MAAM,MAAM,IAAI,IAAI,WAAW,cAAc,MAAM,MAAM,MAAM,6BAA6B;AACzL,MAAI,CAAC,aAAc,CAAE,OAAK,cAAc,oBAAoB;AAC5D,MAAI,QAAQ,cAAc,UAAU,CAAC,GAAI,CAAE,OAAK,kBAAkB,4BAA4B;AAC9F,QAAM,gBAAgB,KAAK,KAAK,EAAE,KAAK,gCAAgC,CAAC,+BAA+B;AACvG,EAAE,QAAM,SAAS,EAAE,KAAK,qBAAqB,CAAC,kCAAkC,EAAE,KAAK,mBAAmB,CAAC,cAAc,aAAa,KAAK,EAAE,KAAK,qBAAqB,CAAC,aAAa;AACvL;AAGA,SAASD,UAAe;AACtB,EAAE,SAAO,YAAY;AACrB,UAAQ,KAAK,CAAC;AAChB;","names":["cancel","note"]}
|
|
@@ -8,7 +8,7 @@ import {
|
|
|
8
8
|
removeCredential,
|
|
9
9
|
requireCloudToken,
|
|
10
10
|
saveCredential
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-W66MJG3R.js";
|
|
12
12
|
import {
|
|
13
13
|
CliError,
|
|
14
14
|
c,
|
|
@@ -110,4 +110,4 @@ export {
|
|
|
110
110
|
whoami,
|
|
111
111
|
projects
|
|
112
112
|
};
|
|
113
|
-
//# sourceMappingURL=chunk-
|
|
113
|
+
//# sourceMappingURL=chunk-H2OU4PJA.js.map
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
analysisLine
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-3H7W4UIT.js";
|
|
5
5
|
import {
|
|
6
6
|
detectProject
|
|
7
7
|
} from "./chunk-6K3MHBT7.js";
|
|
8
8
|
import {
|
|
9
9
|
fetchStatus,
|
|
10
10
|
resolveTarget
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-W66MJG3R.js";
|
|
12
12
|
import {
|
|
13
13
|
bar,
|
|
14
14
|
c,
|
|
@@ -30,7 +30,7 @@ async function status(flags) {
|
|
|
30
30
|
printJson(next ? { ...data, next } : data);
|
|
31
31
|
return;
|
|
32
32
|
}
|
|
33
|
-
console.log(`${c.bold("
|
|
33
|
+
console.log(`${c.bold("SplitHub")} ${c.dim("\xB7")} project ${c.cyan(data.project)} ${c.dim(`\xB7 ${target.url}`)}
|
|
34
34
|
`);
|
|
35
35
|
if (data.experiments.length === 0) {
|
|
36
36
|
console.log(c.dim("No experiments in splithub.config.ts yet. Run `splithub create`."));
|
|
@@ -89,4 +89,4 @@ export {
|
|
|
89
89
|
status,
|
|
90
90
|
printProperties
|
|
91
91
|
};
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-K7KLCGYY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/status.ts"],"sourcesContent":["import { fetchStatus, resolveTarget, type StatusData } from '../api';\nimport { detectProject } from '../project';\nimport { printJson } from '../errors';\nimport { bar, c, starText, statusColor, table, verdictColor, verdictIcon } from '../ui';\nimport { analysisLine } from './results';\n\nexport async function status(flags: Record<string, unknown>): Promise<void> {\n const target = resolveTarget(flags, detectProject());\n const data = await fetchStatus(target);\n const finished = data.experiments.filter((e) => e.status === 'finished').map((e) => e.experiment);\n const next = finished.length ? `Finished but still in the code: ${finished.join(', ')}. Decide which variant to keep, then run npx splithub ship <id> --keep <variant> (agents: the splithub-ship skill).` : null;\n if (flags.json) {\n printJson(next ? { ...data, next } : data);\n return;\n }\n console.log(`${c.bold('SplitHub')} ${c.dim('·')} project ${c.cyan(data.project)} ${c.dim(`· ${target.url}`)}\\n`);\n if (data.experiments.length === 0) {\n console.log(c.dim('No experiments in splithub.config.ts yet. Run `splithub create`.'));\n printProperties(data);\n return;\n }\n const raw = data.analysis?.available === false;\n const name = (id: string) => (id === '__holdout' ? c.bold('Holdout: long-term impact') : c.bold(id));\n // Visitors as a bar relative to the busiest experiment.\n const maxVisitors = Math.max(1, ...data.experiments.map((e) => e.visitors));\n const visitors = (e: { visitors: number; status: string }) => [String(e.visitors), bar(e.visitors, maxVisitors, 12, e.status === 'running' ? c.green : c.dim)];\n if (raw) {\n console.log(table(['EXPERIMENT', 'KIND', 'STATUS', 'VISITORS', '', 'DAYS'], data.experiments.map((e) => [name(e.experiment), e.kind, statusColor(e.status), ...visitors(e), e.days ? String(e.days) : '–'])));\n if (data.analysis) console.log(`\\n${c.dim(analysisLine(data.analysis))}`);\n } else {\n console.log(\n table(\n ['EXPERIMENT', 'KIND', 'STATUS', 'VISITORS', '', 'DAYS', 'VERDICT', 'SAMPLE', 'DATA', 'NEXT CHECK'],\n data.experiments.map((e) => {\n const headline = e.headline ?? (e.goal ? 'no data' : 'no goal');\n return [\n name(e.experiment),\n e.kind,\n statusColor(e.status),\n ...visitors(e),\n e.days ? String(e.days) : '–',\n verdictColor(e.verdict ?? null, `${verdictIcon(e.goal ? e.verdict : null)} ${e.display ? `${e.display.label} · ${headline}` : headline}`),\n e.sample === 'good' ? c.green('good') : e.sample === 'ok' ? 'ok' : e.sample === 'small' ? c.dim('small') : '',\n typeof e.stars === 'number' ? c.yellow(starText(e.stars)) : '',\n e.status === 'running' && e.daysToVerdict && e.daysToVerdict > 0 ? c.dim(`in ~${Math.ceil(e.daysToVerdict)}d`) : '',\n ];\n })\n )\n );\n }\n printProperties(data);\n if (next) console.log(`\\n${c.dim(next)}`);\n}\n\nconst change = (x: number | null, before: number) => (x === null ? (before === 0 ? c.dim('new') : '–') : x >= 0 ? c.green(`+${Math.round(x * 100)}%`) : c.red(`${Math.round(x * 100)}%`));\n\n/** One line per analytics property: its last 7 days against the 7 before (SplitHub Cloud). */\nexport function printProperties(data: Pick<StatusData, 'properties' | 'propertiesRange'>): void {\n if (!data.properties?.length) return;\n const range = data.propertiesRange ? ` ${c.dim(`· ${data.propertiesRange.from} to ${data.propertiesRange.to}`)}` : '';\n console.log(`\\n${c.bold('Analytics')}${range}`);\n console.log(\n table(\n ['PROPERTY', 'STATUS', 'VISITORS', 'VS WEEK BEFORE', 'GOALS'],\n data.properties.map((p) => [c.bold(p.name), statusColor(p.status), String(p.visitors), change(p.change, p.previousVisitors), p.conversions.map((g) => `${g.goal} ${g.conversions}`).join(', ') || c.dim('–')])\n )\n );\n console.log(c.dim('Details: npx splithub analytics <property>'));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAMA,eAAsB,OAAO,OAA+C;AAC1E,QAAM,SAAS,cAAc,OAAO,cAAc,CAAC;AACnD,QAAM,OAAO,MAAM,YAAY,MAAM;AACrC,QAAM,WAAW,KAAK,YAAY,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,EAAE,IAAI,CAAC,MAAM,EAAE,UAAU;AAChG,QAAM,OAAO,SAAS,SAAS,mCAAmC,SAAS,KAAK,IAAI,CAAC,wHAAwH;AAC7M,MAAI,MAAM,MAAM;AACd,cAAU,OAAO,EAAE,GAAG,MAAM,KAAK,IAAI,IAAI;AACzC;AAAA,EACF;AACA,UAAQ,IAAI,GAAG,EAAE,KAAK,UAAU,CAAC,IAAI,EAAE,IAAI,MAAG,CAAC,YAAY,EAAE,KAAK,KAAK,OAAO,CAAC,IAAI,EAAE,IAAI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AAY,kBAAkB,OAAO;AAAA,MAC5D,KAAK,WAAW,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,IAAI,GAAG,YAAY,EAAE,MAAM,GAAG,OAAO,EAAE,QAAQ,GAAG,OAAO,EAAE,QAAQ,EAAE,gBAAgB,GAAG,EAAE,YAAY,IAAI,CAAC,MAAM,GAAG,EAAE,IAAI,IAAI,EAAE,WAAW,EAAE,EAAE,KAAK,IAAI,KAAK,EAAE,IAAI,QAAG,CAAC,CAAC;AAAA,IAC/M;AAAA,EACF;AACA,UAAQ,IAAI,EAAE,IAAI,4CAA4C,CAAC;AACjE;","names":[]}
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
isReactNativeApp,
|
|
10
10
|
nativeSdkInstalled,
|
|
11
11
|
nativeSetup
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-LFEVNQ75.js";
|
|
13
13
|
import {
|
|
14
14
|
versionReport
|
|
15
15
|
} from "./chunk-HFIBLDUA.js";
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
} from "./chunk-6K3MHBT7.js";
|
|
24
24
|
import {
|
|
25
25
|
resolveTarget
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-W66MJG3R.js";
|
|
27
27
|
import {
|
|
28
28
|
c,
|
|
29
29
|
printJson
|
|
@@ -47,8 +47,8 @@ async function doctor(flags) {
|
|
|
47
47
|
}
|
|
48
48
|
};
|
|
49
49
|
const lines = nativeSetup(project.app, null);
|
|
50
|
-
if (nativeSdkInstalled(project.root, project.app, read)) add("ok", `app: ${project.app},
|
|
51
|
-
else add("error", `app: ${project.app},
|
|
50
|
+
if (nativeSdkInstalled(project.root, project.app, read)) add("ok", `app: ${project.app}, SplitHub SDK in the build files`);
|
|
51
|
+
else add("error", `app: ${project.app}, SplitHub SDK not found in the build files. Add it: ${lines.install.split("\n")[1]}`);
|
|
52
52
|
add("warn", "app: create experiments in the dashboard; they reach installed apps through the cloud, no release needed");
|
|
53
53
|
return report(checks, flags);
|
|
54
54
|
}
|
|
@@ -118,7 +118,7 @@ function appChecks(project, config, add) {
|
|
|
118
118
|
for (const exp of config.experiments) {
|
|
119
119
|
if (exp.kind === "redirect") add("warn", `${exp.key}: redirect experiments change URLs, so they do nothing in an app. Use a value or component experiment.`);
|
|
120
120
|
}
|
|
121
|
-
if (config.storage.mode === "self") add("warn", "app: self-hosted, so experiments only change with a store release (the config is built into the app).
|
|
121
|
+
if (config.storage.mode === "self") add("warn", "app: self-hosted, so experiments only change with a store release (the config is built into the app). SplitHub Cloud starts and changes them live.");
|
|
122
122
|
else add("warn", "app: splithub.config.ts is frozen into the binary until the next store release. Create new experiments in the dashboard so installed apps get them now; push config changes too.");
|
|
123
123
|
}
|
|
124
124
|
async function versionChecks(root, add) {
|
|
@@ -151,4 +151,4 @@ export {
|
|
|
151
151
|
doctor,
|
|
152
152
|
appChecks
|
|
153
153
|
};
|
|
154
|
-
//# sourceMappingURL=chunk-
|
|
154
|
+
//# sourceMappingURL=chunk-KXER4ZZ3.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 type { SplitHubConfig } from '@splithub/core';\nimport { ASYNC_STORAGE, isNativeApp, isReactNativeApp, nativeSdkInstalled, nativeSetup, RN_PACKAGE } from '../app-setup';\nimport { detectProject, grepFiles, listSourceFiles, type ProjectInfo } from '../project';\nimport { findRefs } from '../refs';\nimport { c } from '../ui';\nimport { versionReport } from '../update';\nimport type { Flags } from './init';\n\nexport type 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 (isNativeApp(project.app)) {\n // Native SDKs take experiments from the cloud; there is no config file to check.\n const read = (f: string) => {\n try {\n return readFileSync(f, 'utf8');\n } catch {\n return null;\n }\n };\n const lines = nativeSetup(project.app, null);\n if (nativeSdkInstalled(project.root, project.app, read)) add('ok', `app: ${project.app}, SplitHub SDK in the build files`);\n else add('error', `app: ${project.app}, SplitHub SDK not found in the build files. Add it: ${lines.install.split('\\n')[1]}`);\n add('warn', 'app: create experiments in the dashboard; they reach installed apps through the cloud, no release needed');\n return report(checks, flags);\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 (isReactNativeApp(project.app)) appChecks(project, config, add);\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 // An event goal is sent as its key or, when it has one, as its event name ('Video Played').\n const names = [goal.key, ...(goal.event ? [goal.event] : [])];\n if (goal.type === 'event' && names.every((n) => grepFiles(files, `'${n}'`).length + grepFiles(files, `\"${n}\"`).length === 0)) {\n add('warn', `goal \"${goal.key}\": track('${goal.event ?? 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\n/** React Native / Expo: the package, its storage module, and what the frozen config means for experiments. */\nexport function appChecks(project: Pick<ProjectInfo, 'app' | 'deps'>, config: Pick<SplitHubConfig, 'experiments' | 'storage'>, add: (level: Level, message: string) => void): void {\n if (!project.deps[RN_PACKAGE]) add('error', `app: ${RN_PACKAGE} is not in package.json. Install it: npm install ${RN_PACKAGE}`);\n else add('ok', `app: ${project.app}, ${RN_PACKAGE} ${project.deps[RN_PACKAGE]}`);\n if (!project.deps[ASYNC_STORAGE]) add('error', `app: ${ASYNC_STORAGE} is missing (the visitor id and the offline queue live there). Install it: ${project.app === 'expo' ? 'npx expo install' : 'npm install'} ${ASYNC_STORAGE}`);\n for (const exp of config.experiments) {\n if (exp.kind === 'redirect') add('warn', `${exp.key}: redirect experiments change URLs, so they do nothing in an app. Use a value or component experiment.`);\n }\n if (config.storage.mode === 'self') add('warn', 'app: self-hosted, so experiments only change with a store release (the config is built into the app). SplitHub Cloud starts and changes them live.');\n else add('warn', 'app: splithub.config.ts is frozen into the binary until the next store release. Create new experiments in the dashboard so installed apps get them now; push config changes too.');\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.`));\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,WAC9E,EAAE,SAAS,QAAQ;AAC1B,UAAM,OAAO,EAAE,KAAK,OAAO,CAAC,MAAM,EAAE,SAAS,SAAS,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,MAAM,GAAG,EAAE,IAAI,IAAI,EAAE,SAAS,WAAM,EAAE,MAAM,EAAE,EAAE,KAAK,IAAI;AAC7H,QAAI,QAAQ,sBAAsB,IAAI,MAAM,EAAE,WAAW,KAAK,SAAS,EAAE,OAAO,GAAG;AAAA,EACrF;AACF;AAEA,SAAS,OAAO,QAAiB,OAAoB;AACnD,QAAM,SAAS,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,OAAO,EAAE;AACzD,MAAI,MAAM,MAAM;AACd,cAAU,EAAE,IAAI,WAAW,GAAG,QAAQ,UAAU,OAAO,OAAO,CAAC,MAAM,EAAE,UAAU,MAAM,EAAE,QAAQ,OAAO,CAAC;AAAA,EAC3G,OAAO;AACL,eAAW,KAAK,QAAQ;AACtB,YAAM,OAAO,EAAE,UAAU,OAAO,EAAE,MAAM,QAAG,IAAI,EAAE,UAAU,SAAS,EAAE,OAAO,GAAG,IAAI,EAAE,IAAI,QAAG;AAC7F,cAAQ,IAAI,GAAG,IAAI,IAAI,EAAE,OAAO,EAAE;AAAA,IACpC;AACA,YAAQ,IAAI;AACZ,YAAQ,IAAI,WAAW,IAAI,EAAE,MAAM,WAAW,IAAI,EAAE,IAAI,GAAG,MAAM,qBAAqB,CAAC;AAAA,EACzF;AACA,MAAI,SAAS,EAAG,SAAQ,WAAW;AACrC;","names":[]}
|
|
@@ -156,13 +156,13 @@ ${childIndent}<${tracker.name} />${body.slice(at)}`;
|
|
|
156
156
|
var IOS_PACKAGE_URL = "https://github.com/splithub-io/splithub-sdk";
|
|
157
157
|
var ANDROID_ARTIFACT = "io.splithub:splithub";
|
|
158
158
|
var ANDROID_COMPOSE_ARTIFACT = "io.splithub:splithub-compose";
|
|
159
|
-
var NATIVE_SDK_VERSION = "0.6.
|
|
159
|
+
var NATIVE_SDK_VERSION = "0.6.1";
|
|
160
160
|
function nativeSetup(app, publicKey, property = null) {
|
|
161
161
|
const key = publicKey ?? "pk_\u2026";
|
|
162
162
|
const prop = property ?? "sh-\u2026";
|
|
163
163
|
if (app === "ios")
|
|
164
164
|
return {
|
|
165
|
-
install: `// Xcode: File \u2192 Add Package Dependencies \u2192 ${IOS_PACKAGE_URL}, then add
|
|
165
|
+
install: `// Xcode: File \u2192 Add Package Dependencies \u2192 ${IOS_PACKAGE_URL}, then add SplitHub to the target
|
|
166
166
|
.package(url: "${IOS_PACKAGE_URL}", from: "${NATIVE_SDK_VERSION}")`,
|
|
167
167
|
quickStart: `import SplitHub
|
|
168
168
|
|
|
@@ -202,4 +202,4 @@ export {
|
|
|
202
202
|
nativeSetup,
|
|
203
203
|
nativeSdkInstalled
|
|
204
204
|
};
|
|
205
|
-
//# sourceMappingURL=chunk-
|
|
205
|
+
//# sourceMappingURL=chunk-LFEVNQ75.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app-setup.ts"],"sourcesContent":["// Apps (React Native / Expo, native iOS and Android) in `splithub init`, `analytics connect` and `doctor`.\n//\n// React Native / Expo: install @splithub/react-native and wrap the app entry (App.tsx, or app/_layout.tsx with\n// Expo Router) in <SplitHubProvider>, with the screen tracker for the navigation library in use. The entry is\n// rewritten with the TypeScript compiler (the project's own, else the CLI's); without it, or when the entry has\n// a shape we do not recognise, the snippet is printed instead. Native projects get install lines only.\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type * as TS from 'typescript';\nimport type { AppKind, ProjectInfo } from './project';\n\nexport const RN_PACKAGE = '@splithub/react-native';\nexport const ASYNC_STORAGE = '@react-native-async-storage/async-storage';\n\n/** How screens are reported: a tracker component per navigation library, or `useScreen()` by hand. */\nexport type ScreenTracking = 'expo-router' | 'react-navigation' | null;\n\nconst TRACKERS: Record<Exclude<ScreenTracking, null>, { name: string }> = {\n 'expo-router': { name: 'ExpoRouterScreens' },\n 'react-navigation': { name: 'NavigationScreens' },\n};\n\nconst providerImport = (tracker: { name: string } | null) => `import { SplitHubProvider${tracker ? `, ${tracker.name}` : ''} } from '${RN_PACKAGE}';`;\n\nexport function screenTracking(project: Pick<ProjectInfo, 'expoRouter' | 'reactNavigation'>): ScreenTracking {\n return project.expoRouter ? 'expo-router' : project.reactNavigation ? 'react-navigation' : null;\n}\n\nexport const isReactNativeApp = (app: AppKind | null): app is 'expo' | 'react-native' => app === 'expo' || app === 'react-native';\nexport const isNativeApp = (app: AppKind | null): app is 'ios' | 'android' => app === 'ios' || app === 'android';\n\n/** npm packages for a React Native app; Expo installs the storage module with `expo install` (the version matching its SDK). */\nexport function appPackages(project: Pick<ProjectInfo, 'app' | 'deps'>): { runtime: string[]; expo: string[] } {\n const storage = project.deps[ASYNC_STORAGE] ? [] : [ASYNC_STORAGE];\n if (project.app === 'expo') return { runtime: [RN_PACKAGE, '@splithub/core'], expo: storage };\n return { runtime: [RN_PACKAGE, '@splithub/core', ...storage], expo: [] };\n}\n\n/** The file that renders the whole app: the root layout with Expo Router, else App.tsx. */\nexport function findAppEntry(root: string, expoRouter: boolean): string | null {\n const names = expoRouter ? ['app/_layout', 'src/app/_layout'] : ['App', 'src/App', 'app/App'];\n for (const name of names) {\n for (const ext of ['.tsx', '.jsx', '.js', '.ts']) {\n const file = join(root, name + ext);\n if (existsSync(file)) return file;\n }\n }\n return null;\n}\n\nexport interface EntryPatch {\n /** The new source; null when nothing changes. */\n source: string | null;\n status: 'added' | 'already' | 'manual';\n /** Whether the screen tracker was placed (false: add it by hand, see the snippet). */\n screens: boolean;\n reason?: string;\n}\n\n/** The provider snippet to paste when the entry cannot be rewritten. */\nexport function appProviderSnippet(configImport: string, screens: ScreenTracking): string {\n const tracker = screens ? TRACKERS[screens] : null;\n const imports = [providerImport(tracker), `import config from '${configImport}';`];\n if (screens === 'expo-router')\n return `// app/_layout.tsx\\n${imports.join('\\n')}\\n\\n<SplitHubProvider config={config}>\\n <ExpoRouterScreens />\\n <Stack />\\n</SplitHubProvider>`;\n if (screens === 'react-navigation')\n return `// App.tsx\\n${imports.join('\\n')}\\n\\n<SplitHubProvider config={config}>\\n <NavigationContainer>\\n <NavigationScreens />\\n {/* your navigators */}\\n </NavigationContainer>\\n</SplitHubProvider>`;\n return `// App.tsx\\n${imports.join('\\n')}\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>\\n// screens: useScreen('Home') in each screen (from ${RN_PACKAGE})`;\n}\n\nfunction scriptKind(ts: typeof TS, file: string): TS.ScriptKind {\n if (/\\.tsx$/.test(file)) return ts.ScriptKind.TSX;\n if (/\\.ts$/.test(file)) return ts.ScriptKind.TS;\n return ts.ScriptKind.JSX;\n}\n\ntype Fn = TS.FunctionDeclaration | TS.FunctionExpression | TS.ArrowFunction;\n\n/** The component behind `export default`: a function, `export default App`, or a wrapper call like `Sentry.wrap(App)`. */\nfunction defaultComponent(ts: typeof TS, sf: TS.SourceFile): Fn | null {\n const byName = (name: string): Fn | null => {\n for (const st of sf.statements) {\n if (ts.isFunctionDeclaration(st) && st.name?.text === name) return st;\n if (ts.isVariableStatement(st)) {\n for (const d of st.declarationList.declarations) {\n if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer && (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer))) return d.initializer;\n }\n }\n }\n return null;\n };\n const fromExpr = (e: TS.Expression): Fn | null => {\n if (ts.isArrowFunction(e) || ts.isFunctionExpression(e)) return e;\n if (ts.isIdentifier(e)) return byName(e.text);\n if (ts.isCallExpression(e) && e.arguments[0]) return fromExpr(e.arguments[0]);\n if (ts.isParenthesizedExpression(e)) return fromExpr(e.expression);\n return null;\n };\n for (const st of sf.statements) {\n if (ts.isFunctionDeclaration(st) && st.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) return st;\n if (ts.isExportAssignment(st) && !st.isExportEquals) return fromExpr(st.expression);\n }\n return null;\n}\n\nconst isJsx = (ts: typeof TS, n: TS.Node) => ts.isJsxElement(n) || ts.isJsxSelfClosingElement(n) || ts.isJsxFragment(n);\n\nfunction indentAt(src: string, pos: number): string {\n const lineStart = src.lastIndexOf('\\n', pos - 1) + 1;\n return /^[ \\t]*/.exec(src.slice(lineStart))![0];\n}\n\n/** Move lines 2..n of `text` by the difference between where its first line starts and where it will start. */\nfunction shift(text: string, fromCol: number, toCol: number): string {\n const d = toCol - fromCol;\n if (d === 0) return text;\n return text\n .split('\\n')\n .map((line, i) => (i === 0 || !line.trim() ? line : d > 0 ? ' '.repeat(d) + line : line.replace(new RegExp(`^[ \\\\t]{0,${-d}}`), '')))\n .join('\\n');\n}\n\n/**\n * Wraps what the entry's default component returns in <SplitHubProvider config={config}> and adds the imports.\n * Pure: the caller reads and writes the file.\n */\nexport function patchAppEntry(ts: typeof TS, file: string, src: string, opts: { configImport: string; screens: ScreenTracking }): EntryPatch {\n if (/<SplitHubProvider\\b/.test(src)) return { source: null, status: 'already', screens: true };\n const sf = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, scriptKind(ts, file));\n const fn = defaultComponent(ts, sf);\n if (!fn?.body) return { source: null, status: 'manual', screens: false, reason: 'no default-exported component' };\n\n // The returned JSX: the last top-level `return <…>` of a block body, or an arrow's expression body.\n let outer: TS.Expression | undefined;\n if (ts.isBlock(fn.body)) {\n const ret = [...fn.body.statements].reverse().find((s): s is TS.ReturnStatement => ts.isReturnStatement(s) && Boolean(s.expression));\n outer = ret?.expression;\n } else outer = fn.body;\n let inner = outer;\n while (inner && ts.isParenthesizedExpression(inner)) inner = inner.expression;\n if (!outer || !inner || !isJsx(ts, inner)) return { source: null, status: 'manual', screens: false, reason: 'the component does not return JSX directly' };\n\n const tracker = opts.screens ? TRACKERS[opts.screens] : null;\n const start = inner.getStart(sf);\n let body = src.slice(start, inner.end);\n let screensPlaced = !tracker;\n let trackerLine = '';\n if (tracker && opts.screens === 'react-navigation') {\n // Inside <NavigationContainer>, where its ref context is available.\n let container: TS.JsxElement | undefined;\n const find = (n: TS.Node): void => {\n if (!container && ts.isJsxElement(n) && n.openingElement.tagName.getText(sf) === 'NavigationContainer') container = n;\n else ts.forEachChild(n, find);\n };\n find(inner);\n if (container) {\n const at = container.openingElement.end - start;\n const firstChild = container.children.find((ch) => !(ts.isJsxText(ch) && ch.containsOnlyTriviaWhiteSpaces));\n const childIndent = firstChild ? indentAt(src, firstChild.getStart(sf)) : indentAt(src, container.getStart(sf)) + ' ';\n body = `${body.slice(0, at)}\\n${childIndent}<${tracker.name} />${body.slice(at)}`;\n screensPlaced = true;\n }\n } else if (tracker) {\n trackerLine = `<${tracker.name} />`;\n screensPlaced = true;\n }\n\n const configName = /\\bconfig\\b/.test(src) ? 'splithubConfig' : 'config';\n const base = indentAt(src, outer.getStart(sf));\n const col = start - (src.lastIndexOf('\\n', start - 1) + 1);\n const inside = base + ' ';\n const wrapped = [\n '(',\n `${base} <SplitHubProvider config={${configName}}>`,\n ...(trackerLine ? [`${inside}${trackerLine}`] : []),\n `${inside}${shift(body, col, inside.length)}`,\n `${base} </SplitHubProvider>`,\n `${base})`,\n ].join('\\n');\n let out = src.slice(0, outer.getStart(sf)) + wrapped + src.slice(outer.end);\n\n const imports = [providerImport(tracker && screensPlaced ? tracker : null), `import ${configName} from '${opts.configImport}';`].join('\\n');\n const lastImport = [...sf.statements].filter(ts.isImportDeclaration).pop();\n if (lastImport) out = out.slice(0, lastImport.end) + '\\n' + imports + out.slice(lastImport.end);\n else out = imports + '\\n\\n' + out;\n return { source: out, status: 'added', screens: screensPlaced };\n}\n\n// ---------------------------------------------------------------------------\n// Native SDKs: install lines and a quick start, no patching.\n// ---------------------------------------------------------------------------\n\n// The same values as sdks/ios/README.md, sdks/android/README.md and the dashboard's install tabs.\nexport const IOS_PACKAGE_URL = 'https://github.com/splithub-io/splithub-sdk';\nexport const ANDROID_ARTIFACT = 'io.splithub:splithub';\nexport const ANDROID_COMPOSE_ARTIFACT = 'io.splithub:splithub-compose';\nexport const NATIVE_SDK_VERSION = '0.6.0';\n\nexport function nativeSetup(app: 'ios' | 'android', publicKey: string | null, property: string | null = null): { install: string; quickStart: string } {\n const key = publicKey ?? 'pk_…';\n const prop = property ?? 'sh-…';\n if (app === 'ios')\n return {\n install: `// Xcode: File → Add Package Dependencies → ${IOS_PACKAGE_URL}, then add sh2 to the target\\n.package(url: \"${IOS_PACKAGE_URL}\", from: \"${NATIVE_SDK_VERSION}\")`,\n quickStart: `import SplitHub\\n\\nSplitHub.start(publicKey: \"${key}\", property: \"${prop}\") // once, at launch\\nlet cta = SplitHub.variant(\"hero-cta\") // \"control\", \"bold\", ...\\nSplitHub.screen(\"Settings\") // each screen\\nSplitHub.track(\"Signup\") // any event; a goal when marked as one`,\n };\n return {\n install: `// app/build.gradle.kts\\nimplementation(\"${ANDROID_ARTIFACT}:${NATIVE_SDK_VERSION}\")\\nimplementation(\"${ANDROID_COMPOSE_ARTIFACT}:${NATIVE_SDK_VERSION}\") // optional: Experiment(id) { variant -> }, TrackScreen(name)`,\n quickStart: `import io.splithub.SplitHub\\n\\nSplitHub.start(this, \"${key}\", property = \"${prop}\") // once, in Application.onCreate\\nval cta = SplitHub.variant(\"hero-cta\") // \"control\", \"bold\", ...\\nSplitHub.screen(\"Settings\") // each screen\\nSplitHub.track(\"Signup\") // any event; a goal when marked as one`,\n };\n}\n\n/** Whether the native project already depends on the SDK (Package.swift, Podfile, project.pbxproj, Gradle files). */\nexport function nativeSdkInstalled(root: string, app: 'ios' | 'android', read: (file: string) => string | null): boolean {\n const files = app === 'ios' ? ['Package.swift', 'Podfile', 'Package.resolved'] : ['build.gradle', 'build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts', 'gradle/libs.versions.toml'];\n const needle = app === 'ios' ? /splithub/i : /io\\.splithub/;\n return files.some((f) => needle.test(read(join(root, f)) ?? ''));\n}\n"],"mappings":";;;AAMA,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAId,IAAM,aAAa;AACnB,IAAM,gBAAgB;AAK7B,IAAM,WAAo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AA,iBAAgD,eAAe,aAAa,kBAAkB;AAAA,MACrK,YAAY;AAAA;AAAA,6BAAiD,GAAG,iBAAiB,IAAI;AAAA;AAAA;AAAA;AAAA,IACvF;AACF,SAAO;AAAA,IACL,SAAS;AAAA,kBAA4C,gBAAgB,IAAI,kBAAkB;AAAA,kBAAuB,wBAAwB,IAAI,kBAAkB;AAAA,IAChK,YAAY;AAAA;AAAA,wBAAwD,GAAG,kBAAkB,IAAI;AAAA;AAAA;AAAA;AAAA,EAC/F;AACF;AAGO,SAAS,mBAAmB,MAAc,KAAwB,MAAgD;AACvH,QAAM,QAAQ,QAAQ,QAAQ,CAAC,iBAAiB,WAAW,kBAAkB,IAAI,CAAC,gBAAgB,oBAAoB,oBAAoB,wBAAwB,2BAA2B;AAC7L,QAAM,SAAS,QAAQ,QAAQ,cAAc;AAC7C,SAAO,MAAM,KAAK,CAAC,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM,CAAC,CAAC,KAAK,EAAE,CAAC;AACjE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/app-setup.ts"],"sourcesContent":["// Apps (React Native / Expo, native iOS and Android) in `splithub init`, `analytics connect` and `doctor`.\n//\n// React Native / Expo: install @splithub/react-native and wrap the app entry (App.tsx, or app/_layout.tsx with\n// Expo Router) in <SplitHubProvider>, with the screen tracker for the navigation library in use. The entry is\n// rewritten with the TypeScript compiler (the project's own, else the CLI's); without it, or when the entry has\n// a shape we do not recognise, the snippet is printed instead. Native projects get install lines only.\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type * as TS from 'typescript';\nimport type { AppKind, ProjectInfo } from './project';\n\nexport const RN_PACKAGE = '@splithub/react-native';\nexport const ASYNC_STORAGE = '@react-native-async-storage/async-storage';\n\n/** How screens are reported: a tracker component per navigation library, or `useScreen()` by hand. */\nexport type ScreenTracking = 'expo-router' | 'react-navigation' | null;\n\nconst TRACKERS: Record<Exclude<ScreenTracking, null>, { name: string }> = {\n 'expo-router': { name: 'ExpoRouterScreens' },\n 'react-navigation': { name: 'NavigationScreens' },\n};\n\nconst providerImport = (tracker: { name: string } | null) => `import { SplitHubProvider${tracker ? `, ${tracker.name}` : ''} } from '${RN_PACKAGE}';`;\n\nexport function screenTracking(project: Pick<ProjectInfo, 'expoRouter' | 'reactNavigation'>): ScreenTracking {\n return project.expoRouter ? 'expo-router' : project.reactNavigation ? 'react-navigation' : null;\n}\n\nexport const isReactNativeApp = (app: AppKind | null): app is 'expo' | 'react-native' => app === 'expo' || app === 'react-native';\nexport const isNativeApp = (app: AppKind | null): app is 'ios' | 'android' => app === 'ios' || app === 'android';\n\n/** npm packages for a React Native app; Expo installs the storage module with `expo install` (the version matching its SDK). */\nexport function appPackages(project: Pick<ProjectInfo, 'app' | 'deps'>): { runtime: string[]; expo: string[] } {\n const storage = project.deps[ASYNC_STORAGE] ? [] : [ASYNC_STORAGE];\n if (project.app === 'expo') return { runtime: [RN_PACKAGE, '@splithub/core'], expo: storage };\n return { runtime: [RN_PACKAGE, '@splithub/core', ...storage], expo: [] };\n}\n\n/** The file that renders the whole app: the root layout with Expo Router, else App.tsx. */\nexport function findAppEntry(root: string, expoRouter: boolean): string | null {\n const names = expoRouter ? ['app/_layout', 'src/app/_layout'] : ['App', 'src/App', 'app/App'];\n for (const name of names) {\n for (const ext of ['.tsx', '.jsx', '.js', '.ts']) {\n const file = join(root, name + ext);\n if (existsSync(file)) return file;\n }\n }\n return null;\n}\n\nexport interface EntryPatch {\n /** The new source; null when nothing changes. */\n source: string | null;\n status: 'added' | 'already' | 'manual';\n /** Whether the screen tracker was placed (false: add it by hand, see the snippet). */\n screens: boolean;\n reason?: string;\n}\n\n/** The provider snippet to paste when the entry cannot be rewritten. */\nexport function appProviderSnippet(configImport: string, screens: ScreenTracking): string {\n const tracker = screens ? TRACKERS[screens] : null;\n const imports = [providerImport(tracker), `import config from '${configImport}';`];\n if (screens === 'expo-router')\n return `// app/_layout.tsx\\n${imports.join('\\n')}\\n\\n<SplitHubProvider config={config}>\\n <ExpoRouterScreens />\\n <Stack />\\n</SplitHubProvider>`;\n if (screens === 'react-navigation')\n return `// App.tsx\\n${imports.join('\\n')}\\n\\n<SplitHubProvider config={config}>\\n <NavigationContainer>\\n <NavigationScreens />\\n {/* your navigators */}\\n </NavigationContainer>\\n</SplitHubProvider>`;\n return `// App.tsx\\n${imports.join('\\n')}\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>\\n// screens: useScreen('Home') in each screen (from ${RN_PACKAGE})`;\n}\n\nfunction scriptKind(ts: typeof TS, file: string): TS.ScriptKind {\n if (/\\.tsx$/.test(file)) return ts.ScriptKind.TSX;\n if (/\\.ts$/.test(file)) return ts.ScriptKind.TS;\n return ts.ScriptKind.JSX;\n}\n\ntype Fn = TS.FunctionDeclaration | TS.FunctionExpression | TS.ArrowFunction;\n\n/** The component behind `export default`: a function, `export default App`, or a wrapper call like `Sentry.wrap(App)`. */\nfunction defaultComponent(ts: typeof TS, sf: TS.SourceFile): Fn | null {\n const byName = (name: string): Fn | null => {\n for (const st of sf.statements) {\n if (ts.isFunctionDeclaration(st) && st.name?.text === name) return st;\n if (ts.isVariableStatement(st)) {\n for (const d of st.declarationList.declarations) {\n if (ts.isIdentifier(d.name) && d.name.text === name && d.initializer && (ts.isArrowFunction(d.initializer) || ts.isFunctionExpression(d.initializer))) return d.initializer;\n }\n }\n }\n return null;\n };\n const fromExpr = (e: TS.Expression): Fn | null => {\n if (ts.isArrowFunction(e) || ts.isFunctionExpression(e)) return e;\n if (ts.isIdentifier(e)) return byName(e.text);\n if (ts.isCallExpression(e) && e.arguments[0]) return fromExpr(e.arguments[0]);\n if (ts.isParenthesizedExpression(e)) return fromExpr(e.expression);\n return null;\n };\n for (const st of sf.statements) {\n if (ts.isFunctionDeclaration(st) && st.modifiers?.some((m) => m.kind === ts.SyntaxKind.DefaultKeyword)) return st;\n if (ts.isExportAssignment(st) && !st.isExportEquals) return fromExpr(st.expression);\n }\n return null;\n}\n\nconst isJsx = (ts: typeof TS, n: TS.Node) => ts.isJsxElement(n) || ts.isJsxSelfClosingElement(n) || ts.isJsxFragment(n);\n\nfunction indentAt(src: string, pos: number): string {\n const lineStart = src.lastIndexOf('\\n', pos - 1) + 1;\n return /^[ \\t]*/.exec(src.slice(lineStart))![0];\n}\n\n/** Move lines 2..n of `text` by the difference between where its first line starts and where it will start. */\nfunction shift(text: string, fromCol: number, toCol: number): string {\n const d = toCol - fromCol;\n if (d === 0) return text;\n return text\n .split('\\n')\n .map((line, i) => (i === 0 || !line.trim() ? line : d > 0 ? ' '.repeat(d) + line : line.replace(new RegExp(`^[ \\\\t]{0,${-d}}`), '')))\n .join('\\n');\n}\n\n/**\n * Wraps what the entry's default component returns in <SplitHubProvider config={config}> and adds the imports.\n * Pure: the caller reads and writes the file.\n */\nexport function patchAppEntry(ts: typeof TS, file: string, src: string, opts: { configImport: string; screens: ScreenTracking }): EntryPatch {\n if (/<SplitHubProvider\\b/.test(src)) return { source: null, status: 'already', screens: true };\n const sf = ts.createSourceFile(file, src, ts.ScriptTarget.Latest, true, scriptKind(ts, file));\n const fn = defaultComponent(ts, sf);\n if (!fn?.body) return { source: null, status: 'manual', screens: false, reason: 'no default-exported component' };\n\n // The returned JSX: the last top-level `return <…>` of a block body, or an arrow's expression body.\n let outer: TS.Expression | undefined;\n if (ts.isBlock(fn.body)) {\n const ret = [...fn.body.statements].reverse().find((s): s is TS.ReturnStatement => ts.isReturnStatement(s) && Boolean(s.expression));\n outer = ret?.expression;\n } else outer = fn.body;\n let inner = outer;\n while (inner && ts.isParenthesizedExpression(inner)) inner = inner.expression;\n if (!outer || !inner || !isJsx(ts, inner)) return { source: null, status: 'manual', screens: false, reason: 'the component does not return JSX directly' };\n\n const tracker = opts.screens ? TRACKERS[opts.screens] : null;\n const start = inner.getStart(sf);\n let body = src.slice(start, inner.end);\n let screensPlaced = !tracker;\n let trackerLine = '';\n if (tracker && opts.screens === 'react-navigation') {\n // Inside <NavigationContainer>, where its ref context is available.\n let container: TS.JsxElement | undefined;\n const find = (n: TS.Node): void => {\n if (!container && ts.isJsxElement(n) && n.openingElement.tagName.getText(sf) === 'NavigationContainer') container = n;\n else ts.forEachChild(n, find);\n };\n find(inner);\n if (container) {\n const at = container.openingElement.end - start;\n const firstChild = container.children.find((ch) => !(ts.isJsxText(ch) && ch.containsOnlyTriviaWhiteSpaces));\n const childIndent = firstChild ? indentAt(src, firstChild.getStart(sf)) : indentAt(src, container.getStart(sf)) + ' ';\n body = `${body.slice(0, at)}\\n${childIndent}<${tracker.name} />${body.slice(at)}`;\n screensPlaced = true;\n }\n } else if (tracker) {\n trackerLine = `<${tracker.name} />`;\n screensPlaced = true;\n }\n\n const configName = /\\bconfig\\b/.test(src) ? 'splithubConfig' : 'config';\n const base = indentAt(src, outer.getStart(sf));\n const col = start - (src.lastIndexOf('\\n', start - 1) + 1);\n const inside = base + ' ';\n const wrapped = [\n '(',\n `${base} <SplitHubProvider config={${configName}}>`,\n ...(trackerLine ? [`${inside}${trackerLine}`] : []),\n `${inside}${shift(body, col, inside.length)}`,\n `${base} </SplitHubProvider>`,\n `${base})`,\n ].join('\\n');\n let out = src.slice(0, outer.getStart(sf)) + wrapped + src.slice(outer.end);\n\n const imports = [providerImport(tracker && screensPlaced ? tracker : null), `import ${configName} from '${opts.configImport}';`].join('\\n');\n const lastImport = [...sf.statements].filter(ts.isImportDeclaration).pop();\n if (lastImport) out = out.slice(0, lastImport.end) + '\\n' + imports + out.slice(lastImport.end);\n else out = imports + '\\n\\n' + out;\n return { source: out, status: 'added', screens: screensPlaced };\n}\n\n// ---------------------------------------------------------------------------\n// Native SDKs: install lines and a quick start, no patching.\n// ---------------------------------------------------------------------------\n\n// The same values as sdks/ios/README.md, sdks/android/README.md and the dashboard's install tabs.\nexport const IOS_PACKAGE_URL = 'https://github.com/splithub-io/splithub-sdk';\nexport const ANDROID_ARTIFACT = 'io.splithub:splithub';\nexport const ANDROID_COMPOSE_ARTIFACT = 'io.splithub:splithub-compose';\nexport const NATIVE_SDK_VERSION = '0.6.1';\n\nexport function nativeSetup(app: 'ios' | 'android', publicKey: string | null, property: string | null = null): { install: string; quickStart: string } {\n const key = publicKey ?? 'pk_…';\n const prop = property ?? 'sh-…';\n if (app === 'ios')\n return {\n install: `// Xcode: File → Add Package Dependencies → ${IOS_PACKAGE_URL}, then add SplitHub to the target\\n.package(url: \"${IOS_PACKAGE_URL}\", from: \"${NATIVE_SDK_VERSION}\")`,\n quickStart: `import SplitHub\\n\\nSplitHub.start(publicKey: \"${key}\", property: \"${prop}\") // once, at launch\\nlet cta = SplitHub.variant(\"hero-cta\") // \"control\", \"bold\", ...\\nSplitHub.screen(\"Settings\") // each screen\\nSplitHub.track(\"Signup\") // any event; a goal when marked as one`,\n };\n return {\n install: `// app/build.gradle.kts\\nimplementation(\"${ANDROID_ARTIFACT}:${NATIVE_SDK_VERSION}\")\\nimplementation(\"${ANDROID_COMPOSE_ARTIFACT}:${NATIVE_SDK_VERSION}\") // optional: Experiment(id) { variant -> }, TrackScreen(name)`,\n quickStart: `import io.splithub.SplitHub\\n\\nSplitHub.start(this, \"${key}\", property = \"${prop}\") // once, in Application.onCreate\\nval cta = SplitHub.variant(\"hero-cta\") // \"control\", \"bold\", ...\\nSplitHub.screen(\"Settings\") // each screen\\nSplitHub.track(\"Signup\") // any event; a goal when marked as one`,\n };\n}\n\n/** Whether the native project already depends on the SDK (Package.swift, Podfile, project.pbxproj, Gradle files). */\nexport function nativeSdkInstalled(root: string, app: 'ios' | 'android', read: (file: string) => string | null): boolean {\n const files = app === 'ios' ? ['Package.swift', 'Podfile', 'Package.resolved'] : ['build.gradle', 'build.gradle.kts', 'app/build.gradle', 'app/build.gradle.kts', 'gradle/libs.versions.toml'];\n const needle = app === 'ios' ? /splithub/i : /io\\.splithub/;\n return files.some((f) => needle.test(read(join(root, f)) ?? ''));\n}\n"],"mappings":";;;AAMA,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAId,IAAM,aAAa;AACnB,IAAM,gBAAgB;AAK7B,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C,eAAe;AAAA,iBAAqD,eAAe,aAAa,kBAAkB;AAAA,MAC1K,YAAY;AAAA;AAAA,6BAAiD,GAAG,iBAAiB,IAAI;AAAA;AAAA;AAAA;AAAA,IACvF;AACF,SAAO;AAAA,IACL,SAAS;AAAA,kBAA4C,gBAAgB,IAAI,kBAAkB;AAAA,kBAAuB,wBAAwB,IAAI,kBAAkB;AAAA,IAChK,YAAY;AAAA;AAAA,wBAAwD,GAAG,kBAAkB,IAAI;AAAA;AAAA;AAAA;AAAA,EAC/F;AACF;AAGO,SAAS,mBAAmB,MAAc,KAAwB,MAAgD;AACvH,QAAM,QAAQ,QAAQ,QAAQ,CAAC,iBAAiB,WAAW,kBAAkB,IAAI,CAAC,gBAAgB,oBAAoB,oBAAoB,wBAAwB,2BAA2B;AAC7L,QAAM,SAAS,QAAQ,QAAQ,cAAc;AAC7C,SAAO,MAAM,KAAK,CAAC,MAAM,OAAO,KAAK,KAAK,KAAK,MAAM,CAAC,CAAC,KAAK,EAAE,CAAC;AACjE;","names":[]}
|
|
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
CURSOR_RULE,
|
|
5
5
|
MCP_SERVER_ENTRY,
|
|
6
6
|
SKILLS
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-LOYPA5WN.js";
|
|
8
8
|
import {
|
|
9
9
|
detectProject
|
|
10
10
|
} from "./chunk-6K3MHBT7.js";
|
|
11
11
|
import {
|
|
12
12
|
fetchSkills
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-W66MJG3R.js";
|
|
14
14
|
import {
|
|
15
15
|
c
|
|
16
16
|
} from "./chunk-ZISCJRR5.js";
|
|
@@ -35,7 +35,7 @@ function writeFile(file, content, force, out) {
|
|
|
35
35
|
out.skipped.push(file);
|
|
36
36
|
return;
|
|
37
37
|
}
|
|
38
|
-
if (!/SplitHub|splithub
|
|
38
|
+
if (!/SplitHub|splithub/.test(current)) {
|
|
39
39
|
out.skipped.push(file);
|
|
40
40
|
return;
|
|
41
41
|
}
|
|
@@ -74,7 +74,7 @@ function installSkills(root, options = {}) {
|
|
|
74
74
|
writeFileSync(agentsFile, `# ${detectProject(root).name}
|
|
75
75
|
${section}`, "utf8");
|
|
76
76
|
out.written.push(agentsFile);
|
|
77
|
-
} else if (!/SplitHub
|
|
77
|
+
} else if (!/SplitHub/.test(readFileSync(agentsFile, "utf8"))) {
|
|
78
78
|
writeFileSync(agentsFile, readFileSync(agentsFile, "utf8") + `
|
|
79
79
|
${section}`, "utf8");
|
|
80
80
|
out.written.push(`${agentsFile} (section appended)`);
|
|
@@ -100,8 +100,8 @@ async function skills(flags) {
|
|
|
100
100
|
if (result.mcp.length) console.log(`${c.green("\u2714")} MCP server registered in
|
|
101
101
|
${result.mcp.map(rel).join("\n ")}`);
|
|
102
102
|
if (result.skipped.length) console.log(c.dim(`unchanged: ${result.skipped.map(rel).join(", ")}`));
|
|
103
|
-
if (result.source === "bundled") console.log(c.dim("couldn't reach
|
|
104
|
-
if (!flags.mcp) console.log(c.dim(`add --mcp to register the
|
|
103
|
+
if (result.source === "bundled") console.log(c.dim("couldn't reach SplitHub Cloud, so these are the copies bundled with this CLI"));
|
|
104
|
+
if (!flags.mcp) console.log(c.dim(`add --mcp to register the SplitHub MCP server (Claude Code .mcp.json, Cursor .cursor/mcp.json; Codex and Copilot read AGENTS.md)`));
|
|
105
105
|
console.log(c.dim("skills: splithub (library + CLI), ab-testing (how to run experiments well), splithub-analytics (pageviews, events, reports), splithub-api (HTTP API), splithub-mcp (MCP tools), splithub-self-hosted (your own database), splithub-ship (keep the winner, remove the experiment), splithub-loop (the whole loop, tool by tool)"));
|
|
106
106
|
}
|
|
107
107
|
|
|
@@ -111,4 +111,4 @@ export {
|
|
|
111
111
|
installSkills,
|
|
112
112
|
skills
|
|
113
113
|
};
|
|
114
|
-
//# sourceMappingURL=chunk-
|
|
114
|
+
//# sourceMappingURL=chunk-LGL7JY6Y.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/skills.ts"],"sourcesContent":["// `splithub skills [--mcp] [--force]`: install or refresh the agent skills in\n// this project (.claude/skills/<name>/SKILL.md, .cursor/rules/splithub.mdc,\n// an AGENTS.md section) and, with --mcp, register the SplitHub MCP server in\n// .mcp.json (Claude Code) and .cursor/mcp.json (Cursor). `init` calls this too.\n// The text comes from SplitHub Cloud (GET /v1/skills) so it updates with a deploy;\n// the copies bundled here are the offline fallback.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { fetchSkills, type SkillFile } from '../api';\nimport { detectProject } from '../project';\nimport { AGENTS_SECTION, CURSOR_RULE } from '../templates';\nimport { MCP_SERVER_ENTRY, SKILLS } from '../skills';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nexport interface SkillsResult {\n written: string[];\n skipped: string[];\n mcp: string[];\n /** Where the text came from: SplitHub Cloud, or the copies bundled with the CLI. */\n source: 'cloud' | 'bundled';\n}\n\n/** The copies shipped with this CLI, in the shape GET /v1/skills serves. */\nexport const BUNDLED_SKILL_FILES: SkillFile[] = [\n ...SKILLS.map((s) => ({ path: `.claude/skills/${s.dir}/SKILL.md`, body: s.body })),\n { path: '.cursor/rules/splithub.mdc', body: CURSOR_RULE },\n { path: 'AGENTS.md', body: AGENTS_SECTION },\n];\n\n/** Only where skills belong: a server answer never writes anywhere else in the project. */\nconst SAFE_PATH = /^(\\.claude\\/skills\\/[a-z0-9][a-z0-9-]*\\/SKILL\\.md|\\.cursor\\/rules\\/[a-z0-9][a-z0-9-]*\\.mdc|AGENTS\\.md)$/;\n\n/** Fresh text from SplitHub Cloud (1.5 s at most), else the bundled copies. */\nexport async function loadSkillFiles(flags: Record<string, unknown> = {}): Promise<{ files: SkillFile[]; source: 'cloud' | 'bundled' }> {\n const remote = (await fetchSkills(flags))?.filter((f) => SAFE_PATH.test(f.path));\n return remote?.length ? { files: remote, source: 'cloud' } : { files: BUNDLED_SKILL_FILES, source: 'bundled' };\n}\n\nfunction writeFile(file: string, content: string, force: boolean, out: SkillsResult): void {\n if (existsSync(file) && !force) {\n const current = readFileSync(file, 'utf8');\n if (current === content) {\n out.skipped.push(file);\n return;\n }\n // Skills we wrote earlier get refreshed; a user-edited file is left alone unless --force.\n if (!/SplitHub|splithub/.test(current)) {\n out.skipped.push(file);\n return;\n }\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n out.written.push(file);\n}\n\n/** Merge our server into an MCP config file ({ mcpServers: {...} }) without touching other entries. */\nfunction registerMcp(file: string, out: SkillsResult): void {\n let json: { mcpServers?: Record<string, unknown> } = {};\n if (existsSync(file)) {\n try {\n json = JSON.parse(readFileSync(file, 'utf8')) as typeof json;\n } catch {\n out.skipped.push(`${file} (not valid JSON, left untouched)`);\n return;\n }\n }\n const servers = json.mcpServers ?? {};\n if (JSON.stringify(servers.splithub) === JSON.stringify(MCP_SERVER_ENTRY)) {\n out.skipped.push(file);\n return;\n }\n json.mcpServers = { ...servers, splithub: MCP_SERVER_ENTRY };\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, JSON.stringify(json, null, 2) + '\\n', 'utf8');\n out.mcp.push(file);\n}\n\nexport function installSkills(root: string, options: { mcp?: boolean; force?: boolean; files?: SkillFile[]; source?: 'cloud' | 'bundled' } = {}): SkillsResult {\n const out: SkillsResult = { written: [], skipped: [], mcp: [], source: options.source ?? (options.files ? 'cloud' : 'bundled') };\n const files = options.files ?? BUNDLED_SKILL_FILES;\n for (const f of files) if (f.path !== 'AGENTS.md') writeFile(join(root, ...f.path.split('/')), f.body, Boolean(options.force), out);\n\n const section = files.find((f) => f.path === 'AGENTS.md')?.body ?? AGENTS_SECTION;\n const agentsFile = ['AGENTS.md', 'CLAUDE.md'].map((f) => join(root, f)).find((f) => existsSync(f)) ?? join(root, 'AGENTS.md');\n if (!existsSync(agentsFile)) {\n writeFileSync(agentsFile, `# ${detectProject(root).name}\n${section}`, 'utf8');\n out.written.push(agentsFile);\n } else if (!/SplitHub/.test(readFileSync(agentsFile, 'utf8'))) {\n writeFileSync(agentsFile, readFileSync(agentsFile, 'utf8') + `\n${section}`, 'utf8');\n out.written.push(`${agentsFile} (section appended)`);\n } else {\n out.skipped.push(agentsFile);\n }\n\n if (options.mcp) {\n registerMcp(join(root, '.mcp.json'), out);\n registerMcp(join(root, '.cursor', 'mcp.json'), out);\n }\n return out;\n}\n\nexport async function skills(flags: Flags): Promise<void> {\n const project = detectProject();\n const result = installSkills(project.root, { mcp: Boolean(flags.mcp), force: Boolean(flags.force), ...(await loadSkillFiles(flags)) });\n if (flags.json) {\n console.log(JSON.stringify(result));\n return;\n }\n const rel = (f: string) => relative(project.root, f) || f;\n if (result.written.length) console.log(`${c.green('✔')} wrote\\n ${result.written.map(rel).join('\\n ')}`);\n if (result.mcp.length) console.log(`${c.green('✔')} MCP server registered in\\n ${result.mcp.map(rel).join('\\n ')}`);\n if (result.skipped.length) console.log(c.dim(`unchanged: ${result.skipped.map(rel).join(', ')}`));\n if (result.source === 'bundled') console.log(c.dim(\"couldn't reach SplitHub Cloud, so these are the copies bundled with this CLI\"));\n if (!flags.mcp) console.log(c.dim(`add --mcp to register the SplitHub MCP server (Claude Code .mcp.json, Cursor .cursor/mcp.json; Codex and Copilot read AGENTS.md)`));\n console.log(c.dim('skills: splithub (library + CLI), ab-testing (how to run experiments well), splithub-analytics (pageviews, events, reports), splithub-api (HTTP API), splithub-mcp (MCP tools), splithub-self-hosted (your own database), splithub-ship (keep the winner, remove the experiment), splithub-loop (the whole loop, tool by tool)'));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAMA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,MAAM,gBAAgB;AAiBjC,IAAM,sBAAmC;AAAA,EAC9C,GAAG,OAAO,IAAI,CAAC,OAAO,EAAE,MAAM,kBAAkB,EAAE,GAAG,aAAa,MAAM,EAAE,KAAK,EAAE;AAAA,EACjF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