@pgxsinkit/contracts 0.2.4 → 0.2.6

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.
@@ -0,0 +1,214 @@
1
+ import type { z } from "zod";
2
+
3
+ /**
4
+ * Event-stream registration (ADR-0053 decision 1) — the contract half of the **Event lane**, the toolkit's
5
+ * second lane beside the sync rail.
6
+ *
7
+ * An **Event stream** is a named, registered category of append-only client events sharing one payload
8
+ * schema and one consumer-side handling. It is registered on the sync registry
9
+ * (`SyncRegistryDefinition.streams`), where the record KEY is the Event-stream name, so there is one
10
+ * contract artifact rather than a second one to lock, diff and thread through the server and the worker.
11
+ *
12
+ * The registration stays **declarative data only** — no functions. The gating hook (consent/entitlement
13
+ * refusal before enqueue) is a function on `CreateSyncServerOptions`, keyed by Event-stream name, never a
14
+ * field here.
15
+ */
16
+
17
+ /**
18
+ * One claim-derived identity field of an Event stream: the JSON path into the **verified** request claims
19
+ * the value is stamped from at ingest.
20
+ *
21
+ * The same addressing as a managed field's `authClaim` strategy (`ManagedFieldSpec.claimPath`) — `["sub"]`
22
+ * for the auth subject, `["app_metadata", "person_id"]` for an app-minted identity — so the two
23
+ * claim-stamping surfaces of the toolkit read identically. Identity is **server-stamped**, never
24
+ * client-trusted: the client's envelope carries no identity at all (see `eventEnvelopeSchema`), and the
25
+ * stamped value reaches the consumer callback on the queue envelope (`stampedEventSchema`).
26
+ */
27
+ export interface EventStreamIdentityField {
28
+ /** JSON path into the verified claims; each segment a plain identifier. Must be non-empty. */
29
+ claimPath: readonly string[];
30
+ }
31
+
32
+ /**
33
+ * A registered Event stream: its payload contract and its claim→identity stamping rule.
34
+ *
35
+ * `payload` is a **strict** zod schema, and strictness is ENFORCED, not merely advertised: an object-rooted
36
+ * payload (including every object inside a union or discriminated union) must carry a `never` catchall —
37
+ * `.strict()` or `z.strictObject()` — or `defineSyncRegistry` rejects the registration. A stripping object
38
+ * would let a misspelled or newly-added key vanish between the caller and the consumer with no verdict
39
+ * anywhere, which is exactly the silence the Event lane's "everything in the Outbox is well-formed"
40
+ * invariant exists to prevent. A NON-object root (a string, array, record, a transform pipeline, …) is
41
+ * accepted unchanged and follows ordinary parse-contract semantics: what the schema ACCEPTS is what
42
+ * `appendEvent` validates, and the JSON-NORMALIZED form of what the schema PRODUCES is what the consumer
43
+ * receives.
44
+ *
45
+ * **The schema EXECUTES at both boundaries; only ONE execution's output is taken.** `appendEvent` runs it as
46
+ * pure validation — the result is discarded and the Outbox stores the value the caller supplied — and the
47
+ * ingestion endpoint runs it again as the one AUTHORITATIVE parse, whose output is what is enqueued and what
48
+ * the consumer callback receives. A transform callback therefore runs twice, so **transforms must be pure
49
+ * and deterministic**: an effectful or environment-dependent one is unsupported, because the server's run is
50
+ * the one that counts and nothing reconciles it against the client's. Parse output the JSON value domain
51
+ * cannot carry (a `BigInt`, `undefined`) is a terminal per-event `rejected` at ingest, never a batch fault.
52
+ *
53
+ * **What is enqueued is the JSON-NORMALIZED parse output, not the parse output itself.** Ingest serializes
54
+ * the authoritative parse's result and enqueues the round-trip, so every queue backend — the in-memory fake
55
+ * and real pgmq's `jsonb` alike — delivers the identical value. The consequence is worth designing against:
56
+ * a transform producing a `Date` reaches the consumer as that date's ISO STRING, and a nested `undefined`
57
+ * property is dropped (an `undefined` array member becomes `null`). A transform that must round-trip as a
58
+ * rich type has to encode it itself.
59
+ *
60
+ * **Schema evolution is compatibility-bound** (ADR-0053 decision 1): a payload schema may evolve only
61
+ * backward-compatibly — it must keep accepting every previously-valid payload, because events written
62
+ * offline under the old schema are still in flight. An incompatible change requires a NEW Event-stream
63
+ * name. The registry lock records a hash of this entry so a change is a reviewable `risky` diff; the hash
64
+ * DETECTS change, it cannot judge compatibility (see `registryEventStreams`).
65
+ */
66
+ export interface EventStreamEntry<TPayload extends z.ZodType = z.ZodType> {
67
+ payload: TPayload;
68
+ /**
69
+ * The identity fields stamped server-side from verified claims, keyed by field name. The stamped record
70
+ * (field name → value) is what the consumer callback receives on every event.
71
+ */
72
+ identity: Record<string, EventStreamIdentityField>;
73
+ /**
74
+ * An opaque version counter for the part of this payload contract the lock's hash cannot see — the same
75
+ * role `RowFilterSpec.revision` plays for a `customWhere` closure. The lock hashes the payload schema as
76
+ * a **JSON Schema**, and refinements/transforms are simply not representable there: a reviewer
77
+ * demonstrated that `z.string().refine(v => v.length >= 3)` and the INCOMPATIBLE `>= 10` version produce
78
+ * the identical stream hash, so the `risky` diff the ADR relies on never fires.
79
+ *
80
+ * So: whenever you change acceptance logic a JSON Schema cannot express (any `.refine`/`.superRefine`
81
+ * threshold, a cross-field check, a transform), you MUST bump `revision` (positive integer). That is
82
+ * what surfaces the change in the lock diff, where the compatibility rule can actually be reviewed.
83
+ * Leaving it unchanged after a refinement change silently bypasses the gate.
84
+ */
85
+ revision?: number;
86
+ }
87
+
88
+ /** A registry's Event streams, keyed by Event-stream name (the key IS the name). */
89
+ export type EventStreamRegistry = Record<string, EventStreamEntry>;
90
+
91
+ /** The payload TYPE of a registered Event stream — what `appendEvent` accepts for it. */
92
+ export type EventStreamPayload<TEntry extends EventStreamEntry> =
93
+ TEntry extends EventStreamEntry<infer TPayload> ? z.infer<TPayload> : never;
94
+
95
+ /**
96
+ * The queue-name prefix each Event stream's pgmq queue is provisioned under (`pgxsinkit_events_<stream>`,
97
+ * ADR-0053 decision 5). Its length is what bounds {@link EVENT_STREAM_NAME_MAX_LENGTH}.
98
+ */
99
+ export const EVENT_STREAM_QUEUE_PREFIX = "pgxsinkit_events_";
100
+
101
+ /**
102
+ * The maximum length of an Event-stream name: **30**. pgmq's queue-name limit is 47 characters and
103
+ * {@link EVENT_STREAM_QUEUE_PREFIX} consumes 17 of them, so a longer name could not be provisioned. The
104
+ * bound is enforced at `defineSyncRegistry` (module eval) rather than at deployment DDL, because a name
105
+ * that fails only when the queue is created fails far too late.
106
+ */
107
+ export const EVENT_STREAM_NAME_MAX_LENGTH = 47 - EVENT_STREAM_QUEUE_PREFIX.length;
108
+
109
+ /**
110
+ * Event-stream names are lowercase `[a-z][a-z0-9_]*` — the intersection of what pgmq accepts unquoted and
111
+ * what stays legible as a queue/table suffix.
112
+ */
113
+ export const EVENT_STREAM_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
114
+
115
+ /**
116
+ * Declare one Event stream for a registry's `streams` map.
117
+ *
118
+ * The Event-stream NAME is the record key it is registered under, so it is not named here — the name (and
119
+ * this entry's payload/identity shape) is validated fail-closed at `defineSyncRegistry`, which sees the
120
+ * whole map and reports EVERY offender in one error rather than one per build.
121
+ *
122
+ * ```ts
123
+ * import { z } from "zod";
124
+ *
125
+ * export const registry = defineSyncRegistry({
126
+ * tables: { issue },
127
+ * streams: {
128
+ * board_issue_viewed: defineEventStream({
129
+ * payload: z.object({ issueId: z.uuid() }).strict(),
130
+ * identity: { viewerId: { claimPath: ["sub"] } },
131
+ * }),
132
+ * },
133
+ * });
134
+ * ```
135
+ */
136
+ export function defineEventStream<const TPayload extends z.ZodType>(input: {
137
+ payload: TPayload;
138
+ identity: Record<string, EventStreamIdentityField>;
139
+ /** Bump on every change the JSON-Schema hash cannot see. See {@link EventStreamEntry.revision}. */
140
+ revision?: number;
141
+ }): EventStreamEntry<TPayload> {
142
+ return {
143
+ payload: input.payload,
144
+ identity: input.identity,
145
+ ...(input.revision != null ? { revision: input.revision } : {}),
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Whether a value walks and quacks like a zod schema.
151
+ *
152
+ * Duck-typed on `safeParse` (the capability `appendEvent` and the ingest endpoint actually use) rather
153
+ * than `instanceof z.ZodType`: zod is a PEER dependency, so a consumer with a duplicated zod install would
154
+ * fail an `instanceof` against a schema that is perfectly usable.
155
+ */
156
+ export function isZodSchema(value: unknown): value is z.ZodType {
157
+ return (
158
+ typeof value === "object" &&
159
+ value !== null &&
160
+ typeof (value as { safeParse?: unknown }).safeParse === "function" &&
161
+ typeof (value as { parse?: unknown }).parse === "function"
162
+ );
163
+ }
164
+
165
+ /** The bits of zod v4's internal `_zod.def` this module reads. Kept structural — zod is a PEER dependency. */
166
+ interface ZodDefLike {
167
+ type?: unknown;
168
+ catchall?: unknown;
169
+ options?: unknown;
170
+ }
171
+
172
+ function zodDefOf(schema: unknown): ZodDefLike | undefined {
173
+ const def = (schema as { _zod?: { def?: unknown } } | null | undefined)?._zod?.def;
174
+ return def != null && typeof def === "object" ? (def as ZodDefLike) : undefined;
175
+ }
176
+
177
+ /**
178
+ * Whether an Event stream's payload schema has a NON-strict object at its root — the one shape
179
+ * `validateEventStreams` refuses (ADR-0053 decision 1: the payload contract is strict, and the promise is
180
+ * enforced rather than advertised).
181
+ *
182
+ * zod v4 models strictness as the object's **catchall**: `.strict()` / `z.strictObject()` set it to
183
+ * `ZodNever`, a bare `z.object()` leaves it unset (unknown keys are silently STRIPPED), and
184
+ * `z.looseObject()` / `.catchall(…)` set something else. So the rule is exactly "an object root's catchall
185
+ * must be `never`", read off `_zod.def` — the same duck-typed posture as {@link isZodSchema}, never an
186
+ * `instanceof` a peer-installed class.
187
+ *
188
+ * A union (or discriminated union) is walked recursively, because each member is equally a root the client
189
+ * may append against. Every other root — string, array, record, a `.transform()` pipeline — is NOT an
190
+ * object and is accepted unchanged. A schema whose internals cannot be read at all (a duplicated zod
191
+ * install, a hand-rolled duck-typed schema) is likewise accepted: this check can only refuse what it can
192
+ * actually see.
193
+ */
194
+ export function hasNonStrictObjectRoot(schema: unknown): boolean {
195
+ const seen = new Set<unknown>();
196
+ const walk = (candidate: unknown): boolean => {
197
+ if (candidate == null || seen.has(candidate)) {
198
+ return false;
199
+ }
200
+ seen.add(candidate);
201
+ const def = zodDefOf(candidate);
202
+ if (!def) {
203
+ return false;
204
+ }
205
+ if (def.type === "object") {
206
+ return zodDefOf(def.catchall)?.type !== "never";
207
+ }
208
+ if (def.type === "union" && Array.isArray(def.options)) {
209
+ return def.options.some(walk);
210
+ }
211
+ return false;
212
+ };
213
+ return walk(schema);
214
+ }
package/src/events.ts ADDED
@@ -0,0 +1,154 @@
1
+ import { z } from "zod";
2
+
3
+ import { unixMicrosecondsSchema } from "./common";
4
+
5
+ /**
6
+ * The **Event lane**'s wire contracts (ADR-0053 decision 3 + decision 5): the flush endpoint's request and
7
+ * verdict bodies, the request-shape limits both sides enforce, and the stamped envelope that travels the
8
+ * queue to the consumer callback.
9
+ *
10
+ * The mutation endpoint's sibling, minus what events don't need — no `seq` (a batch's internal order is
11
+ * its array order; the Outbox's local append ordinal stays local) and no base version (nothing to conflict
12
+ * with). Same strictness discipline as `mutation.ts`.
13
+ */
14
+
15
+ /**
16
+ * The batch ingestion endpoint. Deliberate constants, not tuning: the client flush loop clamps its
17
+ * batching to them and the server enforces them independently of any client's configuration.
18
+ *
19
+ * **`MAX_EVENTS_PER_BATCH` (1000)** — one flush batch. Large enough that a device draining an offline
20
+ * backlog makes real progress per round trip, small enough that one batch stays a modest request and one
21
+ * queue transaction.
22
+ *
23
+ * **`MAX_EVENT_PAYLOAD_BYTES` (64 KiB)** — the serialized payload of ONE event. Events are facts, not
24
+ * documents; a payload approaching this is a modelling smell. Enforced at `appendEvent` (so the library
25
+ * caller fails at the call site) AND at ingest, where a single oversized payload is a per-event
26
+ * `rejected` verdict rather than a batch fault.
27
+ *
28
+ * **`MAX_EVENT_REQUEST_BYTES` (4 MiB)** — the whole request body, the backstop for the two above (1000
29
+ * events × 64 KiB would exceed it, deliberately: the body cap binds first). A violation is a batch-level
30
+ * 413, reachable only under deployment skew or from a non-library caller.
31
+ */
32
+ export const MAX_EVENTS_PER_BATCH = 1000;
33
+ /** See {@link MAX_EVENTS_PER_BATCH}. Serialized bytes of one event's payload. */
34
+ export const MAX_EVENT_PAYLOAD_BYTES = 64 * 1024;
35
+ /** See {@link MAX_EVENTS_PER_BATCH}. Bytes of the whole `POST /api/events` body. */
36
+ export const MAX_EVENT_REQUEST_BYTES = 4 * 1024 * 1024;
37
+
38
+ /**
39
+ * The batch event-ingestion endpoint path(s) — the Event lane's twin of the mutation route's
40
+ * `batchMutationPaths`. It lives HERE, in contracts, rather than beside the server route: the same
41
+ * constant is the client flush loop's target and the server's mount point, and the neighbouring
42
+ * request-shape limits are already contracts-level toolkit constants both sides read.
43
+ */
44
+ export const batchEventPaths = ["/api/events"] as const;
45
+
46
+ /**
47
+ * One client-produced event as it crosses the wire. The library builds it (`appendEvent` stamps `eventId`
48
+ * and `occurredAtUs`); `stream` is the registered Event-stream name.
49
+ *
50
+ * It carries NO identity: identity is stamped server-side from verified claims per the stream's
51
+ * registration (see `EventStreamIdentityField`), never client-trusted. `stream` is validated only as a
52
+ * non-empty string here — an unregistered name is a per-event `deferred` verdict (ordinary rollout skew),
53
+ * not a framing fault.
54
+ */
55
+ export const eventEnvelopeSchema = z
56
+ .object({
57
+ stream: z.string().trim().min(1),
58
+ eventId: z.uuid(),
59
+ occurredAtUs: unixMicrosecondsSchema,
60
+ payload: z.unknown(),
61
+ })
62
+ .strict();
63
+
64
+ /**
65
+ * The `POST /api/events` body. A request failing this parse — or exceeding the request-shape limits — is a
66
+ * batch-level 400/413: a malformed item without a parseable `eventId` cannot receive a per-event verdict.
67
+ * That layer is unreachable through the library (appends are validated, envelopes are library-built); it
68
+ * exists for library bugs and non-library callers.
69
+ */
70
+ export const batchEventRequestSchema = z
71
+ .object({
72
+ events: z.array(eventEnvelopeSchema).min(1).max(MAX_EVENTS_PER_BATCH),
73
+ })
74
+ .strict();
75
+
76
+ /**
77
+ * The per-event verdict. Three of the four are TERMINAL — the client deletes the Outbox row:
78
+ *
79
+ * - `acked` — enqueued.
80
+ * - `refused` — the consent/entitlement gating hook said no.
81
+ * - `rejected` — a schema-invalid payload for a KNOWN Event stream, or an oversized payload. Given
82
+ * append-time validation and the backward-compatibility rule, this means a non-library caller or a
83
+ * broken consumer deployment — a bug, not a rollout.
84
+ *
85
+ * `deferred` is NOT terminal: an Event stream the server does not (yet) know is ordinary deployment skew
86
+ * (a client rolled out ahead of its server), and deleting those events would be data loss on a normal
87
+ * path. Deferred rows stay in the Outbox, retry with backoff, and drain when the rollout completes.
88
+ */
89
+ export const eventAckStatusSchema = z.enum(["acked", "refused", "rejected", "deferred"]);
90
+
91
+ export const eventAckSchema = z
92
+ .object({
93
+ eventId: z.uuid(),
94
+ status: eventAckStatusSchema,
95
+ reason: z.string().trim().min(1).optional(),
96
+ })
97
+ .strict();
98
+
99
+ /** The 2xx body: one verdict per well-formed envelope in the request. */
100
+ export const batchEventAckSchema = z
101
+ .object({
102
+ acks: z.array(eventAckSchema),
103
+ })
104
+ .strict();
105
+
106
+ /**
107
+ * The body of a non-2xx batch-event response. Unlike the mutation path there is NO per-item rejection
108
+ * field: a well-formed envelope always gets a per-event verdict in a 2xx `acks` array, so a non-2xx is
109
+ * *always* a whole-batch fault (framing, limits, auth, queue unavailable) with nothing to attribute.
110
+ * Unknown extra fields are stripped.
111
+ */
112
+ export const batchEventErrorSchema = z.object({
113
+ message: z.string().optional(),
114
+ });
115
+
116
+ /**
117
+ * The **stamped** envelope (ADR-0053 decision 5): what the server produces at ingest, carries through the
118
+ * queue, and delivers to the consumer callback as-is. `identity` is the record of claim-derived fields the
119
+ * Event stream's registration declares, resolved from the VERIFIED claims of the ingesting request.
120
+ *
121
+ * This is the security-sensitive interface of the lane — the point where a client-supplied event becomes
122
+ * an attributed fact — so its shape is contracts-defined, never implementation-defined. It carries no
123
+ * `stream` (the queue message names it once, below) and no client-supplied identity of any kind.
124
+ */
125
+ export const stampedEventSchema = z
126
+ .object({
127
+ eventId: z.uuid(),
128
+ occurredAtUs: unixMicrosecondsSchema,
129
+ identity: z.record(z.string().trim().min(1), z.string()),
130
+ payload: z.unknown(),
131
+ })
132
+ .strict();
133
+
134
+ /**
135
+ * One queue message: a single-stream sub-batch. The endpoint splits a mixed flush batch by Event stream
136
+ * (preserving array order) and enqueues each sub-batch as ONE message on that stream's queue — one
137
+ * visibility timeout, one ack, one consumer transaction per message. Events arrive at the callback in
138
+ * append order WITHIN a message; across messages there is no ordering promise (ADR-0053 decision 6).
139
+ */
140
+ export const eventQueueMessageSchema = z
141
+ .object({
142
+ stream: z.string().trim().min(1),
143
+ events: z.array(stampedEventSchema).min(1),
144
+ })
145
+ .strict();
146
+
147
+ export type EventEnvelope = z.infer<typeof eventEnvelopeSchema>;
148
+ export type BatchEventRequest = z.infer<typeof batchEventRequestSchema>;
149
+ export type EventAckStatus = z.infer<typeof eventAckStatusSchema>;
150
+ export type EventAck = z.infer<typeof eventAckSchema>;
151
+ export type BatchEventAck = z.infer<typeof batchEventAckSchema>;
152
+ export type BatchEventError = z.infer<typeof batchEventErrorSchema>;
153
+ export type StampedEvent = z.infer<typeof stampedEventSchema>;
154
+ export type EventQueueMessage = z.infer<typeof eventQueueMessageSchema>;
package/src/index.ts CHANGED
@@ -2,12 +2,16 @@ export * from "./apply-strategy";
2
2
  export * from "./common";
3
3
  export * from "./config";
4
4
  export * from "./convergence-model";
5
+ export * from "./event-stream";
6
+ export * from "./events";
5
7
  export * from "./fingerprint";
6
8
  export * from "./registry";
7
9
  export * from "./registry-diff";
10
+ export * from "./registry-invariant";
8
11
  export * from "./mutation";
9
12
  export * from "./projection";
10
13
  export * from "./runtime";
11
14
  export * from "./sql-defaults";
12
15
  export * from "./sql-identifier";
16
+ export * from "./sql-role-guard";
13
17
  export * from "./supabase-rls";
package/src/projection.ts CHANGED
@@ -8,8 +8,8 @@ import type { ClientProjectionSpecForTable, SyncTableEntry, SyncTableRegistry }
8
8
  * Per-client mode projection (ADR-0025). The authoritative (server) registry defines a table once with
9
9
  * its full write contract; a client that must only *read* that table consumes the same entry through
10
10
  * `asReadonly`. The read/identity contract — table, columns, primary key, synced-table name, column
11
- * omission, the shape/row filter, AND the column-builder factory (`makeColumns`) — is preserved
12
- * verbatim; the write-capability metadata is dropped:
11
+ * omission, the shape/row filter, the row classification (`rowClass`), AND the column-builder factory
12
+ * (`makeColumns`) — is preserved verbatim; the write-capability metadata is dropped:
13
13
  *
14
14
  * - `mode` flips to `readonly`;
15
15
  * - the overlay-merged read-model `view` and the overlay/journal client projection (the local write
@@ -54,6 +54,11 @@ export function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgT
54
54
  // Read-relevant (ADR-0045): a readonly projection over a table that receives locally-derived rows must
55
55
  // apply CDC inserts with the same idempotent policy, so carry the resolved applyMode verbatim.
56
56
  applyMode: entry.applyMode,
57
+ // Read-relevant (ADR-0052): the classification describes the KIND of rows this entry carries, which a
58
+ // readonly projection carries unchanged (it syncs the same rows). Dropping it would silently un-enrol the
59
+ // projected entry from every invariant bound to that class — and, in a registry that declares its
60
+ // `rowClasses`, the projection registry would fail closed at module eval instead.
61
+ ...(entry.rowClass != null ? { rowClass: entry.rowClass } : {}),
57
62
  ...(entry.shape != null ? { shape: entry.shape } : {}),
58
63
  ...(readonlyProjection != null ? { clientProjection: readonlyProjection } : {}),
59
64
  ...(entry.serverProjection != null ? { serverProjection: entry.serverProjection } : {}),