@run402/functions 3.7.1 → 3.9.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @run402/functions
2
2
 
3
- In-function helper library for [Run402](https://run402.com) serverless functions. Imported _inside_ a deployed function — gives you typed access to the caller's database (RLS-respecting) and the project's admin database, the caller's auth, the project's mailbox, AI helpers, and runtime asset uploads.
3
+ In-function helper library for [Run402](https://run402.com) serverless functions. Imported _inside_ a deployed function — gives you typed access to the caller's database (RLS-respecting) and the project's admin database, the caller's auth, the project's mailbox, AI helpers, runtime asset uploads, and the project's cursored event feed.
4
4
 
5
5
  ```ts
6
6
  import { db, adminDb, getUser, email, ai, assets } from "@run402/functions";
@@ -303,6 +303,44 @@ export default async function handler(req: Request): Promise<Response> {
303
303
  }
304
304
  ```
305
305
 
306
+ ## `events.emit(type, payload?, opts?)` — emit into the project's event feed
307
+
308
+ Write a fact into this project's cursored event feed (the `internal.project_events` outbox) from inside a deployed function. Every existing and future feed consumer — `run402 events`, the MCP `list_project_events` tool, the operator console's Activity view — reads it back for free the moment your code calls `events.emit`.
309
+
310
+ ```ts
311
+ import { events } from "@run402/functions";
312
+
313
+ await events.emit("signature_completed", { request_id, signer }, {
314
+ idempotencyKey: `sig:${requestId}`,
315
+ });
316
+ ```
317
+
318
+ Read it back with `GET /projects/v1/:project_id/events?source=app` (or `run402 events --source app`) — app events share the exact cursor/pagination/retention machinery as platform events (deploys, suspensions, transfers), just filtered to `source=app`.
319
+
320
+ **Vocabulary.** `type` must be flat snake_case matching `/^[a-z][a-z0-9_]{2,63}$/` — no dots, no `app_` prefix. Platform-registered type names (`deploy_activated`, `mailbox_suspended`, ...) are **reserved**: an app cannot impersonate a platform fact. This is enforced **server-side only** — `events.emit` does not pre-validate the grammar or check the reservation list locally; it sends `type` exactly as given. A bad grammar or a reserved name comes back as a thrown `Run402EventsPlatformError` with `code: "INVALID_EVENT_TYPE"` or `code: "RESERVED_EVENT_TYPE"` (both HTTP 400) — never a silently rewritten or dropped call.
321
+
322
+ **Idempotency.** Pass `idempotencyKey` on any code path that might run more than once for the same real-world fact — webhook retries, function-run retries, anything at-least-once. The gateway dedupes on `(project_id, idempotency_key)` **forever**: this is a durable identity for the fact, not a short-lived retry-window token like an HTTP `Idempotency-Key` header. Reusing a key days or years later still replays the *original* stored event (`deduplicated: true` on the response) instead of creating a new one.
323
+
324
+ **Response shape** — both a fresh emit (`201`) and an idempotent replay (`200`) return this:
325
+
326
+ ```ts
327
+ {
328
+ cursor: "evc_...", // opaque feed position — pass to ?cursor= on a feed read
329
+ event_type: "signature_completed",
330
+ class: "app", // always "app" for events emitted through this namespace
331
+ source: "app",
332
+ payload: { request_id: "req_123", signer: "0x..." },
333
+ payload_truncated: true, // present only if payload exceeded the 8 KiB bound
334
+ occurred_at: "2026-07-15T12:00:00.000Z",
335
+ deduplicated: false, // true on an idempotency-key replay
336
+ next_actions: [ /* platform-synthesized drill-downs, incl. a feed poll entry */ ],
337
+ }
338
+ ```
339
+
340
+ `payload` is a compact JSON fact — ids and verdict fields, never bodies or secrets — bounded to 8 KiB server-side (oversize payloads are truncated with `payload_truncated: true` rather than rejected). `next_actions` is always platform-synthesized; there is no way to supply your own drill-downs from the emit call (an app-supplied action would be prompt-injection-by-schema for agents that treat `next_actions` as trusted).
341
+
342
+ **Errors.** Non-2xx responses throw `Run402EventsPlatformError` — see [Errors](#errors) below. In practice the two you're most likely to see are `code: "QUOTA_EXCEEDED"` (403, the organization's pooled daily quota is exhausted; `details: {resource: "events_per_day", scope, used, limit}`) and cross-project denials (`code: "FORBIDDEN"`, 403), alongside the two vocabulary errors above.
343
+
306
344
  ## Static-site generation (build-time use)
307
345
 
308
346
  The same library works at build time for static-site generation if you set `RUN402_SERVICE_KEY` and `RUN402_PROJECT_ID` in your `.env`:
@@ -394,7 +432,69 @@ The bundled version lands in the deploy response's `runtime_version` field; reso
394
432
 
395
433
  ## Errors
396
434
 
397
- All helpers throw on non-2xx responses. The error message includes the HTTP status and the response body so you can branch on `code` / `category` / `retryable` (the v1.34+ agent-operable error envelope).
435
+ All helpers throw on non-2xx responses.
436
+
437
+ ### `R402DbError` — `db()` / `adminDb()` failures
438
+
439
+ The DB helpers throw a structured `R402DbError` (also exported as a type from the package). Both throw sites carry a stable SDK-level `code`:
440
+
441
+ - `adminDb().sql(...)` → `code: "R402_DB_SQL_ERROR"`
442
+ - `db(req).from(...)` / `adminDb().from(...)` (the `QueryBuilder`) → `code: "R402_DB_QUERY_ERROR"`
443
+
444
+ Branch on the **properties**, not the message string:
445
+
446
+ ```ts
447
+ import { R402DbError } from "@run402/functions";
448
+
449
+ try {
450
+ await adminDb().sql("INSERT INTO items (name) VALUES ($1)", [name]);
451
+ } catch (err) {
452
+ if (err instanceof R402DbError) {
453
+ err.code; // "R402_DB_SQL_ERROR" | "R402_DB_QUERY_ERROR" (stable SDK code)
454
+ err.status; // HTTP status number, e.g. 402
455
+ err.trace_id; // gateway trace id (string) or null — for support tickets
456
+ err.remote_code;// the gateway/PostgREST error code that shaped the message, or null
457
+ err.body; // full response body (parsed object, or raw string when unparseable)
458
+ if (err.status === 402 && err.remote_code === "QUOTA_EXCEEDED") { /* … */ }
459
+ }
460
+ throw err;
461
+ }
462
+ ```
463
+
464
+ **Why the message is a stable template.** `err.message` is intentionally low-cardinality so error monitors group failures by kind instead of by trace id. The high-cardinality material (a fresh `trace_id` per event, the full body) lives on properties. The message follows:
465
+
466
+ | Response body | `message` | `remote_code` | `trace_id` |
467
+ |---|---|---|---|
468
+ | JSON object with `code` | `SQL error (402): QUOTA_EXCEEDED` | `QUOTA_EXCEEDED` | from body, else `null` |
469
+ | JSON object with only `error` | `SQL error (401): PGRST301` | `PGRST301` | from body, else `null` |
470
+ | JSON object, no `code`/`error` | `SQL error (500): <envelope>` | `<envelope>` | from body, else `null` |
471
+ | non-JSON (text/HTML/empty/array) | `SQL error (502): <body verbatim>` | `null` | `null` |
472
+
473
+ (`PostgREST error (…)` is the prefix for the `QueryBuilder` path; `SQL error (…)` for `adminDb().sql()`.) Don't parse `message` — read `err.code` / `err.status` / `err.trace_id` / `err.remote_code`.
474
+
475
+ ### `Run402EventsPlatformError` — `events.emit()` failures
476
+
477
+ `events.emit()` throws a structured `Run402EventsPlatformError` (also exported from the package) on any non-2xx gateway response. The gateway owns event-type grammar, platform-vocabulary reservation, and the per-organization daily quota — this error is a faithful passthrough of whatever canonical envelope the gateway returned, never a client-fabricated message.
478
+
479
+ ```ts
480
+ import { events, Run402EventsPlatformError } from "@run402/functions";
481
+
482
+ try {
483
+ await events.emit("signature_completed", { request_id });
484
+ } catch (err) {
485
+ if (err instanceof Run402EventsPlatformError) {
486
+ err.code; // "QUOTA_EXCEEDED" | "INVALID_EVENT_TYPE" | "RESERVED_EVENT_TYPE" | "FORBIDDEN" | ...
487
+ err.status; // HTTP status, e.g. 403
488
+ err.details; // e.g. {resource: "events_per_day", scope: "organization", used: 1000, limit: 1000}
489
+ err.next_actions; // platform-synthesized drill-downs (e.g. renew_tier, check_usage)
490
+ err.body; // full response body (parsed object, or raw string when unparseable)
491
+ if (err.code === "QUOTA_EXCEEDED") { /* … */ }
492
+ }
493
+ throw err;
494
+ }
495
+ ```
496
+
497
+ Other helpers still throw plain `Error` whose message includes the HTTP status and the response body so you can branch on `code` / `category` / `retryable` (the v1.34+ agent-operable error envelope).
398
498
 
399
499
  ## Engines
400
500
 
package/dist/db.d.ts CHANGED
@@ -3,6 +3,48 @@ interface QueryBuilderOpts {
3
3
  authorization: string | undefined;
4
4
  basePath: string;
5
5
  }
6
+ /** Stable SDK-level codes for the two `db()` throw sites. */
7
+ export type R402DbErrorCode = "R402_DB_QUERY_ERROR" | "R402_DB_SQL_ERROR";
8
+ /**
9
+ * Structured error thrown by the DB helpers on a non-ok gateway/PostgREST
10
+ * response:
11
+ * - `db()` / `adminDb().from()` (QueryBuilder) → code `R402_DB_QUERY_ERROR`
12
+ * - `adminDb().sql()` → code `R402_DB_SQL_ERROR`
13
+ *
14
+ * The `message` is a stable, LOW-cardinality template so error monitors
15
+ * group failures by kind. High-cardinality material — a fresh `trace_id`
16
+ * per event, the full response body — rides on PROPERTIES, never the
17
+ * message (embedding it defeats fingerprint grouping). Catch-sites SHOULD
18
+ * branch on `err.code` / `err.status` / `err.trace_id` / `err.remote_code`
19
+ * instead of parsing the message string.
20
+ *
21
+ * Message template:
22
+ * - Body is a JSON object → `<prefix> (<status>): <remote_code>`, where
23
+ * `remote_code` is `body.code` (else `body.error`, else the literal
24
+ * `<envelope>`).
25
+ * - Body is NOT a JSON object (plain text, HTML, empty, JSON array/
26
+ * primitive) → the legacy verbatim shape `<prefix> (<status>): <body>`,
27
+ * so old-bundle and new-bundle non-JSON failures fingerprint identically.
28
+ *
29
+ * `prefix` is `PostgREST error` for the QueryBuilder path and `SQL error`
30
+ * for the `adminDb().sql()` path.
31
+ */
32
+ export declare class R402DbError extends Error {
33
+ readonly code: R402DbErrorCode;
34
+ readonly status: number;
35
+ readonly trace_id: string | null;
36
+ /** The remote/gateway code that went into the message (`<envelope>` when absent). */
37
+ readonly remote_code: string | null;
38
+ /** Full response body preserved for debugging — parsed object, or raw string when unparseable. */
39
+ readonly body: unknown;
40
+ readonly docs = "https://run402.com/errors/#R402_DB_ERROR";
41
+ constructor(code: R402DbErrorCode, message: string, fields: {
42
+ status: number;
43
+ trace_id: string | null;
44
+ remote_code: string | null;
45
+ body: unknown;
46
+ });
47
+ }
6
48
  export declare class QueryBuilder {
7
49
  #private;
8
50
  constructor(table: string, opts: QueryBuilderOpts);
package/dist/db.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../src/db.ts"],"names":[],"mappings":"AAIA,UAAU,gBAAgB;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,qBAAa,YAAY;;gBASX,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AM,EAAE,EAAE,SAAgB,EAAE;;KAAK,GAAG,IAAI;IAKtD,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAK1B,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAK3B,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,GAAG,IAAI;IAMvE,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI;IAM3C,MAAM,IAAI,IAAI;IAKd,IAAI,CACF,OAAO,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,IAAI,EACnD,MAAM,EAAE,CAAC,MAAM,EAAE,KAAK,KAAK,IAAI,GAC9B,IAAI;CAiDR;AAyDD,UAAU,cAAc;IACtB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,CAAC;CACnC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,EAAE,CAAC,GAAG,CAAC,EAAE,OAAO,GAAG,cAAc,CAkBhD;AAED,UAAU,aAAa;IACrB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,CAAC;IAClC,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;CAC5E;AAED;;;;;;;;GAQG;AACH,wBAAgB,OAAO,IAAI,aAAa,CA+BvC"}
package/dist/db.js CHANGED
@@ -1,6 +1,86 @@
1
1
  import { config } from "./config.js";
2
2
  import { getCurrentContext } from "./runtime-context.js";
3
3
  import jwt from "./lib/jwt.js";
4
+ /**
5
+ * Structured error thrown by the DB helpers on a non-ok gateway/PostgREST
6
+ * response:
7
+ * - `db()` / `adminDb().from()` (QueryBuilder) → code `R402_DB_QUERY_ERROR`
8
+ * - `adminDb().sql()` → code `R402_DB_SQL_ERROR`
9
+ *
10
+ * The `message` is a stable, LOW-cardinality template so error monitors
11
+ * group failures by kind. High-cardinality material — a fresh `trace_id`
12
+ * per event, the full response body — rides on PROPERTIES, never the
13
+ * message (embedding it defeats fingerprint grouping). Catch-sites SHOULD
14
+ * branch on `err.code` / `err.status` / `err.trace_id` / `err.remote_code`
15
+ * instead of parsing the message string.
16
+ *
17
+ * Message template:
18
+ * - Body is a JSON object → `<prefix> (<status>): <remote_code>`, where
19
+ * `remote_code` is `body.code` (else `body.error`, else the literal
20
+ * `<envelope>`).
21
+ * - Body is NOT a JSON object (plain text, HTML, empty, JSON array/
22
+ * primitive) → the legacy verbatim shape `<prefix> (<status>): <body>`,
23
+ * so old-bundle and new-bundle non-JSON failures fingerprint identically.
24
+ *
25
+ * `prefix` is `PostgREST error` for the QueryBuilder path and `SQL error`
26
+ * for the `adminDb().sql()` path.
27
+ */
28
+ export class R402DbError extends Error {
29
+ code;
30
+ status;
31
+ trace_id;
32
+ /** The remote/gateway code that went into the message (`<envelope>` when absent). */
33
+ remote_code;
34
+ /** Full response body preserved for debugging — parsed object, or raw string when unparseable. */
35
+ body;
36
+ docs = "https://run402.com/errors/#R402_DB_ERROR";
37
+ constructor(code, message, fields) {
38
+ super(message);
39
+ this.name = "R402DbError";
40
+ this.code = code;
41
+ this.status = fields.status;
42
+ this.trace_id = fields.trace_id;
43
+ this.remote_code = fields.remote_code;
44
+ this.body = fields.body;
45
+ }
46
+ }
47
+ /**
48
+ * Build a {@link R402DbError} with a fingerprint-stable message and the
49
+ * high-cardinality material on properties. See {@link R402DbError} for the
50
+ * message-template contract (byte-compatible with the gateway's
51
+ * `normalizeErrorMessage` derivation).
52
+ */
53
+ function buildDbError(code, prefix, status, errBody) {
54
+ let parsed;
55
+ try {
56
+ parsed = JSON.parse(errBody);
57
+ }
58
+ catch {
59
+ parsed = undefined;
60
+ }
61
+ // Only a plain JSON object earns the canonical code-in-message shape; the
62
+ // gateway normalizer keys off a `{…}` body, so arrays/primitives/null fall
63
+ // through to the legacy verbatim shape below.
64
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
65
+ const obj = parsed;
66
+ const remoteCode = (typeof obj.code === "string" && obj.code) ||
67
+ (typeof obj.error === "string" && obj.error) ||
68
+ "<envelope>";
69
+ const traceId = typeof obj.trace_id === "string" ? obj.trace_id : null;
70
+ return new R402DbError(code, `${prefix} (${status}): ${remoteCode}`, {
71
+ status,
72
+ trace_id: traceId,
73
+ remote_code: remoteCode,
74
+ body: obj,
75
+ });
76
+ }
77
+ return new R402DbError(code, `${prefix} (${status}): ${errBody}`, {
78
+ status,
79
+ trace_id: null,
80
+ remote_code: null,
81
+ body: errBody,
82
+ });
83
+ }
4
84
  export class QueryBuilder {
5
85
  #table;
6
86
  #params = new URLSearchParams();
@@ -121,7 +201,7 @@ export class QueryBuilder {
121
201
  res.status === 503 ||
122
202
  (res.status === 400 && (errBody.includes("PGRST204") || errBody.includes("PGRST205")));
123
203
  if (!schemaCacheTransient || Date.now() >= deadline) {
124
- throw new Error(`PostgREST error (${res.status}): ${errBody}`);
204
+ throw buildDbError("R402_DB_QUERY_ERROR", "PostgREST error", res.status, errBody);
125
205
  }
126
206
  await new Promise((r) => setTimeout(r, Math.min(500, 100 * (attempt + 1))));
127
207
  }
@@ -261,7 +341,7 @@ export function adminDb() {
261
341
  });
262
342
  if (!res.ok) {
263
343
  const errBody = await res.text();
264
- throw new Error(`SQL error (${res.status}): ${errBody}`);
344
+ throw buildDbError("R402_DB_SQL_ERROR", "SQL error", res.status, errBody);
265
345
  }
266
346
  return res.json();
267
347
  },
package/dist/db.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"db.js","sourceRoot":"","sources":["../src/db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MA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AI,EAAE,CAAC;gBACjC,MAAM,YAAY,CAAC,mBAAmB,EAAE,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YAC5E,CAAC;YACD,OAAO,GAAG,CAAC,IAAI,EAAwC,CAAC;QAC1D,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,132 @@
1
+ /**
2
+ * `events` namespace — emit into the project's cursored event feed
3
+ * (capability `project-events-client-surface`, gateway change
4
+ * `app-events-emit-lane`).
5
+ *
6
+ * A `project_events` row is the platform's tier-1 fact log: deploys,
7
+ * suspensions, transfers — and, through this namespace, an app's OWN
8
+ * business facts too ("signature completed", "booking created"). Every
9
+ * existing and future feed consumer (CLI `run402 events`, MCP, the operator
10
+ * console) reads app events for free the moment code calls `events.emit`.
11
+ *
12
+ * ```ts
13
+ * import { events } from "@run402/functions";
14
+ *
15
+ * await events.emit("signature_completed", { request_id, signer }, {
16
+ * idempotencyKey: `sig:${requestId}`,
17
+ * });
18
+ * ```
19
+ *
20
+ * **Vocabulary.** `type` MUST be flat snake_case matching
21
+ * `/^[a-z][a-z0-9_]{2,63}$/` — no dots, no `app_` prefix. Platform-registered
22
+ * type names (`deploy_activated`, `mailbox_suspended`, ...) are RESERVED: an
23
+ * app cannot impersonate a platform fact. The gateway owns this policy —
24
+ * grammar and the reservation list are validated SERVER-SIDE only. This SDK
25
+ * sends `type` verbatim; a bad grammar or a reserved name comes back as a
26
+ * `Run402EventsPlatformError` (400 `INVALID_EVENT_TYPE` /
27
+ * `RESERVED_EVENT_TYPE`) rather than being caught, rewritten, or dropped
28
+ * locally.
29
+ *
30
+ * **Idempotency.** Pass `idempotencyKey` on any code path that might run
31
+ * more than once for the same real-world fact (webhook retries,
32
+ * function-run retries, anything at-least-once). The gateway dedupes on
33
+ * `(project_id, idempotency_key)` FOREVER — this is a durable identity for
34
+ * the fact, not a short-lived retry-window token like an HTTP
35
+ * `Idempotency-Key` header. Reusing a key days or years later still replays
36
+ * the ORIGINAL stored event (`deduplicated: true`) instead of creating a
37
+ * new one.
38
+ *
39
+ * @see openspec/changes/app-events-emit-lane/design.md (Canonical Agent Contract)
40
+ */
41
+ export interface EventEmitOptions {
42
+ /**
43
+ * Durable identity for this fact. The gateway dedupes on
44
+ * `(project_id, idempotency_key)` forever — reusing a key later still
45
+ * replays the original event rather than creating a new one. Recommended
46
+ * on every at-least-once code path (webhook handlers, function-run
47
+ * retries, anything that might re-execute for the same occurrence).
48
+ */
49
+ idempotencyKey?: string;
50
+ }
51
+ /** A `next_actions[]` entry — platform-synthesized drill-down. Shape is
52
+ * intentionally loose; entries commonly carry `type` plus some subset of
53
+ * `method` / `path` / `command` / `why`. Never app-supplied — see the
54
+ * namespace doc comment. */
55
+ export type EventNextAction = Record<string, unknown>;
56
+ /**
57
+ * The stored event, returned by both a fresh emit (HTTP `201`) and an
58
+ * idempotent replay (HTTP `200`). Matches the shape the feed read routes
59
+ * (`GET /projects/v1/:project_id/events`) render, so `cursor` from this
60
+ * response can be handed straight to a feed consumer's `?cursor=` param.
61
+ */
62
+ export interface EventEmitResult {
63
+ /** Opaque feed position (`evc_...`). Pass to a feed read's `?cursor=` to
64
+ * resume just after this event. Never parse it. */
65
+ cursor: string;
66
+ event_type: string;
67
+ /** Always `"app"` for events emitted through this namespace. */
68
+ class: string;
69
+ /** Always `"app"` for events emitted through this namespace. */
70
+ source: string;
71
+ payload: Record<string, unknown>;
72
+ /** Present (and `true`) only when the payload exceeded the 8 KiB bound
73
+ * and was truncated at write time; omitted otherwise. */
74
+ payload_truncated?: true;
75
+ occurred_at: string;
76
+ /** `true` when this call replayed a previously-stored event (same
77
+ * `idempotency_key`) instead of writing a new row. */
78
+ deduplicated: boolean;
79
+ next_actions: EventNextAction[];
80
+ [key: string]: unknown;
81
+ }
82
+ /**
83
+ * Structured error thrown by `events.emit()` on a non-2xx gateway response.
84
+ * The gateway owns event-type grammar, platform-vocabulary reservation, and
85
+ * the per-organization daily quota — this SDK never re-implements or masks
86
+ * that policy locally; it surfaces exactly what the gateway decided.
87
+ *
88
+ * Common `code` values:
89
+ * - `INVALID_EVENT_TYPE` (400) — `type` fails `/^[a-z][a-z0-9_]{2,63}$/`.
90
+ * - `RESERVED_EVENT_TYPE` (400) — `type` names a platform-registered type.
91
+ * - `QUOTA_EXCEEDED` (403) — the organization's daily app-event quota is
92
+ * exhausted; `details` carries
93
+ * `{ resource: "events_per_day", scope, used, limit }`.
94
+ * - `FORBIDDEN` (403) — the service key does not belong to this project.
95
+ *
96
+ * Branch on `err.code` / `err.status` / `err.details`, not on `message`.
97
+ */
98
+ export declare class Run402EventsPlatformError extends Error {
99
+ readonly code: string;
100
+ readonly status: number;
101
+ /** `details` from the canonical error envelope, when present (e.g. the
102
+ * `{resource, scope, used, limit}` shape on a `QUOTA_EXCEEDED` denial). */
103
+ readonly details: Record<string, unknown> | undefined;
104
+ /** `next_actions` from the canonical error envelope, when present. */
105
+ readonly next_actions: unknown[] | undefined;
106
+ /** Full response body — parsed object, or the raw string when unparseable. */
107
+ readonly body: unknown;
108
+ constructor(status: number, body: unknown, message: string);
109
+ }
110
+ export declare const events: {
111
+ /**
112
+ * Emit a fact into this project's event feed.
113
+ *
114
+ * The gateway owns vocabulary validation (grammar + platform-name
115
+ * reservation), class stamping (`"app"`), namespacing, quota, and
116
+ * `next_actions` synthesis — this call is a dumb pipe. `type` and
117
+ * `payload` are sent exactly as given; a rejection surfaces as a thrown
118
+ * {@link Run402EventsPlatformError}, never a locally-fabricated error or a
119
+ * silently rewritten value.
120
+ *
121
+ * @param type - flat snake_case event type (`/^[a-z][a-z0-9_]{2,63}$/`),
122
+ * validated and reservation-checked server-side only.
123
+ * @param payload - compact JSON fact (ids + verdict fields, never bodies
124
+ * or secrets). Bounded to 8 KiB server-side; oversize payloads are
125
+ * truncated (`payload_truncated: true` on the response) rather than
126
+ * rejected.
127
+ * @param opts.idempotencyKey - durable dedup identity; see the namespace
128
+ * doc comment. Strongly recommended on at-least-once code paths.
129
+ */
130
+ emit(type: string, payload?: Record<string, unknown>, opts?: EventEmitOptions): Promise<EventEmitResult>;
131
+ };
132
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAIH,MAAM,WAAW,gBAAgB;IAC/B;;;;;;OAMG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;6BAG6B;AAC7B,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B;wDACoD;IACpD,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACjC;8DAC0D;IAC1D,iBAAiB,CAAC,EAAE,IAAI,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB;2DACuD;IACvD,YAAY,EAAE,OAAO,CAAC;IACtB,YAAY,EAAE,eAAe,EAAE,CAAC;IAChC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,yBAA0B,SAAQ,KAAK;IAClD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB;gFAC4E;IAC5E,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;IACtD,sEAAsE;IACtE,QAAQ,CAAC,YAAY,EAAE,OAAO,EAAE,GAAG,SAAS,CAAC;IAC7C,8EAA8E;IAC9E,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;gBAEX,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM;CAS3D;AAgDD,eAAO,MAAM,MAAM;IACjB;;;;;;;;;;;;;;;;;;OAkBG;eAEK,MAAM,YACF,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,SAC1B,gBAAgB,GACtB,OAAO,CAAC,eAAe,CAAC;CA0B5B,CAAC"}
package/dist/events.js ADDED
@@ -0,0 +1,165 @@
1
+ /**
2
+ * `events` namespace — emit into the project's cursored event feed
3
+ * (capability `project-events-client-surface`, gateway change
4
+ * `app-events-emit-lane`).
5
+ *
6
+ * A `project_events` row is the platform's tier-1 fact log: deploys,
7
+ * suspensions, transfers — and, through this namespace, an app's OWN
8
+ * business facts too ("signature completed", "booking created"). Every
9
+ * existing and future feed consumer (CLI `run402 events`, MCP, the operator
10
+ * console) reads app events for free the moment code calls `events.emit`.
11
+ *
12
+ * ```ts
13
+ * import { events } from "@run402/functions";
14
+ *
15
+ * await events.emit("signature_completed", { request_id, signer }, {
16
+ * idempotencyKey: `sig:${requestId}`,
17
+ * });
18
+ * ```
19
+ *
20
+ * **Vocabulary.** `type` MUST be flat snake_case matching
21
+ * `/^[a-z][a-z0-9_]{2,63}$/` — no dots, no `app_` prefix. Platform-registered
22
+ * type names (`deploy_activated`, `mailbox_suspended`, ...) are RESERVED: an
23
+ * app cannot impersonate a platform fact. The gateway owns this policy —
24
+ * grammar and the reservation list are validated SERVER-SIDE only. This SDK
25
+ * sends `type` verbatim; a bad grammar or a reserved name comes back as a
26
+ * `Run402EventsPlatformError` (400 `INVALID_EVENT_TYPE` /
27
+ * `RESERVED_EVENT_TYPE`) rather than being caught, rewritten, or dropped
28
+ * locally.
29
+ *
30
+ * **Idempotency.** Pass `idempotencyKey` on any code path that might run
31
+ * more than once for the same real-world fact (webhook retries,
32
+ * function-run retries, anything at-least-once). The gateway dedupes on
33
+ * `(project_id, idempotency_key)` FOREVER — this is a durable identity for
34
+ * the fact, not a short-lived retry-window token like an HTTP
35
+ * `Idempotency-Key` header. Reusing a key days or years later still replays
36
+ * the ORIGINAL stored event (`deduplicated: true`) instead of creating a
37
+ * new one.
38
+ *
39
+ * @see openspec/changes/app-events-emit-lane/design.md (Canonical Agent Contract)
40
+ */
41
+ import { config } from "./config.js";
42
+ /**
43
+ * Structured error thrown by `events.emit()` on a non-2xx gateway response.
44
+ * The gateway owns event-type grammar, platform-vocabulary reservation, and
45
+ * the per-organization daily quota — this SDK never re-implements or masks
46
+ * that policy locally; it surfaces exactly what the gateway decided.
47
+ *
48
+ * Common `code` values:
49
+ * - `INVALID_EVENT_TYPE` (400) — `type` fails `/^[a-z][a-z0-9_]{2,63}$/`.
50
+ * - `RESERVED_EVENT_TYPE` (400) — `type` names a platform-registered type.
51
+ * - `QUOTA_EXCEEDED` (403) — the organization's daily app-event quota is
52
+ * exhausted; `details` carries
53
+ * `{ resource: "events_per_day", scope, used, limit }`.
54
+ * - `FORBIDDEN` (403) — the service key does not belong to this project.
55
+ *
56
+ * Branch on `err.code` / `err.status` / `err.details`, not on `message`.
57
+ */
58
+ export class Run402EventsPlatformError extends Error {
59
+ code;
60
+ status;
61
+ /** `details` from the canonical error envelope, when present (e.g. the
62
+ * `{resource, scope, used, limit}` shape on a `QUOTA_EXCEEDED` denial). */
63
+ details;
64
+ /** `next_actions` from the canonical error envelope, when present. */
65
+ next_actions;
66
+ /** Full response body — parsed object, or the raw string when unparseable. */
67
+ body;
68
+ constructor(status, body, message) {
69
+ super(message);
70
+ this.name = "Run402EventsPlatformError";
71
+ this.status = status;
72
+ this.body = body;
73
+ this.code = platformCode(body);
74
+ this.details = platformDetails(body);
75
+ this.next_actions = platformNextActions(body);
76
+ }
77
+ }
78
+ function platformCode(body) {
79
+ if (body && typeof body === "object") {
80
+ const record = body;
81
+ const code = record.code ?? record.error;
82
+ if (typeof code === "string" && code.trim() !== "")
83
+ return code;
84
+ }
85
+ return "events_platform_error";
86
+ }
87
+ function platformMessage(body) {
88
+ if (body && typeof body === "object") {
89
+ const record = body;
90
+ const message = record.message ?? record.error;
91
+ if (typeof message === "string" && message.trim() !== "")
92
+ return message;
93
+ }
94
+ return "Run402 rejected the event.";
95
+ }
96
+ function platformDetails(body) {
97
+ if (body && typeof body === "object") {
98
+ const details = body.details;
99
+ if (details && typeof details === "object" && !Array.isArray(details)) {
100
+ return details;
101
+ }
102
+ }
103
+ return undefined;
104
+ }
105
+ function platformNextActions(body) {
106
+ if (body && typeof body === "object") {
107
+ const actions = body.next_actions;
108
+ if (Array.isArray(actions))
109
+ return actions;
110
+ }
111
+ return undefined;
112
+ }
113
+ async function readErrorBody(res) {
114
+ const text = await res.text();
115
+ if (!text)
116
+ return {};
117
+ try {
118
+ return JSON.parse(text);
119
+ }
120
+ catch {
121
+ return { message: text };
122
+ }
123
+ }
124
+ export const events = {
125
+ /**
126
+ * Emit a fact into this project's event feed.
127
+ *
128
+ * The gateway owns vocabulary validation (grammar + platform-name
129
+ * reservation), class stamping (`"app"`), namespacing, quota, and
130
+ * `next_actions` synthesis — this call is a dumb pipe. `type` and
131
+ * `payload` are sent exactly as given; a rejection surfaces as a thrown
132
+ * {@link Run402EventsPlatformError}, never a locally-fabricated error or a
133
+ * silently rewritten value.
134
+ *
135
+ * @param type - flat snake_case event type (`/^[a-z][a-z0-9_]{2,63}$/`),
136
+ * validated and reservation-checked server-side only.
137
+ * @param payload - compact JSON fact (ids + verdict fields, never bodies
138
+ * or secrets). Bounded to 8 KiB server-side; oversize payloads are
139
+ * truncated (`payload_truncated: true` on the response) rather than
140
+ * rejected.
141
+ * @param opts.idempotencyKey - durable dedup identity; see the namespace
142
+ * doc comment. Strongly recommended on at-least-once code paths.
143
+ */
144
+ async emit(type, payload, opts) {
145
+ const body = { event_type: type };
146
+ if (payload !== undefined)
147
+ body.payload = payload;
148
+ if (opts?.idempotencyKey !== undefined)
149
+ body.idempotency_key = opts.idempotencyKey;
150
+ const res = await fetch(`${config.API_BASE}/projects/v1/${config.PROJECT_ID}/events`, {
151
+ method: "POST",
152
+ headers: {
153
+ Authorization: "Bearer " + config.SERVICE_KEY,
154
+ "Content-Type": "application/json",
155
+ },
156
+ body: JSON.stringify(body),
157
+ });
158
+ if (!res.ok) {
159
+ const errBody = await readErrorBody(res);
160
+ throw new Run402EventsPlatformError(res.status, errBody, `Event emit failed (${res.status}): ${platformMessage(errBody)}`);
161
+ }
162
+ return res.json();
163
+ },
164
+ };
165
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AA8CrC;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IACzC,IAAI,CAAS;IACb,MAAM,CAAS;IACxB;gFAC4E;IACnE,OAAO,CAAsC;IACtD,sEAAsE;IAC7D,YAAY,CAAwB;IAC7C,8EAA8E;IACrE,IAAI,CAAU;IAEvB,YAAY,MAAc,EAAE,IAAa,EAAE,OAAe;QACxD,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,2BAA2B,CAAC;QACxC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;QACrC,IAAI,CAAC,YAAY,GAAG,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAChD,CAAC;CACF;AAED,SAAS,YAAY,CAAC,IAAa;IACjC,IAAI,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACrC,MAAM,MAA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IAAI,EAA8B,CAAC;IAChD,CAAC;CACF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export { db, adminDb, QueryBuilder } from "./db.js";
1
+ export { db, adminDb, QueryBuilder, R402DbError } from "./db.js";
2
+ export type { R402DbErrorCode } from "./db.js";
2
3
  export { getUser, getUserId, getRole } from "./auth.js";
3
4
  export type { User } from "./auth.js";
4
5
  export { auth } from "./auth/index.js";
@@ -25,4 +26,6 @@ export { CacheInvalidationHostRequiredError, CacheInvalidationHostForbiddenError
25
26
  export { als, getCurrentContext, runWithContext, requireActiveContext, taintCacheBypass, withPaymentTaint, PAYMENT_PRIMITIVES, Run402OutsideRequestContextError, } from "./runtime-context.js";
26
27
  export type { RunRequestContext } from "./runtime-context.js";
27
28
  export { ensureActorContextKeysLoaded } from "./lib/actor-context-verify.js";
29
+ export { events, Run402EventsPlatformError } from "./events.js";
30
+ export type { EventEmitOptions, EventEmitResult, EventNextAction } from "./events.js";
28
31
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACxD,YAAY,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAQtC,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AACvC,YAAY,EACV,KAAK,EACL,UAAU,EACV,aAAa,EACb,UAAU,EACV,wCAAwC,EACxC,eAAe,EACf,cAAc,EACd,kBAAkB,GACnB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,2BAA2B,EAC3B,sBAAsB,EACtB,qBAAqB,EACrB,gBAAgB,E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,OAAO,EAAE,MAAM,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAChE,YAAY,EAAE,gBAAgB,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { db, adminDb, QueryBuilder } from "./db.js";
1
+ export { db, adminDb, QueryBuilder, R402DbError } from "./db.js";
2
2
  export { getUser, getUserId, getRole } from "./auth.js";
3
3
  // Capability `auth-aware-ssr` (v3.0). The canonical server-side auth
4
4
  // namespace. `auth.user()` / `auth.requireUser()` / `auth.requireRole(...)`
@@ -44,4 +44,9 @@ export { als, getCurrentContext, runWithContext, requireActiveContext, taintCach
44
44
  // actor-context verify key once at cold start (the key is never in the
45
45
  // tenant Lambda env). No-op in local dev / in-process gateway (key in env).
46
46
  export { ensureActorContextKeysLoaded } from "./lib/actor-context-verify.js";
47
+ // `events.emit(type, payload?, opts?)` — emit a fact into this project's
48
+ // cursored event feed (gateway change `app-events-emit-lane`). Service-key
49
+ // context inside deployed functions; the gateway owns vocabulary/quota
50
+ // policy, this namespace is a dumb pipe plus idempotency-key ergonomics.
51
+ export { events, Run402EventsPlatformError } from "./events.js";
47
52
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAGxD,qEAAqE;AACrE,4EAA4E;AAC5E,iEAAiE;AACjE,+DAA+D;AAC/D,yEAAyE;AACzE,wEAAwE;AACxE,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAWvC,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EA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;AACrE,yEAAyE;AACzE,8BAA8B;AAC9B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,qEAAqE;AACrE,gEAAgE;AAChE,qEAAqE;AACrE,2EAA2E;AAC3E,2DAA2D;AAC3D,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAiBxD,OAAO,EAAE,KAAK,EAAE,uBAAuB,EAAE,SAAS,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AASrG,OAAO,EACL,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,gBAAgB,EAChB,wBAAwB,EACxB,yBAAyB,EACzB,yBAAyB,EACzB,6BAA6B,EAC7B,wBAAwB,EACxB,2BAA2B,EAC3B,8BAA8B,GAC/B,MAAM,oBAAoB,CAAC;AAkB5B,0CAA0C;AAC1C,mEAAmE;AACnE,2DAA2D;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAOnC,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GACpC,MAAM,YAAY,CAAC;AACpB,wEAAwE;AACxE,yEAAyE;AACzE,wEAAwE;AACxE,iDAAiD;AACjD,OAAO,EACL,GAAG,EACH,iBAAiB,EACjB,cAAc,EACd,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,gCAAgC,GACjC,MAAM,sBAAsB,CAAC;AAE9B,6EAA6E;AAC7E,uEAAuE;AACvE,uEAAuE;AACvE,4EAA4E;AAC5E,OAAO,EAAE,4BAA4B,EAAE,MAAM,+BAA+B,CAAC;AAC7E,yEAAyE;AACzE,2EAA2E;AAC3E,uEAAuE;AACvE,yEAAyE;AACzE,OAAO,EAAE,MAAM,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@run402/functions",
3
- "version": "3.7.1",
3
+ "version": "3.9.0",
4
4
  "description": "In-function helper library for Run402 serverless functions - db, adminDb, getUser, email, ai, assets, verifyWebhook. Auto-bundled into deployed functions; also installable for local TypeScript autocomplete.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",