@splithub/node 0.3.0 → 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.js CHANGED
@@ -66,155 +66,128 @@ async function rawStatusTable(config, store) {
66
66
  });
67
67
  }
68
68
 
69
- // src/validate.ts
70
- import { HOLDOUT_KEY as HOLDOUT_KEY2 } from "@splithub/core";
71
- var ID = /^[a-z0-9_-]{8,64}$/i;
72
- var KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
73
- var MAX_EVENTS = 500;
74
- var MAX_PROPS_BYTES = 4096;
75
- var MAX_SKEW_MS = 7 * 24 * 60 * 60 * 1e3;
76
- function validateBatch(body, expectedProject, now = Date.now()) {
77
- if (!body || typeof body !== "object") return { ok: false, error: "body must be a JSON object" };
78
- const batch = body;
79
- if (typeof batch.project !== "string") return { ok: false, error: '"project" must be a string' };
80
- if (expectedProject !== null && batch.project !== expectedProject) return { ok: false, error: `unknown project "${batch.project}"` };
81
- if (!Array.isArray(batch.events)) return { ok: false, error: '"events" must be an array' };
82
- if (batch.events.length === 0) return { ok: true, events: [] };
83
- if (batch.events.length > MAX_EVENTS) return { ok: false, error: `too many events (max ${MAX_EVENTS})` };
84
- const out = [];
85
- for (const raw of batch.events) {
86
- const e = normalize(raw, now);
87
- if (typeof e === "string") return { ok: false, error: e };
88
- out.push(e);
89
- }
90
- return { ok: true, events: out };
91
- }
92
- function normalize(e, now) {
93
- if (!e || typeof e !== "object") return "event must be an object";
94
- if (typeof e.id !== "string" || !ID.test(e.id)) return "event.id is invalid";
95
- if (typeof e.vid !== "string" || e.vid.length === 0 || e.vid.length > 64) return "event.vid is invalid";
96
- if (typeof e.sid !== "string" || e.sid.length === 0 || e.sid.length > 64) return "event.sid is invalid";
97
- if (typeof e.ts !== "number" || !Number.isFinite(e.ts)) return "event.ts must be a number";
98
- const ts = Math.abs(e.ts - now) > MAX_SKEW_MS ? now : Math.round(e.ts);
99
- const url = typeof e.url === "string" ? e.url.slice(0, 512) : null;
100
- if (e.type === "exposure") {
101
- if (typeof e.exp !== "string" || !(KEY.test(e.exp) || e.exp === HOLDOUT_KEY2)) return "exposure.exp is invalid";
102
- if (typeof e.var !== "string" || !KEY.test(e.var)) return "exposure.var is invalid";
103
- 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 };
104
- }
105
- if (e.type === "goal") {
106
- if (typeof e.goal !== "string" || !KEY.test(e.goal)) return "goal.goal is invalid";
107
- let props = null;
108
- if (e.props !== void 0) {
109
- if (!e.props || typeof e.props !== "object" || Array.isArray(e.props)) return "goal.props must be an object";
110
- if (JSON.stringify(e.props).length > MAX_PROPS_BYTES) return "goal.props too large";
111
- props = e.props;
112
- }
113
- return { id: e.id, type: "goal", experiment: null, variant: null, goal: e.goal, visitorId: e.vid, sessionId: e.sid, ts, url, props, receivedAt: now };
114
- }
115
- return `unknown event type "${String(e.type)}"`;
116
- }
117
-
118
- // src/handler.ts
119
- var isBotUserAgent = (ua) => isCrawler(ua);
120
- var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
121
- function createSplitHubHandler(options) {
122
- const { config, store } = options;
123
- const corsHeaders = (request) => {
124
- if (!options.cors) return {};
125
- const origin = request.headers.get("origin") ?? "";
126
- const allowed = options.cors === "*" ? "*" : options.cors.includes(origin) ? origin : "";
127
- 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);
128
83
  return {
129
- "access-control-allow-origin": allowed,
130
- "access-control-allow-methods": "GET, POST, OPTIONS",
131
- "access-control-allow-headers": "content-type, authorization",
132
- "access-control-max-age": "86400"
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
+ })
133
90
  };
134
91
  };
135
- const json = (request, body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...corsHeaders(request) } });
136
- const authorized = (request) => {
137
- if (!options.adminToken) return true;
138
- const header = request.headers.get("authorization") ?? "";
139
- return header === `Bearer ${options.adminToken}`;
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")}`)
140
102
  };
