railyard/apps/insights-edge/test/vitals.test.mjs
caelum0x 3dca41bef0 feat(analytics): the analytics slot reaches product analytics; /s.js page speed; web view (QY1.2, A26, A18, I7, P-Y12)
Product analytics (A26, contract 5.3)
- Bridge: new signed route product_analytics {scribase_org_id, app, days?,
  with_server_key?} -> host, public key (the site key), first product event,
  web view; the server key only when asked, only to the Scribase control plane.
- sites answers analytics_host and analytics_key next to the page-tag values
  (nothing of the Insights path removed); insights answers
  first_product_event_at; the analytics proof falls back to
  first_product_event when no page-tag event came.
- lib/product-analytics.ts: one-app, viewer-scoped org tokens for every call;
  PRODUCT_ANALYTICS_PUBLIC_URL (default the SDK default host).
- PA: POST /v1/server/{app_id}/batch with Authorization: Bearer ry_pak_<hex>
  (HMAC of the app id under PRODUCT_ANALYTICS_CONSOLE_SECRET, constant-time
  check) for server-side forwarders (QU1.4); the public key is refused there.
- Contract tests/contract/fixtures/scribase-bridge/contract.json stays
  version 2 with additive QY1.2 keys: product_analytics route and answer
  keys, analytics_host section (env names, capture paths, server door).

Web view (A18)
- PA src/web/query.ts: visitors, page views, visits, bounce, daily series,
  top pages, entry referrers ($direct), entry UTM, p75 page speed with
  ratings, from pa.events under RLS. Shapes follow PostHog web analytics
  stats_table (MIT, 7b13402a6350, nothing from ee/), NOTICE updated.
- Console: product-analytics/web screen (range picker, tables, page speed).

/s.js page speed (I7, P-Y12)
- The page tag sends LCP, INP, CLS, FCP and TTFB once per page view
  (hidden, pagehide, or before a route change) as a performance event;
  data-vitals="off" turns it off. Port of insights-web metrics.ts; metric
  definitions per GoogleChrome/web-vitals (Apache-2.0), NOTICE added.
  1,620 bytes gzip (budget 3,072).
- With PRODUCT_ANALYTICS_URL the edge collector also forwards every stored
  event to product analytics ($pageview, $web_vitals, custom events,
  $identify) with cookieless daily ids, no IP, retried on 5xx with the same
  uuids, so the web view reads the same store.

Also: lib/ship/ship.test.ts type errors from QY1.1 fixed (doneText helper).

Tests
- insights-edge 34/34 (19 existing + 11 vitals within 10% of
  chrome-page-loads.json and 3 KB gzip + 4 forwarding).
- console 135/135; contract 6/6; console tsc clean.
- product-analytics a1 52/52; test/qy 7/7 (web view hand counts, isolation,
  edge-shape events, server door, and an end-to-end bridge -> SDK event ->
  first_product_event proof: 31 ms against the 60 s target); tsc clean.

Note: performance events still count toward the collector's monthly cap,
as the insights-web ones already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 12:36:08 +03:00

118 lines
4.9 KiB
JavaScript

