cursedbelt-server 4.59.0 → 4.60.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.
Files changed (37) hide show
  1. package/dist/server/engagement/api.d.ts +6 -0
  2. package/dist/server/engagement/api.js +3 -0
  3. package/dist/server/engagement/d1.d.ts +7 -0
  4. package/dist/server/engagement/d1.js +4 -0
  5. package/dist/server/engagement/events.d.ts +26 -0
  6. package/dist/server/engagement/events.js +52 -0
  7. package/dist/server/events/actions.d.ts +46 -0
  8. package/dist/server/events/actions.js +62 -0
  9. package/dist/server/events/actor.d.ts +19 -0
  10. package/dist/server/events/actor.js +30 -0
  11. package/dist/server/events/gauge.d.ts +21 -0
  12. package/dist/server/events/gauge.js +60 -0
  13. package/dist/server/events/index.d.ts +14 -0
  14. package/dist/server/events/index.js +14 -0
  15. package/dist/server/events/point.d.ts +77 -0
  16. package/dist/server/events/point.js +149 -0
  17. package/dist/server/events/sink.d.ts +97 -0
  18. package/dist/server/events/sink.js +119 -0
  19. package/dist/server/events/views.d.ts +24 -0
  20. package/dist/server/events/views.js +41 -0
  21. package/package.json +8 -2
  22. package/src/server/bench/cpuBudget.spec.ts +12 -8
  23. package/src/server/engagement/api.ts +8 -0
  24. package/src/server/engagement/d1.ts +9 -0
  25. package/src/server/engagement/events.ts +79 -0
  26. package/src/server/events/actions.spec.ts +128 -0
  27. package/src/server/events/actions.ts +113 -0
  28. package/src/server/events/actor.ts +34 -0
  29. package/src/server/events/gauge.spec.ts +75 -0
  30. package/src/server/events/gauge.ts +81 -0
  31. package/src/server/events/index.ts +47 -0
  32. package/src/server/events/point.spec.ts +145 -0
  33. package/src/server/events/point.ts +197 -0
  34. package/src/server/events/sink.spec.ts +291 -0
  35. package/src/server/events/sink.ts +228 -0
  36. package/src/server/events/views.ts +62 -0
  37. package/src/server/telemetryIsWorkerSafe.spec.ts +23 -0
@@ -35,6 +35,7 @@
35
35
  */
36
36
  import { Hono } from "hono";
37
37
  import type { Context } from "hono";
38
+ import { type EngagementEvents } from "./events.js";
38
39
  import { type ActionRef, type PlaceRef } from "./policy.js";
39
40
  import type { EngagementStore } from "./store.js";
40
41
  import { type AppEngagement } from "./summary.js";
@@ -56,6 +57,11 @@ export interface EngagementApiOptions {
56
57
  actions?: readonly ActionRef[];
57
58
  /** Resolve the CURRENT request's account. Null → 401, nothing recorded. */
58
59
  resolveUser: (c: Context) => string | null;
60
+ /**
61
+ * The app's `EVENTS` sink (`cursedbelt-server/events`): present, every accepted view and action
62
+ * is also a user-event point (`./events.ts`). Absent, nothing changes.
63
+ */
64
+ events?: EngagementEvents;
59
65
  /** Injectable clock, so the tests are not timing-dependent. */
60
66
  now?: () => number;
61
67
  }
@@ -35,6 +35,7 @@
35
35
  */
36
36
  import { Hono } from "hono";
37
37
  import { actionDoor } from "./actions.js";
38
+ import { recordEngagementActions, recordEngagementView } from "./events.js";
38
39
  import { OTHER_PLACE, resolvePlace } from "./policy.js";
39
40
  import { returnCurve, summarize } from "./summary.js";
40
41
  /** The recorder half — session-gated, mounted at `/api/engagement`. */