141
- return async (request) => {
142
- const url = new URL(request.url);
143
- const path = url.pathname.replace(/\/+$/, "");
144
- const tail = path.split("/").slice(-2);
145
- if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(request) });
146
- if (request.method === "POST") {
147
- let body;
148
- try {
149
- body = await request.json();
150
- } catch {
151
- return json(request, { error: "invalid JSON" }, 400);
152
- }
153
- const result = validateBatch(body, config.project);
154
- if (!result.ok) return json(request, { error: result.error }, 400);
155
- if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received: result.events.length, inserted: 0 }, 202);
156
- const inserted = await store.insertEvents(result.events);
157
- return json(request, { ok: true, received: result.events.length, inserted }, 202);
158
- }
159
- if (request.method === "GET") {
160
- if (tail[1] === "health") return json(request, { ok: true, project: config.project });
161
- if (!authorized(request)) return json(request, { error: "unauthorized" }, 401);
162
- if (tail[1] === "status") return json(request, { project: config.project, experiments: await rawStatusTable(config, store), analysis: ANALYSIS_UNAVAILABLE });
163
- if (tail[0] === "results" && tail[1]) {
164
- const r = await rawResults(config, store, tail[1]);
165
- return r ? json(request, r) : json(request, { error: `unknown experiment "${tail[1]}"` }, 404);
166
- }
167
- }
168
- 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) }))
169
116
  };
170
117
  }
171
-
172
- // src/nodeAdapter.ts
173
- function toNodeListener(handler) {
174
- return (req, res) => {
175
- void (async () => {
176
- try {
177
- const request = await toRequest(req);
178
- const response = await handler(request);
179
- res.statusCode = response.status;
180
- response.headers.forEach((value, key) => res.setHeader(key, value));
181
- const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;
182
- res.end(body);
183
- } catch (error) {
184
- res.statusCode = 500;
185
- res.setHeader("content-type", "application/json");
186
- res.end(JSON.stringify({ error: error instanceof Error ? error.message : "internal error" }));
187
- }
188
- })();
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)
189
144
  };
190
145
  }
191
- async function toRequest(req) {
192
- const host = req.headers.host ?? "localhost";
193
- const proto = req.headers["x-forwarded-proto"] ?? "http";
194
- const rawUrl = req.originalUrl ?? req.url ?? "/";
195
- const url = new URL(rawUrl, `${proto}://${host}`);
196
- const headers = new Headers();
197
- for (const [key, value] of Object.entries(req.headers)) {
198
- if (Array.isArray(value)) value.forEach((v) => headers.append(key, v));
199
- else if (typeof value === "string") headers.set(key, value);
200
- }
201
- const method = req.method ?? "GET";
202
- let body;
203
- if (method !== "GET" && method !== "HEAD") {
204
- const chunks = [];
205
- for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
206
- const all = Buffer.concat(chunks);
207
- const copy = new Uint8Array(all.byteLength);
208
- copy.set(all);
209
- 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) } };
210
160
  }
211
- return new Request(url, { method, headers, body });
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
+ };
212
185
  }
213
186
 
214
187
  // src/attribution.ts
215
188
  var ATTRIBUTION_SKEW_MS = 6e4;
216
189
  var GOAL_DAILY_CAP = 50;
217
- var DAY_MS2 = 864e5;
190
+ var DAY_MS3 = 864e5;
218
191
  function revenueOf(props) {
219
192
  const v = props?.revenue;
220
193
  return typeof v === "number" && Number.isFinite(v) ? v : 0;
@@ -227,8 +200,8 @@ function attributeVariants(events, experiment, goal2) {
227
200
  if (e.experiment !== experiment || !e.variant) continue;
228
201
  const prev = first.get(e.visitorId);
229
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 });
230
- } else if (e.goal === goal2) {
231
- const key = `${e.visitorId}\0${e.ts - e.ts % DAY_MS2}`;
203
+ } else if (e.type === "goal" && e.goal === goal2) {
204
+ const key = `${e.visitorId}\0${e.ts - e.ts % DAY_MS3}`;
232
205
  const list = goals.get(key) ?? [];
233
206
  list.push(e);
234
207
  goals.set(key, list);
@@ -266,7 +239,7 @@ function attributeVariants(events, experiment, goal2) {
266
239
  }
267
240
  return [...out.values()];
268
241
  }
