splithub 0.2.1 → 0.2.3
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 +9 -1
- package/dist/chunk-5VFCW4FI.js +75 -0
- package/dist/chunk-5VFCW4FI.js.map +1 -0
- package/dist/{chunk-B6FITBWN.js → chunk-6OXCLYOI.js} +2 -2
- package/dist/{chunk-NMN5YGNP.js → chunk-7EB5WOYE.js} +4 -4
- package/dist/{chunk-E5VH4BQX.js → chunk-AZJEZFOB.js} +5 -5
- package/dist/{chunk-DDWYTOX4.js → chunk-BQAWJPIK.js} +4 -2
- package/dist/chunk-BQAWJPIK.js.map +1 -0
- package/dist/{chunk-5C24F2ZN.js → chunk-BSWCWCYP.js} +3 -3
- package/dist/{chunk-GVARYUL3.js → chunk-D7KVM4L7.js} +2 -2
- package/dist/{chunk-3RVNT2HA.js → chunk-ECV5QR6H.js} +5 -5
- package/dist/{chunk-V3DLUVOE.js → chunk-EJC4E3VD.js} +7 -2
- package/dist/{chunk-V3DLUVOE.js.map → chunk-EJC4E3VD.js.map} +1 -1
- package/dist/{chunk-OHA2M7QR.js → chunk-IFCSJYXN.js} +2 -2
- package/dist/{chunk-LT4JP3IF.js → chunk-IGYK7N2F.js} +7 -7
- package/dist/{chunk-PNPOOAHF.js → chunk-LK3NRAHA.js} +14 -13
- package/dist/chunk-LK3NRAHA.js.map +1 -0
- package/dist/{chunk-EYYLDI5J.js → chunk-NTAIRQP6.js} +3 -3
- package/dist/{chunk-PLXDG4B5.js → chunk-PLZRB3VX.js} +2 -2
- package/dist/{chunk-DUIJ5DTV.js → chunk-VKLZJRYW.js} +57 -68
- package/dist/chunk-VKLZJRYW.js.map +1 -0
- package/dist/{chunk-RYDA7PQF.js → chunk-X5AV7YBR.js} +27 -10
- package/dist/chunk-X5AV7YBR.js.map +1 -0
- package/dist/{chunk-KMO5GGGC.js → chunk-XVWJZJSF.js} +5 -5
- package/dist/{chunk-BJQJGLOB.js → chunk-ZND3T67D.js} +31 -10
- package/dist/chunk-ZND3T67D.js.map +1 -0
- package/dist/{ci-ZQZ6RBUJ.js → ci-4OC23DTI.js} +4 -4
- package/dist/create-NCBDS2YG.js +18 -0
- package/dist/dev-7FXVGFL6.js +11 -0
- package/dist/doctor-E4KLPZZI.js +14 -0
- package/dist/{holdout-BWVTTLEY.js → holdout-OKHR2CKW.js} +4 -4
- package/dist/index.js +28 -28
- package/dist/index.js.map +1 -1
- package/dist/init-PFNPS6XO.js +15 -0
- package/dist/lifecycle-G7OAC4ZZ.js +12 -0
- package/dist/{login-TIIX5V4O.js → login-ZEIH7KIH.js} +4 -4
- package/dist/{menu-S3WDS4JY.js → menu-4X5S37OK.js} +21 -21
- package/dist/plan-QLYHRYCV.js +71 -0
- package/dist/plan-QLYHRYCV.js.map +1 -0
- package/dist/push-3NDLL7US.js +16 -0
- package/dist/{refs-RY7H3J7L.js → refs-IWZ5GP7Q.js} +5 -5
- package/dist/{remove-EQQCDJRU.js → remove-YDJ7JTPR.js} +6 -6
- package/dist/report-JS7Z42FD.js +58 -0
- package/dist/report-JS7Z42FD.js.map +1 -0
- package/dist/results-HCXQH7IY.js +17 -0
- package/dist/{review-7E7JVMMV.js → review-BGGNVL6L.js} +3 -3
- package/dist/{ship-MRBHWFZR.js → ship-C22SGFUD.js} +6 -6
- package/dist/skills-UBPQOTDQ.js +18 -0
- package/dist/status-6IODQYHV.js +12 -0
- package/dist/{update-67QDJ6GF.js → update-SAHMBHIZ.js} +3 -3
- package/package.json +4 -5
- package/dist/chunk-BJQJGLOB.js.map +0 -1
- package/dist/chunk-DDWYTOX4.js.map +0 -1
- package/dist/chunk-DUIJ5DTV.js.map +0 -1
- package/dist/chunk-OYM64FMD.js +0 -63
- package/dist/chunk-OYM64FMD.js.map +0 -1
- package/dist/chunk-PNPOOAHF.js.map +0 -1
- package/dist/chunk-RYDA7PQF.js.map +0 -1
- package/dist/create-AEJVXN25.js +0 -18
- package/dist/dev-W2JGUV2A.js +0 -11
- package/dist/doctor-D3KOGOX6.js +0 -14
- package/dist/init-UBUDSJBD.js +0 -15
- package/dist/lifecycle-ZLZUTASA.js +0 -12
- package/dist/plan-G2A55FR7.js +0 -135
- package/dist/plan-G2A55FR7.js.map +0 -1
- package/dist/push-OJX4F2BH.js +0 -16
- package/dist/report-6WNO576N.js +0 -69
- package/dist/report-6WNO576N.js.map +0 -1
- package/dist/results-ZDOCWN6U.js +0 -21
- package/dist/skills-JJOKGNO5.js +0 -13
- package/dist/status-SATP23WK.js +0 -12
- /package/dist/{chunk-B6FITBWN.js.map → chunk-6OXCLYOI.js.map} +0 -0
- /package/dist/{chunk-NMN5YGNP.js.map → chunk-7EB5WOYE.js.map} +0 -0
- /package/dist/{chunk-E5VH4BQX.js.map → chunk-AZJEZFOB.js.map} +0 -0
- /package/dist/{chunk-5C24F2ZN.js.map → chunk-BSWCWCYP.js.map} +0 -0
- /package/dist/{chunk-GVARYUL3.js.map → chunk-D7KVM4L7.js.map} +0 -0
- /package/dist/{chunk-3RVNT2HA.js.map → chunk-ECV5QR6H.js.map} +0 -0
- /package/dist/{chunk-OHA2M7QR.js.map → chunk-IFCSJYXN.js.map} +0 -0
- /package/dist/{chunk-LT4JP3IF.js.map → chunk-IGYK7N2F.js.map} +0 -0
- /package/dist/{chunk-EYYLDI5J.js.map → chunk-NTAIRQP6.js.map} +0 -0
- /package/dist/{chunk-PLXDG4B5.js.map → chunk-PLZRB3VX.js.map} +0 -0
- /package/dist/{chunk-KMO5GGGC.js.map → chunk-XVWJZJSF.js.map} +0 -0
- /package/dist/{ci-ZQZ6RBUJ.js.map → ci-4OC23DTI.js.map} +0 -0
- /package/dist/{create-AEJVXN25.js.map → create-NCBDS2YG.js.map} +0 -0
- /package/dist/{dev-W2JGUV2A.js.map → dev-7FXVGFL6.js.map} +0 -0
- /package/dist/{doctor-D3KOGOX6.js.map → doctor-E4KLPZZI.js.map} +0 -0
- /package/dist/{holdout-BWVTTLEY.js.map → holdout-OKHR2CKW.js.map} +0 -0
- /package/dist/{init-UBUDSJBD.js.map → init-PFNPS6XO.js.map} +0 -0
- /package/dist/{lifecycle-ZLZUTASA.js.map → lifecycle-G7OAC4ZZ.js.map} +0 -0
- /package/dist/{login-TIIX5V4O.js.map → login-ZEIH7KIH.js.map} +0 -0
- /package/dist/{menu-S3WDS4JY.js.map → menu-4X5S37OK.js.map} +0 -0
- /package/dist/{push-OJX4F2BH.js.map → push-3NDLL7US.js.map} +0 -0
- /package/dist/{refs-RY7H3J7L.js.map → refs-IWZ5GP7Q.js.map} +0 -0
- /package/dist/{remove-EQQCDJRU.js.map → remove-YDJ7JTPR.js.map} +0 -0
- /package/dist/{results-ZDOCWN6U.js.map → results-HCXQH7IY.js.map} +0 -0
- /package/dist/{review-7E7JVMMV.js.map → review-BGGNVL6L.js.map} +0 -0
- /package/dist/{ship-MRBHWFZR.js.map → ship-C22SGFUD.js.map} +0 -0
- /package/dist/{skills-JJOKGNO5.js.map → skills-UBPQOTDQ.js.map} +0 -0
- /package/dist/{status-SATP23WK.js.map → status-6IODQYHV.js.map} +0 -0
- /package/dist/{update-67QDJ6GF.js.map → update-SAHMBHIZ.js.map} +0 -0
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
findRefs
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-D7KVM4L7.js";
|
|
5
5
|
import {
|
|
6
6
|
loadConfig,
|
|
7
7
|
readSource,
|
|
8
8
|
removeExperiment,
|
|
9
9
|
writeConfigChecked
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-6OXCLYOI.js";
|
|
11
11
|
import {
|
|
12
12
|
archiveLive
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-ZND3T67D.js";
|
|
14
14
|
import {
|
|
15
15
|
grepFiles,
|
|
16
16
|
listSourceFiles,
|
|
17
17
|
quoted,
|
|
18
18
|
requireConfig
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-PLZRB3VX.js";
|
|
20
20
|
import {
|
|
21
21
|
c,
|
|
22
22
|
fail,
|
|
23
23
|
printJson
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-EJC4E3VD.js";
|
|
25
25
|
|
|
26
26
|
// src/commands/ship.ts
|
|
27
27
|
import { readFileSync, writeFileSync } from "fs";
|
|
@@ -447,4 +447,4 @@ async function ship(id, flags) {
|
|
|
447
447
|
export {
|
|
448
448
|
ship
|
|
449
449
|
};
|
|
450
|
-
//# sourceMappingURL=ship-
|
|
450
|
+
//# sourceMappingURL=ship-C22SGFUD.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
BUNDLED_SKILL_FILES,
|
|
4
|
+
installSkills,
|
|
5
|
+
loadSkillFiles,
|
|
6
|
+
skills
|
|
7
|
+
} from "./chunk-X5AV7YBR.js";
|
|
8
|
+
import "./chunk-BQAWJPIK.js";
|
|
9
|
+
import "./chunk-ZND3T67D.js";
|
|
10
|
+
import "./chunk-PLZRB3VX.js";
|
|
11
|
+
import "./chunk-EJC4E3VD.js";
|
|
12
|
+
export {
|
|
13
|
+
BUNDLED_SKILL_FILES,
|
|
14
|
+
installSkills,
|
|
15
|
+
loadSkillFiles,
|
|
16
|
+
skills
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=skills-UBPQOTDQ.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
status
|
|
4
|
+
} from "./chunk-5VFCW4FI.js";
|
|
5
|
+
import "./chunk-VKLZJRYW.js";
|
|
6
|
+
import "./chunk-ZND3T67D.js";
|
|
7
|
+
import "./chunk-PLZRB3VX.js";
|
|
8
|
+
import "./chunk-EJC4E3VD.js";
|
|
9
|
+
export {
|
|
10
|
+
status
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=status-6IODQYHV.js.map
|
|
@@ -7,11 +7,11 @@ import {
|
|
|
7
7
|
fetchLatest,
|
|
8
8
|
isNewer,
|
|
9
9
|
updateFlow
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-IFCSJYXN.js";
|
|
11
11
|
import {
|
|
12
12
|
fail,
|
|
13
13
|
printJson
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-EJC4E3VD.js";
|
|
15
15
|
|
|
16
16
|
// src/commands/update.ts
|
|
17
17
|
async function update(flags) {
|
|
@@ -34,4 +34,4 @@ async function update(flags) {
|
|
|
34
34
|
export {
|
|
35
35
|
update
|
|
36
36
|
};
|
|
37
|
-
//# sourceMappingURL=update-
|
|
37
|
+
//# sourceMappingURL=update-SAHMBHIZ.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "splithub",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "A/B testing for your app in one command. Create a test, start it, read a plain verdict. Works for you and for your coding agent.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -23,15 +23,14 @@
|
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@clack/prompts": "^0.9.1",
|
|
25
25
|
"jiti": "^2.4.2",
|
|
26
|
-
"@splithub/core": "0.2.
|
|
27
|
-
"@splithub/node": "0.2.
|
|
26
|
+
"@splithub/core": "0.2.3",
|
|
27
|
+
"@splithub/node": "0.2.3"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@types/node": "^22.13.0",
|
|
31
31
|
"tsup": "^8.3.5",
|
|
32
32
|
"typescript": "^5.6.3",
|
|
33
|
-
"vitest": "^4.1.11"
|
|
34
|
-
"@splithub/stats": "0.2.1"
|
|
33
|
+
"vitest": "^4.1.11"
|
|
35
34
|
},
|
|
36
35
|
"publishConfig": {
|
|
37
36
|
"access": "public"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/credentials.ts","../src/api.ts"],"sourcesContent":["// Credentials saved by `splithub login`: ~/.config/splithub/credentials.json\n// { \"<api base>\": { \"<project root>\": { apiKey, projectId, projectName, savedAt } } }\n// `cloudTarget` falls back to the entry for the current directory when neither\n// --token nor SPLITHUB_API_KEY is set.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\nexport interface SavedCredential {\n apiKey: string;\n projectId: string | null;\n projectName: string | null;\n /** Public key of the project (pk_...), written into splithub.config.ts by init. */\n publicKey?: string | null;\n savedAt: string;\n}\n\ntype Store = Record<string, Record<string, SavedCredential>>;\n\nexport function credentialsFile(): string {\n const base = process.env.XDG_CONFIG_HOME || (process.platform === 'win32' ? process.env.APPDATA || join(homedir(), 'AppData', 'Roaming') : join(homedir(), '.config'));\n return join(base, 'splithub', 'credentials.json');\n}\n\nfunction read(): Store {\n const file = credentialsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, 'utf8')) as Store;\n } catch {\n return {};\n }\n}\n\nexport function loadCredential(api: string, root = process.cwd()): SavedCredential | null {\n return read()[api]?.[resolve(root)] ?? null;\n}\n\nexport function saveCredential(api: string, root: string, cred: SavedCredential): string {\n const file = credentialsFile();\n const store = read();\n store[api] = { ...(store[api] ?? {}), [resolve(root)]: cred };\n mkdirSync(join(file, '..'), { recursive: true });\n writeFileSync(file, JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n return file;\n}\n\n/** Every saved credential on this machine: which directory is connected to which project. */\nexport function listCredentials(api?: string): Array<{ api: string; root: string; cred: SavedCredential }> {\n const store = read();\n const out: Array<{ api: string; root: string; cred: SavedCredential }> = [];\n for (const [a, dirs] of Object.entries(store)) {\n if (api && a !== api) continue;\n for (const [root, cred] of Object.entries(dirs)) out.push({ api: a, root, cred });\n }\n return out.sort((x, y) => y.cred.savedAt.localeCompare(x.cred.savedAt));\n}\n\nexport function removeCredential(api: string, root = process.cwd()): boolean {\n const store = read();\n const key = resolve(root);\n if (!store[api]?.[key]) return false;\n delete store[api][key];\n writeFileSync(credentialsFile(), JSON.stringify(store, null, 2) + '\\n', { mode: 0o600 });\n return true;\n}\n","import type { ExperimentResults, StatusRow } from '@splithub/node';\nimport { readFileSync } from 'node:fs';\nimport { loadCredential } from './credentials';\nimport { CliError, fail } from './errors';\nimport type { ProjectInfo } from './project';\n\nexport interface Target {\n url: string;\n token?: string;\n}\n\nexport const CLOUD_API = 'https://go.splithub.io/v1';\n\n/** Storage settings from splithub.config.ts, read textually to avoid loading the config. */\nfunction storageFromConfig(project?: ProjectInfo): { mode: 'self' | 'cloud'; endpoint: string } {\n const fallback = { mode: 'self' as const, endpoint: '/api/splithub' };\n if (!project?.configFile) return fallback;\n try {\n const src = readFileSync(project.configFile, 'utf8');\n const mode = /mode\\s*:\\s*['\"](cloud|self)['\"]/.exec(src)?.[1] as 'self' | 'cloud' | undefined;\n const endpoint = /endpoint\\s*:\\s*['\"]([^'\"]+)['\"]/.exec(src)?.[1];\n return { mode: mode ?? 'self', endpoint: endpoint ?? '/api/splithub' };\n } catch {\n return fallback;\n }\n}\n\n/** Cloud API base + project API key (sk_...). */\nexport function cloudTarget(flags: Record<string, unknown>): Target {\n const url = (typeof flags.api === 'string' && flags.api) || process.env.SPLITHUB_API || CLOUD_API;\n const base = url.replace(/\\/+$/, '');\n const token = (typeof flags.token === 'string' && flags.token) || process.env.SPLITHUB_API_KEY || loadCredential(base)?.apiKey || undefined;\n return { url: base, token };\n}\n\n/**\n * Where to read results from:\n * - --url / SPLITHUB_URL always win;\n * - cloud mode → the cloud API with the project API key;\n * - self mode → the local dev server (3000 for Next.js, 5173 for Vite) + the endpoint from the config.\n */\nexport function resolveTarget(flags: Record<string, unknown>, project?: ProjectInfo): Target {\n const explicit = (typeof flags.url === 'string' && flags.url) || process.env.SPLITHUB_URL;\n const storage = storageFromConfig(project);\n if (!explicit && storage.mode === 'cloud') return cloudTarget(flags);\n const port = project?.framework === 'next' ? 3000 : 5173;\n const url = explicit || `http://localhost:${port}${storage.endpoint}`;\n const token = (typeof flags.token === 'string' && flags.token) || process.env.SPLITHUB_ADMIN_TOKEN || undefined;\n return { url: url.replace(/\\/+$/, ''), token };\n}\n\n/**\n * Readable message from an API error body. Most routes answer `{ error: 'text' }`; the auth layer\n * answers `{ success: false, error: { code, message } }`. Without this the CLI printed \"[object Object]\".\n */\nexport function apiErrorMessage(status: number, body: unknown, fallback: string): string {\n const error = (body as { error?: unknown } | null)?.error;\n const text = typeof error === 'string' ? error : typeof (error as { message?: unknown } | undefined)?.message === 'string' ? (error as { message: string }).message : fallback;\n return status === 401 ? `${text} This folder is not signed in: run npx splithub login (or set SPLITHUB_API_KEY).` : text;\n}\n\n/** CliError for a failed API response: 401 → NOT_LOGGED_IN, 404 on an experiment → EXPERIMENT_NOT_FOUND. */\nexport function apiError(status: number, body: unknown, fallback: string, experiment?: string): CliError {\n const message = apiErrorMessage(status, body, fallback);\n if (status === 401) return new CliError('NOT_LOGGED_IN', message, 'Run npx splithub login (or set SPLITHUB_API_KEY), then retry.');\n const b = body as { code?: unknown; needed?: unknown } | null;\n if (status === 403 && b?.code === 'insufficient_scope') return new CliError('INSUFFICIENT_SCOPE', message, `This API key lacks the \"${typeof b.needed === 'string' ? b.needed : 'write'}\" scope. Create one with it in the dashboard (Settings, API keys) or run npx splithub login --yes.`);\n if (status === 404 && experiment) return new CliError('EXPERIMENT_NOT_FOUND', message, `Check the id with npx splithub status. In cloud mode, push the config first.`);\n return new CliError('API_ERROR', message);\n}\n\nasync function request<T>(target: Target, path: string, init: RequestInit = {}, experiment?: string): Promise<T> {\n const headers: Record<string, string> = { ...((init.headers as Record<string, string> | undefined) ?? {}) };\n if (target.token) headers.authorization = `Bearer ${target.token}`;\n if (init.body) headers['content-type'] = 'application/json';\n let res: Response;\n try {\n res = await fetch(`${target.url}${path}`, { ...init, headers });\n } catch (error) {\n throw new CliError('UNREACHABLE', `Can't reach ${target.url}: ${error instanceof Error ? error.message : String(error)}.`, 'Is your app running? Set --url or SPLITHUB_URL.');\n }\n const body: unknown = await res.json().catch(() => ({}));\n if (!res.ok) throw apiError(res.status, body, `${target.url}${path} responded ${res.status}`, experiment);\n return body as T;\n}\n\n/** Cloud target that must carry an API key. */\nexport function requireCloudToken(flags: Record<string, unknown>): Target & { token: string } {\n const target = cloudTarget(flags);\n if (!target.token) fail('NOT_LOGGED_IN', 'This folder is not connected to SplitHub Cloud.', 'Run npx splithub login, or pass --token sk_... / SPLITHUB_API_KEY.');\n return target as Target & { token: string };\n}\n\n/** PUT /overrides/<experiment>: live status, traffic or weights without a deploy. */\nexport function putOverride(target: Target, experiment: string, body: Record<string, unknown>): Promise<unknown> {\n return request<unknown>(target, `/overrides/${encodeURIComponent(experiment)}`, { method: 'PUT', body: JSON.stringify(body) }, experiment);\n}\n\n/**\n * Apply a status live in cloud mode. Never throws: the config file already changed,\n * so a refused or unreachable cloud is reported, not fatal.\n */\nexport async function applyLiveStatus(flags: Record<string, unknown>, experiment: string, status: string): Promise<string> {\n const target = cloudTarget(flags);\n if (!target.token) return 'no API key (run npx splithub login or set SPLITHUB_API_KEY to apply it without a deploy)';\n try {\n await putOverride(target, experiment, { status });\n return 'applied';\n } catch (error) {\n return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\n/** daysToVerdict: days until a verdict at the current traffic; null when unknown (older servers omit it). */\n/**\n * Archive an experiment in the cloud (PUT /archive/<id>): it stops, keeps its numbers and leaves the\n * active list. Older servers without the route get it finished instead. Never throws.\n */\nexport async function archiveLive(flags: Record<string, unknown>, experiment: string): Promise<string> {\n const target = cloudTarget(flags);\n if (!target.token) return 'no API key (run npx splithub login or set SPLITHUB_API_KEY to archive it in the cloud)';\n try {\n await request<unknown>(target, `/archive/${encodeURIComponent(experiment)}`, { method: 'PUT', body: '{}' });\n return 'archived';\n } catch (error) {\n // 404 from a server without the route (or any non-auth refusal): finishing still stops the test.\n if (error instanceof CliError && (error.code === 'EXPERIMENT_NOT_FOUND' || error.code === 'API_ERROR')) {\n const finished = await applyLiveStatus(flags, experiment, 'finished');\n return finished === 'applied' ? 'finished' : finished;\n }\n return `cloud refused: ${error instanceof Error ? error.message : String(error)}`;\n }\n}\n\nexport type ResultsWithPlan = ExperimentResults & { daysToVerdict?: number | null; visitorsPerDay?: number | null };\n/** `sample` is optional: older servers omit it. */\nexport type StatusRowWithPlan = Omit<StatusRow, 'sample' | 'stars'> & { sample?: StatusRow['sample']; stars?: StatusRow['stars']; daysToVerdict?: number | null };\n\nexport const fetchStatus = (t: Target) => request<{ project: string; experiments: StatusRowWithPlan[] }>(t, '/status');\nexport const fetchResults = (t: Target, key: string) => request<ResultsWithPlan>(t, `/results/${encodeURIComponent(key)}`, {}, key);\n"],"mappings":";;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAavB,SAAS,kBAA0B;AACxC,QAAM,OAAO,QAAQ,IAAI,oBAAoB,QAAQ,aAAa,UAAU,QAAQ,IAAI,WAAW,KAAK,QAAQ,GAAG,WAAW,SAAS,IAAI,KAAK,QAAQ,GAAG,SAAS;AACpK,SAAO,KAAK,MAAM,YAAY,kBAAkB;AAClD;AAEA,SAAS,OAAc;AACrB,QAAM,OAAO,gBAAgB;AAC7B,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO,CAAC;AAC/B,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,SAAS,eAAe,KAAa,OAAO,QAAQ,IAAI,GAA2B;AACxF,SAAO,KAAK,EAAE,GAAG,IAAI,QAAQ,IAAI,CAAC,KAAK;AACzC;AAEO,SAAS,eAAe,KAAa,MAAc,MAA+B;AACvF,QAAM,OAAO,gBAAgB;AAC7B,QAAM,QAAQ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AAE,QAAQ,OAAO,MAAM,KAAK,UAAU,IAAI,EAAE,GAAG,UAAU;AAC3I;AAMA,eAAsB,gBAAgB,OAAgC,YAAoB,QAAiC;AACzH,QAAM,SAAS,YAAY,KAAK;AAChC,MAAI,CAAC,OAAO,MAAO,QAAO;AAC1B,MAAI;AACF,UAAM,YAAY,QAAQ,YAAY,EAAE,OAAO,CAAC;AAChD,WAAO;AAAA,EACT,SAAS,OAAO;AACd,WAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,EACjF;AACF;AAOA,eAAsB,YAAY,OAAgC,YAAqC;AACrG,QAAM,SAAS,YAAY,KAAK;AAChC,MAAI,CAAC,OAAO,MAAO,QAAO;AAC1B,MAAI;AACF,UAAM,QAAiB,QAAQ,YAAY,mBAAmB,UAAU,CAAC,IAAI,EAAE,QAAQ,OAAO,MAAM,KAAK,CAAC;AAC1G,WAAO;AAAA,EACT,SAAS,OAAO;AAEd,QAAI,iBAAiB,aAAa,MAAM,SAAS,0BAA0B,MAAM,SAAS,cAAc;AACtG,YAAM,WAAW,MAAM,gBAAgB,OAAO,YAAY,UAAU;AACpE,aAAO,aAAa,YAAY,aAAa;AAAA,IAC/C;AACA,WAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,EACjF;AACF;AAMO,IAAM,cAAc,CAAC,MAAc,QAA+D,GAAG,SAAS;AAC9G,IAAM,eAAe,CAAC,GAAW,QAAgB,QAAyB,GAAG,YAAY,mBAAmB,GAAG,CAAC,IAAI,CAAC,GAAG,GAAG;","names":["readFileSync","readFileSync"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/skills-self-hosted.ts","../src/skills-ship.ts","../src/skills.ts","../src/templates.ts"],"sourcesContent":["// Skill: SplitHub with the user's own database (self mode) and reporting from the cloud.\nexport const SKILL_SELF_HOSTED = `---\nname: splithub-self-hosted\ndescription: Keep SplitHub events in your own database (self mode): which tables, how to write a Store for Postgres, MySQL, Prisma, Drizzle, Supabase or anything else, where the ingest route lives, how the CLI reads results from it, and how to get cloud data into your own database for reports. Use when the user wants data in their infra or asks about tables, schema or reporting.\n---\n\n# SplitHub with your own database\n\nTwo ways to own the data:\n\n1. **Self mode** — the app hosts the ingest route and the store; nothing leaves your infra.\n \\`splithub.config.ts\\`: \\`storage: { mode: 'self', endpoint: '/api/splithub' }\\`.\n2. **Cloud + export** — events go to SplitHub Cloud; you pull summaries into your warehouse for reports.\n\n## Self mode: the pieces\n\n- Route: \\`app/api/splithub/[[...path]]/route.ts\\` (Next.js) or any fetch-style handler from\n \\`createSplitHubHandler({ config, store, adminToken })\\` in \\`@splithub/node\\`. It accepts\n \\`POST /events\\` from the SDK and answers \\`GET /status\\`, \\`GET /results/<id>\\` for the CLI\n (\\`npx splithub status\\` talks to the local dev server, or \\`--url https://your.app/api/splithub\\`).\n- Store: an object with three methods (below). Ready-made: \\`@splithub/adapter-sqlite\\`\n (Node 22.13+, \\`node:sqlite\\`, zero setup) and \\`@splithub/adapter-d1\\` (Cloudflare D1).\n \\`npx splithub init --mode self --db postgres|mysql|custom\\` writes \\`splithub/store.ts\\` with a\n working Postgres (pg) or MySQL (mysql2) store, or a documented stub for anything else.\n- Admin token: set \\`SPLITHUB_ADMIN_TOKEN\\` in the app and \\`--token\\` / \\`SPLITHUB_ADMIN_TOKEN\\` for\n the CLI, so results are not public.\n\n## The events table\n\nOne table, one row per event. Column names are yours; the templates use these:\n\n| column | type | meaning |\n|---|---|---|\n| id | text, primary key | client-generated, unique; dedupe on it (retries resend batches) |\n| type | text | \\`exposure\\` or \\`goal\\` |\n| experiment, variant | text | for exposures |\n| goal | text | for goals |\n| visitor_id, session_id | text | \\`sh_vid\\` cookie / session |\n| ts | bigint | client time, unix ms |\n| url | text | page |\n| props | json | goal payload, e.g. \\`{ \"revenue\": 49 }\\` |\n| received_at | bigint | server time, unix ms |\n| host, country, device, browser | text | request metadata (fill from headers if you want breakdowns) |\n\nIndexes: \\`(type, experiment, visitor_id, ts)\\` and \\`(type, goal, visitor_id, ts)\\`.\n\n## The Store interface (\\`@splithub/node\\`)\n\n\\`\\`\\`ts\ninterface Store {\n insertEvents(events: StoredEvent[]): Promise<number>; // skip existing ids, return inserted count\n variantCounts(experiment: string, goal: string): Promise<VariantCounts[]>; // per variant: exposures, conversions, revenue\n summaries(): Promise<ExperimentSummary[]>; // per experiment: exposures, visitors, first/last ts\n close?(): Promise<void> | void;\n}\n\\`\\`\\`\n\nAttribution rule — keep it exactly, so self-hosted results equal the cloud's:\n**a visitor converts for a variant when they sent the goal at or after their first exposure to\nthat variant; exposures and conversions count unique visitors.** The SQL in the generated\n\\`splithub/store.ts\\` implements it (CTE \\`first_exposure\\`, then goals joined with \\`ts >= first_ts\\`).\n\nPrisma / Drizzle: map the table in your schema and write the three methods with the ORM, or run the\none raw query for \\`variantCounts\\`. Supabase: the same SQL as a Postgres function called through\n\\`rpc\\`. Mongo: \\`$group\\` by variant and visitor with \\`$min ts\\`, then \\`$lookup\\` goals.\n\n## Reports from the cloud into your database\n\n- CSV: dashboard → experiment → Export (summary, daily timeline, raw events up to 50k rows).\n- Webhook channel for alerts and the digest: POST JSON to your endpoint when something happens.\n- Scheduled pull: a cron in your app calls \\`GET /v1/status\\` and \\`GET /v1/results/<id>\\` with the\n API key (\\`sk_…\\`) and stores the verdicts. Raw events live 30–90 days in the cloud (plan dependent),\n aggregates a year: pull summaries, not raw rows, for long-term reporting.\n- Need every raw event forever in your infra? Use self mode; one store per project.\n\n## Do not\n\n- Put database credentials in \\`splithub.config.ts\\` (it ships to the browser). They belong in the route's env.\n- Compute winners from raw rates in SQL; use \\`npx splithub results\\` (or \\`@splithub/stats\\`) for the verdict.\n`;\n","// Skills: ship the winner (`splithub ship`) and the full agent loop. Installed next\n// to the other skills by `splithub init` / `splithub skills`.\n\nexport const SKILL_SHIP = `---\nname: splithub-ship\ndescription: Ship the winner of an A/B test and remove the test from the code: keep only the winning value, component or page, delete the losing variants, finish the experiment and clean splithub.config.ts. Use when a test has a verdict and the user says ship it, roll out the winner, remove the test, or clean up; and whenever a test shows status finished and the user agreed on which variant to keep.\n---\n\n# Shipping the winner\n\nGoal: the app behaves exactly as the kept variant did, with no experiment left in the code or in the config.\n\n## 1. Decide\n\n\\`npx splithub results <id> --json\\` (MCP: \\`splithub_results\\`). Act on \\`verdict.status\\`:\n- \\`winner_found\\`: keep \\`verdict.winner\\`.\n- \\`no_significant_difference\\`: keep the control, or the simpler variant if the user agrees.\n- \\`insufficient_sample\\`: do not ship. Say when to look again: \\`daysToVerdict\\` days at the current traffic.\n- \\`srm_detected\\`: do not ship. The split is broken; fix the setup first.\n- \\`guardrail_breached\\`: do not ship the variant in \\`verdict.guardrailBreached\\`; it made a guardrail worse. Say what broke.\nAsk the user which variant to keep before going on. Never pick from raw rates.\n\n## 2. Preview, then ship\n\n\\`\\`\\`bash\nnpx splithub ship <id> --keep <variant> --dry-run --json # diff + leftovers, nothing written\nnpx splithub ship <id> --keep <variant> --json # apply\n\\`\\`\\`\nMCP: \\`splithub_ship\\` with \\`dryRun: true\\`, then without. It archives the test in the cloud (numbers stay readable), removes it from\n\\`splithub.config.ts\\` (checked by reloading the file) and rewrites the code:\n- \\`<Experiment id>\\` → the kept \\`<Variant>\\`'s children; the other variants are dropped.\n- \\`useValue('<id>')\\` / \\`sh.value('<id>')\\` → the kept value as a literal.\n- \\`useVariant('<id>')\\` comparisons, ternaries, \\`&&\\`, \\`if\\` and \\`switch\\` → the kept branch.\n- Unused \\`Experiment\\`, \\`Variant\\`, \\`useVariant\\`, \\`useValue\\` imports go.\n\n## 3. Finish by hand\n\n- \\`leftovers[]\\`: each \\`{ file, line, text, reason }\\` still mentions the experiment; rewrite those yourself.\n- component kind: delete components and files only the losing variants used (e.g. \\`splithub/<id>/\\`).\n- redirect kind: make the kept URL the real page (move the route or add a permanent redirect), delete the other page.\n- Goal: keep \\`track('<goal>')\\` when another test measures it (\\`next\\` says so); otherwise ask before removing it.\n- Cloud mode: \\`npx splithub push\\`. Then \\`npx splithub doctor\\` and the project's typecheck and tests.\n- \\`npx splithub refs <id> --json\\` must return \\`count: 0\\` for the experiment.\n\nReport what changed (files, the kept content) and the verdict in one line with its numbers. Never reuse the id.\n`;\n\nexport const SKILL_LOOP = `---\nname: splithub-loop\ndescription: The whole A/B test loop for an agent with SplitHub, step by step with the MCP tools and CLI --json fields: plan, create, implement, check, push, read results, finish, ship. Use when the user asks to run an A/B test end to end, or to pick up a test where it stands.\n---\n\n# The full loop\n\nEach step: MCP tool, or the CLI with \\`--json\\` (one line of JSON; errors are \\`{ error, code, hint }\\`, exit 1).\n\n| step | MCP tool | CLI | read |\n|---|---|---|---|\n| 0. size it | \\`splithub_plan\\` | \\`plan --baseline 0.05 --mde 0.1 [<id>]\\` | \\`perVariant\\`, \\`total\\`, \\`traffic.daysLeft\\` |\n| 1. create | \\`splithub_create_experiment\\` | \\`create --kind … --id … --goal … --yes\\` | \\`snippet\\`, \\`files\\`, \\`nextStep\\`, \\`handoff\\` |\n| 2. implement | (edit code) | | wire \\`snippet\\`; \\`track('<goal>')\\` where it converts |\n| 3. check | \\`splithub_doctor\\`, \\`splithub_refs\\` | \\`doctor\\`, \\`refs <id>\\` | \\`ok\\`, \\`checks[]\\`; \\`refs[]\\` shows the wiring |\n| 4. push (cloud) | \\`splithub_push\\` | \\`push\\` (\\`--dry-run\\` to preview) | \\`adopted\\`, \\`diff\\` |\n| 5. results | \\`splithub_status\\`, \\`splithub_results\\` | \\`status\\`, \\`results <id>\\` | \\`verdict.status\\`, \\`verdict.message\\`, \\`verdict.notes[]\\`, \\`daysToVerdict\\` |\n| 6. finish | \\`splithub_set_status\\` | \\`finish <id>\\` | \\`live\\`, \\`next\\` |\n| 7. ship | \\`splithub_ship\\` | \\`ship <id> --keep <v> [--dry-run]\\` | \\`diff\\`, \\`leftovers[]\\`, \\`next\\` |\n\nRules that keep the answer honest:\n- Plan before creating: if \\`traffic.daysLeft\\` is months, test a bigger change or a busier page.\n- \\`create\\` writes a running test; it goes live when the code is deployed (and pushed in cloud mode). Tell the user.\n- Verdicts are sequential (always-valid): checking any day is safe. Quote \\`verdict.message\\` and the always-valid\n \\`comparisons[].sequential.pValue\\`, not the fixed-horizon \\`pValue\\` (p = 0.01 there can still be not significant).\n Relay \\`verdict.notes[]\\`. Verdicts depend on sample size, not days. Say \\`verdict.sample.quality\\` (small | ok | good;\n good = every variant has its share of \\`goodSample\\`, default 5000 visitors, \\`create --good-sample\\`) next to the verdict.\n- \\`daysToVerdict\\` is the re-check date: schedule (or tell the user) a look in that many days instead of polling.\n- \\`srm_detected\\`: the split is broken; fix the setup, do not read the numbers.\n- \\`guardrail_breached\\`: don't ship. A variant made a guardrail worse (\\`verdict.guardrailBreached[]\\`), e.g. \"bold wins on\n signups but raises refunds\". \\`verdict.metrics[]\\` has the secondary metrics and guardrails, read like the main table.\n- Guard what matters when creating: \\`--secondary pricing_view --guardrail refunds:higher\\` (MCP: \\`secondary\\`, \\`guardrails\\`).\n Tests that could clash on one page go in one layer: \\`--layer checkout:0-50\\` and \\`checkout:50-100\\` never share a visitor.\n- \\`splithub holdout set 5\\` keeps 5% of visitors out of every test; the \\`__holdout\\` row (\"Holdout: long-term impact\")\n compares them with everyone else.\n- Ask the user which variant to keep before \\`ship\\`; preview with \\`dryRun\\` and show them the diff.\n- Error \\`code\\` → action: \\`NOT_LOGGED_IN\\` → \\`splithub_login\\`, show the link, wait, retry · \\`INSUFFICIENT_SCOPE\\` → the key\n can only read; ask for a key with write scope · \\`NO_CONFIG\\` → \\`splithub_init\\` ·\n \\`EXPERIMENT_NOT_FOUND\\` → \\`splithub_status\\` for ids · \\`CONFIG_UNSAFE\\` → edit the config by hand where the experiment is\n defined · \\`CONFIG_WRITE\\` → the file was restored; edit by hand, then \\`doctor\\`.\n`;\n","// Agent skills installed by `splithub init` / `splithub skills`. One folder per\n// topic under .claude/skills/, so an agent loads only what the task needs:\n// splithub — the library, the config file, the CLI, where things live\n// ab-testing — what a good test is, metrics, sample size, when to stop\n// splithub-api — the HTTP API (keys, endpoints, payloads) for scripts and servers\n// splithub-mcp — the MCP server: tools, how to register it in Claude Code / Cursor\n// splithub-ship — keep a variant and take the test out (`splithub ship`)\n// splithub-loop — the whole loop for an agent, tool by tool\n// Same text goes to .cursor/rules and the AGENTS.md section points here.\n\nexport interface Skill {\n dir: string;\n body: string;\n}\n\nexport const SKILL_SPLITHUB = `---\nname: splithub\ndescription: Add, change, run or read A/B experiments in an app that uses SplitHub (@splithub/react, splithub.config.ts, the splithub CLI, SplitHub Cloud). Use when the user asks to A/B test a component, headline, image, price, CTA or page, asks which variant is winning, or wants to start, pause or finish a test.\n---\n\n# SplitHub for coding agents\n\nThree pieces: \\`splithub.config.ts\\` (the experiments; source of truth when it exists),\n\\`@splithub/react\\` (renders variants), the \\`splithub\\` CLI (creates, pushes, reads results).\nEvents go to the app's own database (self mode) or to SplitHub Cloud (cloud mode).\n\n## Where things live\n\n- Config: \\`splithub.config.ts\\` in the project root. Experiments and goals. Ships to the browser: never put secrets in it.\n- Credentials: \\`npx splithub login\\` (or \\`init --mode cloud\\`) prints a link; the human approves it in the browser; the CLI\n stores a project API key for this folder. Never ask the user to paste keys. CI uses \\`SPLITHUB_API_KEY\\`.\n- The public key (\\`pk_\\`) ends up in \\`storage.key\\` of the config from any of: \\`login\\` (saved credentials), the first\n \\`push\\`, \\`init --key\\`, or \\`SPLITHUB_API_KEY\\` in the environment (init asks the cloud). Missing key = events go nowhere.\n- Cloud: \\`npx splithub push\\` uploads the config; \\`npx splithub pull\\` writes dashboard-created experiments into the file.\n- Results: \\`npx splithub status --json\\`, \\`npx splithub results <id> --json\\`. Sizing: \\`npx splithub plan --baseline 0.05 --mde 0.1\\`.\n- Code that uses a test: \\`npx splithub refs <id> --json\\`. Keep a variant and remove the test: \\`npx splithub ship <id> --keep <v>\\`.\n- \\`--json\\` prints one line; errors are \\`{ error, code, hint }\\` with exit code 1. The \\`splithub-loop\\` skill has the whole flow.\n- Everything interactive: \\`npx splithub\\` (menu). Everything scriptable: subcommands + \\`--json\\`.\n\n## Pick the kind\n\n| kind | use it when | create | read in code |\n|---|---|---|---|\n| \\`value\\` | only data changes: text, number, image URL, price, JSON. The default choice: no new components. | \\`--variants control,bold --value control=\"Old text\" --value bold=\"New text\"\\` | \\`const text = useValue<string>('<id>')\\`; server components: \\`getValue\\` from \\`@splithub/next\\`; no SDK: \\`sh.value('<id>')\\` |\n| \\`component\\` | structure changes: a layout, a section, a flow, a different component per variant | \\`--variants control,bold\\` (the CLI scaffolds \\`splithub/<id>/<Variant>.tsx\\` stubs) | \\`<Experiment id=\"<id>\"><Variant name=\"control\">…</Variant><Variant name=\"bold\">…</Variant></Experiment>\\`, or \\`useVariant('<id>')\\` in a switch |\n| \\`redirect\\` | a whole page changes: another URL per variant | \\`--match / --to control=/ --to v2=/home-v2\\` | nothing: \\`@splithub/next\\` middleware or the drop-in script \\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_…\">\\` sends visitors there |\n| \\`mvt\\` | several things change at once (headline × button × image) and the user wants to know which of them matters; every combination is tested and each factor is read on its own | \\`--factor headline=old:\"Old text\",new:\"New text\" --factor button=blue:#2563eb,green:#16a34a\\` (no \\`--variants\\`; first level = control; at most 4 factors × 4 levels, 16 combinations) | \\`const { headline, button } = useValue<{ headline: string; button: string }>('<id>')\\` |\n\nmvt needs more visitors than an A/B test: every combination must reach the minimum on its own (the results show the\ncombinations and, below them, each factor summed over its combinations). With little traffic, test one thing with \\`value\\`.\n\n## Create an experiment\n\n1. \\`npx splithub create --kind <value|component|redirect|mvt> --id <key> … --goal <goal> --yes --json\\` (see the table).\n2. Goal: pick an existing key or add one to \\`goals\\`:\n \\`{ type: 'event' }\\` + \\`track('<goal>')\\` where the conversion happens; \\`{ type: 'pageview', path: '/thanks' }\\`;\n \\`{ type: 'click', selector: '#buy' }\\` (tracked automatically by the SDK and the script).\n3. Wire it in code. \\`create\\` writes \\`status: 'running'\\`: the test goes live for every visitor, first page view\n included, as soon as this code is deployed. Use \\`--status draft\\` only when the user asks to hold it.\n4. Cloud mode: \\`npx splithub push\\` after any config change.\n5. Hand-off, always: end your reply by saying the test is **running in the config** and goes live when the user deploys\n this code; nothing is recorded before that, and local development never sends events to the cloud. Tell them how to\n check it locally (\\`?sh_force=<id>:<variant>\\`) and that Pause in the dashboard or \\`npx splithub pause <id>\\` holds it.\n In cloud mode a status set in the dashboard wins over the file for every visitor, first page included.\n For a draft (only if asked): say visitors do not see it and nothing is recorded until \\`npx splithub start <id>\\`.\n\nA draft is invisible to visitors. To check one before starting: \\`runDraftsInDev: true\\` at the top level of the config\nserves drafts like running tests in development only (\\`NODE_ENV=development\\`: \\`next dev\\`, \\`vite\\`);\n\\`?sh_force=<id>:<variant>\\` shows one variant on any page, draft or not, without recording an exposure;\n\\`?sh_debug=1\\` (or \\`npx splithub dev\\`) logs every decision and opens a panel to switch variants.\nIn development the SDK explains drafts, paused tests and held-back events in one line each. Vite apps: add \\`splithub()\\`\nfrom \\`@splithub/core/vite\\` to the plugins in vite.config so these lines and a summary of every experiment appear in the\nterminal that runs \\`vite\\`; Next.js server code prints them in its terminal anyway.\n\nKeys: lowercase a-z 0-9 - _, max 64 chars. First variant = control. Weights are relative (50/50, 1/1, 90/10).\nTargeting (country, device, UTM, cookie, time) is a \\`flow\\` graph on the experiment, edited in the dashboard; \\`pull\\` brings it into the file.\n\n## Read results\n\n\\`verdict.status\\` ∈ no_data | insufficient_sample | srm_detected | winner_found | no_significant_difference.\nReport \\`verdict.message\\` verbatim and the numbers behind it (visitors per variant, lift, the always-valid\n\\`comparisons[].sequential.pValue\\` and \\`sequential.ci\\`; the plain \\`pValue\\` is fixed-horizon, for display only) and relay\n\\`verdict.notes[]\\`. Verdicts are sequential and depend on sample size, not days: safe to check any time. \\`verdict.sample.quality\\` is\nsmall (below 100 visitors per variant or 50 conversions), ok, or good (every variant has its share of \\`goodSample\\`, default 5000\nvisitors; \\`create --good-sample\\`); say it next to the verdict. \\`verdict.sample.stars\\` (0..5) scores data quality from\n\\`verdict.sample.checks[]\\`: report the stars and the unmet labels; they never override the verdict. \\`daysToVerdict\\` says when to look again.\nNever declare a winner from raw rates. \\`srm_detected\\` means the split is broken: fix the setup before anything else.\n\n## Finish, and what to do when a test is finished\n\n\\`npx splithub finish <id>\\` stops the test (live within a minute in cloud mode). A finished test keeps its numbers for as long\nas it stays in the config; the code still contains every variant until someone removes it.\n\nWhenever you see a test with \\`status: finished\\` (in \\`status\\`, \\`results\\`, the MCP tools, or right after you finished it):\n1. Read \\`npx splithub results <id> --json\\` and tell the user the verdict in one line with its numbers.\n2. Ask two questions, do not assume: **which variant to keep** (recommend \\`verdict.winner\\`; with no significant\n difference, the control or the simpler one) and **whether to remove the test from the code now**.\n3. On yes, follow the \\`splithub-ship\\` skill: \\`npx splithub ship <id> --keep <variant> --dry-run\\`, show the diff, then run it\n without \\`--dry-run\\`; fix the \\`leftovers\\`, \\`push\\` in cloud mode, run \\`doctor\\` and the project's checks.\n4. On no, leave everything: a finished test costs nothing and the user may come back to it.\n\nA \\`paused\\` test is not over: say so and ask whether to resume (\\`start\\`) or finish it.\n\n## Do not\n\n- Nest an \\`<Experiment>\\` inside a \\`<Variant>\\` of the same id; call hooks conditionally.\n- Change \\`seed\\`, weights or variants of a running experiment (reshuffles visitors). Create a new experiment instead.\n- Edit in the dashboard what the config file owns: file experiments are read-only there (pause/finish still work).\n- Run more than 2-3 experiments on one page of a low-traffic site.\n- Put secrets, API keys or database credentials in the config or in the browser. \\`pk_\\` is public, \\`sk_\\` is not.\n`;\n\nexport const SKILL_AB_TESTING = `---\nname: ab-testing\ndescription: How to design, run and read an A/B test correctly: hypothesis, control, primary metric, sample size, significance, SRM, peeking, when to stop. Use before creating an experiment or when interpreting results, with any tool.\n---\n\n# A/B testing, the parts that matter\n\nAn A/B test splits visitors at random into variants and compares one metric. It answers one question:\n\"does this change move this metric?\" Everything below exists to keep that answer honest.\n\n## Before creating a test\n\n1. **One hypothesis, one primary metric.** \"A shorter signup form raises signup completion.\" The metric is a goal\n (event, page visit or click) that happens after the exposure. Pick it before looking at data.\n2. **Control first.** The first variant is what exists today. Change one thing per variant; several unrelated changes\n in one variant cannot be attributed.\n3. **Traffic reality.** Rough rule: to detect a relative lift L on a baseline rate p you need about\n \\`16 · p(1-p) / (p·L)²\\` visitors per variant (95% confidence, 80% power).\n Examples: baseline 5%, lift 20% → ~7,600 per variant; baseline 2%, lift 10% → ~78,000 per variant.\n If the site cannot reach that in 2-4 weeks, test a bigger change or a higher-traffic page.\n4. **Few tests per page.** Interactions between simultaneous tests on the same page muddy both.\n\n## While it runs\n\n- **Do not peek and stop early.** Checking daily and stopping at the first \"significant\" moment inflates false\n positives several times. Decide the sample or the duration up front; run whole weeks (weekday/weekend cycles).\n- **SRM (sample ratio mismatch).** If the split is 50/50 and you see 60/40, the assignment or the tracking is broken\n (bots, caching, redirect loops, a variant that errors). Fix first; results from an SRM run are meaningless.\n- **Keep variants frozen.** Changing copy, weights or targeting mid-run reshuffles who saw what. Start a new test.\n- **Watch the guardrails.** A variant that wins the primary metric but breaks revenue, errors or latency is not a win.\n\n## Reading results\n\n- Significance (p < 0.05 after correction for several variants) says the difference is unlikely to be noise;\n the confidence interval says how big it plausibly is. A \"winner\" with a CI that touches 0 is a weak win.\n- \"No significant difference\" with a sample smaller than needed means **keep running**, not \"no effect\".\n With enough sample it means the change does not matter: ship whichever is cheaper or cleaner.\n- Relative lift is on the baseline rate: 5% → 6% is +20% relative, +1 point absolute. Report both.\n- Attribution: conversions count only after the visitor's first exposure, per unique visitor.\n- Segments (country, device) are for hypotheses, not verdicts: slicing after the fact finds noise.\n\n## When to stop\n\n- Winner found with the planned sample → ship it, finish the test, remove the losing code.\n- Planned sample reached, no difference → ship the simpler variant, finish.\n- SRM or broken tracking → stop, fix, restart as a new test.\n- The business moved on → finish; do not leave tests running forever (they cost events and split traffic).\n\n## Vocabulary\n\nexposure = a visitor saw a variant · conversion = the goal happened after exposure · lift = relative change in rate ·\np-value = chance of seeing this difference by luck · CI = range the true difference likely lies in ·\nSRM = the split differs from the configured weights · guardrail = a metric that must not get worse.\n`;\n\nexport const SKILL_SPLITHUB_API = `---\nname: splithub-api\ndescription: Use the SplitHub Cloud HTTP API directly: public key event ingest, API-key endpoints for config, status, results and overrides, hosted experiments. Use when writing a server, a script, a non-JS client, or when the CLI is not available.\n---\n\n# SplitHub Cloud API\n\nBase URL: \\`https://go.splithub.io\\`. JSON in, JSON out (no envelope under \\`/v1/*\\`). Two credentials:\n\n- **Public key \\`pk_…\\`**: identifies the project to browsers and SDKs. Safe to ship. Can only send events and read\n the public overrides JSON.\n- **API key \\`sk_…\\`**: project-scoped secret for servers, CI and the CLI (\\`npx splithub login\\` mints one through a\n browser approval; or Settings → API keys in the dashboard). Never in client code.\n\n## Send events (public key)\n\n\\`\\`\\`http\nPOST /v1/events\nAuthorization: Bearer pk_live_…\nContent-Type: application/json\n\n{ \"project\": \"my-app\", \"sdk\": \"custom/1.0\", \"events\": [\n { \"id\": \"e_01h…\", \"type\": \"exposure\", \"exp\": \"hero-cta\", \"var\": \"bold\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000000000, \"url\": \"/\" },\n { \"id\": \"g_01h…\", \"type\": \"goal\", \"goal\": \"signup\", \"vid\": \"v_abc\", \"sid\": \"s_1\", \"ts\": 1760000010000, \"props\": { \"revenue\": 49 } }\n] }\n\\`\\`\\`\n\n- \\`id\\`: unique per event (8-64 chars, [a-z0-9_-]); duplicates are ignored. \\`vid\\`: stable visitor id (cookie \\`sh_vid\\`).\n- Reply \\`202 { ok, received, inserted, dropped }\\`. A project with nothing running or no config yet answers\n \\`202 { ok, inserted: 0, idle: 'no_running' | 'no_config' }\\`: nothing stored, not an error. \\`429\\` with \\`code\\` ∈\n quota_exceeded | deleted: back off for \\`Retry-After\\` seconds; nothing was stored. \\`403 origin_not_allowed\\` when the project restricts domains.\n- Exposures for experiments that are not running are dropped and not billed. Goals are never billed.\n\n## Live config for clients (public key)\n\n\\`GET /v1/overrides/<pk>.json\\` → \\`{ version, experiments: { <id>: { status?, traffic?, weights?, values? } }, added: [ …hosted experiments… ], goals: [...], ctx: { country, region, city } }\\`.\nPoll it at most once a minute; the SDK caches it in localStorage. \\`ctx\\` is the visitor's geo for targeting.\n\n## Project endpoints (API key)\n\n\\`\\`\\`http\nGET /v1/status every experiment: status, visitors, days, verdict headline\nGET /v1/results/<experiment> full verdict: sample, comparisons (lift, p-value, CI, P(beat)), srm, winner\nGET /v1/config the config stored in the cloud (file + dashboard experiments)\nPUT /v1/config { config } push a normalized config (what defineConfig returns); answers cloudOnly experiments to adopt\nGET /v1/overrides live overrides\nPUT /v1/overrides/<experiment> { status | traffic | weights | values } pause / resume / reweight without a deploy\nDELETE /v1/overrides/<experiment>\n\\`\\`\\`\n\n\\`Authorization: Bearer sk_live_…\\` on each. Status values: draft | running | paused | finished.\n\n## Dashboard-scope endpoints (session, same shapes the dashboard uses)\n\nUnder \\`/v1/projects/<projectId>/…\\` with a user session: \\`experiments\\` (hosted experiments CRUD incl. \\`flow\\` targeting),\n\\`goals\\`, \\`timeline\\`, \\`breakdown\\`, \\`realtime\\`, \\`events\\`, \\`export\\`, \\`notes\\`, \\`domains\\`, \\`links\\`, \\`alerts\\`, \\`billing\\`, \\`ai\\`.\nScripts should prefer the API-key endpoints above; the session ones exist for the UI.\n\n## Drop-in script (no SDK)\n\n\\`<script src=\"https://go.splithub.io/sh.js\" data-key=\"pk_live_…\"></script>\\` in \\`<head>\\`: redirect experiments, page-visit and\nclick goals from the cloud config, \\`window.splithub.track('goal')\\` for custom events,\n\\`<meta name=\"splithub-experiment\" content=\"<id>\">\\` on a tested page for an instant decision.\n\n## Errors\n\n\\`400\\` validation (message in \\`error\\`), \\`401\\` bad key, \\`403\\` forbidden, \\`404\\` unknown experiment/project, \\`409\\` state\n(e.g. \\`config_not_pushed\\`, \\`file_owned\\`), \\`429\\` gate or rate limit. Bodies: \\`{ error, code? }\\`.\n`;\n\nexport const SKILL_SPLITHUB_MCP = `---\nname: splithub-mcp\ndescription: Use or set up the SplitHub MCP server (@splithub/mcp) so an agent can create experiments, read verdicts, start/pause/finish tests and push config through tools instead of shelling out. Use when the user asks to connect SplitHub to Claude Code, Cursor, Codex or another MCP client.\n---\n\n# SplitHub MCP server\n\n\\`@splithub/mcp\\` is a stdio MCP server that wraps the \\`splithub\\` CLI for the current project folder.\nSame credentials and config file as the CLI; nothing extra to configure.\n\n## Register it\n\nClaude Code (project scope, committed in \\`.mcp.json\\`):\n\n\\`\\`\\`json\n{ \"mcpServers\": { \"splithub\": { \"command\": \"npx\", \"args\": [\"-y\", \"@splithub/mcp\"] } } }\n\\`\\`\\`\n\nor \\`claude mcp add splithub -- npx -y @splithub/mcp\\`. Cursor: the same object in \\`.cursor/mcp.json\\`.\nCodex / other clients: command \\`npx\\`, args \\`-y @splithub/mcp\\`. \\`npx splithub skills --mcp\\` writes both files.\nEnv: \\`SPLITHUB_PROJECT_DIR\\` (defaults to the MCP client's working directory), \\`SPLITHUB_API\\` (staging or self-hosted cloud), \\`SPLITHUB_API_KEY\\` (CI).\n\n## Tools\n\n| tool | does | notes |\n|---|---|---|\n| \\`splithub_status\\` | all experiments with verdict headline | start here |\n| \\`splithub_results\\` | full verdict for one experiment | report \\`verdict.message\\` verbatim; \\`daysToVerdict\\` = when to check again |\n| \\`splithub_review\\` | stored AI reviews (Pro): at start, on verdict changes, on finish, on demand | quote them as the analyst's opinion, the verdict stays the source of truth |\n| \\`splithub_plan\\` | visitors per variant for a baseline and a lift; days at an experiment's traffic | before creating |\n| \\`splithub_create_experiment\\` | adds an experiment to splithub.config.ts | kind value / component / redirect / mvt, id, variants (or factors for mvt), goal, values/to, weights, traffic, maxVisitors, start/end; running by default |\n| \\`splithub_refs\\` | files and lines that use an experiment and its goal | check the wiring, find leftovers |\n| \\`splithub_ship\\` | finish, remove from the config, rewrite the code to the kept variant | \\`dryRun: true\\` first; returns \\`diff\\` and \\`leftovers\\` |\n| \\`splithub_remove\\` | removes an experiment from the config (finished in the cloud) | when the code is already clean |\n| \\`splithub_projects\\` | every folder on this machine connected to a cloud project | |\n| \\`splithub_set_status\\` | start / pause / finish | applies live in cloud mode; after \\`finished\\`, ask which variant to keep and whether to clean the code (splithub-ship skill) |\n| \\`splithub_push\\` / \\`splithub_pull\\` | sync the config with the cloud | pull adopts dashboard-created experiments |\n| \\`splithub_doctor\\` | checks the installation | run after wiring code |\n| \\`splithub_login\\` | returns a sign-in link; the human approves it in the browser | show the link, then call \\`splithub_whoami\\` |\n| \\`splithub_whoami\\` | connected project and keys | |\n\n## Working rules\n\n- Create (running by default) → wire in code → \\`doctor\\` → \\`push\\` (cloud mode) → tell the user it goes live when they\n deploy this code and that \\`set_status paused\\` or Pause in the dashboard holds it.\n- Results: never call a winner from raw rates; quote the verdict. \\`srm_detected\\` = fix the setup first.\n- Running experiments are frozen: no weight / variant / seed edits; create a new one.\n- Errors carry a \\`code\\`. \\`NOT_LOGGED_IN\\`: call \\`splithub_login\\`, show the link to the user, wait for them, then retry.\n- The whole loop (plan → create → implement → doctor → push → results → finish → ship) is in the \\`splithub-loop\\` skill.\n- A \\`finished\\` experiment in \\`splithub_status\\` or \\`splithub_results\\` means the test is over but its code is still there: report\n the verdict, ask which variant to keep and whether to remove the test from the code, then follow the \\`splithub-ship\\` skill.\n`;\n\nexport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nimport { SKILL_SELF_HOSTED } from './skills-self-hosted';\nexport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\nimport { SKILL_LOOP, SKILL_SHIP } from './skills-ship';\n\nexport const SKILLS: Skill[] = [\n { dir: 'splithub', body: SKILL_SPLITHUB },\n { dir: 'ab-testing', body: SKILL_AB_TESTING },\n { dir: 'splithub-api', body: SKILL_SPLITHUB_API },\n { dir: 'splithub-mcp', body: SKILL_SPLITHUB_MCP },\n { dir: 'splithub-self-hosted', body: SKILL_SELF_HOSTED },\n { dir: 'splithub-ship', body: SKILL_SHIP },\n { dir: 'splithub-loop', body: SKILL_LOOP },\n];\n\nexport const MCP_SERVER_ENTRY = { command: 'npx', args: ['-y', '@splithub/mcp'] };\n","export function configTemplate(project: string, mode: 'self' | 'cloud', key?: string): string {\n const storage = mode === 'self' ? `{ mode: 'self', endpoint: '/api/splithub' }` : `{ mode: 'cloud', key: ${key ? `'${key}'` : \"process.env.NEXT_PUBLIC_SPLITHUB_KEY ?? ''\"} }`;\n return `import { defineConfig } from '@splithub/core';\n\n// SplitHub experiments. This file is the source of truth: the SDK, the CLI\n// and the dashboard all read it. Keys: lowercase a-z 0-9 - _. First variant = control.\nexport default defineConfig({\n project: '${project}',\n storage: ${storage},\n // Drafts behave like running tests while you develop (next dev, vite); production ignores them.\n runDraftsInDev: true,\n\n goals: {\n // call track('signup') where the conversion happens\n signup: { type: 'event' },\n },\n\n experiments: {\n // run \\`npx splithub create\\` or add entries here:\n //\n // 'hero-title': {\n // kind: 'value',\n // status: 'running',\n // variants: {\n // control: { weight: 50, value: 'Ship faster' },\n // direct: { weight: 50, value: 'Know which version wins' },\n // },\n // goal: 'signup',\n // },\n },\n});\n`;\n}\n\nexport function nextMiddlewareTemplate(configImport: string): string {\n return `import { splithubMiddleware } from '@splithub/next';\nimport splithub from '${configImport}';\n\n// Sets the visitor cookie, forwards it to Server Components and serves\n// redirect experiments with an invisible rewrite.\nexport default splithubMiddleware(splithub);\n\nexport const config = {\n matcher: ['/((?!_next|api|.*\\\\\\\\..*).*)'],\n};\n`;\n}\n\nexport function nextRouteTemplate(configImport: string, store: { imports: string; factory: string } = { imports: \"import { sqliteStore } from '@splithub/adapter-sqlite';\", factory: \"sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })\" }): string {\n return `import { createSplitHubHandler } from '@splithub/node';\n${store.imports}\nimport config from '${configImport}';\n\n// Self-hosted ingest + results: events stay in your database. The CLI reads\n// status / results from this route; set SPLITHUB_ADMIN_TOKEN to protect it.\nconst handler = createSplitHubHandler({\n config,\n store: ${store.factory},\n adminToken: process.env.SPLITHUB_ADMIN_TOKEN,\n});\n\nexport const POST = handler;\nexport const GET = handler;\nexport const runtime = 'nodejs';\n`;\n}\n\nexport function componentVariantTemplate(name: string, experiment: string, variant: string): string {\n return `// Variant \"${variant}\" of experiment \"${experiment}\". Edit freely.\nexport function ${name}() {\n return (\n <section>\n <h2>${experiment} · ${variant}</h2>\n </section>\n );\n}\n`;\n}\n\nexport const AGENTS_SECTION = `\n## A/B testing (SplitHub)\n\nThis project uses SplitHub (\\`@splithub/react\\`). Experiments are declared in\n\\`splithub.config.ts\\` and rendered with \\`<Experiment id>\\` / \\`useVariant(id)\\` /\n\\`useValue(id)\\`. Conversions: \\`useTrack()\\` then \\`track('<goal>')\\`.\n\n- Not connected yet? \\`npx splithub init --mode cloud\\` (or \\`npx splithub login\\`) prints a link: show it to the user, they sign in and approve, the CLI gets the keys. Never ask the user to paste keys.\n- New experiment: \\`npx splithub create --kind value|component|redirect|mvt --id <key> --variants control,<other> --goal <goal> --yes\\`\n then wire it in code (value → \\`useValue\\`, component → \\`<Experiment>\\` with one \\`<Variant>\\` per key, redirect → nothing,\n mvt → \\`--factor name=level:value,…\\` and \\`const { a, b } = useValue(id)\\`).\n- Results: \\`npx splithub results <id> --json\\`; report \\`verdict.message\\` verbatim, never call a winner from raw rates.\n- Lifecycle: \\`npx splithub start|pause|finish <id>\\`. Check setup: \\`npx splithub doctor\\`.\n- A \\`finished\\` test still has all its variants in the code: report the verdict, ask which variant to keep and whether to\n remove the test from the code, then follow .claude/skills/splithub-ship/SKILL.md. Never delete test code unasked.\n- \\`create\\` writes \\`status: 'running'\\`: the test goes live when the code is deployed. Always tell the user that, and that\n \\`npx splithub pause <id>\\` or Pause in the dashboard holds it. Never change \\`seed\\` of a running experiment.\n- Config ships to the browser: no secrets in it. Full rules: .claude/skills/splithub/SKILL.md\n`;\n\nexport { SKILL_SPLITHUB as SKILL_MD } from './skills';\nimport { SKILL_SPLITHUB } from './skills';\n\nexport const CUR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ACe,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUpC;AAEO,SAAS,kBAAkB,cAAsB,QAA8C,EAAE,SAAS,2DAA2D,SAAS,oEAAoE,GAAW;AAClQ,SAAO;AAAA,EACP,MAAM,OAAO;AAAA,sBACO,YAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAMvB,MAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQxB;AAEO,SAAS,yBAAyB,MAAc,YAAoB,SAAyB;AAClG,SAAO,eAAe,OAAO,oBAAoB,UAAU;AAAA,kBAC3C,IAAI;AAAA;AAAA;AAAA,YAGV,UAAU,SAAM,OAAO;AAAA;AAAA;AAAA;AAAA;AAKnC;AAEO,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAuBvB,IAAM,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA,EAKzB,eAAe,QAAQ,qBAAqB,EAAE,CAAC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/results.ts"],"sourcesContent":["import type { ExperimentResults } from '@splithub/node';\nimport { fetchResults, resolveTarget } from '../api';\nimport { fail, printJson } from '../errors';\nimport { detectProject } from '../project';\nimport { bar, c, pct, statusColor, table, verdictColor, verdictIcon } from '../ui';\n\nexport async function results(key: string | undefined, flags: Record<string, unknown>): Promise<void> {\n if (!key) fail('USAGE', 'Which experiment? npx splithub results <id>');\n const target = resolveTarget(flags, detectProject());\n const r = await fetchResults(target, key);\n if (flags.json) {\n printJson({ ...r, daysToVerdict: r.daysToVerdict ?? null, ...(r.status === 'finished' ? { next: FINISHED_NEXT } : {}) });\n return;\n }\n const v = r.verdict;\n const title = r.experiment === HOLDOUT ? 'Holdout: long-term impact' : r.experiment;\n console.log(`${c.bold(title)} ${c.dim(`· ${r.kind} · `)}${statusColor(r.status)} ${c.dim(`· goal: ${r.goal ?? 'none'}`)}`);\n if (r.description) console.log(c.dim(r.description));\n console.log();\n console.log(verdictColor(v.status, `${label(v.status)} ${v.message}`));\n const eta = daysLeft(r.daysToVerdict);\n if (eta && r.status === 'running') console.log(c.dim(eta));\n for (const line of dataLines(v)) console.log(c.dim(line));\n for (const note of v.notes ?? []) console.log(c.dim(`· ${note}`));\n console.log();\n\n const rates = new Map<string, number>();\n for (const cnt of v.sample.variants) rates.set(cnt.variant, cnt.exposures > 0 ? cnt.conversions / cnt.exposures : 0);\n\n console.log(\n table(\n ['VARIANT', 'VISITORS', 'CONV', 'RATE', 'LIFT', 'P(BEAT)', 'P-VALUE', '95% CI'],\n // Always-valid (sequential) p-value and interval: the ones the verdict uses, safe to read any day.\n v.sample.variants.map((cnt, i) => {\n const cmp = v.comparisons.find((x) => x.variant === cnt.variant);\n const name = i === 0 ? `${cnt.variant} ${c.dim('(control)')}` : cnt.variant;\n const marked = v.winner === cnt.variant ? c.green(`★ ${name}`) : name;\n return [\n marked,\n String(cnt.exposures),\n String(cnt.conversions),\n pct(rates.get(cnt.variant)),\n cmp ? pct(cmp.relativeLift, true) : '–',\n cmp ? pct(cmp.probabilityToBeat) : '–',\n cmp ? (cmp.sequential?.pValue ?? cmp.pValue).toFixed(4) : '–',\n cmp ? `${pct((cmp.sequential?.ci ?? cmp.ci).low, true)} … ${pct((cmp.sequential?.ci ?? cmp.ci).high, true)}` : '–',\n ];\n })\n )\n );\n // Rates as bars, lift next to them; P(beat) as a second bar. Reads at a glance in a terminal.\n const maxRate = Math.max(0.0001, ...v.sample.variants.map((cnt) => rates.get(cnt.variant) ?? 0));\n const nameWidth = Math.max(...v.sample.variants.map((cnt) => cnt.variant.length));\n console.log();\n console.log(c.dim('RATE'));\n for (const cnt of v.sample.variants) {\n const cmp = v.comparisons.find((x) => x.variant === cnt.variant);\n const paint = v.winner === cnt.variant ? c.green : cmp && (cmp.relativeLift ?? 0) < 0 ? c.red : c.cyan;\n const lift = cmp ? (cmp.relativeLift ?? 0) >= 0 ? c.green(`▲ ${pct(cmp.relativeLift, true)}`) : c.red(`▼ ${pct(cmp.relativeLift, true)}`) : c.dim('baseline');\n console.log(`${cnt.variant.padEnd(nameWidth)} ${bar(rates.get(cnt.variant) ?? 0, maxRate, 24, paint)} ${pct(rates.get(cnt.variant)).padStart(6)} ${lift}`);\n }\n if (v.comparisons.length) {\n console.log();\n console.log(c.dim('CHANCE TO BEAT THE CONTROL'));\n for (const cmp of v.comparisons) {\n const paint = cmp.probabilityToBeat >= 0.95 ? c.green : cmp.probabilityToBeat <= 0.05 ? c.red : c.yellow;\n console.log(`${cmp.variant.padEnd(nameWidth)} ${bar(cmp.probabilityToBeat, 1, 24, paint)} ${pct(cmp.probabilityToBeat).padStart(6)}`);\n }\n }\n if (v.srm) {\n console.log();\n console.log(c.dim(`SRM check: chi²=${v.srm.chiSquare.toFixed(2)} p=${v.srm.pValue.toExponential(2)} ${v.srm.detected ? c.red('DETECTED') : 'ok'}`));\n }\n if (v.status === 'insufficient_sample' && v.sample.neededPerVariant) {\n console.log(c.dim(`Estimated ${v.sample.neededPerVariant} visitors per variant needed to confirm the current lift.`));\n }\n if (r.factors?.length) {\n console.log();\n console.log(c.bold('Each factor on its own') + c.dim(' (a level sums every combination that uses it, compared with the first level)'));\n for (const f of r.factors) {\n console.log(\n table(\n [f.key.toUpperCase(), 'VISITORS', 'CONV.', 'RATE', 'LIFT', 'P-VALUE'],\n f.levels.map((l) => [l.level + (f.best === l.level ? c.green(' ✔') : ''), String(l.exposures), String(l.conversions), pct(l.rate), l.relativeLift === null ? '–' : pct(l.relativeLift, true), l.pValue === null ? '–' : l.pValue.toFixed(3)])\n )\n );\n }\n }\n if (v.metrics?.length) {\n console.log();\n console.log(metricsText(v));\n }\n if (r.status === 'finished' && r.experiment !== HOLDOUT) {\n console.log();\n console.log(c.dim(FINISHED_NEXT));\n }\n}\n\n/** Printed for finished tests, so a human or an agent knows the code still carries every variant. */\nconst FINISHED_NEXT = 'This test is finished but its variants are still in the code. Decide which variant to keep, then run npx splithub ship <id> --keep <variant> (agents: the splithub-ship skill).';\n\n/** \"About 6 more days\" for a verdict ETA; null when unknown or already there. */\nexport function daysLeft(days: number | null | undefined): string | null {\n if (days === null || days === undefined || !Number.isFinite(days) || days <= 0) return null;\n const d = Math.ceil(days);\n return d === 1 ? 'About 1 more day to a verdict at this traffic.' : `About ${d} more days to a verdict at this traffic.`;\n}\n\nconst num = (n: number) => n.toLocaleString('en-US');\n\n/** \"★★★☆☆\" for 0..5 met checks. */\nexport function starText(stars: number): string {\n const n = Math.max(0, Math.min(5, Math.round(stars)));\n return '★'.repeat(n) + '☆'.repeat(5 - n);\n}\n\n/** \"Data ★★★☆☆ 3/5\" and one line per unmet check. Empty for servers without the score. */\nexport function dataLines(v: { sample: { stars?: number; checks?: Array<{ met: boolean; label: string }> } }): string[] {\n const { stars, checks } = v.sample;\n if (stars === undefined || !checks?.length) return [];\n return [`Data ${starText(stars)} ${stars}/5`, ...checks.filter((x) => !x.met).map((x) => ` ✗ ${x.label}`)];\n}\n\nfunction label(status: string): string {\n const icon = verdictIcon(status);\n switch (status) {\n case 'winner_found':\n return `${icon} WINNER`;\n case 'srm_detected':\n return `${icon} SRM`;\n case 'insufficient_sample':\n return `${icon} TOO EARLY`;\n case 'no_significant_difference':\n return `${icon} NO DIFFERENCE`;\n case 'guardrail_breached':\n return `${icon} DON'T SHIP`;\n default:\n return `${icon} NO DATA`;\n }\n}\n\nexport const HOLDOUT = '__holdout';\n\ntype V = ExperimentResults['verdict'];\n\n/** Secondary metrics and guardrails, one small table each. A breached guardrail is marked. */\nexport function metricsText(v: V): string {\n const out: string[] = [];\n for (const m of v.metrics ?? []) {\n const head = m.role === 'guardrail' ? `GUARDRAIL ${m.metric}${m.worse === 'higher' ? ' (a rise is bad)' : ''}` : `ALSO ${m.metric}`;\n out.push(c.dim(head));\n out.push(\n table(\n ['VARIANT', 'CONV', 'RATE', 'LIFT', 'P-VALUE', ''],\n m.variants.map((cnt) => {\n const cmp = m.comparisons.find((x) => x.variant === cnt.variant);\n const breach = v.guardrailBreached?.find((b) => b.metric === m.metric && b.variant === cnt.variant);\n return [cnt.variant, String(cnt.conversions), pct(cnt.exposures ? cnt.conversions / cnt.exposures : 0), cmp ? pct(cmp.relativeLift, true) : '–', cmp ? (cmp.sequential?.pValue ?? cmp.pValue).toFixed(4) : '–', breach ? c.red('✖ worse') : ''];\n })\n )\n );\n }\n return out.join('\\n');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAMA,eAAsB,QAAQ,KAAyB,OAA+C;AACpG,MAAI,CAAC,IAAK,MAAK,SAAS,6CAA6C;AACrE,QAAM,SAAS,cAAc,OAAO,cAAc,CAAC;AACnD,QAAM,IAAI,MAAM,aAAa,QAAQ,GAAG;AACxC,MAAI,MAAM,MAAM;AACd,cAAU,EAAE,GAAG,GAAG,eAAe,EAAE,iBAAiB,MAAM,GAAI,EAAE,WAAW,aAAa,EAAE,MAAM,cAAc,IAAI,CAAC,EAAG,CAAC;AACvH;AAAA,EACF;AACA,QAAM,IAAI,EAAE;AACZ,QAAM,QAAQ,EAAE,eAAe,UAAU,8BAA8B,EAAE;AACzE,UAAQ,IAAI,GAAG,EAAE,KAAK,KAAK,CAAC,IAAI,EAAE,IAAI,QAAK,EAAE,IAAI,QAAK,CAAC,GAAG,YAAY,EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,cAAW,EAAE,QAAQ,MAAM,EAAE,CAAC,EAAE;AACzH,MAAI,EAAE,YAAa,SAAQ,IAAI,EAAE,IAAI,EAAE,WAAW,CAAC;AACnD,UAAQ,IAAI;AACZ,UAAQ,IAAI,aAAa,EAAE,QAAQ,GAAG,MAAM,EAAE,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC;AACtE,QAAM,MAAM,SAAS,EAAE,aAAa;AACpC,MAAI,OAAO,EAAE,WAAW,UAAW,SAAQ,IA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E,SAAS,cAAc,aAAa,EAAE,MAAM,GAAG,EAAE,UAAU,WAAW,qBAAqB,EAAE,KAAK,QAAQ,EAAE,MAAM;AACjI,QAAI,KAAK,EAAE,IAAI,IAAI,CAAC;AACpB,QAAI;AAAA,MACF;AAAA,QACE,CAAC,WAAW,QAAQ,QAAQ,QAAQ,WAAW,EAAE;AAAA,QACjD,EAAE,SAAS,IAAI,CAAC,QAAQ;AACtB,gBAAM,MAAM,EAAE,YAAY,KAAK,CAAC,MAAM,EAAE,YAAY,IAAI,OAAO;AAC/D,gBAAM,SAAS,EAAE,mBAAmB,KAAK,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,IAAI,OAAO;AAClG,iBAAO,CAAC,IAAI,SAAS,OAAO,IAAI,WAAW,GAAG,IAAI,IAAI,YAAY,IAAI,cAAc,IAAI,YAAY,CAAC,GAAG,MAAM,IAAI,IAAI,cAAc,IAAI,IAAI,UAAK,OAAO,IAAI,YAAY,UAAU,IAAI,QAAQ,QAAQ,CAAC,IAAI,UAAK,SAAS,EAAE,IAAI,cAAS,IAAI,EAAE;AAAA,QAChP,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACA,SAAO,IAAI,KAAK,IAAI;AACtB;","names":[]}
|
package/dist/chunk-OYM64FMD.js
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
starText
|
|
4
|
-
} from "./chunk-DUIJ5DTV.js";
|
|
5
|
-
import {
|
|
6
|
-
fetchStatus,
|
|
7
|
-
resolveTarget
|
|
8
|
-
} from "./chunk-BJQJGLOB.js";
|
|
9
|
-
import {
|
|
10
|
-
detectProject
|
|
11
|
-
} from "./chunk-PLXDG4B5.js";
|
|
12
|
-
import {
|
|
13
|
-
bar,
|
|
14
|
-
c,
|
|
15
|
-
printJson,
|
|
16
|
-
statusColor,
|
|
17
|
-
table,
|
|
18
|
-
verdictColor,
|
|
19
|
-
verdictIcon
|
|
20
|
-
} from "./chunk-V3DLUVOE.js";
|
|
21
|
-
|
|
22
|
-
// src/commands/status.ts
|
|
23
|
-
async function status(flags) {
|
|
24
|
-
const target = resolveTarget(flags, detectProject());
|
|
25
|
-
const data = await fetchStatus(target);
|
|
26
|
-
const finished = data.experiments.filter((e) => e.status === "finished").map((e) => e.experiment);
|
|
27
|
-
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;
|
|
28
|
-
if (flags.json) {
|
|
29
|
-
printJson(next ? { ...data, next } : data);
|
|
30
|
-
return;
|
|
31
|
-
}
|
|
32
|
-
console.log(`${c.bold("SplitHub")} ${c.dim("\xB7")} project ${c.cyan(data.project)} ${c.dim(`\xB7 ${target.url}`)}
|
|
33
|
-
`);
|
|
34
|
-
if (data.experiments.length === 0) {
|
|
35
|
-
console.log(c.dim("No experiments in splithub.config.ts yet. Run `splithub create`."));
|
|
36
|
-
return;
|
|
37
|
-
}
|
|
38
|
-
const maxVisitors = Math.max(1, ...data.experiments.map((e) => e.visitors));
|
|
39
|
-
console.log(
|
|
40
|
-
table(
|
|
41
|
-
["EXPERIMENT", "KIND", "STATUS", "VISITORS", "", "DAYS", "VERDICT", "SAMPLE", "DATA", "NEXT CHECK"],
|
|
42
|
-
data.experiments.map((e) => [
|
|
43
|
-
e.experiment === "__holdout" ? c.bold("Holdout: long-term impact") : c.bold(e.experiment),
|
|
44
|
-
e.kind,
|
|
45
|
-
statusColor(e.status),
|
|
46
|
-
String(e.visitors),
|
|
47
|
-
bar(e.visitors, maxVisitors, 12, e.status === "running" ? c.green : c.dim),
|
|
48
|
-
e.days ? String(e.days) : "\u2013",
|
|
49
|
-
verdictColor(e.verdict, `${verdictIcon(e.goal ? e.verdict : null)} ${e.headline ?? (e.goal ? "no data" : "no goal")}`),
|
|
50
|
-
e.sample === "good" ? c.green("good") : e.sample === "ok" ? "ok" : e.sample === "small" ? c.dim("small") : "",
|
|
51
|
-
typeof e.stars === "number" ? c.yellow(starText(e.stars)) : "",
|
|
52
|
-
e.status === "running" && e.daysToVerdict && e.daysToVerdict > 0 ? c.dim(`in ~${Math.ceil(e.daysToVerdict)}d`) : ""
|
|
53
|
-
])
|
|
54
|
-
)
|
|
55
|
-
);
|
|
56
|
-
if (next) console.log(`
|
|
57
|
-
${c.dim(next)}`);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export {
|
|
61
|
-
status
|
|
62
|
-
};
|
|
63
|
-
//# sourceMappingURL=chunk-OYM64FMD.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/status.ts"],"sourcesContent":["import { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { printJson } from '../errors';\nimport { bar, c, statusColor, table, verdictColor, verdictIcon } from '../ui';\nimport { starText } 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 return;\n }\n // Visitors as a bar relative to the busiest experiment, verdict with its icon.\n const maxVisitors = Math.max(1, ...data.experiments.map((e) => e.visitors));\n console.log(\n table(\n ['EXPERIMENT', 'KIND', 'STATUS', 'VISITORS', '', 'DAYS', 'VERDICT', 'SAMPLE', 'DATA', 'NEXT CHECK'],\n data.experiments.map((e) => [\n e.experiment === '__holdout' ? c.bold('Holdout: long-term impact') : c.bold(e.experiment),\n e.kind,\n statusColor(e.status),\n String(e.visitors),\n bar(e.visitors, maxVisitors, 12, e.status === 'running' ? c.green : c.dim),\n e.days ? String(e.days) : '–',\n verdictColor(e.verdict, `${verdictIcon(e.goal ? e.verdict : null)} ${e.headline ?? (e.goal ? 'no data' : 'no goal')}`),\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 if (next) console.log(`\\n${c.dim(next)}`);\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,QAAK,OAAO,GAAG,EAAE,CAAC;AAAA,CAAI;AAC/G,MAAI,KAAK,YAAY,WAAW,GAAG;AACjC,YAAQ,IAAI,EAAE,IAAI,kEAAkE,CAAC;AACrF;AAAA,EACF;AAEA,QAAM,cAAc,KAAK,IAAI,GAAG,GAAG,KAAK,YAAY,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC;AAC1E,UAAQ;AAAA,IACN;AAAA,MACE,CAAC,cAAc,QAAQ,UAAU,YAAY,IAAI,QAAQ,WAAW,UAAU,QAAQ,YAAY;AAAA,MAClG,KAAK,YAAY,IAAI,CAAC,MAAM;AAAA,QAC1B,EAAE,eAAe,cAAc,EAAE,KAAK,2BAA2B,IAAI,EAAE,KAAK,EAAE,UAAU;AAAA,QACxF,EAAE;AAAA,QACF,YAAY,EAAE,MAAM;AAAA,QACpB,OAAO,EAAE,QAAQ;AAAA,QACjB,IAAI,EAAE,UAAU,aAAa,IAAI,EAAE,WAAW,YAAY,EAAE,QAAQ,EAAE,GAAG;AAAA,QACzE,EAAE,OAAO,OAAO,EAAE,IAAI,IAAI;AAAA,QAC1B,aAAa,EAAE,SAAS,GAAG,YAAY,EAAE,OAAO,EAAE,UAAU,IAAI,CAAC,IAAI,EAAE,aAAa,EAAE,OAAO,YAAY,UAAU,EAAE;AAAA,QACrH,EAAE,WAAW,SAAS,EAAE,MAAM,MAAM,IAAI,EAAE,WAAW,OAAO,OAAO,EAAE,WAAW,UAAU,EAAE,IAAI,OAAO,IAAI;AAAA,QAC3G,OAAO,EAAE,UAAU,WAAW,EAAE,OAAO,SAAS,EAAE,KAAK,CAAC,IAAI;AAAA,QAC5D,EAAE,WAAW,aAAa,EAAE,iBAAiB,EAAE,gBAAgB,IAAI,EAAE,IAAI,OAAO,KAAK,KAAK,EAAE,aAAa,CAAC,GAAG,IAAI;AAAA,MACnH,CAAC;AAAA,IACH;AAAA,EACF;AACA,MAAI,KAAM,SAAQ,IAAI;AAAA,EAAK,EAAE,IAAI,IAAI,CAAC,EAAE;AAC1C;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/init.ts","../src/templates-store.ts"],"sourcesContent":["import * as p from '@clack/prompts';\nimport { execSync } from 'node:child_process';\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { cloudTarget } from '../api';\nimport { loadCredential } from '../credentials';\nimport { detectProject, installCommand } from '../project';\nimport { deviceLogin } from './login';\nimport { configTemplate, nextMiddlewareTemplate, nextRouteTemplate } from '../templates';\nimport { DB_KINDS, runtimePackages, storeTemplate, storeUsage, type DbKind } from '../templates-store';\nimport { installSkills } from './skills';\nimport { writeWorkflow } from './ci';\nimport { c } from '../ui';\n\nexport type Flags = Record<string, string | boolean | string[] | undefined>;\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined;\n}\n\nfunction writeIfMissing(file: string, content: string, created: string[], skipped: string[]): void {\n if (existsSync(file)) {\n skipped.push(file);\n return;\n }\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, content, 'utf8');\n created.push(file);\n}\n\nfunction importPath(fromFile: string, toFile: string): string {\n let rel = relative(dirname(fromFile), toFile).replace(/\\\\/g, '/').replace(/\\.(ts|mts|js|mjs)$/, '');\n if (!rel.startsWith('.')) rel = `./${rel}`;\n return rel;\n}\n\n// Vite apps run the SDK in the browser; this plugin prints what each experiment does in the dev server's terminal.\nconst VITE_PLUGIN_HINT = `// vite.config.ts\nimport { splithub } from '@splithub/core/vite';\n\nexport default defineConfig({ plugins: [react(), splithub()] });`;\n\nexport async function init(flags: Flags): Promise<void> {\n const yes = Boolean(flags.yes);\n const json = Boolean(flags.json);\n const project = detectProject();\n const created: string[] = [];\n const skipped: string[] = [];\n\n if (!json) p.intro(c.bold('splithub init'));\n\n let mode = str(flags.mode) as 'self' | 'cloud' | undefined;\n if (!mode) {\n if (yes) mode = 'self';\n else {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'self', label: 'My own database (self-hosted)', hint: 'free forever, nothing leaves your infra' },\n { value: 'cloud', label: 'SplitHub Cloud', hint: 'hosted dashboard, no server code' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n mode = picked as 'self' | 'cloud';\n }\n }\n\n // Cloud: connect this directory to a project. A saved login or SPLITHUB_API_KEY\n // is enough; otherwise run the device flow — print a link, the human signs in\n // and picks (or creates) the project, the CLI gets the keys. Works when an\n // agent runs init: it relays the link, the user clicks it.\n // Self mode: which database keeps the events. sqlite needs nothing; postgres / mysql\n // get a ready Store in splithub/store.ts; custom gets a documented stub.\n let db: DbKind = (DB_KINDS as string[]).includes(str(flags.db) ?? '') ? (str(flags.db) as DbKind) : 'sqlite';\n if (mode === 'self' && !flags.db && !yes) {\n const picked = await p.select({\n message: 'Where should events be stored?',\n options: [\n { value: 'sqlite', label: 'SQLite file (zero setup)', hint: './splithub.db via node:sqlite' },\n { value: 'postgres', label: 'Postgres', hint: 'pg + DATABASE_URL, table splithub_events' },\n { value: 'mysql', label: 'MySQL / MariaDB / PlanetScale', hint: 'mysql2 + DATABASE_URL' },\n { value: 'custom', label: 'My own store (Prisma, Drizzle, Supabase, Mongo…)', hint: 'a stub with the three methods to fill in' },\n ],\n });\n if (p.isCancel(picked)) return cancel();\n db = picked as DbKind;\n }\n\n let key = str(flags.key);\n let connected: { projectName: string | null; projectId: string | null } | null = null;\n if (mode === 'cloud') {\n const api = cloudTarget(flags).url;\n const saved = loadCredential(api, project.root);\n if (saved) {\n key ??= saved.publicKey ?? undefined;\n connected = { projectName: saved.projectName, projectId: saved.projectId };\n } else if (!process.env.SPLITHUB_API_KEY && !flags['no-login']) {\n if (!json) p.log.step('Connect to SplitHub Cloud');\n try {\n const cred = await deviceLogin({\n api,\n root: project.root,\n json,\n onCode: json\n ? (s) => console.log(JSON.stringify({ step: 'approve', verifyUrl: s.verifyUrl, userCode: s.userCode, expiresIn: s.expiresIn, hint: 'Show this link to the user and wait; init continues once approved.' }))\n : (s) => p.note(`${c.cyan(s.verifyUrl)}\\n\\nCode ${c.green(s.userCode)} · sign in, pick or create the project, approve.`, 'Open this link'),\n });\n key ??= cred.publicKey ?? undefined;\n connected = { projectName: cred.projectName, projectId: cred.projectId };\n if (!json) p.log.success(`connected to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n } catch (error) {\n if (!json) p.log.warn(`not connected: ${error instanceof Error ? error.message : String(error)}. Run ${c.cyan('npx splithub login')} later.`);\n }\n }\n // An API key in the environment (CI, agents) identifies the project: ask the cloud for its public key.\n if (!key && process.env.SPLITHUB_API_KEY) {\n try {\n const res = await fetch(`${api}/config`, { headers: { authorization: `Bearer ${process.env.SPLITHUB_API_KEY}` } });\n const body = (await res.json().catch(() => ({}))) as { publicKey?: string };\n if (typeof body.publicKey === 'string' && body.publicKey.startsWith('pk_')) {\n key = body.publicKey;\n connected ??= { projectName: null, projectId: null };\n }\n } catch {\n // offline: the first push writes the key into the config anyway\n }\n }\n if (!key && !yes) {\n const k = await p.text({ message: 'Cloud public key (pk_...), leave empty to set later via NEXT_PUBLIC_SPLITHUB_KEY', placeholder: 'pk_' });\n if (p.isCancel(k)) return cancel();\n key = k || undefined;\n }\n }\n\n // 1. config\n const configFile = project.configFile ?? join(project.root, 'splithub.config.ts');\n writeIfMissing(configFile, configTemplate(project.name, mode, key), created, skipped);\n\n // 2a. store for self mode (postgres / mysql / custom); sqlite needs no file.\n const storeBody = mode === 'self' ? storeTemplate(db) : null;\n const storeFile = storeBody ? join(project.root, 'splithub', 'store.ts') : null;\n if (storeFile && storeBody) writeIfMissing(storeFile, storeBody, created, skipped);\n\n // 2. framework files\n if (project.framework === 'next') {\n const mwFile = join(project.root, project.hasSrc ? 'src/middleware.ts' : 'middleware.ts');\n writeIfMissing(mwFile, nextMiddlewareTemplate(importPath(mwFile, configFile)), created, skipped);\n if (mode === 'self' && project.appDir) {\n const routeFile = join(project.root, project.appDir, 'api/splithub/[[...path]]/route.ts');\n writeIfMissing(routeFile, nextRouteTemplate(importPath(routeFile, configFile), storeUsage(db, storeFile ? importPath(routeFile, storeFile) : '')), created, skipped);\n }\n }\n\n // 3. agent skills (+ MCP server registration): the agent learns the library, how to test\n // well, the API and the MCP tools from .claude/skills/*; Cursor gets the rule file.\n let mcp = !flags['no-mcp'];\n if (!yes && !json && mcp) {\n const want = await p.confirm({ message: 'Register the SplitHub MCP server for Claude Code / Cursor (.mcp.json, .cursor/mcp.json)?', initialValue: true });\n if (p.isCancel(want)) return cancel();\n mcp = want;\n }\n const skillsResult = installSkills(project.root, { mcp });\n created.push(...skillsResult.written, ...skillsResult.mcp.map((f) => `${f} (MCP server)`));\n skipped.push(...skillsResult.skipped);\n\n // 3b. GitHub workflow: checks on PRs, results comment on a schedule.\n if (flags['github-action']) {\n const wf = writeWorkflow(project.root, Boolean(flags.force));\n (wf.written ? created : skipped).push(join(project.root, wf.file));\n }\n\n // 4. dependencies\n const runtime = ['@splithub/react', '@splithub/core'];\n if (project.framework === 'next') runtime.push('@splithub/next');\n if (mode === 'self') runtime.push('@splithub/node', ...runtimePackages(db));\n const installRuntime = installCommand(project.packageManager, runtime);\n const installDev = installCommand(project.packageManager, ['splithub'], true);\n let installed = false;\n if (!flags['no-install']) {\n const go = yes ? true : await p.confirm({ message: `Install packages now? (${installRuntime})` });\n if (p.isCancel(go)) return cancel();\n if (go) {\n const s = json ? null : p.spinner();\n s?.start('Installing');\n try {\n execSync(installRuntime, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n execSync(installDev, { cwd: project.root, stdio: json ? 'ignore' : 'inherit' });\n installed = true;\n s?.stop('Installed');\n } catch (error) {\n s?.stop('Install failed; run it manually');\n if (!json) p.log.error(error instanceof Error ? error.message : String(error));\n }\n }\n }\n\n const providerHint =\n project.framework === 'next'\n ? `// ${project.appDir ?? 'app'}/layout.tsx\\nimport { SplitHubNextProvider } from '@splithub/next/client';\\nimport { getSplitHub } from '@splithub/next/server';\\nimport config from '${importPath(join(project.root, project.appDir ?? 'app', 'layout.tsx'), configFile)}';\\n\\nexport default async function RootLayout({ children }) {\\n const sh = await getSplitHub(config);\\n return <html><body><SplitHubNextProvider config={config} visitorId={sh.visitorId ?? undefined} remoteOverrides={sh.overrides}>{children}</SplitHubNextProvider></body></html>;\\n}`\n : `// main.tsx\\nimport { SplitHubProvider } from '@splithub/react';\\nimport config from './splithub.config';\\n\\n<SplitHubProvider config={config}><App /></SplitHubProvider>`;\n\n const warning = mode === 'cloud' && !key ? 'No public key yet: storage.key falls back to process.env.NEXT_PUBLIC_SPLITHUB_KEY. It is written into the config by the first `npx splithub push`, by `npx splithub login` (saved with the credentials), or pass --key pk_… (dashboard → Setup); SPLITHUB_API_KEY in the environment also resolves it.' : null;\n const summary = { project: project.name, framework: project.framework, mode, db: mode === 'self' ? db : null, connected, publicKey: key ?? null, warning, created, skipped, installed, installCommands: installed ? [] : [installRuntime, installDev], nextStep: providerHint, ...(project.framework === 'vite' ? { vitePlugin: VITE_PLUGIN_HINT } : {}) };\n\n if (json) {\n console.log(JSON.stringify(summary));\n return;\n }\n if (warning) p.log.warn(warning);\n if (mode === 'self' && db !== 'sqlite') p.note(db === 'custom' ? 'Fill in the three methods in splithub/store.ts (the comments say what each must return).' : `Set DATABASE_URL and run the SCHEMA_SQL from splithub/store.ts once (or add it to your migrations).`, `Database: ${db}`);\n if (created.length) p.note(created.map((f) => relative(project.root, f) || f).join('\\n'), 'Created');\n if (skipped.length) p.note(skipped.map((f) => relative(project.root, f)).join('\\n'), 'Already present, left untouched');\n if (!installed) p.note(`${installRuntime}\\n${installDev}`, 'Install');\n p.note(providerHint, 'Wrap your app once');\n if (project.framework === 'vite') p.note(VITE_PLUGIN_HINT, 'Notes in your dev terminal');\n p.outro(`Next: ${c.cyan('npx splithub create')} to add your first experiment, ${c.cyan('npx splithub push')} to sync it, ${c.cyan('npx splithub doctor')} to verify.`);\n}\n\n\nfunction cancel(): void {\n p.cancel('Cancelled.');\n process.exit(0);\n}\n","// Store templates for self-hosted mode: `splithub init --mode self --db postgres|mysql|custom`\n// writes splithub/store.ts from one of these. Each implements the Store interface\n// from @splithub/node (insertEvents, variantCounts, summaries) with the same\n// attribution rule as the cloud, through variantCountsSql from @splithub/node.\n\nexport type DbKind = 'sqlite' | 'postgres' | 'mysql' | 'custom';\nexport const DB_KINDS: DbKind[] = ['sqlite', 'postgres', 'mysql', 'custom'];\n\nexport const PG_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\nimport { Pool } from 'pg';\n\n// SplitHub events in your Postgres. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id text PRIMARY KEY,\n type text NOT NULL, -- exposure | goal\n experiment text,\n variant text,\n goal text,\n visitor_id text NOT NULL,\n session_id text NOT NULL,\n ts bigint NOT NULL, -- client clock, unix ms\n url text,\n props jsonb,\n received_at bigint NOT NULL, -- server clock, unix ms\n host text,\n country text,\n device text,\n browser text\n);\nCREATE INDEX IF NOT EXISTS splithub_events_exp ON splithub_events (type, experiment, visitor_id, ts);\nCREATE INDEX IF NOT EXISTS splithub_events_goal ON splithub_events (type, goal, visitor_id, ts);\n\\`;\n\n// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).\nconst counts = variantCountsSql({ dialect: 'postgres', table: 'splithub_events' });\n\nexport function pgStore(pool: Pool = new Pool({ connectionString: process.env.DATABASE_URL })): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const cols = 15;\n const values: unknown[] = [];\n const rows = events.map((e, i) => {\n values.push(e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null);\n return '(' + Array.from({ length: cols }, (_, j) => '$' + (i * cols + j + 1)).join(', ') + ')';\n });\n const r = await pool.query(\n 'INSERT INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ' + rows.join(', ') + ' ON CONFLICT (id) DO NOTHING',\n values\n );\n return r.rowCount ?? 0;\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n const r = await pool.query(counts.sql, counts.bind({ experiment, goal }));\n return r.rows.map(countsFromRow);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const r = await pool.query(\n \\`SELECT experiment, COUNT(*)::int AS exposures, COUNT(DISTINCT visitor_id)::int AS visitors, MIN(ts)::bigint AS first_ts, MAX(ts)::bigint AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return r.rows.map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const MYSQL_STORE = `import { countsFromRow, variantCountsSql, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\nimport mysql, { type Pool } from 'mysql2/promise';\n\n// SplitHub events in your MySQL / MariaDB / PlanetScale. Run once (or add to your migrations):\nexport const SCHEMA_SQL = \\`\nCREATE TABLE IF NOT EXISTS splithub_events (\n id VARCHAR(64) PRIMARY KEY,\n type VARCHAR(16) NOT NULL,\n experiment VARCHAR(64) NULL,\n variant VARCHAR(64) NULL,\n goal VARCHAR(64) NULL,\n visitor_id VARCHAR(64) NOT NULL,\n session_id VARCHAR(64) NOT NULL,\n ts BIGINT NOT NULL,\n url VARCHAR(512) NULL,\n props JSON NULL,\n received_at BIGINT NOT NULL,\n host VARCHAR(255) NULL,\n country VARCHAR(8) NULL,\n device VARCHAR(16) NULL,\n browser VARCHAR(32) NULL,\n INDEX splithub_events_exp (type, experiment, visitor_id, ts),\n INDEX splithub_events_goal (type, goal, visitor_id, ts)\n);\n\\`;\n\n// The attribution rule shared by every SplitHub store (first exposure, 60 s clock skew, 50 goals per visitor and day).\nconst counts = variantCountsSql({ dialect: 'mysql', table: 'splithub_events' });\n\nexport function mysqlStore(pool: Pool = mysql.createPool(process.env.DATABASE_URL ?? '')): Store {\n return {\n async insertEvents(events: StoredEvent[]) {\n if (events.length === 0) return 0;\n const values = events.map((e) => [e.id, e.type, e.experiment, e.variant, e.goal, e.visitorId, e.sessionId, e.ts, e.url, e.props ? JSON.stringify(e.props) : null, e.receivedAt, e.host ?? null, e.country ?? null, e.device ?? null, e.browser ?? null]);\n const [r] = await pool.query(\n 'INSERT IGNORE INTO splithub_events (id, type, experiment, variant, goal, visitor_id, session_id, ts, url, props, received_at, host, country, device, browser) VALUES ?',\n [values]\n );\n return (r as { affectedRows: number }).affectedRows;\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n const [rows] = await pool.query(counts.sql, counts.bind({ experiment, goal }));\n return (rows as Array<Record<string, unknown>>).map(countsFromRow);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n const [rows] = await pool.query(\n \\`SELECT experiment, COUNT(*) AS exposures, COUNT(DISTINCT visitor_id) AS visitors, MIN(ts) AS first_ts, MAX(ts) AS last_ts\n FROM splithub_events WHERE type = 'exposure' GROUP BY experiment\\`\n );\n return (rows as Array<Record<string, unknown>>).map((x) => ({ experiment: String(x.experiment), exposures: Number(x.exposures), visitors: Number(x.visitors), firstExposureAt: x.first_ts == null ? null : Number(x.first_ts), lastExposureAt: x.last_ts == null ? null : Number(x.last_ts) }));\n },\n close: () => pool.end(),\n };\n}\n`;\n\nexport const CUSTOM_STORE = `import { attributeVariants, type ExperimentSummary, type Store, type StoredEvent, type StoreVariantCounts } from '@splithub/node';\n\n/**\n * Your own store (Prisma, Drizzle, Supabase, Mongo, anything). Three methods.\n * Attribution rule (keep it, so results match the dashboard):\n * a visitor counts once per experiment, in the variant of their earliest\n * exposure (same ts: smallest variant key), and converts when they sent the\n * goal at or after that exposure (60 s of clock skew allowed); only the first\n * 50 events of one goal per visitor and UTC day count; count unique visitors.\n * SQL database: run variantCountsSql({ dialect }) from @splithub/node.\n * Anything else: load the experiment's exposures and the goal's events and\n * return attributeVariants(events, experiment, goal).\n * Columns worth keeping: id (unique, dedupe on it), type, experiment, variant,\n * goal, visitor_id, session_id, ts, url, props (json), received_at, host,\n * country, device, browser.\n */\nexport function customStore(): Store {\n return {\n async insertEvents(events: StoredEvent[]): Promise<number> {\n // Insert, skipping ids that already exist. Return how many were inserted.\n throw new Error('implement insertEvents ' + events.length);\n },\n async variantCounts(experiment: string, goal: string): Promise<StoreVariantCounts[]> {\n // Per variant: exposures, conversions, revenueSum and revenueSumSq (per-visitor revenue).\n // Load the exposures of this experiment and the events of this goal, then apply the shared rule.\n const events: StoredEvent[] = [];\n if (events.length === 0) throw new Error('implement variantCounts ' + experiment + ' ' + goal);\n return attributeVariants(events, experiment, goal);\n },\n async summaries(): Promise<ExperimentSummary[]> {\n // Per experiment: exposures, unique visitors, first and last exposure ts (unix ms).\n throw new Error('implement summaries');\n },\n };\n}\n`;\n\nexport function storeTemplate(db: DbKind): string | null {\n return db === 'postgres' ? PG_STORE : db === 'mysql' ? MYSQL_STORE : db === 'custom' ? CUSTOM_STORE : null;\n}\n\n/** Import line + factory call used by the route template. */\nexport function storeUsage(db: DbKind, storeImport: string): { imports: string; factory: string } {\n switch (db) {\n case 'postgres':\n return { imports: `import { pgStore } from '${storeImport}';`, factory: 'pgStore()' };\n case 'mysql':\n return { imports: `import { mysqlStore } from '${storeImport}';`, factory: 'mysqlStore()' };\n case 'custom':\n return { imports: `import { customStore } from '${storeImport}';`, factory: 'customStore()' };\n default:\n return { imports: `import { sqliteStore } from '@splithub/adapter-sqlite';`, factory: `sqliteStore({ file: process.env.SPLITHUB_DB ?? './splithub.db' })` };\n }\n}\n\nexport function runtimePackages(db: DbKind): string[] {\n return db === 'postgres' ? ['pg'] : db === 'mysql' ? ['mysql2'] : db === 'sqlite' ? ['@splithub/adapter-sqlite'] : [];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,YAAY,OAAO;AACnB,SAAS,gBAAgB;AACzB,SAAS,YAAY,WAAW,qBAAqB;AACrD,SAAS,SAAS,MAAM,gBAAgB;;;ACGjC,IAAM,WAAqB,CAAC,UAAU,YAAY,SAAS,QAAQ;AAEnE,IAAM,WAAW;AAAA;AAAA;AAAA;AAAA;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}
|
|
@@ -1 +0,0 @@
|
|
|
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.\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\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}\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 } = {}): SkillsResult {\n const out: SkillsResult = { written: [], skipped: [], mcp: [] };\n for (const s of SKILLS) writeFile(join(root, '.claude', 'skills', s.dir, 'SKILL.md'), s.body, Boolean(options.force), out);\n writeFile(join(root, '.cursor', 'rules', 'splithub.mdc'), CURSOR_RULE, Boolean(options.force), out);\n\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${AGENTS_SECTION}`, 'utf8');\n out.written.push(agentsFile);\n } else if (!/SplitHub/.test(readFileSync(agentsFile, 'utf8'))) {\n writeFileSync(agentsFile, readFileSync(agentsFile, 'utf8') + `\\n${AGENTS_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) });\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 (!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 test well), splithub-api (HTTP API), splithub-mcp (MCP tools), splithub-self-hosted (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AACA,QAAM,MAAM,CAAC,MAAc,SAAS,QAAQ,MAAM,CAAC,KAAK;AACxD,MAAI,OAAO,QAAQ,OAAQ,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC;AAAA,IAAa,OAAO,QAAQ,IAAI,GAAG,EAAE,KAAK,MAAM,CAAC,EAAE;AACzG,MAAI,OAAO,IAAI,OAAQ,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC;AAAA,IAAgC,OAAO,IAAI,IAAI,GAAG,EAAE,KAAK,MAAM,CAAC,EAAE;AACpH,MAAI,OAAO,QAAQ,OAAQ,SAAQ,IAAI,EAAE,IAAI,cAAc,OAAO,QAAQ,IAAI,GAAG,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;AAChG,MAAI,CAAC,MAAM,IAAK,SAAQ,IAAI,EAAE,IAAI,kIAAkI,CAAC;AACrK,UAAQ,IAAI,EAAE,IAAI,8PAA8P,CAAC;AACnR;","names":[]}
|
package/dist/create-AEJVXN25.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
create,
|
|
4
|
-
parseExtras,
|
|
5
|
-
parseLimits,
|
|
6
|
-
parseWeights
|
|
7
|
-
} from "./chunk-E5VH4BQX.js";
|
|
8
|
-
import "./chunk-B6FITBWN.js";
|
|
9
|
-
import "./chunk-DDWYTOX4.js";
|
|
10
|
-
import "./chunk-PLXDG4B5.js";
|
|
11
|
-
import "./chunk-V3DLUVOE.js";
|
|
12
|
-
export {
|
|
13
|
-
create,
|
|
14
|
-
parseExtras,
|
|
15
|
-
parseLimits,
|
|
16
|
-
parseWeights
|
|
17
|
-
};
|
|
18
|
-
//# sourceMappingURL=create-AEJVXN25.js.map
|
package/dist/dev-W2JGUV2A.js
DELETED
package/dist/doctor-D3KOGOX6.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
doctor
|
|
4
|
-
} from "./chunk-LT4JP3IF.js";
|
|
5
|
-
import "./chunk-GVARYUL3.js";
|
|
6
|
-
import "./chunk-OHA2M7QR.js";
|
|
7
|
-
import "./chunk-B6FITBWN.js";
|
|
8
|
-
import "./chunk-BJQJGLOB.js";
|
|
9
|
-
import "./chunk-PLXDG4B5.js";
|
|
10
|
-
import "./chunk-V3DLUVOE.js";
|
|
11
|
-
export {
|
|
12
|
-
doctor
|
|
13
|
-
};
|
|
14
|
-
//# sourceMappingURL=doctor-D3KOGOX6.js.map
|
package/dist/init-UBUDSJBD.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
init
|
|
4
|
-
} from "./chunk-PNPOOAHF.js";
|
|
5
|
-
import "./chunk-5C24F2ZN.js";
|
|
6
|
-
import "./chunk-BJQJGLOB.js";
|
|
7
|
-
import "./chunk-RYDA7PQF.js";
|
|
8
|
-
import "./chunk-DDWYTOX4.js";
|
|
9
|
-
import "./chunk-EYYLDI5J.js";
|
|
10
|
-
import "./chunk-PLXDG4B5.js";
|
|
11
|
-
import "./chunk-V3DLUVOE.js";
|
|
12
|
-
export {
|
|
13
|
-
init
|
|
14
|
-
};
|
|
15
|
-
//# sourceMappingURL=init-UBUDSJBD.js.map
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
lifecycle
|
|
4
|
-
} from "./chunk-3RVNT2HA.js";
|
|
5
|
-
import "./chunk-B6FITBWN.js";
|
|
6
|
-
import "./chunk-BJQJGLOB.js";
|
|
7
|
-
import "./chunk-PLXDG4B5.js";
|
|
8
|
-
import "./chunk-V3DLUVOE.js";
|
|
9
|
-
export {
|
|
10
|
-
lifecycle
|
|
11
|
-
};
|
|
12
|
-
//# sourceMappingURL=lifecycle-ZLZUTASA.js.map
|