@splithub/node 0.2.3 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +446 -145
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +146 -5
- package/dist/index.d.ts +146 -5
- package/dist/index.js +434 -144
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -48,6 +48,7 @@ async function rawResults(config, store, key, options = {}) {
|
|
|
48
48
|
status: experiment.status,
|
|
49
49
|
goal: goal2,
|
|
50
50
|
description: experiment.description ?? null,
|
|
51
|
+
name: experiment.name ?? null,
|
|
51
52
|
variants: rawVariants(experiment, observed, withRevenue),
|
|
52
53
|
...metrics?.length ? { metrics } : {},
|
|
53
54
|
days: Math.round(span * 10) / 10,
|
|
@@ -61,159 +62,132 @@ async function rawStatusTable(config, store) {
|
|
|
61
62
|
return all.map((exp) => {
|
|
62
63
|
const s = byKey.get(exp.key);
|
|
63
64
|
const days = s?.firstExposureAt && s.lastExposureAt ? Math.max(1, Math.ceil((s.lastExposureAt - s.firstExposureAt) / DAY_MS)) : 0;
|
|
64
|
-
return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };
|
|
65
|
+
return { experiment: exp.key, kind: exp.kind, status: exp.status, goal: exp.goal, description: exp.description ?? null, name: exp.name ?? null, exposures: s?.exposures ?? 0, visitors: s?.visitors ?? 0, days };
|
|
65
66
|
});
|
|
66
67
|
}
|
|
67
68
|
|
|
68
|
-
// src/
|
|
69
|
-
|
|
70
|
-
var
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };
|
|
83
|
-
const out = [];
|
|
84
|
-
for (const raw of batch.events) {
|
|
85
|
-
const e = normalize(raw, now);
|
|
86
|
-
if (typeof e === "string") return { ok: false, error: e };
|
|
87
|
-
out.push(e);
|
|
88
|
-
}
|
|
89
|
-
return { ok: true, events: out };
|
|
90
|
-
}
|
|
91
|
-
function normalize(e, now) {
|
|
92
|
-
if (!e || typeof e !== "object") return "event must be an object";
|
|
93
|
-
if (typeof e.id !== "string" || !ID.test(e.id)) return "event.id is invalid";
|
|
94
|
-
if (typeof e.vid !== "string" || e.vid.length === 0 || e.vid.length > 64) return "event.vid is invalid";
|
|
95
|
-
if (typeof e.sid !== "string" || e.sid.length === 0 || e.sid.length > 64) return "event.sid is invalid";
|
|
96
|
-
if (typeof e.ts !== "number" || !Number.isFinite(e.ts)) return "event.ts must be a number";
|
|
97
|
-
const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);
|
|
98
|
-
const url = typeof e.url === "string" ? e.url.slice(0, 512) : null;
|
|
99
|
-
if (e.type === "exposure") {
|
|
100
|
-
if (typeof e.exp !== "string" || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY2)) return "exposure.exp is invalid";
|
|
101
|
-
if (typeof e.var !== "string" || !KEY.test(e.var)) return "exposure.var is invalid";
|
|
102
|
-
return { id: e.id, type: "exposure", experiment: e.exp, variant: e.var, goal: null, visitorId: e.vid, sessionId: e.sid, ts, url, props: null, receivedAt: now };
|
|
103
|
-
}
|
|
104
|
-
if (e.type === "goal") {
|
|
105
|
-
if (typeof e.goal !== "string" || !KEY.test(e.goal)) return "goal.goal is invalid";
|
|
106
|
-
let props = null;
|
|
107
|
-
if (e.props !== void 0) {
|
|
108
|
-
if (!e.props || typeof e.props !== "object" || Array.isArray(e.props)) return "goal.props must be an object";
|
|
109
|
-
if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return "goal.props too large";
|
|
110
|
-
props = e.props;
|
|
111
|
-
}
|
|
112
|
-
return { id: e.id, type: "goal", experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };
|
|
113
|
-
}
|
|
114
|
-
return `unknown event type "${String(e.type)}"`;
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
// src/handler.ts
|
|
118
|
-
var isBotUserAgent = (ua) => isCrawler(ua);
|
|
119
|
-
var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
|
|
120
|
-
function createSplitHubHandler(options) {
|
|
121
|
-
const { config, store } = options;
|
|
122
|
-
const corsHeaders = (request) => {
|
|
123
|
-
if (!options.cors) return {};
|
|
124
|
-
const origin = request.headers.get("origin") ?? "";
|
|
125
|
-
const allowed = options.cors === "*" ? "*" : options.cors.includes(origin) ? origin : "";
|
|
126
|
-
if (!allowed) return {};
|
|
69
|
+
// src/analytics.ts
|
|
70
|
+
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
71
|
+
var DAY_MS2 = 864e5;
|
|
72
|
+
function propertyCountsSql(options) {
|
|
73
|
+
const t = options.table ?? "splithub_events";
|
|
74
|
+
if (!IDENT.test(t)) throw new Error("[splithub] invalid table name");
|
|
75
|
+
if (options.projectColumn !== void 0 && !IDENT.test(options.projectColumn)) throw new Error("[splithub] invalid column name");
|
|
76
|
+
const build = (parts) => {
|
|
77
|
+
const params = [];
|
|
78
|
+
const p = (name) => {
|
|
79
|
+
params.push(name);
|
|
80
|
+
return options.dialect === "postgres" ? `$${params.length}` : "?";
|
|
81
|
+
};
|
|
82
|
+
const sql = parts(p);
|
|
127
83
|
return {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
84
|
+
sql,
|
|
85
|
+
bind: (values) => params.map((name) => {
|
|
86
|
+
const v = name === "until" && values.until === void 0 ? Number.MAX_SAFE_INTEGER : values[name];
|
|
87
|
+
if (v === void 0) throw new Error(`[splithub] missing "${name}" for the property query`);
|
|
88
|
+
return v;
|
|
89
|
+
})
|
|
132
90
|
};
|
|
133
91
|
};
|
|
134
|
-
const
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
92
|
+
const scope = (p, types) => `${options.projectColumn ? `${options.projectColumn} = ${p("project")} AND ` : ""}type IN (${types}) AND experiment = ${p("property")}`;
|
|
93
|
+
const seen = `type IN ('page', 'event')`;
|
|
94
|
+
return {
|
|
95
|
+
totals: build(
|
|
96
|
+
(p) => `SELECT SUM(CASE WHEN type = 'page' THEN 1 ELSE 0 END) AS pageviews, COUNT(DISTINCT CASE WHEN ${seen} THEN visitor_id END) AS visitors, COUNT(DISTINCT CASE WHEN ${seen} THEN session_id END) AS sessions, COUNT(DISTINCT CASE WHEN type = 'identify' THEN ${uidExpr(options.dialect)} END) AS users FROM ${t} WHERE ${scope(p, `'page', 'event', 'identify'`)} AND ts >= ${p("since")} AND ts < ${p("until")}`
|
|
97
|
+
),
|
|
98
|
+
events: build(
|
|
99
|
+
(p) => `SELECT goal AS name, COUNT(*) AS count, COUNT(DISTINCT visitor_id) AS visitors FROM ${t} WHERE ${scope(p, `'event'`)} AND ts >= ${p("since")} AND ts < ${p("until")} GROUP BY goal ORDER BY count DESC LIMIT 200`
|
|
100
|
+
),
|
|
101
|
+
rows: build((p) => `SELECT * FROM ${t} WHERE ${scope(p, `'page', 'event', 'engage', 'identify'`)} AND ts < ${p("before")} ORDER BY ts DESC LIMIT ${p("limit")}`)
|
|
139
102
|
};
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if (!result.ok) return json(request, { error: result.error }, 400);
|
|
154
|
-
if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);
|
|
155
|
-
const inserted = await store.insertEvents(result.events);
|
|
156
|
-
return json(request, { ok: true, received: result.events.length, inserted }, 202);
|
|
157
|
-
}
|
|
158
|
-
if (request.method === "GET") {
|
|
159
|
-
if (tail[1] === "health") return json(request, { ok: true, project: config.project });
|
|
160
|
-
if (!authorized(request)) return json(request, { error: "unauthorized" }, 401);
|
|
161
|
-
if (tail[1] === "status") return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });
|
|
162
|
-
if (tail[0] === "results" && tail[1]) {
|
|
163
|
-
const r = await rawResults(config, store, tail[1]);
|
|
164
|
-
return r ? json(request, r) : json(request, { error: `unknown experiment "${tail[1]}"` }, 404);
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
return json(request, { error: "not found" }, 404);
|
|
103
|
+
}
|
|
104
|
+
function uidExpr(dialect) {
|
|
105
|
+
if (dialect === "postgres") return `(props::jsonb ->> 'uid')`;
|
|
106
|
+
if (dialect === "mysql") return `JSON_UNQUOTE(JSON_EXTRACT(props, '$.uid'))`;
|
|
107
|
+
return `json_extract(props, '$.uid')`;
|
|
108
|
+
}
|
|
109
|
+
function propertyCountsFromRows(totals, events) {
|
|
110
|
+
return {
|
|
111
|
+
pageviews: Number(totals?.pageviews ?? 0),
|
|
112
|
+
visitors: Number(totals?.visitors ?? 0),
|
|
113
|
+
sessions: Number(totals?.sessions ?? 0),
|
|
114
|
+
users: Number(totals?.users ?? 0),
|
|
115
|
+
events: events.map((r) => ({ name: String(r.name), count: Number(r.count ?? 0), visitors: Number(r.visitors ?? 0) }))
|
|
168
116
|
};
|
|
169
117
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
118
|
+
function storedEventFromRow(r) {
|
|
119
|
+
let props = null;
|
|
120
|
+
if (typeof r.props === "string") {
|
|
121
|
+
try {
|
|
122
|
+
props = JSON.parse(r.props);
|
|
123
|
+
} catch {
|
|
124
|
+
props = null;
|
|
125
|
+
}
|
|
126
|
+
} else if (r.props && typeof r.props === "object") props = r.props;
|
|
127
|
+
const s = (v) => v === null || v === void 0 ? null : String(v);
|
|
128
|
+
return {
|
|
129
|
+
id: String(r.id),
|
|
130
|
+
type: String(r.type),
|
|
131
|
+
experiment: s(r.experiment),
|
|
132
|
+
variant: s(r.variant),
|
|
133
|
+
goal: s(r.goal),
|
|
134
|
+
visitorId: String(r.visitor_id),
|
|
135
|
+
sessionId: String(r.session_id),
|
|
136
|
+
ts: Number(r.ts),
|
|
137
|
+
url: s(r.url),
|
|
138
|
+
props,
|
|
139
|
+
receivedAt: Number(r.received_at ?? r.ts),
|
|
140
|
+
host: s(r.host),
|
|
141
|
+
country: s(r.country),
|
|
142
|
+
device: s(r.device),
|
|
143
|
+
browser: s(r.browser)
|
|
188
144
|
};
|
|
189
145
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
205
|
-
const all = Buffer.concat(chunks);
|
|
206
|
-
const copy = new Uint8Array(all.byteLength);
|
|
207
|
-
copy.set(all);
|
|
208
|
-
body = copy.buffer;
|
|
146
|
+
var PROPERTY_REPORTS_UNAVAILABLE = {
|
|
147
|
+
...ANALYSIS_UNAVAILABLE,
|
|
148
|
+
message: "Reports with pages, sources, sessions and conversions come with SplitHub Cloud."
|
|
149
|
+
};
|
|
150
|
+
var DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
151
|
+
var dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
152
|
+
function rawPropertyRange(options) {
|
|
153
|
+
const now = options.now ?? Date.now();
|
|
154
|
+
const { from, to } = options;
|
|
155
|
+
if (from && !DAY.test(from) || to && !DAY.test(to)) return "from and to are days like 2026-10-01";
|
|
156
|
+
if (!from && !to) {
|
|
157
|
+
const days2 = Math.max(1, Math.min(365, Math.floor(options.days ?? 30)));
|
|
158
|
+
const since2 = now - days2 * DAY_MS2;
|
|
159
|
+
return { since: since2, until: now + 1, days: days2, range: { from: dayOf(since2), to: dayOf(now) } };
|
|
209
160
|
}
|
|
210
|
-
|
|
161
|
+
const end = to ? Date.parse(`${to}T00:00:00Z`) + DAY_MS2 : now + 1;
|
|
162
|
+
const since = from ? Date.parse(`${from}T00:00:00Z`) : end - 30 * DAY_MS2;
|
|
163
|
+
if (Number.isNaN(since) || Number.isNaN(end)) return "from and to are days like 2026-10-01";
|
|
164
|
+
if (since >= end) return "from must be on or before to";
|
|
165
|
+
const days = Math.ceil((end - since) / DAY_MS2);
|
|
166
|
+
if (days > 400) return "a range covers at most 400 days";
|
|
167
|
+
return { since, until: end, days, range: { from: dayOf(since), to: dayOf(end - 1) } };
|
|
168
|
+
}
|
|
169
|
+
async function rawPropertyReport(config, store, key, options = {}) {
|
|
170
|
+
const property = (config.properties ?? []).find((p) => p.key === key);
|
|
171
|
+
if (!property) return null;
|
|
172
|
+
const span = rawPropertyRange(options);
|
|
173
|
+
if (typeof span === "string") throw new Error(`[splithub] ${span}`);
|
|
174
|
+
return {
|
|
175
|
+
property: key,
|
|
176
|
+
status: property.status,
|
|
177
|
+
name: property.name ?? null,
|
|
178
|
+
description: property.description,
|
|
179
|
+
goals: property.goals,
|
|
180
|
+
days: span.days,
|
|
181
|
+
range: span.range,
|
|
182
|
+
counts: store.propertyCounts ? await store.propertyCounts(key, span.since, span.until) : null,
|
|
183
|
+
analysis: PROPERTY_REPORTS_UNAVAILABLE
|
|
184
|
+
};
|
|
211
185
|
}
|
|
212
186
|
|
|
213
187
|
// src/attribution.ts
|
|
214
188
|
var ATTRIBUTION_SKEW_MS = 6e4;
|
|
215
189
|
var GOAL_DAILY_CAP = 50;
|
|
216
|
-
var
|
|
190
|
+
var DAY_MS3 = 864e5;
|
|
217
191
|
function revenueOf(props) {
|
|
218
192
|
const v = props?.revenue;
|
|
219
193
|
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
@@ -226,8 +200,8 @@ function attributeVariants(events, experiment, goal2) {
|
|
|
226
200
|
if (e.experiment !== experiment || !e.variant) continue;
|
|
227
201
|
const prev = first.get(e.visitorId);
|
|
228
202
|
if (prev === void 0 || e.ts < prev.ts || e.ts === prev.ts && e.variant < prev.variant) first.set(e.visitorId, { variant: e.variant, ts: e.ts });
|
|
229
|
-
} else if (e.goal === goal2) {
|
|
230
|
-
const key = `${e.visitorId}\0${e.ts - e.ts %
|
|
203
|
+
} else if (e.type === "goal" && e.goal === goal2) {
|
|
204
|
+
const key = `${e.visitorId}\0${e.ts - e.ts % DAY_MS3}`;
|
|
231
205
|
const list = goals.get(key) ?? [];
|
|
232
206
|
list.push(e);
|
|
233
207
|
goals.set(key, list);
|
|
@@ -265,7 +239,7 @@ function attributeVariants(events, experiment, goal2) {
|
|
|
265
239
|
}
|
|
266
240
|
return [...out.values()];
|
|
267
241
|
}
|
|
268
|
-
var
|
|
242
|
+
var IDENT2 = /^[a-z_][a-z0-9_]*$/i;
|
|
269
243
|
function revenueExpr(dialect, alias) {
|
|
270
244
|
if (dialect === "postgres") return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;
|
|
271
245
|
if (dialect === "mysql") return `CASE WHEN JSON_TYPE(JSON_EXTRACT(${alias}.props, '$.revenue')) IN ('INTEGER', 'UNSIGNED INTEGER', 'DOUBLE', 'DECIMAL') THEN JSON_EXTRACT(${alias}.props, '$.revenue') + 0 ELSE 0 END`;
|
|
@@ -274,8 +248,8 @@ function revenueExpr(dialect, alias) {
|
|
|
274
248
|
function variantCountsSql(options) {
|
|
275
249
|
const { dialect } = options;
|
|
276
250
|
const t = options.table ?? "splithub_events";
|
|
277
|
-
if (!
|
|
278
|
-
if (options.projectColumn !== void 0 && !
|
|
251
|
+
if (!IDENT2.test(t)) throw new Error("[splithub] invalid table name");
|
|
252
|
+
if (options.projectColumn !== void 0 && !IDENT2.test(options.projectColumn)) throw new Error("[splithub] invalid column name");
|
|
279
253
|
const params = [];
|
|
280
254
|
const p = (name) => {
|
|
281
255
|
if (dialect === "postgres") {
|
|
@@ -296,7 +270,7 @@ function variantCountsSql(options) {
|
|
|
296
270
|
const goalJoin = `${proj("g")}g.type = 'goal' AND g.goal = ${p("goal")} AND g.visitor_id = fe.visitor_id AND g.ts >= fe.first_ts - ${ATTRIBUTION_SKEW_MS}
|
|
297
271
|
AND (SELECT COUNT(*) FROM ${t} g2
|
|
298
272
|
WHERE ${proj("g2")}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id
|
|
299
|
-
AND g2.ts >= g.ts - (g.ts % ${
|
|
273
|
+
AND g2.ts >= g.ts - (g.ts % ${DAY_MS3}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;
|
|
300
274
|
const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,
|
|
301
275
|
COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq
|
|
302
276
|
FROM (
|
|
@@ -333,6 +307,34 @@ function countsFromRow(row) {
|
|
|
333
307
|
}
|
|
334
308
|
|
|
335
309
|
// src/store.ts
|
|
310
|
+
var ANALYTICS_TYPES = /* @__PURE__ */ new Set(["page", "event", "engage", "identify"]);
|
|
311
|
+
function countProperty(events, property, since, until = Number.POSITIVE_INFINITY) {
|
|
312
|
+
let pageviews = 0;
|
|
313
|
+
const visitors = /* @__PURE__ */ new Set();
|
|
314
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
315
|
+
const users = /* @__PURE__ */ new Set();
|
|
316
|
+
const byName = /* @__PURE__ */ new Map();
|
|
317
|
+
for (const e of events) {
|
|
318
|
+
if (!ANALYTICS_TYPES.has(e.type) || e.experiment !== property || e.ts < since || e.ts >= until) continue;
|
|
319
|
+
if (e.type === "identify") {
|
|
320
|
+
if (typeof e.props?.uid === "string") users.add(e.props.uid);
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
if (e.type === "engage") continue;
|
|
324
|
+
visitors.add(e.visitorId);
|
|
325
|
+
sessions.add(e.sessionId);
|
|
326
|
+
if (e.type === "page") pageviews++;
|
|
327
|
+
else if (e.goal) {
|
|
328
|
+
const n = byName.get(e.goal) ?? { count: 0, visitors: /* @__PURE__ */ new Set() };
|
|
329
|
+
n.count++;
|
|
330
|
+
n.visitors.add(e.visitorId);
|
|
331
|
+
byName.set(e.goal, n);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const list = [...byName].map(([name, n]) => ({ name, count: n.count, visitors: n.visitors.size }));
|
|
335
|
+
list.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
|
|
336
|
+
return { pageviews, visitors: visitors.size, sessions: sessions.size, users: users.size, events: list };
|
|
337
|
+
}
|
|
336
338
|
function createMemoryStore() {
|
|
337
339
|
const events = [];
|
|
338
340
|
const ids = /* @__PURE__ */ new Set();
|
|
@@ -351,6 +353,12 @@ function createMemoryStore() {
|
|
|
351
353
|
async variantCounts(experiment, goal2) {
|
|
352
354
|
return attributeVariants(events, experiment, goal2);
|
|
353
355
|
},
|
|
356
|
+
async propertyCounts(property, since, until) {
|
|
357
|
+
return countProperty(events, property, since, until);
|
|
358
|
+
},
|
|
359
|
+
async propertyEvents(property, { before, limit }) {
|
|
360
|
+
return events.filter((e) => ANALYTICS_TYPES.has(e.type) && e.experiment === property && e.ts < before).sort((a, b) => b.ts - a.ts).slice(0, limit);
|
|
361
|
+
},
|
|
354
362
|
async summaries() {
|
|
355
363
|
const map = /* @__PURE__ */ new Map();
|
|
356
364
|
for (const e of events) {
|
|
@@ -374,9 +382,280 @@ function createMemoryStore() {
|
|
|
374
382
|
};
|
|
375
383
|
}
|
|
376
384
|
|
|
385
|
+
// src/validate.ts
|
|
386
|
+
import { EVENT_NAME_PATTERN, HOLDOUT_KEY as HOLDOUT_KEY2 } from "@splithub/core";
|
|
387
|
+
var ID = /^[a-z0-9_-]{8,64}$/i;
|
|
388
|
+
var KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
389
|
+
var MAX_EVENTS = 500;
|
|
390
|
+
var MAX_PROPS_BYTES = 4096;
|
|
391
|
+
var MAX_ENGAGE_MS = 36e5;
|
|
392
|
+
var MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
393
|
+
function validateBatch(body, expectedProject, now = Date.now()) {
|
|
394
|
+
if (!body || typeof body !== "object") return { ok: false, error: "body must be a JSON object" };
|
|
395
|
+
const batch = body;
|
|
396
|
+
if (typeof batch.project !== "string") return { ok: false, error: '"project" must be a string' };
|
|
397
|
+
if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project "${batch.project}"` };
|
|
398
|
+
if (!Array.isArray(batch.events)) return { ok: false, error: '"events" must be an array' };
|
|
399
|
+
if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };
|
|
400
|
+
const out = [];
|
|
401
|
+
const errors = [];
|
|
402
|
+
let dropped = 0;
|
|
403
|
+
for (const raw of batch.events) {
|
|
404
|
+
const e = normalize(raw, now);
|
|
405
|
+
if (typeof e === "string") {
|
|
406
|
+
dropped++;
|
|
407
|
+
if (errors.length < 5 && !errors.includes(e)) errors.push(e);
|
|
408
|
+
} else out.push(e);
|
|
409
|
+
}
|
|
410
|
+
return { ok: true, events: out, dropped, errors };
|
|
411
|
+
}
|
|
412
|
+
function normalize(e, now) {
|
|
413
|
+
if (!e || typeof e !== "object") return "event must be an object";
|
|
414
|
+
if (typeof e.id !== "string" || !ID.test(e.id)) return "event.id is invalid";
|
|
415
|
+
if (typeof e.vid !== "string" || e.vid.length === 0 || e.vid.length > 64) return "event.vid is invalid";
|
|
416
|
+
if (typeof e.sid !== "string" || e.sid.length === 0 || e.sid.length > 64) return "event.sid is invalid";
|
|
417
|
+
if (typeof e.ts !== "number" || !Number.isFinite(e.ts)) return "event.ts must be a number";
|
|
418
|
+
const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);
|
|
419
|
+
const url = "url" in e && typeof e.url === "string" ? e.url.slice(0, 512) : null;
|
|
420
|
+
const base = { id: e.id, visitorId: e.vid, sessionId: e.sid, ts, url, receivedAt: now };
|
|
421
|
+
if (e.type === "exposure") {
|
|
422
|
+
if (typeof e.exp !== "string" || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY2)) return "exposure.exp is invalid";
|
|
423
|
+
if (typeof e.var !== "string" || !KEY.test(e.var)) return "exposure.var is invalid";
|
|
424
|
+
const ref = typeof e.ref === "string" ? e.ref.slice(0, 300) : null;
|
|
425
|
+
return { ...base, type: "exposure", experiment: e.exp, variant: e.var, goal: null, props: ref === null ? null : { ref } };
|
|
426
|
+
}
|
|
427
|
+
if (e.type === "goal") {
|
|
428
|
+
if (typeof e.goal !== "string" || !KEY.test(e.goal)) return "goal.goal is invalid";
|
|
429
|
+
const props = propsOf(e.props, "goal");
|
|
430
|
+
if (typeof props === "string") return props;
|
|
431
|
+
return { ...base, type: "goal", experiment: null, variant: null, goal: e.goal, props };
|
|
432
|
+
}
|
|
433
|
+
const prop = "prop" in e && typeof e.prop === "string" ? e.prop.trim().toLowerCase() : null;
|
|
434
|
+
if (e.type === "page") {
|
|
435
|
+
if (!prop || !KEY.test(prop)) return "page.prop is invalid";
|
|
436
|
+
if (!url) return "page.url is required";
|
|
437
|
+
const title = typeof e.title === "string" && e.title ? e.title.slice(0, 200) : null;
|
|
438
|
+
const ref = typeof e.ref === "string" && e.ref ? e.ref.slice(0, 512) : null;
|
|
439
|
+
const props = title || ref ? { ...title ? { title } : {}, ...ref ? { ref } : {} } : null;
|
|
440
|
+
return { ...base, type: "page", experiment: prop, variant: null, goal: null, props };
|
|
441
|
+
}
|
|
442
|
+
if (e.type === "event") {
|
|
443
|
+
if (!prop || !KEY.test(prop)) return "event.prop is invalid";
|
|
444
|
+
if (typeof e.name !== "string" || !EVENT_NAME_PATTERN.test(e.name)) return "event.name is invalid";
|
|
445
|
+
const props = propsOf(e.props, "event");
|
|
446
|
+
if (typeof props === "string") return props;
|
|
447
|
+
return { ...base, type: "event", experiment: prop, variant: null, goal: e.name, props };
|
|
448
|
+
}
|
|
449
|
+
if (e.type === "engage") {
|
|
450
|
+
if (!prop || !KEY.test(prop)) return "engage.prop is invalid";
|
|
451
|
+
if (!url) return "engage.url is required";
|
|
452
|
+
if (typeof e.ms !== "number" || !Number.isFinite(e.ms) || e.ms < 0) return "engage.ms must be a number of milliseconds";
|
|
453
|
+
if (typeof e.scroll !== "number" || !Number.isFinite(e.scroll) || e.scroll < 0) return "engage.scroll must be a percent";
|
|
454
|
+
const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms));
|
|
455
|
+
const scroll = Math.min(100, Math.round(e.scroll));
|
|
456
|
+
return { ...base, type: "engage", experiment: prop, variant: null, goal: null, props: { ms, scroll } };
|
|
457
|
+
}
|
|
458
|
+
if (e.type === "identify") {
|
|
459
|
+
if (!prop || !KEY.test(prop)) return "identify.prop is invalid";
|
|
460
|
+
const uid = typeof e.uid === "string" ? e.uid.trim() : "";
|
|
461
|
+
if (!uid || uid.length > 128) return "identify.uid must be 1 to 128 characters";
|
|
462
|
+
const traits = traitsOf(e.traits);
|
|
463
|
+
if (typeof traits === "string") return traits;
|
|
464
|
+
return { ...base, type: "identify", experiment: prop, variant: null, goal: null, url: null, props: { uid, ...traits ? { traits } : {} } };
|
|
465
|
+
}
|
|
466
|
+
return `unknown event type "${String(e.type)}"`;
|
|
467
|
+
}
|
|
468
|
+
function propsOf(value, kind) {
|
|
469
|
+
if (value === void 0) return null;
|
|
470
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${kind}.props must be an object`;
|
|
471
|
+
if (JSON.stringify(value).length > MAX_PROPS_BYTES) return `${kind}.props too large`;
|
|
472
|
+
return value;
|
|
473
|
+
}
|
|
474
|
+
function traitsOf(value) {
|
|
475
|
+
if (value === void 0 || value === null) return null;
|
|
476
|
+
if (typeof value !== "object" || Array.isArray(value)) return "identify.traits must be an object";
|
|
477
|
+
const out = {};
|
|
478
|
+
for (const [k, v] of Object.entries(value)) {
|
|
479
|
+
if (typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v)) out[k] = v;
|
|
480
|
+
}
|
|
481
|
+
if (JSON.stringify(out).length > MAX_PROPS_BYTES) return "identify.traits too large";
|
|
482
|
+
return Object.keys(out).length ? out : null;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/derive.ts
|
|
486
|
+
import { goalKeyFor, matchPath, measuredGoals } from "@splithub/core";
|
|
487
|
+
var SAME_ACTION_MS = 1e3;
|
|
488
|
+
function experimentGoals(config) {
|
|
489
|
+
const measured = measuredGoals(config);
|
|
490
|
+
const keys = /* @__PURE__ */ new Set();
|
|
491
|
+
for (const key of Object.values(measured.goals)) if (key) keys.add(key);
|
|
492
|
+
for (const list of Object.values(measured.metrics)) for (const key of list) keys.add(key);
|
|
493
|
+
const out = [];
|
|
494
|
+
for (const key of keys) {
|
|
495
|
+
const g = config.goals.find((d) => d.key === key);
|
|
496
|
+
out.push(g ? { key, type: g.type, ...g.event ? { event: g.event } : {}, ...g.type === "pageview" && g.path ? { path: g.path } : {} } : { key, type: "event" });
|
|
497
|
+
}
|
|
498
|
+
return out;
|
|
499
|
+
}
|
|
500
|
+
function pathOf(url) {
|
|
501
|
+
let path = url;
|
|
502
|
+
if (/^https?:\/\//i.test(url)) {
|
|
503
|
+
try {
|
|
504
|
+
path = new URL(url).pathname;
|
|
505
|
+
} catch {
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
return path.split(/[?#]/)[0] || "/";
|
|
509
|
+
}
|
|
510
|
+
function goalsFromAnalytics(events, goals) {
|
|
511
|
+
if (goals.length === 0) return [];
|
|
512
|
+
const sent = events.filter((e) => e.type === "goal");
|
|
513
|
+
const alreadySent = (key, e) => sent.some((g) => g.goal === key && g.visitorId === e.visitorId && Math.abs(g.ts - e.ts) <= SAME_ACTION_MS);
|
|
514
|
+
const out = [];
|
|
515
|
+
for (const e of events) {
|
|
516
|
+
let keys = [];
|
|
517
|
+
if (e.type === "event" && e.goal) {
|
|
518
|
+
const key = goalKeyFor(goals, e.goal);
|
|
519
|
+
if (key && goals.some((g) => g.key === key)) keys = [key];
|
|
520
|
+
} else if (e.type === "page" && e.url) {
|
|
521
|
+
const path = pathOf(e.url);
|
|
522
|
+
keys = goals.filter((g) => g.type === "pageview" && g.path && matchPath(g.path, path)).map((g) => g.key);
|
|
523
|
+
}
|
|
524
|
+
keys.forEach((key, i) => {
|
|
525
|
+
if (alreadySent(key, e)) return;
|
|
526
|
+
out.push({ ...e, id: `${e.id.slice(0, 60)}-g${i}`, type: "goal", experiment: null, variant: null, goal: key, props: e.type === "event" ? e.props : null, derived: true });
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
return out;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// src/handler.ts
|
|
533
|
+
var isBotUserAgent = (ua) => isCrawler(ua);
|
|
534
|
+
var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
|
|
535
|
+
function createSplitHubHandler(options) {
|
|
536
|
+
const { config, store } = options;
|
|
537
|
+
const derivable = experimentGoals(config);
|
|
538
|
+
const corsHeaders = (request) => {
|
|
539
|
+
if (!options.cors) return {};
|
|
540
|
+
const origin = request.headers.get("origin") ?? "";
|
|
541
|
+
const allowed = options.cors === "*" ? "*" : options.cors.includes(origin) ? origin : "";
|
|
542
|
+
if (!allowed) return {};
|
|
543
|
+
return {
|
|
544
|
+
"access-control-allow-origin": allowed,
|
|
545
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
546
|
+
"access-control-allow-headers": "content-type, authorization",
|
|
547
|
+
"access-control-max-age": "86400"
|
|
548
|
+
};
|
|
549
|
+
};
|
|
550
|
+
const json = (request, body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...corsHeaders(request) } });
|
|
551
|
+
const authorized = (request) => {
|
|
552
|
+
if (!options.adminToken) return true;
|
|
553
|
+
const header = request.headers.get("authorization") ?? "";
|
|
554
|
+
return header === `Bearer ${options.adminToken}`;
|
|
555
|
+
};
|
|
556
|
+
return async (request) => {
|
|
557
|
+
const url = new URL(request.url);
|
|
558
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
559
|
+
const tail = path.split("/").slice(-2);
|
|
560
|
+
if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(request) });
|
|
561
|
+
if (request.method === "POST") {
|
|
562
|
+
let body;
|
|
563
|
+
try {
|
|
564
|
+
body = await request.json();
|
|
565
|
+
} catch {
|
|
566
|
+
return json(request, { error: "invalid JSON" }, 400);
|
|
567
|
+
}
|
|
568
|
+
const result = validateBatch(body, config.project);
|
|
569
|
+
if (!result.ok) return json(request, { error: result.error }, 400);
|
|
570
|
+
const dropped = result.dropped ? { dropped: result.dropped, errors: result.errors } : {};
|
|
571
|
+
const received = result.events.length + result.dropped;
|
|
572
|
+
if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received, inserted: 0, ...dropped }, 202);
|
|
573
|
+
const running = new Set((config.properties ?? []).filter((p) => p.status === "running").map((p) => p.key));
|
|
574
|
+
const derived = goalsFromAnalytics(result.events, derivable).map(({ derived: _, ...goal2 }) => goal2);
|
|
575
|
+
const events = [...result.events.filter((e) => !ANALYTICS_TYPES.has(e.type) || e.experiment !== null && running.has(e.experiment)), ...derived];
|
|
576
|
+
const inserted = events.length ? await store.insertEvents(events) : 0;
|
|
577
|
+
return json(request, { ok: true, received, inserted, ...dropped }, 202);
|
|
578
|
+
}
|
|
579
|
+
if (request.method === "GET") {
|
|
580
|
+
if (tail[1] === "health") return json(request, { ok: true, project: config.project });
|
|
581
|
+
if (!authorized(request)) return json(request, { error: "unauthorized" }, 401);
|
|
582
|
+
if (tail[1] === "status") return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });
|
|
583
|
+
const segments = path.split("/");
|
|
584
|
+
const at = segments.lastIndexOf("properties");
|
|
585
|
+
if (at >= 0 && segments.length - at <= 3) {
|
|
586
|
+
const [key, sub] = [segments[at + 1], segments[at + 2]];
|
|
587
|
+
const span = { days: Number(url.searchParams.get("days") ?? 30) || 30, from: url.searchParams.get("from"), to: url.searchParams.get("to") };
|
|
588
|
+
const bad = rawPropertyRange(span);
|
|
589
|
+
if (typeof bad === "string") return json(request, { error: bad, code: "invalid_range", hint: "Send from and to as days like 2026-10-01 (UTC), from on or before to." }, 400);
|
|
590
|
+
if (!key) {
|
|
591
|
+
const list = await Promise.all((config.properties ?? []).map((p) => rawPropertyReport(config, store, p.key, span)));
|
|
592
|
+
return json(request, { properties: list.filter(Boolean) });
|
|
593
|
+
}
|
|
594
|
+
if (sub === "events") {
|
|
595
|
+
if (!store.propertyEvents) return json(request, { error: "this store keeps no raw property events", code: "not_implemented" }, 501);
|
|
596
|
+
const before = Number(url.searchParams.get("before")) || Date.now() + 1;
|
|
597
|
+
const limit = Math.max(1, Math.min(500, Number(url.searchParams.get("limit")) || 100));
|
|
598
|
+
return json(request, { property: key, events: await store.propertyEvents(key, { before, limit }) });
|
|
599
|
+
}
|
|
600
|
+
if (sub === void 0) {
|
|
601
|
+
const r = await rawPropertyReport(config, store, key, span);
|
|
602
|
+
return r ? json(request, r) : json(request, { error: `unknown property "${key}"` }, 404);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (tail[0] === "results" && tail[1]) {
|
|
606
|
+
const r = await rawResults(config, store, tail[1]);
|
|
607
|
+
return r ? json(request, r) : json(request, { error: `unknown experiment "${tail[1]}"` }, 404);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return json(request, { error: "not found" }, 404);
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
// src/nodeAdapter.ts
|
|
615
|
+
function toNodeListener(handler) {
|
|
616
|
+
return (req, res) => {
|
|
617
|
+
void (async () => {
|
|
618
|
+
try {
|
|
619
|
+
const request = await toRequest(req);
|
|
620
|
+
const response = await handler(request);
|
|
621
|
+
res.statusCode = response.status;
|
|
622
|
+
response.headers.forEach((value, key) => res.setHeader(key, value));
|
|
623
|
+
const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;
|
|
624
|
+
res.end(body);
|
|
625
|
+
} catch (error) {
|
|
626
|
+
res.statusCode = 500;
|
|
627
|
+
res.setHeader("content-type", "application/json");
|
|
628
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : "internal error" }));
|
|
629
|
+
}
|
|
630
|
+
})();
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
async function toRequest(req) {
|
|
634
|
+
const host = req.headers.host ?? "localhost";
|
|
635
|
+
const proto = req.headers["x-forwarded-proto"] ?? "http";
|
|
636
|
+
const rawUrl = req.originalUrl ?? req.url ?? "/";
|
|
637
|
+
const url = new URL(rawUrl, `${proto}://${host}`);
|
|
638
|
+
const headers = new Headers();
|
|
639
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
640
|
+
if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
|
|
641
|
+
else if (typeof value === "string") headers.set(key, value);
|
|
642
|
+
}
|
|
643
|
+
const method = req.method ?? "GET";
|
|
644
|
+
let body;
|
|
645
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
646
|
+
const chunks = [];
|
|
647
|
+
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
648
|
+
const all = Buffer.concat(chunks);
|
|
649
|
+
const copy = new Uint8Array(all.byteLength);
|
|
650
|
+
copy.set(all);
|
|
651
|
+
body = copy.buffer;
|
|
652
|
+
}
|
|
653
|
+
return new Request(url, { method, headers, body });
|
|
654
|
+
}
|
|
655
|
+
|
|
377
656
|
// src/conformance.ts
|
|
378
657
|
var T = Date.UTC(2026, 0, 10, 12, 0, 0);
|
|
379
|
-
var
|
|
658
|
+
var DAY2 = 864e5;
|
|
380
659
|
var seq = 0;
|
|
381
660
|
function exposure(visitorId, variant, ts, experiment = "hero") {
|
|
382
661
|
seq++;
|
|
@@ -449,7 +728,7 @@ var attributionConformance = [
|
|
|
449
728
|
events: [
|
|
450
729
|
exposure("v1", "control", T),
|
|
451
730
|
...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal("v1", T + 1e3 + i, 1)),
|
|
452
|
-
...Array.from({ length: 3 }, (_, i) => goal("v1", T +
|
|
731
|
+
...Array.from({ length: 3 }, (_, i) => goal("v1", T + DAY2 + i, 1))
|
|
453
732
|
],
|
|
454
733
|
expected: [counts("control", 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)]
|
|
455
734
|
},
|
|
@@ -480,18 +759,29 @@ function sortCounts(rows) {
|
|
|
480
759
|
}
|
|
481
760
|
export {
|
|
482
761
|
ANALYSIS_UNAVAILABLE,
|
|
762
|
+
ANALYTICS_TYPES,
|
|
483
763
|
ATTRIBUTION_SKEW_MS,
|
|
484
764
|
GOAL_DAILY_CAP,
|
|
765
|
+
PROPERTY_REPORTS_UNAVAILABLE,
|
|
766
|
+
SAME_ACTION_MS,
|
|
485
767
|
attributeVariants,
|
|
486
768
|
attributionConformance,
|
|
769
|
+
countProperty,
|
|
487
770
|
countsFromRow,
|
|
488
771
|
createMemoryStore,
|
|
489
772
|
createSplitHubHandler,
|
|
773
|
+
experimentGoals,
|
|
774
|
+
goalsFromAnalytics,
|
|
775
|
+
propertyCountsFromRows,
|
|
776
|
+
propertyCountsSql,
|
|
777
|
+
rawPropertyRange,
|
|
778
|
+
rawPropertyReport,
|
|
490
779
|
rawResults,
|
|
491
780
|
rawStatusTable,
|
|
492
781
|
resultsExperiment,
|
|
493
782
|
revenueOf,
|
|
494
783
|
sortCounts,
|
|
784
|
+
storedEventFromRow,
|
|
495
785
|
toNodeListener,
|
|
496
786
|
validateBatch,
|
|
497
787
|
variantCountsSql
|