269
- var IDENT = /^[a-z_][a-z0-9_]*$/i;
242
+ var IDENT2 = /^[a-z_][a-z0-9_]*$/i;
270
243
  function revenueExpr(dialect, alias) {
271
244
  if (dialect === "postgres") return `CASE WHEN jsonb_typeof(${alias}.props::jsonb -> 'revenue') = 'number' THEN (${alias}.props::jsonb ->> 'revenue')::float8 ELSE 0 END`;
272
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`;
@@ -275,8 +248,8 @@ function revenueExpr(dialect, alias) {
275
248
  function variantCountsSql(options) {
276
249
  const { dialect } = options;
277
250
  const t = options.table ?? "splithub_events";
278
- if (!IDENT.test(t)) throw new Error("[splithub] invalid table name");
279
- if (options.projectColumn !== void 0 && !IDENT.test(options.projectColumn)) throw new Error("[splithub] invalid column name");
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");
280
253
  const params = [];
281
254
  const p = (name) => {
282
255
  if (dialect === "postgres") {
@@ -297,7 +270,7 @@ function variantCountsSql(options) {
297
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}
298
271
  AND (SELECT COUNT(*) FROM ${t} g2
299
272
  WHERE ${proj("g2")}g2.type = 'goal' AND g2.goal = g.goal AND g2.visitor_id = g.visitor_id
300
- AND g2.ts >= g.ts - (g.ts % ${DAY_MS2}) AND (g2.ts < g.ts OR (g2.ts = g.ts AND g2.id < g.id))) < ${GOAL_DAILY_CAP}`;
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}`;
301
274
  const sql = `SELECT v.variant AS variant, COUNT(*) AS exposures, SUM(v.converted) AS conversions,
302
275
  COALESCE(SUM(v.revenue), 0) AS revenue_sum, COALESCE(SUM(v.revenue * v.revenue), 0) AS revenue_sum_sq
303
276
  FROM (
@@ -334,6 +307,34 @@ function countsFromRow(row) {
334
307
  }
335
308
 
336
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
+ }
337
338
  function createMemoryStore() {
338
339
  const events = [];
339
340
  const ids = /* @__PURE__ */ new Set();
@@ -352,6 +353,12 @@ function createMemoryStore() {
352
353
  async variantCounts(experiment, goal2) {
353
354
  return attributeVariants(events, experiment, goal2);
354
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
+ },
355
362
  async summaries() {
356
363
  const map = /* @__PURE__ */ new Map();
357
364
  for (const e of events) {
@@ -375,9 +382,280 @@ function createMemoryStore() {
375
382
  };
376
383
  }
377
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
+
378
656
  // src/conformance.ts
379
657
  var T = Date.UTC(2026, 0, 10, 12, 0, 0);
380
- var DAY = 864e5;
658
+ var DAY2 = 864e5;
381
659
  var seq = 0;
382
660
  function exposure(visitorId, variant, ts, experiment = "hero") {
383
661
  seq++;
@@ -450,7 +728,7 @@ var attributionConformance = [
450
728
  events: [
451
729
  exposure("v1", "control", T),
452
730
  ...Array.from({ length: GOAL_DAILY_CAP + 10 }, (_, i) => goal("v1", T + 1e3 + i, 1)),
453
- ...Array.from({ length: 3 }, (_, i) => goal("v1", T + DAY + i, 1))
731
+ ...Array.from({ length: 3 }, (_, i) => goal("v1", T + DAY2 + i, 1))
454
732
  ],
455
733
  expected: [counts("control", 1, 1, GOAL_DAILY_CAP + 3, (GOAL_DAILY_CAP + 3) ** 2)]
456
734
  },
@@ -481,18 +759,29 @@ function sortCounts(rows) {
481
759
  }
482
760
  export {
483
761
  ANALYSIS_UNAVAILABLE,
762
+ ANALYTICS_TYPES,
484
763
  ATTRIBUTION_SKEW_MS,
485
764
  GOAL_DAILY_CAP,
765
+ PROPERTY_REPORTS_UNAVAILABLE,
766
+ SAME_ACTION_MS,
486
767
  attributeVariants,
487
768
  attributionConformance,
769
+ countProperty,
488
770
  countsFromRow,
489
771
  createMemoryStore,
490
772
  createSplitHubHandler,
773
+ experimentGoals,
774
+ goalsFromAnalytics,
775
+ propertyCountsFromRows,
776
+ propertyCountsSql,
777
+ rawPropertyRange,
778
+ rawPropertyReport,
491
779
  rawResults,
492
780
  rawStatusTable,
493
781
  resultsExperiment,
494
782
  revenueOf,
495
783
  sortCounts,
784
+ storedEventFromRow,
496
785
  toNodeListener,
497
786
  validateBatch,
498
787
  variantCountsSql