@splithub/node 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +444 -144
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +142 -5
- package/dist/index.d.ts +142 -5
- package/dist/index.js +432 -143
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -21,18 +21,29 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
ANALYSIS_UNAVAILABLE: () => ANALYSIS_UNAVAILABLE,
|
|
24
|
+
ANALYTICS_TYPES: () => ANALYTICS_TYPES,
|
|
24
25
|
ATTRIBUTION_SKEW_MS: () => ATTRIBUTION_SKEW_MS,
|
|
25
26
|
GOAL_DAILY_CAP: () => GOAL_DAILY_CAP,
|
|
27
|
+
PROPERTY_REPORTS_UNAVAILABLE: () => PROPERTY_REPORTS_UNAVAILABLE,
|
|
28
|
+
SAME_ACTION_MS: () => SAME_ACTION_MS,
|
|
26
29
|
attributeVariants: () => attributeVariants,
|
|
27
30
|
attributionConformance: () => attributionConformance,
|
|
31
|
+
countProperty: () => countProperty,
|
|
28
32
|
countsFromRow: () => countsFromRow,
|
|
29
33
|
createMemoryStore: () => createMemoryStore,
|
|
30
34
|
createSplitHubHandler: () => createSplitHubHandler,
|
|
35
|
+
experimentGoals: () => experimentGoals,
|
|
36
|
+
goalsFromAnalytics: () => goalsFromAnalytics,
|
|
37
|
+
propertyCountsFromRows: () => propertyCountsFromRows,
|
|
38
|
+
propertyCountsSql: () => propertyCountsSql,
|
|
39
|
+
rawPropertyRange: () => rawPropertyRange,
|
|
40
|
+
rawPropertyReport: () => rawPropertyReport,
|
|
31
41
|
rawResults: () => rawResults,
|
|
32
42
|
rawStatusTable: () => rawStatusTable,
|
|
33
43
|
resultsExperiment: () => resultsExperiment,
|
|
34
44
|
revenueOf: () => revenueOf,
|
|
35
45
|
sortCounts: () => sortCounts,
|
|
46
|
+
storedEventFromRow: () => storedEventFromRow,
|
|
36
47
|
toNodeListener: () => toNodeListener,
|
|
37
48
|
validateBatch: () => validateBatch,
|
|
38
49
|
variantCountsSql: () => variantCountsSql
|
|
@@ -40,7 +51,7 @@ __export(index_exports, {
|
|
|
40
51
|
module.exports = __toCommonJS(index_exports);
|
|
41
52
|
|
|
42
53
|
// src/handler.ts
|
|
43
|
-
var
|
|
54
|
+
var import_core4 = require("@splithub/core");
|
|
44
55
|
|
|
45
56
|
// src/raw.ts
|
|
46
57
|
var import_core = require("@splithub/core");
|
|
@@ -107,155 +118,128 @@ async function rawStatusTable(config, store) {
|
|
|
107
118
|
});
|
|
108
119
|
}
|
|
109
120
|
|
|
110
|
-
// src/
|
|
111
|
-
var
|
|
112
|
-
var
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };
|
|
125
|
-
const out = [];
|
|
126
|
-
for (const raw of batch.events) {
|
|
127
|
-
const e = normalize(raw, now);
|
|
128
|
-
if (typeof e === "string") return { ok: false, error: e };
|
|
129
|
-
out.push(e);
|
|
130
|
-
}
|
|
131
|
-
return { ok: true, events: out };
|
|
132
|
-
}
|
|
133
|
-
function normalize(e, now) {
|
|
134
|
-
if (!e || typeof e !== "object") return "event must be an object";
|
|
135
|
-
if (typeof e.id !== "string" || !ID.test(e.id)) return "event.id is invalid";
|
|
136
|
-
if (typeof e.vid !== "string" || e.vid.length === 0 || e.vid.length > 64) return "event.vid is invalid";
|
|
137
|
-
if (typeof e.sid !== "string" || e.sid.length === 0 || e.sid.length > 64) return "event.sid is invalid";
|
|
138
|
-
if (typeof e.ts !== "number" || !Number.isFinite(e.ts)) return "event.ts must be a number";
|
|
139
|
-
const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);
|
|
140
|
-
const url = typeof e.url === "string" ? e.url.slice(0, 512) : null;
|
|
141
|
-
if (e.type === "exposure") {
|
|
142
|
-
if (typeof e.exp !== "string" || !(KEY.test(e.exp) || e.exp === import_core2.HOLDOUT_KEY)) return "exposure.exp is invalid";
|
|
143
|
-
if (typeof e.var !== "string" || !KEY.test(e.var)) return "exposure.var is invalid";
|
|
144
|
-
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 };
|
|
145
|
-
}
|
|
146
|
-
if (e.type === "goal") {
|
|
147
|
-
if (typeof e.goal !== "string" || !KEY.test(e.goal)) return "goal.goal is invalid";
|
|
148
|
-
let props = null;
|
|
149
|
-
if (e.props !== void 0) {
|
|
150
|
-
if (!e.props || typeof e.props !== "object" || Array.isArray(e.props)) return "goal.props must be an object";
|
|
151
|
-
if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return "goal.props too large";
|
|
152
|
-
props = e.props;
|
|
153
|
-
}
|
|
154
|
-
return { id: e.id, type: "goal", experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };
|
|
155
|
-
}
|
|
156
|
-
return `unknown event type "${String(e.type)}"`;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
// src/handler.ts
|
|
160
|
-
var isBotUserAgent = (ua) => (0, import_core3.isCrawler)(ua);
|
|
161
|
-
var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
|
|
162
|
-
function createSplitHubHandler(options) {
|
|
163
|
-
const { config, store } = options;
|
|
164
|
-
const corsHeaders = (request) => {
|
|
165
|
-
if (!options.cors) return {};
|
|
166
|
-
const origin = request.headers.get("origin") ?? "";
|
|
167
|
-
const allowed = options.cors === "*" ? "*" : options.cors.includes(origin) ? origin : "";
|
|
168
|
-
if (!allowed) return {};
|
|
121
|
+
// src/analytics.ts
|
|
122
|
+
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
123
|
+
var DAY_MS2 = 864e5;
|
|
124
|
+
function propertyCountsSql(options) {
|
|
125
|
+
const t = options.table ?? "splithub_events";
|
|
126
|
+
if (!IDENT.test(t)) throw new Error("[splithub] invalid table name");
|
|
127
|
+
if (options.projectColumn !== void 0 && !IDENT.test(options.projectColumn)) throw new Error("[splithub] invalid column name");
|
|
128
|
+
const build = (parts) => {
|
|
129
|
+
const params = [];
|
|
130
|
+
const p = (name) => {
|
|
131
|
+
params.push(name);
|
|
132
|
+
return options.dialect === "postgres" ? `$${params.length}` : "?";
|
|
133
|
+
};
|
|
134
|
+
const sql = parts(p);
|
|
169
135
|
return {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
136
|
+
sql,
|
|
137
|
+
bind: (values) => params.map((name) => {
|
|
138
|
+
const v = name === "until" && values.until === void 0 ? Number.MAX_SAFE_INTEGER : values[name];
|
|
139
|
+
if (v === void 0) throw new Error(`[splithub] missing "${name}" for the property query`);
|
|
140
|
+
return v;
|
|
141
|
+
})
|
|
174
142
|
};
|
|
175
143
|
};
|
|
176
|
-
const
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
144
|
+
const scope = (p, types) => `${options.projectColumn ? `${options.projectColumn} = ${p("project")} AND ` : ""}type IN (${types}) AND experiment = ${p("property")}`;
|
|
145
|
+
const seen = `type IN ('page', 'event')`;
|
|
146
|
+
return {
|
|
147
|
+
totals: build(
|
|
148
|
+
(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")}`
|
|
149
|
+
),
|
|
150
|
+
events: build(
|
|
151
|
+
(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`
|
|
152
|
+
),
|
|
153
|
+
rows: build((p) => `SELECT * FROM ${t} WHERE ${scope(p, `'page', 'event', 'engage', 'identify'`)} AND ts < ${p("before")} ORDER BY ts DESC LIMIT ${p("limit")}`)
|
|
181
154
|
};
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
if (!result.ok) return json(request, { error: result.error }, 400);
|
|
196
|
-
if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);
|
|
197
|
-
const inserted = await store.insertEvents(result.events);
|
|
198
|
-
return json(request, { ok: true, received: result.events.length, inserted }, 202);
|
|
199
|
-
}
|
|
200
|
-
if (request.method === "GET") {
|
|
201
|
-
if (tail[1] === "health") return json(request, { ok: true, project: config.project });
|
|
202
|
-
if (!authorized(request)) return json(request, { error: "unauthorized" }, 401);
|
|
203
|
-
if (tail[1] === "status") return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });
|
|
204
|
-
if (tail[0] === "results" && tail[1]) {
|
|
205
|
-
const r = await rawResults(config, store, tail[1]);
|
|
206
|
-
return r ? json(request, r) : json(request, { error: `unknown experiment "${tail[1]}"` }, 404);
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
return json(request, { error: "not found" }, 404);
|
|
155
|
+
}
|
|
156
|
+
function uidExpr(dialect) {
|
|
157
|
+
if (dialect === "postgres") return `(props::jsonb ->> 'uid')`;
|
|
158
|
+
if (dialect === "mysql") return `JSON_UNQUOTE(JSON_EXTRACT(props, '$.uid'))`;
|
|
159
|
+
return `json_extract(props, '$.uid')`;
|
|
160
|
+
}
|
|
161
|
+
function propertyCountsFromRows(totals, events) {
|
|
162
|
+
return {
|
|
163
|
+
pageviews: Number(totals?.pageviews ?? 0),
|
|
164
|
+
visitors: Number(totals?.visitors ?? 0),
|
|
165
|
+
sessions: Number(totals?.sessions ?? 0),
|
|
166
|
+
users: Number(totals?.users ?? 0),
|
|
167
|
+
events: events.map((r) => ({ name: String(r.name), count: Number(r.count ?? 0), visitors: Number(r.visitors ?? 0) }))
|
|
210
168
|
};
|
|
211
169
|
}
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
170
|
+
function storedEventFromRow(r) {
|
|
171
|
+
let props = null;
|
|
172
|
+
if (typeof r.props === "string") {
|
|
173
|
+
try {
|
|
174
|
+
props = JSON.parse(r.props);
|
|
175
|
+
} catch {
|
|
176
|
+
props = null;
|
|
177
|
+
}
|
|
178
|
+
} else if (r.props && typeof r.props === "object") props = r.props;
|
|
179
|
+
const s = (v) => v === null || v === void 0 ? null : String(v);
|
|
180
|
+
return {
|
|
181
|
+
id: String(r.id),
|
|
182
|
+
type: String(r.type),
|
|
183
|
+
experiment: s(r.experiment),
|
|
184
|
+
variant: s(r.variant),
|
|
185
|
+
goal: s(r.goal),
|
|
186
|
+
visitorId: String(r.visitor_id),
|
|
187
|
+
sessionId: String(r.session_id),
|
|
188
|
+
ts: Number(r.ts),
|
|
189
|
+
url: s(r.url),
|
|
190
|
+
props,
|
|
191
|
+
receivedAt: Number(r.received_at ?? r.ts),
|
|
192
|
+
host: s(r.host),
|
|
193
|
+
country: s(r.country),
|
|
194
|
+
device: s(r.device),
|
|
195
|
+
browser: s(r.browser)
|
|
230
196
|
};
|
|
231
197
|
}
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
247
|
-
const all = Buffer.concat(chunks);
|
|
248
|
-
const copy = new Uint8Array(all.byteLength);
|
|
249
|
-
copy.set(all);
|
|
250
|
-
body = copy.buffer;
|
|
198
|
+
var PROPERTY_REPORTS_UNAVAILABLE = {
|
|
199
|
+
...ANALYSIS_UNAVAILABLE,
|
|
200
|
+
message: "Reports with pages, sources, sessions and conversions come with SplitHub Cloud."
|
|
201
|
+
};
|
|
202
|
+
var DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
203
|
+
var dayOf = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
204
|
+
function rawPropertyRange(options) {
|
|
205
|
+
const now = options.now ?? Date.now();
|
|
206
|
+
const { from, to } = options;
|
|
207
|
+
if (from && !DAY.test(from) || to && !DAY.test(to)) return "from and to are days like 2026-10-01";
|
|
208
|
+
if (!from && !to) {
|
|
209
|
+
const days2 = Math.max(1, Math.min(365, Math.floor(options.days ?? 30)));
|
|
210
|
+
const since2 = now - days2 * DAY_MS2;
|
|
211
|
+
return { since: since2, until: now + 1, days: days2, range: { from: dayOf(since2), to: dayOf(now) } };
|
|
251
212
|
}
|
|
252
|
-
|
|
213
|
+
const end = to ? Date.parse(`${to}T00:00:00Z`) + DAY_MS2 : now + 1;
|
|
214
|
+
const since = from ? Date.parse(`${from}T00:00:00Z`) : end - 30 * DAY_MS2;
|
|
215
|
+
if (Number.isNaN(since) || Number.isNaN(end)) return "from and to are days like 2026-10-01";
|
|
216
|
+
if (since >= end) return "from must be on or before to";
|
|
217
|
+
const days = Math.ceil((end - since) / DAY_MS2);
|
|
218
|
+
if (days > 400) return "a range covers at most 400 days";
|
|
219
|
+
return { since, until: end, days, range: { from: dayOf(since), to: dayOf(end - 1) } };
|
|
220
|
+
}
|
|
221
|
+
async function rawPropertyReport(config, store, key, options = {}) {
|
|
222
|
+
const property = (config.properties ?? []).find((p) => p.key === key);
|
|
223
|
+
if (!property) return null;
|
|
224
|
+
const span = rawPropertyRange(options);
|
|
225
|
+
if (typeof span === "string") throw new Error(`[splithub] ${span}`);
|
|
226
|
+
return {
|
|
227
|
+
property: key,
|
|
228
|
+
status: property.status,
|
|
229
|
+
name: property.name ?? null,
|
|
230
|
+
description: property.description,
|
|
231
|
+
goals: property.goals,
|
|
232
|
+
days: span.days,
|
|
233
|
+
range: span.range,
|
|
234
|
+
counts: store.propertyCounts ? await store.propertyCounts(key, span.since, span.until) : null,
|
|
235
|
+
analysis: PROPERTY_REPORTS_UNAVAILABLE
|
|
236
|
+
};
|
|
253
237
|
}
|
|
254
238
|
|
|
255
239
|
// src/attribution.ts
|
|
256
240
|
var ATTRIBUTION_SKEW_MS = 6e4;
|
|
257
241
|
var GOAL_DAILY_CAP = 50;
|
|
258
|
-
var
|
|
242
|
+
var DAY_MS3 = 864e5;
|
|
259
243
|
function revenueOf(props) {
|
|
260
244
|
const v = props?.revenue;
|
|
261
245
|
return typeof v === "number" && Number.isFinite(v) ? v : 0;
|
|
@@ -268,8 +252,8 @@ function attributeVariants(events, experiment, goal2) {
|
|
|
268
252
|
if (e.experiment !== experiment || !e.variant) continue;
|
|
269
253
|
const prev = first.get(e.visitorId);
|
|
270
254
|
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 });
|
|
271
|
-
} else if (e.goal === goal2) {
|
|
272
|
-
const key = `${e.visitorId}\0${e.ts - e.ts %
|
|
255
|
+
} else if (e.type === "goal" && e.goal === goal2) {
|
|
256
|
+
const key = `${e.visitorId}\0${e.ts - e.ts % DAY_MS3}`;
|
|
273
257
|
const list = goals.get(key) ?? [];
|
|
274
258
|
list.push(e);
|
|
275
259
|
goals.set(key, list);
|
|
@@ -307,7 +291,7 @@ function attributeVariants(events, experiment, goal2) {
|
|
|
307
291
|
}
|
|
308
292
|
return [...out.values()];
|
|
309
293
|
}
|
|
310
|
-
var
|
|
294
|
+
var IDENT2 = /^[a-z_][a-z0-9_]*$/i;
|
|
311
295
|
function revenueExpr(dialect, alias) {
|
|
312
296
|
if (dialect === "postgres") return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;
|
|
313
297
|
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`;
|
|
@@ -316,8 +300,8 @@ function revenueExpr(dialect, alias) {
|
|
|
316
300
|
function variantCountsSql(options) {
|
|
317
301
|
const { dialect } = options;
|
|
318
302
|
const t = options.table ?? "splithub_events";
|
|
319
|
-
if (!
|
|
320
|
-
if (options.projectColumn !== void 0 && !
|
|
303
|
+
if (!IDENT2.test(t)) throw new Error("[splithub] invalid table name");
|
|
304
|
+
if (options.projectColumn !== void 0 && !IDENT2.test(options.projectColumn)) throw new Error("[splithub] invalid column name");
|
|
321
305
|
const params = [];
|
|
322
306
|
const p = (name) => {
|
|
323
307
|
if (dialect === "postgres") {
|
|
@@ -338,7 +322,7 @@ function variantCountsSql(options) {
|
|
|
338
322
|
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}
|
|
339
323
|
AND (SELECT COUNT(*) FROM ${t} g2
|
|
340
324
|
WHERE ${proj("g2")}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id
|
|
341
|
-
AND g2.ts >= g.ts - (g.ts % ${
|
|
325
|
+
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}`;
|
|
342
326
|
const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,
|
|
343
327
|
COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq
|
|
344
328
|
FROM (
|
|
@@ -375,6 +359,34 @@ function countsFromRow(row) {
|
|
|
375
359
|
}
|
|
376
360
|
|
|
377
361
|
// src/store.ts
|
|
362
|
+
var ANALYTICS_TYPES = /* @__PURE__ */ new Set(["page", "event", "engage", "identify"]);
|
|
363
|
+
function countProperty(events, property, since, until = Number.POSITIVE_INFINITY) {
|
|
364
|
+
let pageviews = 0;
|
|
365
|
+
const visitors = /* @__PURE__ */ new Set();
|
|
366
|
+
const sessions = /* @__PURE__ */ new Set();
|
|
367
|
+
const users = /* @__PURE__ */ new Set();
|
|
368
|
+
const byName = /* @__PURE__ */ new Map();
|
|
369
|
+
for (const e of events) {
|
|
370
|
+
if (!ANALYTICS_TYPES.has(e.type) || e.experiment !== property || e.ts < since || e.ts >= until) continue;
|
|
371
|
+
if (e.type === "identify") {
|
|
372
|
+
if (typeof e.props?.uid === "string") users.add(e.props.uid);
|
|
373
|
+
continue;
|
|
374
|
+
}
|
|
375
|
+
if (e.type === "engage") continue;
|
|
376
|
+
visitors.add(e.visitorId);
|
|
377
|
+
sessions.add(e.sessionId);
|
|
378
|
+
if (e.type === "page") pageviews++;
|
|
379
|
+
else if (e.goal) {
|
|
380
|
+
const n = byName.get(e.goal) ?? { count: 0, visitors: /* @__PURE__ */ new Set() };
|
|
381
|
+
n.count++;
|
|
382
|
+
n.visitors.add(e.visitorId);
|
|
383
|
+
byName.set(e.goal, n);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
const list = [...byName].map(([name, n]) => ({ name, count: n.count, visitors: n.visitors.size }));
|
|
387
|
+
list.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
|
|
388
|
+
return { pageviews, visitors: visitors.size, sessions: sessions.size, users: users.size, events: list };
|
|
389
|
+
}
|
|
378
390
|
function createMemoryStore() {
|
|
379
391
|
const events = [];
|
|
380
392
|
const ids = /* @__PURE__ */ new Set();
|
|
@@ -393,6 +405,12 @@ function createMemoryStore() {
|
|
|
393
405
|
async variantCounts(experiment, goal2) {
|
|
394
406
|
return attributeVariants(events, experiment, goal2);
|
|
395
407
|
},
|
|
408
|
+
async propertyCounts(property, since, until) {
|
|
409
|
+
return countProperty(events, property, since, until);
|
|
410
|
+
},
|
|
411
|
+
async propertyEvents(property, { before, limit }) {
|
|
412
|
+
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);
|
|
413
|
+
},
|
|
396
414
|
async summaries() {
|
|
397
415
|
const map = /* @__PURE__ */ new Map();
|
|
398
416
|
for (const e of events) {
|
|
@@ -416,9 +434,280 @@ function createMemoryStore() {
|
|
|
416
434
|
};
|
|
417
435
|
}
|
|
418
436
|
|
|
437
|
+
// src/validate.ts
|
|
438
|
+
var import_core2 = require("@splithub/core");
|
|
439
|
+
var ID = /^[a-z0-9_-]{8,64}$/i;
|
|
440
|
+
var KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
441
|
+
var MAX_EVENTS = 500;
|
|
442
|
+
var MAX_PROPS_BYTES = 4096;
|
|
443
|
+
var MAX_ENGAGE_MS = 36e5;
|
|
444
|
+
var MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
445
|
+
function validateBatch(body, expectedProject, now = Date.now()) {
|
|
446
|
+
if (!body || typeof body !== "object") return { ok: false, error: "body must be a JSON object" };
|
|
447
|
+
const batch = body;
|
|
448
|
+
if (typeof batch.project !== "string") return { ok: false, error: '"project" must be a string' };
|
|
449
|
+
if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project "${batch.project}"` };
|
|
450
|
+
if (!Array.isArray(batch.events)) return { ok: false, error: '"events" must be an array' };
|
|
451
|
+
if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };
|
|
452
|
+
const out = [];
|
|
453
|
+
const errors = [];
|
|
454
|
+
let dropped = 0;
|
|
455
|
+
for (const raw of batch.events) {
|
|
456
|
+
const e = normalize(raw, now);
|
|
457
|
+
if (typeof e === "string") {
|
|
458
|
+
dropped++;
|
|
459
|
+
if (errors.length < 5 && !errors.includes(e)) errors.push(e);
|
|
460
|
+
} else out.push(e);
|
|
461
|
+
}
|
|
462
|
+
return { ok: true, events: out, dropped, errors };
|
|
463
|
+
}
|
|
464
|
+
function normalize(e, now) {
|
|
465
|
+
if (!e || typeof e !== "object") return "event must be an object";
|
|
466
|
+
if (typeof e.id !== "string" || !ID.test(e.id)) return "event.id is invalid";
|
|
467
|
+
if (typeof e.vid !== "string" || e.vid.length === 0 || e.vid.length > 64) return "event.vid is invalid";
|
|
468
|
+
if (typeof e.sid !== "string" || e.sid.length === 0 || e.sid.length > 64) return "event.sid is invalid";
|
|
469
|
+
if (typeof e.ts !== "number" || !Number.isFinite(e.ts)) return "event.ts must be a number";
|
|
470
|
+
const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);
|
|
471
|
+
const url = "url" in e && typeof e.url === "string" ? e.url.slice(0, 512) : null;
|
|
472
|
+
const base = { id: e.id, visitorId: e.vid, sessionId: e.sid, ts, url, receivedAt: now };
|
|
473
|
+
if (e.type === "exposure") {
|
|
474
|
+
if (typeof e.exp !== "string" || !(KEY.test(e.exp) || e.exp === import_core2.HOLDOUT_KEY)) return "exposure.exp is invalid";
|
|
475
|
+
if (typeof e.var !== "string" || !KEY.test(e.var)) return "exposure.var is invalid";
|
|
476
|
+
const ref = typeof e.ref === "string" ? e.ref.slice(0, 300) : null;
|
|
477
|
+
return { ...base, type: "exposure", experiment: e.exp, variant: e.var, goal: null, props: ref === null ? null : { ref } };
|
|
478
|
+
}
|
|
479
|
+
if (e.type === "goal") {
|
|
480
|
+
if (typeof e.goal !== "string" || !KEY.test(e.goal)) return "goal.goal is invalid";
|
|
481
|
+
const props = propsOf(e.props, "goal");
|
|
482
|
+
if (typeof props === "string") return props;
|
|
483
|
+
return { ...base, type: "goal", experiment: null, variant: null, goal: e.goal, props };
|
|
484
|
+
}
|
|
485
|
+
const prop = "prop" in e && typeof e.prop === "string" ? e.prop.trim().toLowerCase() : null;
|
|
486
|
+
if (e.type === "page") {
|
|
487
|
+
if (!prop || !KEY.test(prop)) return "page.prop is invalid";
|
|
488
|
+
if (!url) return "page.url is required";
|
|
489
|
+
const title = typeof e.title === "string" && e.title ? e.title.slice(0, 200) : null;
|
|
490
|
+
const ref = typeof e.ref === "string" && e.ref ? e.ref.slice(0, 512) : null;
|
|
491
|
+
const props = title || ref ? { ...title ? { title } : {}, ...ref ? { ref } : {} } : null;
|
|
492
|
+
return { ...base, type: "page", experiment: prop, variant: null, goal: null, props };
|
|
493
|
+
}
|
|
494
|
+
if (e.type === "event") {
|
|
495
|
+
if (!prop || !KEY.test(prop)) return "event.prop is invalid";
|
|
496
|
+
if (typeof e.name !== "string" || !import_core2.EVENT_NAME_PATTERN.test(e.name)) return "event.name is invalid";
|
|
497
|
+
const props = propsOf(e.props, "event");
|
|
498
|
+
if (typeof props === "string") return props;
|
|
499
|
+
return { ...base, type: "event", experiment: prop, variant: null, goal: e.name, props };
|
|
500
|
+
}
|
|
501
|
+
if (e.type === "engage") {
|
|
502
|
+
if (!prop || !KEY.test(prop)) return "engage.prop is invalid";
|
|
503
|
+
if (!url) return "engage.url is required";
|
|
504
|
+
if (typeof e.ms !== "number" || !Number.isFinite(e.ms) || e.ms < 0) return "engage.ms must be a number of milliseconds";
|
|
505
|
+
if (typeof e.scroll !== "number" || !Number.isFinite(e.scroll) || e.scroll < 0) return "engage.scroll must be a percent";
|
|
506
|
+
const ms = Math.min(MAX_ENGAGE_MS, Math.round(e.ms));
|
|
507
|
+
const scroll = Math.min(100, Math.round(e.scroll));
|
|
508
|
+
return { ...base, type: "engage", experiment: prop, variant: null, goal: null, props: { ms, scroll } };
|
|
509
|
+
}
|
|
510
|
+
if (e.type === "identify") {
|
|
511
|
+
if (!prop || !KEY.test(prop)) return "identify.prop is invalid";
|
|
512
|
+
const uid = typeof e.uid === "string" ? e.uid.trim() : "";
|
|
513
|
+
if (!uid || uid.length > 128) return "identify.uid must be 1 to 128 characters";
|
|
514
|
+
const traits = traitsOf(e.traits);
|
|
515
|
+
if (typeof traits === "string") return traits;
|
|
516
|
+
return { ...base, type: "identify", experiment: prop, variant: null, goal: null, url: null, props: { uid, ...traits ? { traits } : {} } };
|
|
517
|
+
}
|
|
518
|
+
return `unknown event type "${String(e.type)}"`;
|
|
519
|
+
}
|
|
520
|
+
function propsOf(value, kind) {
|
|
521
|
+
if (value === void 0) return null;
|
|
522
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return `${kind}.props must be an object`;
|
|
523
|
+
if (JSON.stringify(value).length > MAX_PROPS_BYTES) return `${kind}.props too large`;
|
|
524
|
+
return value;
|
|
525
|
+
}
|
|
526
|
+
function traitsOf(value) {
|
|
527
|
+
if (value === void 0 || value === null) return null;
|
|
528
|
+
if (typeof value !== "object" || Array.isArray(value)) return "identify.traits must be an object";
|
|
529
|
+
const out = {};
|
|
530
|
+
for (const [k, v] of Object.entries(value)) {
|
|
531
|
+
if (typeof v === "string" || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v)) out[k] = v;
|
|
532
|
+
}
|
|
533
|
+
if (JSON.stringify(out).length > MAX_PROPS_BYTES) return "identify.traits too large";
|
|
534
|
+
return Object.keys(out).length ? out : null;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/derive.ts
|
|
538
|
+
var import_core3 = require("@splithub/core");
|
|
539
|
+
var SAME_ACTION_MS = 1e3;
|
|
540
|
+
function experimentGoals(config) {
|
|
541
|
+
const measured = (0, import_core3.measuredGoals)(config);
|
|
542
|
+
const keys = /* @__PURE__ */ new Set();
|
|
543
|
+
for (const key of Object.values(measured.goals)) if (key) keys.add(key);
|
|
544
|
+
for (const list of Object.values(measured.metrics)) for (const key of list) keys.add(key);
|
|
545
|
+
const out = [];
|
|
546
|
+
for (const key of keys) {
|
|
547
|
+
const g = config.goals.find((d) => d.key === key);
|
|
548
|
+
out.push(g ? { key, type: g.type, ...g.event ? { event: g.event } : {}, ...g.type === "pageview" && g.path ? { path: g.path } : {} } : { key, type: "event" });
|
|
549
|
+
}
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
function pathOf(url) {
|
|
553
|
+
let path = url;
|
|
554
|
+
if (/^https?:\/\//i.test(url)) {
|
|
555
|
+
try {
|
|
556
|
+
path = new URL(url).pathname;
|
|
557
|
+
} catch {
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
return path.split(/[?#]/)[0] || "/";
|
|
561
|
+
}
|
|
562
|
+
function goalsFromAnalytics(events, goals) {
|
|
563
|
+
if (goals.length === 0) return [];
|
|
564
|
+
const sent = events.filter((e) => e.type === "goal");
|
|
565
|
+
const alreadySent = (key, e) => sent.some((g) => g.goal === key && g.visitorId === e.visitorId && Math.abs(g.ts - e.ts) <= SAME_ACTION_MS);
|
|
566
|
+
const out = [];
|
|
567
|
+
for (const e of events) {
|
|
568
|
+
let keys = [];
|
|
569
|
+
if (e.type === "event" && e.goal) {
|
|
570
|
+
const key = (0, import_core3.goalKeyFor)(goals, e.goal);
|
|
571
|
+
if (key && goals.some((g) => g.key === key)) keys = [key];
|
|
572
|
+
} else if (e.type === "page" && e.url) {
|
|
573
|
+
const path = pathOf(e.url);
|
|
574
|
+
keys = goals.filter((g) => g.type === "pageview" && g.path && (0, import_core3.matchPath)(g.path, path)).map((g) => g.key);
|
|
575
|
+
}
|
|
576
|
+
keys.forEach((key, i) => {
|
|
577
|
+
if (alreadySent(key, e)) return;
|
|
578
|
+
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 });
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
return out;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// src/handler.ts
|
|
585
|
+
var isBotUserAgent = (ua) => (0, import_core4.isCrawler)(ua);
|
|
586
|
+
var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
|
|
587
|
+
function createSplitHubHandler(options) {
|
|
588
|
+
const { config, store } = options;
|
|
589
|
+
const derivable = experimentGoals(config);
|
|
590
|
+
const corsHeaders = (request) => {
|
|
591
|
+
if (!options.cors) return {};
|
|
592
|
+
const origin = request.headers.get("origin") ?? "";
|
|
593
|
+
const allowed = options.cors === "*" ? "*" : options.cors.includes(origin) ? origin : "";
|
|
594
|
+
if (!allowed) return {};
|
|
595
|
+
return {
|
|
596
|
+
"access-control-allow-origin": allowed,
|
|
597
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
598
|
+
"access-control-allow-headers": "content-type, authorization",
|
|
599
|
+
"access-control-max-age": "86400"
|
|
600
|
+
};
|
|
601
|
+
};
|
|
602
|
+
const json = (request, body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...corsHeaders(request) } });
|
|
603
|
+
const authorized = (request) => {
|
|
604
|
+
if (!options.adminToken) return true;
|
|
605
|
+
const header = request.headers.get("authorization") ?? "";
|
|
606
|
+
return header === `Bearer ${options.adminToken}`;
|
|
607
|
+
};
|
|
608
|
+
return async (request) => {
|
|
609
|
+
const url = new URL(request.url);
|
|
610
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
611
|
+
const tail = path.split("/").slice(-2);
|
|
612
|
+
if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(request) });
|
|
613
|
+
if (request.method === "POST") {
|
|
614
|
+
let body;
|
|
615
|
+
try {
|
|
616
|
+
body = await request.json();
|
|
617
|
+
} catch {
|
|
618
|
+
return json(request, { error: "invalid JSON" }, 400);
|
|
619
|
+
}
|
|
620
|
+
const result = validateBatch(body, config.project);
|
|
621
|
+
if (!result.ok) return json(request, { error: result.error }, 400);
|
|
622
|
+
const dropped = result.dropped ? { dropped: result.dropped, errors: result.errors } : {};
|
|
623
|
+
const received = result.events.length + result.dropped;
|
|
624
|
+
if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received, inserted: 0, ...dropped }, 202);
|
|
625
|
+
const running = new Set((config.properties ?? []).filter((p) => p.status === "running").map((p) => p.key));
|
|
626
|
+
const derived = goalsFromAnalytics(result.events, derivable).map(({ derived: _, ...goal2 }) => goal2);
|
|
627
|
+
const events = [...result.events.filter((e) => !ANALYTICS_TYPES.has(e.type) || e.experiment !== null && running.has(e.experiment)), ...derived];
|
|
628
|
+
const inserted = events.length ? await store.insertEvents(events) : 0;
|
|
629
|
+
return json(request, { ok: true, received, inserted, ...dropped }, 202);
|
|
630
|
+
}
|
|
631
|
+
if (request.method === "GET") {
|
|
632
|
+
if (tail[1] === "health") return json(request, { ok: true, project: config.project });
|
|
633
|
+
if (!authorized(request)) return json(request, { error: "unauthorized" }, 401);
|
|
634
|
+
if (tail[1] === "status") return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });
|
|
635
|
+
const segments = path.split("/");
|
|
636
|
+
const at = segments.lastIndexOf("properties");
|
|
637
|
+
if (at >= 0 && segments.length - at <= 3) {
|
|
638
|
+
const [key, sub] = [segments[at + 1], segments[at + 2]];
|
|
639
|
+
const span = { days: Number(url.searchParams.get("days") ?? 30) || 30, from: url.searchParams.get("from"), to: url.searchParams.get("to") };
|
|
640
|
+
const bad = rawPropertyRange(span);
|
|
641
|
+
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);
|
|
642
|
+
if (!key) {
|
|
643
|
+
const list = await Promise.all((config.properties ?? []).map((p) => rawPropertyReport(config, store, p.key, span)));
|
|
644
|
+
return json(request, { properties: list.filter(Boolean) });
|
|
645
|
+
}
|
|
646
|
+
if (sub === "events") {
|
|
647
|
+
if (!store.propertyEvents) return json(request, { error: "this store keeps no raw property events", code: "not_implemented" }, 501);
|
|
648
|
+
const before = Number(url.searchParams.get("before")) || Date.now() + 1;
|
|
649
|
+
const limit = Math.max(1, Math.min(500, Number(url.searchParams.get("limit")) || 100));
|
|
650
|
+
return json(request, { property: key, events: await store.propertyEvents(key, { before, limit }) });
|
|
651
|
+
}
|
|
652
|
+
if (sub === void 0) {
|
|
653
|
+
const r = await rawPropertyReport(config, store, key, span);
|
|
654
|
+
return r ? json(request, r) : json(request, { error: `unknown property "${key}"` }, 404);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (tail[0] === "results" && tail[1]) {
|
|
658
|
+
const r = await rawResults(config, store, tail[1]);
|
|
659
|
+
return r ? json(request, r) : json(request, { error: `unknown experiment "${tail[1]}"` }, 404);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return json(request, { error: "not found" }, 404);
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// src/nodeAdapter.ts
|
|
667
|
+
function toNodeListener(handler) {
|
|
668
|
+
return (req, res) => {
|
|
669
|
+
void (async () => {
|
|
670
|
+
try {
|
|
671
|
+
const request = await toRequest(req);
|
|
672
|
+
const response = await handler(request);
|
|
673
|
+
res.statusCode = response.status;
|
|
674
|
+
response.headers.forEach((value, key) => res.setHeader(key, value));
|
|
675
|
+
const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;
|
|
676
|
+
res.end(body);
|
|
677
|
+
} catch (error) {
|
|
678
|
+
res.statusCode = 500;
|
|
679
|
+
res.setHeader("content-type", "application/json");
|
|
680
|
+
res.end(JSON.stringify({ error: error instanceof Error ? error.message : "internal error" }));
|
|
681
|
+
}
|
|
682
|
+
})();
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
async function toRequest(req) {
|
|
686
|
+
const host = req.headers.host ?? "localhost";
|
|
687
|
+
const proto = req.headers["x-forwarded-proto"] ?? "http";
|
|
688
|
+
const rawUrl = req.originalUrl ?? req.url ?? "/";
|
|
689
|
+
const url = new URL(rawUrl, `${proto}://${host}`);
|
|
690
|
+
const headers = new Headers();
|
|
691
|
+
for (const [key, value] of Object.entries(req.headers)) {
|
|
692
|
+
if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
|
|
693
|
+
else if (typeof value === "string") headers.set(key, value);
|
|
694
|
+
}
|
|
695
|
+
const method = req.method ?? "GET";
|
|
696
|
+
let body;
|
|
697
|
+
if (method !== "GET" && method !== "HEAD") {
|
|
698
|
+
const chunks = [];
|
|
699
|
+
for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
700
|
+
const all = Buffer.concat(chunks);
|
|
701
|
+
const copy = new Uint8Array(all.byteLength);
|
|
702
|
+
copy.set(all);
|
|
703
|
+
body = copy.buffer;
|
|
704
|
+
}
|
|
705
|
+
return new Request(url, { method, headers, body });
|
|
706
|
+
}
|
|
707
|
+
|
|
419
708
|
// src/conformance.ts
|
|
420
709
|
var T = Date.UTC(2026, 0, 10, 12, 0, 0);
|
|
421
|
-
var
|
|
710
|
+
var DAY2 = 864e5;
|
|
422
711
|
var seq = 0;
|
|
423
712
|
function exposure(visitorId, variant, ts, experiment = "hero") {
|
|
424
713
|
seq++;
|
|
@@ -491,7 +780,7 @@ var attributionConformance = [
|
|
|
491
780
|
events: [
|
|
492
781
|
exposure("v1", "control", T),
|
|
493
782
|
...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal("v1", T + 1e3 + i, 1)),
|
|
494
|
-
...Array.from({ length: 3 }, (_, i) => goal("v1", T +
|
|
783
|
+
...Array.from({ length: 3 }, (_, i) => goal("v1", T + DAY2 + i, 1))
|
|
495
784
|
],
|
|
496
785
|
expected: [counts("control", 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)]
|
|
497
786
|
},
|
|
@@ -523,18 +812,29 @@ function sortCounts(rows) {
|
|
|
523
812
|
// Annotate the CommonJS export names for ESM import in node:
|
|
524
813
|
0 && (module.exports = {
|
|
525
814
|
ANALYSIS_UNAVAILABLE,
|
|
815
|
+
ANALYTICS_TYPES,
|
|
526
816
|
ATTRIBUTION_SKEW_MS,
|
|
527
817
|
GOAL_DAILY_CAP,
|
|
818
|
+
PROPERTY_REPORTS_UNAVAILABLE,
|
|
819
|
+
SAME_ACTION_MS,
|
|
528
820
|
attributeVariants,
|
|
529
821
|
attributionConformance,
|
|
822
|
+
countProperty,
|
|
530
823
|
countsFromRow,
|
|
531
824
|
createMemoryStore,
|
|
532
825
|
createSplitHubHandler,
|
|
826
|
+
experimentGoals,
|
|
827
|
+
goalsFromAnalytics,
|
|
828
|
+
propertyCountsFromRows,
|
|
829
|
+
propertyCountsSql,
|
|
830
|
+
rawPropertyRange,
|
|
831
|
+
rawPropertyReport,
|
|
533
832
|
rawResults,
|
|
534
833
|
rawStatusTable,
|
|
535
834
|
resultsExperiment,
|
|
536
835
|
revenueOf,
|
|
537
836
|
sortCounts,
|
|
837
|
+
storedEventFromRow,
|
|
538
838
|
toNodeListener,
|
|
539
839
|
validateBatch,
|
|
540
840
|
variantCountsSql
|