@splithub/node 0.4.3 → 0.5.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.js CHANGED
@@ -140,7 +140,10 @@ function storedEventFromRow(r) {
140
140
  host: s(r.host),
141
141
  country: s(r.country),
142
142
  device: s(r.device),
143
- browser: s(r.browser)
143
+ browser: s(r.browser),
144
+ // Columns added for apps; rows of stores without them keep the old shape.
145
+ ..."platform" in r ? { platform: s(r.platform) } : {},
146
+ ..."app_version" in r ? { app_version: s(r.app_version) } : {}
144
147
  };
145
148
  }
146
149
  var PROPERTY_REPORTS_UNAVAILABLE = {
@@ -407,7 +410,33 @@ function validateBatch(body, expectedProject, now = Date.now()) {
407
410
  if (errors.length < 5 && !errors.includes(e)) errors.push(e);
408
411
  } else out.push(e);
409
412
  }
410
- return { ok: true, events: out, dropped, errors };
413
+ const app = sanitizeApp(batch.app);
414
+ return { ok: true, events: out, dropped, errors, ...app ? { app } : {} };
415
+ }
416
+ var APP_PLATFORMS = /* @__PURE__ */ new Set(["ios", "android", "macos", "windows", "linux"]);
417
+ var APP_DEVICES = /* @__PURE__ */ new Set(["mobile", "tablet", "desktop"]);
418
+ function text(value, max) {
419
+ if (typeof value !== "string") return void 0;
420
+ const t = value.trim();
421
+ return t ? t.slice(0, max) : void 0;
422
+ }
423
+ function sanitizeApp(raw) {
424
+ if (!raw || typeof raw !== "object") return void 0;
425
+ const a = raw;
426
+ if (typeof a.platform !== "string" || !APP_PLATFORMS.has(a.platform)) return void 0;
427
+ const out = { platform: a.platform };
428
+ const id = text(a.id, 128);
429
+ const version = text(a.version, 32);
430
+ const build = text(a.build, 32);
431
+ const os = text(a.os, 32);
432
+ const model = text(a.model, 64);
433
+ if (id) out.id = id.toLowerCase();
434
+ if (version) out.version = version;
435
+ if (build) out.build = build;
436
+ if (os) out.os = os;
437
+ if (model) out.model = model;
438
+ if (typeof a.device === "string" && APP_DEVICES.has(a.device)) out.device = a.device;
439
+ return out;
411
440
  }