@@ -60,6 +61,7 @@ export function createEngagementRecorder(options) {
60
61
  // check in the right place beats two in the wrong ones.
61
62
  const place = resolvePlace(claimed, options.places);
62
63
  const fold = options.store.recordView({ userKey, place, ts: now() });
64
+ recordEngagementView(options.events, c, userKey, place);
63
65
  // Echo the RESOLVED place, not the claimed one. A client that sent
64
66
  // something off-manifest learns that it was bucketed, which is how a
65
67
  // missing manifest entry gets noticed instead of quietly reading as an
@@ -83,6 +85,7 @@ export function createEngagementRecorder(options) {
83
85
  if ("error" in door)
84
86
  return c.json({ error: door.error }, 400);
85
87
  options.store.recordActions(door.uses);
88
+ recordEngagementActions(options.events, c, userKey, door.uses);
86
89
  return c.json(door.reply);
87
90
  });
88
91
  }
@@ -40,6 +40,7 @@ import type { D1LikeDatabase } from "../d1/types.js";
40
40
  import type { Context } from "hono";
41
41
  import { Hono } from "hono";
42
42
  import { type ActionUse } from "./actions.js";
43
+ import { type EngagementEvents } from "./events.js";
43
44
  import { type ActionRef, type PlaceRef } from "./policy.js";
44
45
  /** The kit store's own tables and indexes, as one-line DDL — see the header. */
45
46
  export declare const ENGAGEMENT_DDL: readonly string[];
@@ -74,8 +75,14 @@ export declare function createD1EngagementRecorder(options: {
74
75
  */
75
76
  actions?: readonly ActionRef[];
76
77
  resolveUser: (c: Context) => string | null;
78
+ /**
79
+ * The app's `EVENTS` sink (`cursedbelt-server/events`): present, every accepted view and action
80
+ * is also a user-event point (`./events.ts`), beside the D1 fold. Absent, nothing changes.
81
+ */
82
+ events?: EngagementEvents;
77
83
  now?: () => number;
78
84
  }): Hono;
79
85
  export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
86
+ export { type EngagementEvents, actionPurpose, placePurpose } from "./events.js";
80
87
  export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
81
88
  export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
@@ -1,5 +1,6 @@
1
1
  import { Hono } from "hono";
2
2
  import { actionDoor, actionStatements } from "./actions.js";
3
+ import { recordEngagementActions, recordEngagementView } from "./events.js";
3
4
  import { dayKey, foldView, OTHER_PLACE, resolvePlace } from "./policy.js";
4
5
  import { ENGAGEMENT_SESSION_DDL, visitStatements } from "./visits.js";
5
6
  /** The kit store's own tables and indexes, as one-line DDL — see the header. */
@@ -106,6 +107,7 @@ export function createD1EngagementRecorder(options) {
106
107
  return c.json({ error: "place must be a string" }, 400);
107
108
  const place = resolvePlace(claimed, options.places);
108
109
  const fold = await recordViewD1(options.db, { userKey, place, ts: now() });
110
+ recordEngagementView(options.events, c, userKey, place);
109
111
  return c.json({ ok: true, place, bucketed: place === OTHER_PLACE, ...fold });
110
112
  });
111
113
  const actions = options.actions;
@@ -125,11 +127,13 @@ export function createD1EngagementRecorder(options) {
125
127
  if ("error" in door)
126
128
  return c.json({ error: door.error }, 400);
127
129
  await recordActionsD1(options.db, door.uses);
130
+ recordEngagementActions(options.events, c, userKey, door.uses);
128
131
  return c.json(door.reply);
129
132
  });
130
133
  }
131
134
  return app;
132
135
  }
133
136
  export { ENGAGEMENT_ACTION_DDL } from "./actions.js";
137
+ export { actionPurpose, placePurpose } from "./events.js";
134
138
  export { ENGAGEMENT_SESSION_DDL } from "./visits.js";
135
139
  export { actionsFromManifest, placesFromManifest } from "./manifestPlaces.js";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The engagement beacon's second write: every accepted `POST /view` is a `view` point and every