// QY1.2 (P-Y12): the /s.js page tag sends LCP, INP and CLS (and FCP, TTFB)
// within 10% of Chrome's field values for every load in the shared fixture
// (packages/insights-web/test/fixtures/chrome-page-loads.json), once per page
// view, and the whole tag stays at or under 3 KB gzip.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { gzipSync } from "node:zlib";
import { TRACKER_JS } from "../src/tracker.mjs";
const fixture = JSON.parse(readFileSync(new URL("../../../packages/insights-web/test/fixtures/chrome-page-loads.json", import.meta.url), "utf8"));
const METRICS = ["lcp", "inp", "cls", "fcp", "ttfb"];
const within10 = (got, want) => typeof got === "number" && (want === 0 ? got === 0 : Math.abs(got - want) / want <= 0.1);
/** Runs the tag in a fake page whose performance observers replay `entries`. */
function page({ entries = [], interactionCount, supported = ["navigation", "paint", "largest-contentful-paint", "layout-shift", "event", "first-input"], attrs = {} } = {}) {
const sent = [];
const listeners = {};
const win = {};
const loc = { pathname: "/", search: "", hostname: "shop.example" };
const doc = { currentScript: { getAttribute: (n) => ({ "data-site": "ry_site_abcdefgh", ...attrs })[n] ?? null, src: "https://c.test/s.js" }, readyState: "complete", referrer: "", title: "T", visibilityState: "visible" };
class PO {
static supportedEntryTypes = supported;
constructor(cb) {
this.cb = cb;
}
observe({ type }) {
if (!supported.includes(type)) throw new TypeError("unsupported");
const mine = entries.filter((e) => e.entryType === type);
if (mine.length) this.cb({ getEntries: () => mine });
}
}
const ctx = {
document: doc,
location: loc,
navigator: { doNotTrack: "0", language: "en", sendBeacon: (_u, blob) => (sent.push(JSON.parse(blob.text)), true) },
screen: { width: 1, height: 1 },
history: { pushState() {} },
addEventListener: (n, f) => ((listeners[n] ??= []).push(f)),
Blob: class {
constructor(parts) {
this.text = parts.join("");
}
},
URL,
fetch: () => Promise.resolve(),
window: win,
PerformanceObserver: PO,
performance: { interactionCount },
};
new Function(...Object.keys(ctx), TRACKER_JS)(...Object.values(ctx));
const fire = (n) => (listeners[n] ?? []).forEach((f) => f());
return {
sent,
win,
loc,
hide() {
doc.visibilityState = "hidden";
fire("visibilitychange");
},
fire,
};
}
for (const load of fixture.loads) {
test(`/s.js vitals within 10% of Chrome: ${load.name}`, () => {
const p = page({ entries: load.entries, interactionCount: load.interactionCount });
p.hide();
const perf = p.sent.filter((b) => b.type === "performance");
assert.equal(perf.length, 1, "one performance event per page view");
for (const m of METRICS) {
const want = load.chrome[m];
if (want === undefined) assert.equal(perf[0].payload[m], undefined, `${m} should be absent`);
else assert.ok(within10(perf[0].payload[m], want), `${m}: got ${perf[0].payload[m]}, Chrome ${want}`);
}
assert.equal(perf[0].payload.website, "ry_site_abcdefgh");
assert.equal(perf[0].payload.url, "/");
});
}
test("/s.js sends the metrics once: hide then pagehide is one event", () => {
const p = page({ entries: fixture.loads[0].entries });
p.hide();
p.fire("pagehide");
assert.equal(p.sent.filter((b) => b.type === "performance").length, 1);
assert.equal(p.sent.filter((b) => b.type === "event").length, 1, "the page view itself");
});
test("/s.js: a client-side route change sends the previous page's metrics under the previous URL first", () => {
const p = page({ entries: fixture.loads[0].entries });
p.loc.pathname = "/pricing";
p.fire("popstate");
const types = p.sent.map((b) => [b.type, b.payload.url]);
assert.deepEqual(types, [["event", "/"], ["performance", "/"], ["event", "/pricing"]]);
});
test("/s.js: no vitals without performance observers, with data-vitals=off, or without any metric", () => {
const off = page({ entries: fixture.loads[0].entries, attrs: { "data-vitals": "off" } });
off.hide();
assert.equal(off.sent.filter((b) => b.type === "performance").length, 0);
const none = page({ entries: [], supported: [] });
none.hide();
assert.equal(none.sent.filter((b) => b.type === "performance").length, 0);
});
test("/s.js: a browser without layout-shift reporting sends no made-up CLS", () => {
const p = page({ entries: fixture.loads[3].entries, supported: ["navigation", "paint", "largest-contentful-paint"] });
p.hide();
const perf = p.sent.find((b) => b.type === "performance");
assert.equal(perf.payload.cls, undefined);
assert.equal(typeof perf.payload.lcp, "number");
});
test("/s.js stays at or under 3 KB gzip", () => {
const size = gzipSync(Buffer.from(TRACKER_JS)).length;
assert.ok(size <= 3072, `the page tag is ${size} bytes gzip`);
});