412
441
  function normalize(e, now) {
413
442
  if (!e || typeof e !== "object") return "event must be an object";
@@ -529,9 +558,45 @@ function goalsFromAnalytics(events, goals) {
529
558
  return out;
530
559
  }
531
560
 
561
+ // src/app.ts
562
+ var APP_OS = { ios: "iOS", android: "Android", macos: "macOS", windows: "Windows", linux: "Linux" };
563
+ function appDimensions(app) {
564
+ if (!app) return { platform: "web", app_version: null };
565
+ return { platform: app.platform, app_version: app.version ?? null, device: app.device ?? "mobile", os: APP_OS[app.platform], browser: "App", host: app.id ?? null };
566
+ }
567
+ function withAppDimensions(events, app) {
568
+ const d = appDimensions(app);
569
+ return events.map((e) => ({ ...e, ...d, ...e.host ? { host: e.host } : {} }));
570
+ }
571
+
532
572
  // src/handler.ts
533
573
  var isBotUserAgent = (ua) => isCrawler(ua);
534
574
  var visitorUserAgent = (request) => request.headers.get("x-splithub-ua") ?? request.headers.get("user-agent");
575
+ var MAX_BODY_BYTES = 1024 * 1024;
576
+ async function readCapped(request, max) {
577
+ if (Number(request.headers.get("content-length") ?? 0) > max) return null;
578
+ if (!request.body) return "";
579
+ const reader = request.body.getReader();
580
+ const chunks = [];
581
+ let size = 0;
582
+ for (; ; ) {
583
+ const { done, value } = await reader.read();
584
+ if (done) break;
585
+ size += value.byteLength;
586
+ if (size > max) {
587
+ await reader.cancel().catch(() => void 0);
588
+ return null;
589
+ }
590
+ chunks.push(value);
591
+ }
592
+ const all = new Uint8Array(size);
593
+ let at = 0;
594
+ for (const c of chunks) {
595
+ all.set(c, at);
596
+ at += c.byteLength;
597
+ }
598
+ return new TextDecoder().decode(all);
599
+ }
535
600
  function createSplitHubHandler(options) {
536
601
  const { config, store } = options;
537
602
  const derivable = experimentGoals(config);
@@ -559,9 +624,11 @@ function createSplitHubHandler(options) {
559
624
  const tail = path.split("/").slice(-2);
560
625
  if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: corsHeaders(request) });
561
626
  if (request.method === "POST") {
627
+ const text2 = await readCapped(request, MAX_BODY_BYTES);
628
+ if (text2 === null) return json(request, { error: `body larger than ${MAX_BODY_BYTES} bytes` }, 413);
562
629
  let body;
563
630
  try {
564
- body = await request.json();
631
+ body = JSON.parse(text2);
565
632
  } catch {
566
633
  return json(request, { error: "invalid JSON" }, 400);
567
634
  }
@@ -571,8 +638,9 @@ function createSplitHubHandler(options) {
571
638
  const received = result.events.length + result.dropped;
572
639
  if (isBotUserAgent(visitorUserAgent(request))) return json(request, { ok: true, received, inserted: 0, ...dropped }, 202);
573
640
  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];
641
+ const stamped = withAppDimensions(result.events, result.app);
642
+ const derived = goalsFromAnalytics(stamped, derivable).map(({ derived: _, ...goal2 }) => goal2);
643
+ const events = [...stamped.filter((e) => !ANALYTICS_TYPES.has(e.type) || e.experiment !== null && running.has(e.experiment)), ...derived];
576
644
  const inserted = events.length ? await store.insertEvents(events) : 0;
577
645
  return json(request, { ok: true, received, inserted, ...dropped }, 202);
578
646
  }
@@ -612,6 +680,8 @@ function createSplitHubHandler(options) {
612
680
  }
613
681
 
614
682
  // src/nodeAdapter.ts
683
+ var BodyTooLarge = class extends Error {
684
+ };
615
685
  function toNodeListener(handler) {
616
686
  return (req, res) => {
617
687
  void (async () => {
@@ -623,9 +693,12 @@ function toNodeListener(handler) {
623
693
  const body = response.body ? Buffer.from(await response.arrayBuffer()) : null;
624
694
  res.end(body);
625
695
  } catch (error) {
626
- res.statusCode = 500;
696
+ const tooLarge = error instanceof BodyTooLarge;
697
+ res.statusCode = tooLarge ? 413 : 500;
627
698
  res.setHeader("content-type", "application/json");
628
- res.end(JSON.stringify({ error: error instanceof Error ? error.message : "internal error" }));
699
+ if (tooLarge) res.setHeader("connection", "close");
700
+ res.end(JSON.stringify({ error: tooLarge ? `body larger than ${MAX_BODY_BYTES} bytes` : error instanceof Error ? error.message : "internal error" }));
701
+ if (tooLarge) req.destroy();
629
702
  }
630
703
  })();
631
704
  };
@@ -643,11 +716,21 @@ async function toRequest(req) {
643
716
  const method = req.method ?? "GET";
644
717
  let body;
645
718
  if (method !== "GET" && method !== "HEAD") {
719
+ if (Number(req.headers["content-length"] ?? 0) > MAX_BODY_BYTES) throw new BodyTooLarge();
646
720
  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);
721
+ let size = 0;
722
+ for await (const chunk of req) {
723
+ const b = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
724
+ size += b.byteLength;
725
+ if (size > MAX_BODY_BYTES) throw new BodyTooLarge();
726
+ chunks.push(b);
727
+ }
728
+ const copy = new Uint8Array(size);
729
+ let at = 0;
730
+ for (const c of chunks) {
731
+ copy.set(c, at);
732
+ at += c.byteLength;
733
+ }
651
734
  body = copy.buffer;
652
735
  }
653
736
  return new Request(url, { method, headers, body });
@@ -762,8 +845,10 @@ export {
762
845
  ANALYTICS_TYPES,
763
846
  ATTRIBUTION_SKEW_MS,
764
847
  GOAL_DAILY_CAP,
848
+ MAX_BODY_BYTES,
765
849
  PROPERTY_REPORTS_UNAVAILABLE,
766
850
  SAME_ACTION_MS,
851
+ appDimensions,
767
852
  attributeVariants,
768
853
  attributionConformance,
769
854
  countProperty,
@@ -780,10 +865,12 @@ export {
780
865
  rawStatusTable,
781
866
  resultsExperiment,
782
867
  revenueOf,
868
+ sanitizeApp,
783
869
  sortCounts,
784
870
  storedEventFromRow,
785
871
  toNodeListener,
786
872
  validateBatch,
787
- variantCountsSql
873
+ variantCountsSql,
874
+ withAppDimensions
788
875
  };
789
876
  //# sourceMappingURL=index.js.map