3
+ * accepted `POST /action` an `action` point in the app's `EVENTS` dataset (`../events`), beside
4
+ * the D1/sqlite fold that station reads. The store is untouched; the recorder calls these after
5
+ * it has recorded, and nothing here can fail the beacon's answer.
6
+ *
7
+ * Purposes come from a small per-app map; what the map leaves out follows the schema's defaults:
8
+ * a sign-in or settings place is `account`, an admin place `admin`, a help/docs place `support`,
9
+ * a search place `search`, anything else `read`; an action defaults to `edit`.
10
+ */
11
+ import type { Context } from "hono";
12
+ import type { EventActor, EventPurpose, EventSink } from "../events/index.js";
13
+ import type { ActionUse } from "./actions.js";
14
+ export interface EngagementEvents {
15
+ sink: EventSink;
16
+ /** Place id → purpose, for the places the defaults below get wrong. */
17
+ purposes?: Readonly<Record<string, EventPurpose>>;
18
+ /** Action id → purpose; the default is `edit`. */
19
+ actionPurposes?: Readonly<Record<string, EventPurpose>>;
20
+ /** The account beyond its key — label and ownership. Default: the key as the id. */
21
+ actorOf?: (c: Context) => EventActor | null;
22
+ }
23
+ export declare function placePurpose(place: string, purposes?: Readonly<Record<string, EventPurpose>>): EventPurpose;
24
+ export declare function actionPurpose(action: string, purposes?: Readonly<Record<string, EventPurpose>>): EventPurpose;
25
+ export declare function recordEngagementView(events: EngagementEvents | undefined, c: Context, userKey: string, place: string): void;
26
+ export declare function recordEngagementActions(events: EngagementEvents | undefined, c: Context, userKey: string, uses: readonly ActionUse[]): void;
@@ -0,0 +1,52 @@
1
+ const ACCOUNT_RE = /sign-?in|log-?in|settings|account|profile|session/i;
2
+ const ADMIN_RE = /admin|owner/i;
3
+ const SUPPORT_RE = /help|docs|manual|support|about/i;
4
+ const SEARCH_RE = /search/i;
5
+ export function placePurpose(place, purposes) {
6
+ const mapped = purposes?.[place];
7
+ if (mapped)
8
+ return mapped;
9
+ if (ACCOUNT_RE.test(place))
10
+ return "account";
11
+ if (ADMIN_RE.test(place))
12
+ return "admin";
13
+ if (SUPPORT_RE.test(place))
14
+ return "support";
15
+ if (SEARCH_RE.test(place))
16
+ return "search";
17
+ return "read";
18
+ }
19
+ export function actionPurpose(action, purposes) {
20
+ return purposes?.[action] ?? "edit";
21
+ }
22
+ function actorFor(events, c, userKey) {
23
+ return events.actorOf?.(c) ?? { id: userKey };
24
+ }
25
+ export function recordEngagementView(events, c, userKey, place) {
26
+ if (!events)
27
+ return;
28
+ events.sink.record(c.req.raw, {
29
+ kind: "view",
30
+ name: place,
31
+ place,
32
+ purpose: placePurpose(place, events.purposes),
33
+ actor: actorFor(events, c, userKey),
34
+ status: 200,
35
+ });
36
+ }
37
+ export function recordEngagementActions(events, c, userKey, uses) {
38
+ if (!events)
39
+ return;
40
+ const actor = actorFor(events, c, userKey);
41
+ for (const use of uses) {
42
+ events.sink.record(c.req.raw, {
43
+ kind: "action",
44
+ name: use.action,
45
+ place: use.place,
46
+ purpose: actionPurpose(use.action, events.actionPurposes),
47
+ actor,
48
+ status: 200,
49
+ value: use.uses ?? 1,
50
+ });
51
+ }
52
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * `serverActions(events, rules, options)` — the one Hono seam that turns a state-changing API call
3
+ * into an `action` point, classified by method + matched route pattern (`normalizeRoute`, so a
4
+ * ctgr GET-twin counts as its real verb).
5
+ *
6
+ * ```ts
7
+ * app.use("/api/*", serverActions(events, MUSIC_ACTIONS, { actorOf: (c) => actorOf(door.sso.userOf(c)) }));
8
+ * ```
9
+ *
10
+ * Every rule names ONE (name, purpose) for one `METHOD /route/:pattern`; a request matching no rule
11
+ * writes nothing (the requests layer already counts it). A 5xx on a matched rule also writes an
12
+ * `error` point named after the action — "an act that failed in front of the person".
13
+ *
14
+ * Only after `next()`: the point carries the response status, the elapsed ms and, when the rule
15
+ * says so, the bytes the request carried (`Content-Length`) or the response sent — never the body.
16
+ */
17
+ import type { Context, MiddlewareHandler } from "hono";
18
+ import type { EventPurpose, EventVia } from "./point.js";
19
+ import type { EventActor, EventSink } from "./sink.js";
20
+ export interface ServerActionRule {
21
+ /** `POST`, `GET`, `DELETE`, … — compared case-insensitively. */
22
+ method: string;
23
+ /** The Hono route pattern as `normalizeRoute` reports it: `/api/tracks/:id/stream`. */
24
+ route: string;
25
+ /** Verb-object, short, stable: `file.upload`, `track.play`, `search`. */
26
+ name: string;
27
+ purpose: EventPurpose;
28
+ /** The page/view the act belongs to, when the app has one. */
29
+ place?: string;
30
+ /** Which `Content-Length` becomes the point's bytes. */
31
+ bytes?: "request" | "response";
32
+ }
33
+ export interface ServerActionsOptions {
34
+ /** Who sent it — `null` for no session (the anonymous hash then). */
35
+ actorOf?: (c: Context) => EventActor | null | undefined;
36
+ /** Default `web`; an API-token surface says `api`. */
37
+ via?: EventVia | ((c: Context) => EventVia);
38
+ /** Workspace/tenant id when the app has one. */
39
+ tenantOf?: (c: Context) => string | undefined;
40
+ /** A number worth keeping with the point (items returned, tracks zipped). */
41
+ valueFor?: (c: Context, rule: ServerActionRule) => number | undefined;
42
+ now?: () => number;
43
+ }
44
+ /** The rule a method + route pattern maps to, or `null` — exposed so an app can pin its table. */
45
+ export declare function matchServerAction(rules: readonly ServerActionRule[], method: string, route: string): ServerActionRule | null;
46
+ export declare function serverActions(events: EventSink, rules: readonly ServerActionRule[], options?: ServerActionsOptions): MiddlewareHandler;
@@ -0,0 +1,62 @@
1
+ import { normalizeRoute } from "../metrics/normalizeRoute.js";
2
+ function ruleKey(method, route) {
3
+ return `${method.toUpperCase()} ${route}`;
4
+ }
5
+ /** The rule a method + route pattern maps to, or `null` — exposed so an app can pin its table. */
6
+ export function matchServerAction(rules, method, route) {
7
+ const key = ruleKey(method, route);
8
+ for (const rule of rules)
9
+ if (ruleKey(rule.method, rule.route) === key)
10
+ return rule;
11
+ return null;
12
+ }
13
+ function contentLength(headers) {
14
+ const raw = headers?.get("content-length");
15
+ const n = raw ? Number(raw) : 0;
16
+ return Number.isFinite(n) && n > 0 ? n : 0;
17
+ }
18
+ export function serverActions(events, rules, options = {}) {
19
+ const now = options.now ?? (() => Date.now());
20
+ const index = new Map();
21
+ for (const rule of rules)
22
+ index.set(ruleKey(rule.method, rule.route), rule);
23
+ return async (c, next) => {
24
+ const started = now();
25
+ await next();
26
+ if (!events.bound)
27
+ return;
28
+ try {
29
+ const { method, route } = normalizeRoute(c);
30
+ const rule = index.get(ruleKey(method, route));
31
+ if (!rule)
32
+ return;
33
+ const status = c.res.status;
34
+ const ms = Math.max(0, now() - started);
35
+ const bytes = rule.bytes === "request"
36
+ ? contentLength(c.req.raw.headers)
37
+ : rule.bytes === "response"
38
+ ? contentLength(c.res.headers)
39
+ : 0;
40
+ const via = typeof options.via === "function" ? options.via(c) : options.via;
41
+ const tenant = options.tenantOf?.(c);
42
+ const value = options.valueFor?.(c, rule);
43
+ const base = {
44
+ place: rule.place ?? "",
45
+ purpose: rule.purpose,
46
+ actor: options.actorOf?.(c) ?? null,
47
+ status,
48
+ ms,
49
+ bytes,
50
+ ...(via ? { via } : {}),
51
+ ...(tenant ? { tenant } : {}),
52
+ ...(value !== undefined ? { value } : {}),
53
+ };
54
+ events.record(c.req.raw, { kind: "action", name: rule.name, ...base });
55
+ if (status >= 500)
56
+ events.record(c.req.raw, { kind: "error", name: rule.name, ...base });
57
+ }
58
+ catch (error) {
59
+ console.warn(`[events] a server action was not classified: ${String(error)}`);
60
+ }
61
+ };
62
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What a deployment with NO `EVENTS_SALT` hashes with — local dev and tests. A production write
3
+ * still happens with it (the schema says so); `worker:secrets` is what makes it a real secret.
4
+ */
5
+ export declare const LOCAL_EVENTS_SALT = "local-events-salt";
6
+ export declare const ANON_PREFIX = "anon:";
7
+ /** The hash input as the schema spells it, so a test can pin the exact string. */
8
+ export declare function anonymousActorInput(input: {
9
+ ip: string;
10
+ userAgent: string;
11
+ salt: string;
12
+ now: number;
13
+ }): string;
14
+ export declare function anonymousActor(input: {
15
+ ip: string;
16
+ userAgent: string;
17
+ salt?: string | null;
18
+ now?: number;
19
+ }): Promise<string>;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The anonymous actor: `"anon:"` + the first 16 hex characters of
3
+ * `sha256(`${utcDay}|${ip}|${userAgent}|${EVENTS_SALT}`)`. It rotates daily and is stored nowhere
4
+ * else, so a visitor is countable within a day and unlinkable across days — the schema's rule.
5
+ *
6
+ * Web Crypto only (`crypto.subtle`), so a Worker, Bun and Node all hash the same way with no
7
+ * `bun:` or `node:` import — `telemetryIsWorkerSafe.spec.ts` walks this file.
8
+ */
9
+ import { utcDay } from "./point.js";
10
+ /**
11
+ * What a deployment with NO `EVENTS_SALT` hashes with — local dev and tests. A production write
12
+ * still happens with it (the schema says so); `worker:secrets` is what makes it a real secret.
13
+ */
14
+ export const LOCAL_EVENTS_SALT = "local-events-salt";
15
+ export const ANON_PREFIX = "anon:";
16
+ /** The hash input as the schema spells it, so a test can pin the exact string. */
17
+ export function anonymousActorInput(input) {
18
+ return `${utcDay(input.now)}|${input.ip}|${input.userAgent}|${input.salt}`;
19
+ }
20
+ export async function anonymousActor(input) {
21
+ const text = anonymousActorInput({
22
+ ip: input.ip,
23
+ userAgent: input.userAgent,
24
+ salt: input.salt || LOCAL_EVENTS_SALT,
25
+ now: input.now ?? Date.now(),
26
+ });
27
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
28
+ const hex = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
29
+ return `${ANON_PREFIX}${hex.slice(0, 16)}`;
30
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * `dailyGauge(db, key, emit)` — runs `emit` at most once per UTC day per key, guarded in the app's
3
+ * own D1 (`events_days`, created on first use like the engagement tables). The schema's `storage`
4
+ * gauge comes from "an existing cron or the first request of the day"; a Worker has many isolates
5
+ * and a cron may fire more than once, so the day's claim lives in the database, not in memory.
6
+ *
7
+ * ```ts
8
+ * ctx.waitUntil(dailyGauge(db, "storage", () => emitStorageGauges(events, db)));
9
+ * ```
10
+ *
11
+ * Returns `true` when `emit` ran. A failed claim (D1 down) runs nothing and warns; the gauge is
12
+ * counted nowhere else, so a lost day is a gap, never a double. A thrown `emit` releases the claim
13
+ * so the next trigger retries.
14
+ */
15
+ import type { D1LikeDatabase } from "../d1/types.js";
16
+ export declare const EVENTS_DAYS_DDL: string[];
17
+ export declare function dailyGauge(db: D1LikeDatabase, key: string, emit: (day: string) => Promise<void> | void, options?: {
18
+ now?: () => number;
19
+ }): Promise<boolean>;
20
+ /** Test seam: forget what this isolate claimed. */
21
+ export declare function resetDailyGaugeMemo(): void;
@@ -0,0 +1,60 @@
1
+ import { utcDay } from "./point.js";
2
+ export const EVENTS_DAYS_DDL = [
3
+ "CREATE TABLE IF NOT EXISTS events_days (key TEXT NOT NULL, day TEXT NOT NULL, PRIMARY KEY (key, day))",
4
+ ];
5
+ const CLAIM = "INSERT OR IGNORE INTO events_days (key, day) VALUES (?, ?)";
6
+ const RELEASE = "DELETE FROM events_days WHERE key = ? AND day = ?";
7
+ /** Days older than this leave the table on each claim, so it never grows past a few rows per key. */
8
+ const KEEP_DAYS = 7;
9
+ /** The isolate remembers the day it already claimed, so a busy Worker asks D1 once per day. */
10
+ const claimed = new Map();
11
+ async function claimDay(db, key, day) {
12
+ const run = () => db.prepare(CLAIM).bind(key, day).run();
13
+ const result = await run().catch(async (error) => {
14
+ if (!/no such table/i.test(String(error)))
15
+ throw error;
16
+ await db.batch(EVENTS_DAYS_DDL.map((ddl) => db.prepare(ddl)));
17
+ return run();
18
+ });
19
+ return (result.meta?.changes ?? 0) > 0;
20
+ }
21
+ export async function dailyGauge(db, key, emit, options = {}) {
22
+ const day = utcDay((options.now ?? Date.now)());
23
+ if (claimed.get(key) === day)
24
+ return false;
25
+ let won = false;
26
+ try {
27
+ won = await claimDay(db, key, day);
28
+ }
29
+ catch (error) {
30
+ console.warn(`[events] the ${key} gauge's day was not claimed: ${String(error)}`);
31
+ return false;
32
+ }
33
+ claimed.set(key, day);
34
+ if (!won)
35
+ return false;
36
+ try {
37
+ await emit(day);
38
+ }
39
+ catch (error) {
40
+ console.warn(`[events] the ${key} gauge was not emitted: ${String(error)}`);
41
+ claimed.delete(key);
42
+ await db
43
+ .prepare(RELEASE)
44
+ .bind(key, day)
45
+ .run()
46
+ .catch(() => undefined);
47
+ return false;
48
+ }
49
+ const cutoff = utcDay((options.now ?? Date.now)() - KEEP_DAYS * 86_400_000);
50
+ await db
51
+ .prepare("DELETE FROM events_days WHERE key = ? AND day < ?")
52
+ .bind(key, cutoff)
53
+ .run()
54
+ .catch(() => undefined);
55
+ return true;
56
+ }
57
+ /** Test seam: forget what this isolate claimed. */
58
+ export function resetDailyGaugeMemo() {
59
+ claimed.clear();
60
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `cursedbelt-server/events` — first-party user-event telemetry into a Worker's `EVENTS`
3
+ * Analytics Engine dataset, beside (never instead of) `./telemetry`'s per-request points.
4
+ *
5
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`
6
+ * (`telemetryIsWorkerSafe.spec.ts` walks it). `./point.ts` is the wire format; `./sink.ts` the
7
+ * seam; `./actor.ts` the anonymous hash; `./views.ts` the server-side view of an HTML navigation.
8
+ */
9
+ export { ANON_PREFIX, LOCAL_EVENTS_SALT, anonymousActor, anonymousActorInput } from "./actor.js";
10
+ export { ACTOR_KINDS, type ActorKind, BOT_USER_AGENT_WORDS, EVENT_KINDS, EVENT_PURPOSES, EVENT_SCHEMA, EVENT_VIAS, type EventDevice, type EventKind, type EventOutcome, type EventPoint, type EventPurpose, type EventVia, classifyDevice, isBotUserAgent, outcomeOf, referrerHost, toEventPoint, truncateUtf8, utcDay, } from "./point.js";
11
+ export { DEFAULT_SMOKE_ACCOUNTS, type EventActor, type EventFields, type EventSink, type EventSinkOptions, type EventsDataset, type RequestFacts, createEventSink, recordEvent, requestFacts, resolveActorKind, } from "./sink.js";
12
+ export { type HtmlNavigation, htmlNavigationOf, recordHtmlView } from "./views.js";
13
+ export { type ServerActionRule, type ServerActionsOptions, matchServerAction, serverActions } from "./actions.js";
14
+ export { EVENTS_DAYS_DDL, dailyGauge, resetDailyGaugeMemo } from "./gauge.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * `cursedbelt-server/events` — first-party user-event telemetry into a Worker's `EVENTS`
3
+ * Analytics Engine dataset, beside (never instead of) `./telemetry`'s per-request points.
4
+ *
5
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`
6
+ * (`telemetryIsWorkerSafe.spec.ts` walks it). `./point.ts` is the wire format; `./sink.ts` the
7
+ * seam; `./actor.ts` the anonymous hash; `./views.ts` the server-side view of an HTML navigation.
8
+ */
9
+ export { ANON_PREFIX, LOCAL_EVENTS_SALT, anonymousActor, anonymousActorInput } from "./actor.js";
10
+ export { ACTOR_KINDS, BOT_USER_AGENT_WORDS, EVENT_KINDS, EVENT_PURPOSES, EVENT_SCHEMA, EVENT_VIAS, classifyDevice, isBotUserAgent, outcomeOf, referrerHost, toEventPoint, truncateUtf8, utcDay, } from "./point.js";
11
+ export { DEFAULT_SMOKE_ACCOUNTS, createEventSink, recordEvent, requestFacts, resolveActorKind, } from "./sink.js";
12
+ export { htmlNavigationOf, recordHtmlView } from "./views.js";
13
+ export { matchServerAction, serverActions } from "./actions.js";
14
+ export { EVENTS_DAYS_DDL, dailyGauge, resetDailyGaugeMemo } from "./gauge.js";
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The user-event data point — the ONE schema every app in every workspace writes to its own
3
+ * `<app>_events` Analytics Engine dataset (the event schema, v1, 2026-10-31). A collector on the
4
+ * Mac reads every dataset through the account's SQL API, so nothing here is read back by an app.
5
+ *
6
+ * 🔴 **The layout is a WIRE FORMAT.** Analytics Engine columns are positional (`blob1`,
7
+ * `double1`, …) and the collector's queries name them by position: append only, never reorder,
8
+ * never repurpose. `point.spec.ts` pins every position.
9
+ *
10
+ * ```
11
+ * index1 = `${kind}:${name}`, ≤96 bytes
12
+ * blob1 = "e1" (schema) blob2 = app blob3 = kind blob4 = name
13
+ * blob5 = place blob6 = actor blob7 = actorKind blob8 = actorLabel
14
+ * blob9 = tenant blob10 = via blob11 = purpose blob12 = device
15
+ * blob13 = country blob14 = outcome blob15 = referrer blob16 = build
16
+ * double1 = 1 (count) double2 = ms double3 = bytes double4 = value
17
+ * ```
18
+ *
19
+ * Every vocabulary below is CLOSED: the collector groups by these words, and a new one is a
20
+ * schema change for every workspace, not a local choice. Nothing private goes in a blob — no
21
+ * titles, file names, query strings, search terms, raw addresses: a place is a route PATTERN.
22
+ */
23
+ export declare const EVENT_SCHEMA = "e1";
24
+ export type EventKind = "view" | "action" | "auth" | "storage" | "error";
25
+ export declare const EVENT_KINDS: readonly EventKind[];
26
+ export type ActorKind = "owner" | "user" | "anon" | "agent" | "smoke" | "bot";
27
+ export declare const ACTOR_KINDS: readonly ActorKind[];
28
+ export type EventVia = "web" | "api" | "mcp" | "agent" | "cli" | "cron" | "hook";
29
+ export declare const EVENT_VIAS: readonly EventVia[];
30
+ export type EventPurpose = "read" | "create" | "edit" | "organize" | "search" | "ask" | "share" | "play" | "upload" | "download" | "account" | "admin" | "support" | "land";
31
+ export declare const EVENT_PURPOSES: readonly EventPurpose[];
32
+ export type EventDevice = "desktop" | "phone" | "tablet" | "bot" | "other";
33
+ export type EventOutcome = "ok" | "fail" | "refused" | "error";
34
+ /** One event, fully resolved — what {@link toEventPoint} lays out. `''` means unknown or n/a. */
35
+ export interface EventPoint {
36
+ app: string;
37
+ kind: EventKind;
38
+ name: string;
39
+ place: string;
40
+ actor: string;
41
+ actorKind: ActorKind;
42
+ actorLabel: string;
43
+ tenant: string;
44
+ via: EventVia;
45
+ purpose: EventPurpose;
46
+ device: EventDevice;
47
+ country: string;
48
+ outcome: EventOutcome;
49
+ referrer: string;
50
+ build: string;
51
+ ms: number;
52
+ bytes: number;
53
+ value: number;
54
+ }
55
+ /**
56
+ * Truncate to at most `maxBytes` UTF-8 bytes without splitting a code point — `String.slice`
57
+ * counts UTF-16 units, so a name with one multi-byte character can be ≤96 chars and still exceed
58
+ * the 96-BYTE index limit. (The same rule `metrics/telemetrySink.ts` keeps for its index.)
59
+ */
60
+ export declare function truncateUtf8(value: string, maxBytes: number): string;
61
+ /** The documented layout above, as data. Exported so the spec asserts the wire format itself. */
62
+ export declare function toEventPoint(event: EventPoint): {
63
+ indexes: string[];
64
+ blobs: string[];
65
+ doubles: number[];
66
+ };
67
+ /** The schema's crawler words, matched case-insensitively anywhere in the User-Agent. */
68
+ export declare const BOT_USER_AGENT_WORDS: readonly string[];
69
+ export declare function isBotUserAgent(userAgent: string | null | undefined): boolean;
70
+ /** The schema's device classes, from the User-Agent alone. */
71
+ export declare function classifyDevice(userAgent: string | null | undefined): EventDevice;
72
+ /** `ok` | `fail` (4xx) | `refused` (401/403) | `error` (5xx), from a response status. */
73
+ export declare function outcomeOf(status: number | null | undefined): EventOutcome;
74
+ /** The Referer's HOST and nothing else — never a path, never a query. `''` when absent or unparsable. */
75
+ export declare function referrerHost(referer: string | null | undefined): string;
76
+ /** `YYYY-MM-DD` in UTC — the day an anonymous actor's hash rotates on. */
77
+ export declare function utcDay(ms: number): string;