@pgxsinkit/contracts 0.1.32 → 0.1.40

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 (44) hide show
  1. package/README.md +13 -0
  2. package/dist/apply-strategy.d.ts +35 -0
  3. package/dist/apply-strategy.d.ts.map +1 -0
  4. package/dist/config.d.ts +210 -32
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +106 -0
  7. package/dist/convergence-model.d.ts.map +1 -0
  8. package/dist/fingerprint.d.ts +136 -0
  9. package/dist/fingerprint.d.ts.map +1 -0
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +5222 -3494
  13. package/dist/index.js.map +37 -30
  14. package/dist/mutation.d.ts +78 -0
  15. package/dist/mutation.d.ts.map +1 -1
  16. package/dist/projection.d.ts +88 -0
  17. package/dist/projection.d.ts.map +1 -0
  18. package/dist/registry-diff.d.ts +50 -0
  19. package/dist/registry-diff.d.ts.map +1 -0
  20. package/dist/registry.d.ts +253 -2
  21. package/dist/registry.d.ts.map +1 -1
  22. package/dist/runtime.d.ts +21 -1
  23. package/dist/runtime.d.ts.map +1 -1
  24. package/dist/sql-defaults.d.ts +27 -0
  25. package/dist/sql-defaults.d.ts.map +1 -0
  26. package/dist/sql-identifier.d.ts +26 -0
  27. package/dist/sql-identifier.d.ts.map +1 -0
  28. package/dist/supabase-rls.d.ts +99 -3
  29. package/dist/supabase-rls.d.ts.map +1 -1
  30. package/package.json +8 -3
  31. package/skills/registry-authoring/SKILL.md +376 -0
  32. package/src/apply-strategy.ts +124 -0
  33. package/src/config.ts +254 -106
  34. package/src/convergence-model.ts +190 -0
  35. package/src/fingerprint.ts +265 -0
  36. package/src/index.ts +7 -0
  37. package/src/mutation.ts +94 -2
  38. package/src/projection.ts +150 -0
  39. package/src/registry-diff.ts +215 -0
  40. package/src/registry.ts +751 -23
  41. package/src/runtime.ts +21 -1
  42. package/src/sql-defaults.ts +29 -0
  43. package/src/sql-identifier.ts +130 -0
  44. package/src/supabase-rls.ts +515 -37
package/src/config.ts CHANGED
@@ -1,7 +1,104 @@
1
+ import { sql, type AnyColumn, type SQL } from "drizzle-orm";
2
+ import { PgDialect } from "drizzle-orm/pg-core";
1
3
  import { z } from "zod";
2
4
 
5
+ const pgDialect = new PgDialect();
6
+
3
7
  export type TableMode = "readonly" | "writeonly" | "readwrite";
4
8
 
9
+ /**
10
+ * The per-writable-table Conflict policy (ADR-0015): what happens to a **stale** write — one whose
11
+ * Base server version is behind the row's current Server version at apply (an external write
12
+ * interleaved). It is a **required** declaration on every writable table; there is no silent default
13
+ * (registry validation rejects an undeclared writable table — the third hard-require). v1:
14
+ *
15
+ * - `last-write-wins` — apply the stale write anyway. This is today's implicit behaviour, but now a
16
+ * conscious, named choice rather than silent clobbering.
17
+ * - `reject-if-stale` — do not apply; surface the conflict so the user's edit is kept (the optimistic
18
+ * Overlay stays, marked conflicted) and resolved as a new write.
19
+ *
20
+ * `field-merge` (apply only the changed fields over the current row) and `custom-resolver` (a client
21
+ * re-resolution protocol) are reserved; the union is additive so they slot in without a breaking
22
+ * change.
23
+ */
24
+ export type ConflictPolicy = "last-write-wins" | "reject-if-stale";
25
+
26
+ /** The Conflict policy values accepted in v1 (ADR-0015). Source of truth for registry validation. */
27
+ export const CONFLICT_POLICIES = ["last-write-wins", "reject-if-stale"] as const satisfies readonly ConflictPolicy[];
28
+
29
+ /** Type guard: is `value` one of the v1 {@link ConflictPolicy} values? */
30
+ export function isConflictPolicy(value: unknown): value is ConflictPolicy {
31
+ return typeof value === "string" && (CONFLICT_POLICIES as readonly string[]).includes(value);
32
+ }
33
+
34
+ /**
35
+ * Subscription timing for a synced table (ADR-0021): **when** its Electric shape subscribes.
36
+ *
37
+ * - `eager` (default) — subscribed in the boot set, as today.
38
+ * - `lazy` — excluded from boot; subscribed on first query-reference. With `persistent` retention,
39
+ * first use is a one-time ignition that promotes the table to a normal eager table for subsequent
40
+ * sessions; with `ephemeral` retention it is session-scoped.
41
+ *
42
+ * A property of the **consistency group**: every table sharing a `consistencyGroup` must agree, since
43
+ * a group commits atomically on one `MultiShapeStream` and cannot be partly lazy (ADR-0021 §4).
44
+ */
45
+ export type SubscriptionTiming = "eager" | "lazy";
46
+
47
+ /** The {@link SubscriptionTiming} values. Source of truth for registry validation. */
48
+ export const SUBSCRIPTION_TIMINGS = ["eager", "lazy"] as const satisfies readonly SubscriptionTiming[];
49
+
50
+ /** Type guard: is `value` a {@link SubscriptionTiming}? */
51
+ export function isSubscriptionTiming(value: unknown): value is SubscriptionTiming {
52
+ return typeof value === "string" && (SUBSCRIPTION_TIMINGS as readonly string[]).includes(value);
53
+ }
54
+
55
+ /**
56
+ * Retention for a synced table (ADR-0021): **whether** its local copy is durable.
57
+ *
58
+ * - `persistent` (default) — the durable PGlite backend with a resumable subscription-state.
59
+ * - `ephemeral` — the table's whole per-table local cluster (read cache, overlay, journal, sequence,
60
+ * views, reconcile trigger/function) is emitted as `TEMP`, so reads **and** writes leave no durable
61
+ * trace. Consequence: no durable offline write queue — pair a must-not-lose write with a pessimistic
62
+ * flush (ADR-0022).
63
+ *
64
+ * Like {@link SubscriptionTiming}, a property of the consistency group: every table in a group agrees.
65
+ */
66
+ export type Retention = "persistent" | "ephemeral";
67
+
68
+ /** The {@link Retention} values. Source of truth for registry validation. */
69
+ export const RETENTIONS = ["persistent", "ephemeral"] as const satisfies readonly Retention[];
70
+
71
+ /** Type guard: is `value` a {@link Retention}? */
72
+ export function isRetention(value: unknown): value is Retention {
73
+ return typeof value === "string" && (RETENTIONS as readonly string[]).includes(value);
74
+ }
75
+
76
+ /**
77
+ * Write-mode (ADR-0022): **how** a write reaches the server — the write-side twin of {@link Retention}.
78
+ *
79
+ * - `optimistic` (default) — the write enters the local journal with an optimistic overlay, the UI updates
80
+ * immediately, and the convergence loop flushes the journal as one all-or-nothing batch; the canonical
81
+ * row returns via the sync echo. The path that has always existed.
82
+ * - `pessimistic` — the write is **server-authoritative**: it flush-routes to an authoritative endpoint that
83
+ * applies it in its own isolated, serialised transaction and returns a per-mutation result (accepted, or
84
+ * rejected-with-typed-reason) **before** the UI shows success. For invariants the client cannot evaluate
85
+ * locally — a capacity/quota/uniqueness gate enforced by a server-side rule.
86
+ *
87
+ * Write-mode is a property of an atomic **write-unit**, not a single table (ADR-0022 §1): a unit is uniformly
88
+ * one mode. The *static* write-unit is the **consistency group** — so, like {@link SubscriptionTiming} and
89
+ * {@link Retention}, every table sharing a `consistencyGroup` must agree (validated). A *dynamic* override is
90
+ * the imperative `transaction({ mode })` block, which scopes a mode to an ad-hoc set of mutations.
91
+ */
92
+ export type WriteMode = "optimistic" | "pessimistic";
93
+
94
+ /** The {@link WriteMode} values. Source of truth for registry validation. */
95
+ export const WRITE_MODES = ["optimistic", "pessimistic"] as const satisfies readonly WriteMode[];
96
+
97
+ /** Type guard: is `value` a {@link WriteMode}? */
98
+ export function isWriteMode(value: unknown): value is WriteMode {
99
+ return typeof value === "string" && (WRITE_MODES as readonly string[]).includes(value);
100
+ }
101
+
5
102
  /**
6
103
  * Minimal verified-JWT claim shape the sync layer understands. Providers may
7
104
  * attach arbitrary extra claims; those stay reachable through index access and
@@ -26,13 +123,27 @@ export interface PrimaryKeySpec {
26
123
  export interface ShapeSpec {
27
124
  tableName: string;
28
125
  shapeKey: string;
126
+ /**
127
+ * INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the
128
+ * shape's own `tableName`. A read PROJECTION (`defineReadProjection`) sets it to the OWNING table's
129
+ * name so several shapes can read one physical table under distinct `shapeKey`s; the engine resolves
130
+ * an incoming request by `shapeKey` and consults this only on egress, to build the upstream Electric
131
+ * `table` param. `attachSyncRegistrySchema` also fills/qualifies it for schema-bound registries.
132
+ *
133
+ * Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or
134
+ * wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The
135
+ * combinator derives it from the owner; `defineSyncTable` never sets it from input.
136
+ */
29
137
  electricTable?: string;
30
138
  rowFilter?: RowFilterSpec;
31
139
  }
32
140
 
33
141
  /** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.
34
- * When omitted, both default to the top-level `tableName` of the `defineSyncTable` call. */
35
- export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey"> & {
142
+ * When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.
143
+ * `electricTable` is deliberately absent — it is a resolved/internal field, never a consumer input
144
+ * (see {@link ShapeSpec.electricTable}); a read projection over an existing table is authored with
145
+ * `defineReadProjection`, which derives it from the owner. */
146
+ export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "electricTable"> & {
36
147
  tableName?: string;
37
148
  shapeKey?: string;
38
149
  };
@@ -61,13 +172,22 @@ export interface ClientProjectionSpec {
61
172
  overlayTable?: string;
62
173
  journalTable?: string;
63
174
  omitColumns?: readonly string[];
175
+ localPrimaryKey?: PrimaryKeySpec;
176
+ }
177
+
178
+ /**
179
+ * Server-side projection applied in the proxy response path. This is server
180
+ * authority, not client shape — it never alters the local PGlite schema or the
181
+ * Electric shape URL — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).
182
+ */
183
+ export interface ServerProjectionSpec {
64
184
  /**
65
185
  * Optional per-row rewrite applied in the proxy response path. Runs before column
66
- * omission, so it may read a column (e.g. a control flag) that `omitColumns` then
67
- * removes from the client-visible row. See {@link RowTransform}.
186
+ * omission, so it may read a column (e.g. a control flag) that
187
+ * `clientProjection.omitColumns` then removes from the client-visible row. See
188
+ * {@link RowTransform}.
68
189
  */
69
190
  rowTransform?: RowTransform;
70
- localPrimaryKey?: PrimaryKeySpec;
71
191
  }
72
192
 
73
193
  export interface DeferrableConstraintSpec {
@@ -77,12 +197,38 @@ export interface DeferrableConstraintSpec {
77
197
  }
78
198
 
79
199
  export type ManagedFieldApplyOn = "create" | "update";
80
- export type ManagedFieldStrategy = "authUid" | "nowMicroseconds";
200
+
201
+ /**
202
+ * How the applier stamps a server-managed column (it overrides any client-sent value — the client write
203
+ * payload omits managed fields, and the apply function re-derives them under the verified request claims):
204
+ *
205
+ * - `nowMicroseconds` — `clock_timestamp()` microseconds, stamped via the canonical `pgxsinkit_clock_us()`
206
+ * DB function (installed by the utilities migration). The audit/version columns (`created_at_us`,
207
+ * `updated_at_us`); the `updated_at_us`-on-update field is the strictly-monotonic Server version (ADR-0010).
208
+ * - `authClaim` — a value read from the **verified JWT claims** at a JSON {@link ManagedFieldSpec.claimPath}
209
+ * (e.g. `["sub"]` for the auth subject, or `["app_metadata","person_id"]` for an app-minted identity). This
210
+ * is the single claim-stamping strategy: the old `authUid` is exactly `{ claimPath: ["sub"], cast: "uuid" }`,
211
+ * so there is one mechanism, not a `sub`-only special case beside a general one.
212
+ */
213
+ export type ManagedFieldStrategy = "nowMicroseconds" | "authClaim";
81
214
 
82
215
  export interface ManagedFieldSpec {
83
216
  column: string;
84
217
  applyOn: ManagedFieldApplyOn[];
85
218
  strategy: ManagedFieldStrategy;
219
+ /**
220
+ * For `strategy: "authClaim"` only (required there, forbidden otherwise): the JSON path into the verified
221
+ * request claims to stamp from — `["sub"]`, `["app_metadata", "person_id"]`, etc. Each segment must be a
222
+ * plain identifier (`[A-Za-z_][A-Za-z0-9_]*`); it is emitted into the apply-function DDL as a `jsonb #>>`
223
+ * text-array path, so it is never a value-injection surface.
224
+ */
225
+ claimPath?: string[];
226
+ /**
227
+ * Optional SQL cast for an `authClaim` value (`jsonb #>>` yields text). Defaults to the **target column's
228
+ * own SQL type** (so a `uuid` column casts to `uuid` with no declaration needed). Override only to force a
229
+ * different cast; must be a plain SQL type name.
230
+ */
231
+ cast?: string;
86
232
  }
87
233
 
88
234
  export interface TableGovernanceSpec {
@@ -96,6 +242,27 @@ export interface TableSpecInput {
96
242
  shape?: ShapeSpec;
97
243
  clientProjection?: ClientProjectionSpec;
98
244
  governance?: TableGovernanceSpec;
245
+ /**
246
+ * Consistency group (ADR-0009 decision 2): tables sharing a group sync on one `MultiShapeStream`
247
+ * and commit atomically at a shared LSN frontier. Absent → the table is its own singleton group.
248
+ */
249
+ consistencyGroup?: string;
250
+ /**
251
+ * Subscription timing (ADR-0021). Absent → `eager`. A `lazy` table is excluded from the boot
252
+ * subscription set and subscribed on first query-reference. See {@link SubscriptionTiming}.
253
+ */
254
+ subscription?: SubscriptionTiming;
255
+ /**
256
+ * Retention (ADR-0021). Absent → `persistent`. An `ephemeral` table's whole local cluster is emitted
257
+ * as `TEMP` — no durable trace. See {@link Retention}.
258
+ */
259
+ retention?: Retention;
260
+ /**
261
+ * Write-mode (ADR-0022). Absent → `optimistic`. A `pessimistic` consistency group is a standing
262
+ * server-authoritative write-unit whose writes flush-route to the authoritative endpoint. See
263
+ * {@link WriteMode}.
264
+ */
265
+ writeMode?: WriteMode;
99
266
  }
100
267
 
101
268
  export interface SyncConfigInput<TTables extends Record<string, TableSpecInput> = Record<string, TableSpecInput>> {
@@ -119,126 +286,107 @@ export function getLocalSyncPrimaryKeyColumns(source: {
119
286
  }
120
287
 
121
288
  export interface RowFilterSpec {
122
- /** WHERE "column" = '<owner claim>' — ownership-based row filtering. */
123
- ownership?: {
124
- column: string;
125
- /**
126
- * Dot-path into the JWT claims used as the owner value (e.g.
127
- * "app_metadata.person_id"). Defaults to "sub". A missing, empty, or
128
- * non-primitive claim denies all rows, matching the missing-sub behavior.
129
- */
130
- claim?: string;
131
- };
132
- /** OR clause for shared content: adds rows owned by sharedUserId. */
133
- shared?: {
134
- /** Column used for owner comparison. Defaults to ownership.column. */
135
- ownerColumn?: string;
136
- /** If set, also requires "sharedColumn" = true. */
137
- sharedColumn?: string;
138
- /** Static UUID or a function that returns a UUID given runtime params. */
139
- sharedUserId: string | ((params: Record<string, unknown>) => string);
140
- };
141
289
  /**
142
- * Escape hatch: returns a raw SQL fragment ANDed with other filters.
143
- * Return `null` to bypass all filters (e.g. admin access).
290
+ * The row filter: returns the Electric shape `where` for this request, or `null` to bypass
291
+ * filtering (e.g. admin access). **Prefer returning a Drizzle `SQL` fragment** built from the
292
+ * table's columns: reference each column through {@link c} (a bare, rename-safe identifier) and
293
+ * embed request-derived values directly — they become **bound `$n` params**, never hand-escaped
294
+ * literals. Enum columns must be cast to text (`${c(col)}::text = 'x'`) for Electric's grammar,
295
+ * and subqueries must be self-contained (not correlated), since Electric needs plain column refs.
296
+ *
297
+ * Returning a raw **string** is the escape hatch for a predicate Drizzle can't express. SECURITY:
298
+ * a string is interpolated verbatim into the `where` — it is NOT escaped, so any request-derived
299
+ * value you embed must be escaped/validated (`escapeSqlLiteral`) inside this function, or it is a
300
+ * SQL-injection vector. Reach for the string form only when the Drizzle fragment cannot express it.
144
301
  */
145
- customWhere?: (claims: JwtClaims, params?: Record<string, unknown>) => string | null;
302
+ customWhere?: (claims: JwtClaims, params?: Record<string, unknown>) => string | SQL | null;
146
303
  /** Column projection for the shape URL (e.g. ["id", "source_text"]). */
147
304
  columns?: string[];
148
- }
149
-
150
- function escapeSqlLiteral(value: string): string {
151
- return value.replace(/'/g, "''");
152
- }
153
-
154
- function readOwnerClaim(claims: JwtClaims | null, claimPath: string): string | null {
155
- let current: unknown = claims;
156
-
157
- for (const segment of claimPath.split(".")) {
158
- if (typeof current !== "object" || current === null || Array.isArray(current)) {
159
- return null;
160
- }
161
- current = (current as Record<string, unknown>)[segment];
162
- }
163
-
164
- switch (typeof current) {
165
- case "string":
166
- return current.length > 0 ? current : null;
167
- case "number":
168
- case "bigint":
169
- case "boolean":
170
- // Mirrors the historical truthiness check on claims.sub.
171
- return current ? String(current) : null;
172
- default:
173
- return null;
174
- }
305
+ /**
306
+ * An opaque version tag for the part of this filter the fingerprint cannot see — the `customWhere`
307
+ * body (you cannot hash a closure; only its *presence* is fingerprinted). Bump this (any new
308
+ * string/number) whenever you change that logic so the fingerprint shifts and the local read cache
309
+ * rebuilds + the shape subscription resets. Leaving it unchanged after a `customWhere`
310
+ * authorization change would silently serve the stale shape.
311
+ */
312
+ revision?: string | number;
175
313
  }
176
314
 
177
315
  /**
178
- * Composes ownership, shared, and customWhere filters into a single
179
- * SQL WHERE clause suitable for Electric shape requests.
180
- *
181
- * Returns null if no filters apply (all rows visible).
316
+ * The non-parameterized inline `where` for a filter: the string a `customWhere` returns (the raw
317
+ * escape hatch), or `null` when there is no filter or `customWhere` returns a Drizzle `SQL` fragment
318
+ * (which is parameterized by {@link buildRowFilterShape}, not inlined here). Most callers want
319
+ * `buildRowFilterShape` — this is the inline-string view it composes from.
182
320
  */
183
321
  export function buildRowFilterWhere(
184
322
  filter: RowFilterSpec,
185
323
  claims: JwtClaims | null,
186
324
  params?: Record<string, unknown>,
187
325
  ): string | null {
188
- const parts: string[] = [];
189
- const { ownership, shared, customWhere } = filter;
326
+ const custom = filter.customWhere?.(claims ?? {}, params);
327
+ return typeof custom === "string" && custom ? custom : null;
328
+ }
190
329
 
191
- // Ownership
192
- if (ownership) {
193
- const ownerValue = readOwnerClaim(claims, ownership.claim ?? "sub");
330
+ /**
331
+ * A **bare** (table-unqualified) quoted identifier for a Drizzle column — `"workspace_id"`, never
332
+ * `"work_items"."workspace_id"`. Electric's shape `where` grammar requires *plain* column references
333
+ * (it rejects a qualified one with "Expected a plain column reference"), and Drizzle qualifies columns
334
+ * by default — so reference columns through `c()` when authoring a `customWhere` Drizzle fragment. The
335
+ * column object keeps the reference rename-safe and existence-checked at compile time; only the bare
336
+ * name reaches the wire. Subqueries must stay self-contained (not correlated), since bare names then
337
+ * resolve unambiguously to each FROM — a correlated subquery would need qualification Electric rejects.
338
+ */
339
+ export function c(column: AnyColumn): SQL {
340
+ return sql`${sql.identifier(column.name)}`;
341
+ }
194
342
 
195
- if (ownerValue === null) {
196
- // No authenticated owner claim — block all rows
197
- return "1 = 0";
198
- }
343
+ /**
344
+ * The deny-all row filter: a `customWhere` returns this to make **no** rows visible (e.g. an
345
+ * unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows
346
+ * visible). It is a Drizzle `SQL` fragment (`false`), so it stays on the typed/parameterized path
347
+ * with the rest of the filter rather than being a hand-written `"1 = 0"` string. `WHERE false`
348
+ * matches nothing; Electric accepts it (verified) exactly as it accepts `1 = 0`.
349
+ */
350
+ export const DENY_ALL: SQL = sql`false`;
199
351
 
200
- parts.push(`"${ownership.column}" = '${escapeSqlLiteral(ownerValue)}'`);
201
- }
352
+ /**
353
+ * The ownership shape `where` — the read-path mirror of an owner-column RLS policy: rows whose owner
354
+ * column equals the caller's subject, {@link DENY_ALL} for an unauthenticated caller. Takes the real
355
+ * Drizzle owner column (bare via {@link c}, rename-safe); the subject rides as a typed interpolation —
356
+ * a bound param through `buildRowFilterShape`, or a drizzle-escaped literal when a proxy renders it
357
+ * inline for a shape URL.
358
+ */
359
+ export function buildOwnershipShapeWhere(ownerColumn: AnyColumn, subject: string | null | undefined): SQL {
360
+ return subject == null || subject === "" ? DENY_ALL : sql`${c(ownerColumn)} = ${subject}`;
361
+ }
202
362
 
203
- // Shared content
204
- if (shared) {
205
- const ownerCol = shared.ownerColumn ?? ownership?.column;
206
- if (!ownerCol) {
207
- throw new Error("shared.ownerColumn or ownership.column is required for shared row filter");
208
- }
209
-
210
- const sharedUserId =
211
- typeof shared.sharedUserId === "function" ? shared.sharedUserId(params ?? {}) : shared.sharedUserId;
212
- const escapedSharedUserId = escapeSqlLiteral(sharedUserId);
213
-
214
- let sharedClause: string;
215
- if (shared.sharedColumn) {
216
- sharedClause = `("${shared.sharedColumn}" = true AND "${ownerCol}" = '${escapedSharedUserId}')`;
217
- } else {
218
- sharedClause = `"${ownerCol}" = '${escapedSharedUserId}'`;
219
- }
220
-
221
- if (parts.length > 0) {
222
- parts.push(`OR ${sharedClause}`);
223
- } else {
224
- parts.push(sharedClause);
225
- }
226
- }
363
+ /** The parameterized shape filter the proxy sends to Electric: a `where` and its positional params. */
364
+ export interface RowFilterShape {
365
+ where: string;
366
+ params: string[];
367
+ }
227
368
 
228
- // Custom where
229
- if (customWhere) {
230
- const custom = customWhere(claims ?? {}, params);
231
- if (custom) {
232
- if (parts.length > 0) {
233
- return `(${parts.join(" ")}) AND (${custom})`;
234
- }
235
- return custom;
236
- }
237
- }
369
+ /**
370
+ * The shape filter the proxy sends to Electric: the `where` plus its positional `params` (`$1`, `$2`,
371
+ * …). A `customWhere` returning a Drizzle `SQL` fragment is serialized here, so request-derived values
372
+ * become **bound params** — never hand-escaped literals; a string `customWhere` is the raw escape
373
+ * hatch (no params). Returns `null` when there is no filter (all rows visible).
374
+ */
375
+ export function buildRowFilterShape(
376
+ filter: RowFilterSpec,
377
+ claims: JwtClaims | null,
378
+ params?: Record<string, unknown>,
379
+ ): RowFilterShape | null {
380
+ const custom = filter.customWhere?.(claims ?? {}, params);
238
381
 
239
- if (parts.length === 0) {
382
+ if (custom == null) {
240
383
  return null;
241
384
  }
242
385
 
243
- return parts.length > 1 ? `(${parts.join(" ")})` : parts[0]!;
386
+ if (typeof custom === "string") {
387
+ return custom ? { where: custom, params: [] } : null;
388
+ }
389
+
390
+ const compiled = pgDialect.sqlToQuery(custom);
391
+ return { where: compiled.sql, params: compiled.params.map((value) => String(value)) };
244
392
  }
@@ -0,0 +1,190 @@
1
+ import { type AnyPgTable, getTableConfig } from "drizzle-orm/pg-core";
2
+
3
+ import { resolveServerVersionColumnName, type SyncTableEntry } from "./registry";
4
+ import { quoteIdentifier } from "./sql-identifier";
5
+
6
+ /**
7
+ * The Convergence model (ADR-0011): the single owner of *how* local optimistic state converges to
8
+ * server state. It owns the shared barrier predicate, the per-table sync-state **view** generator,
9
+ * and the event-model spec below. Read sync (the Sync applier) and write sync (the mutation runtime)
10
+ * remain the two edges with their own transaction paths, but neither independently decides whether an
11
+ * entity is resolved — this module is the one resolution authority.
12
+ *
13
+ * Distinct from the convergence *driver* (`convergence.ts`, ADR-0005), which schedules *when* to
14
+ * converge. This module defines *how* an entity resolves.
15
+ */
16
+
17
+ /**
18
+ * The Convergence barrier predicate (ADR-0010): an acked create/update is resolved only once the
19
+ * synced echo's Server version has reached the write's acked version. Emitted identically by the
20
+ * reconcile trigger (schema.ts), `reconcileTable` (mutation.ts), **and** the per-table sync-state
21
+ * view (decision 4) — one rule, three consumers, no drift (ADR-0004).
22
+ *
23
+ * `syncedAlias` is the synced-side reference (a table alias, or `NEW` inside the trigger);
24
+ * `journalAlias` qualifies the journal's `server_updated_at_us` (omit it where the journal is the
25
+ * unaliased target of the `DELETE`).
26
+ */
27
+ export function buildOverlayResolutionBarrier<TTable extends AnyPgTable>(
28
+ entry: SyncTableEntry<TTable>,
29
+ options: { syncedAlias: string; journalAlias?: string },
30
+ ): string {
31
+ const serverVersionColumn = resolveServerVersionColumnName(entry);
32
+
33
+ if (!serverVersionColumn) {
34
+ throw new Error(
35
+ `writable table ${getTableConfig(entry.table).name} has no Server version; cannot build the convergence barrier (ADR-0010)`,
36
+ );
37
+ }
38
+
39
+ const journalRef = options.journalAlias ? `${options.journalAlias}.server_updated_at_us` : "server_updated_at_us";
40
+ return `${journalRef} <= ${options.syncedAlias}.${quoteIdentifier(serverVersionColumn)}`;
41
+ }
42
+
43
+ /**
44
+ * The qualified object names the sync-state view is generated over. The synced read cache is
45
+ * droppable (ADR-0006); overlay + journal are the authority. The view joins all three but stores
46
+ * nothing — it is a derived projection (ADR-0011 decision 2).
47
+ */
48
+ export interface SyncStateViewProjection {
49
+ /** Qualified synced read-cache table. */
50
+ syncedTable: string;
51
+ /** Qualified overlay (optimistic intent) table. */
52
+ overlayTable: string;
53
+ /** Qualified mutation-journal table. */
54
+ journalTable: string;
55
+ }
56
+
57
+ /**
58
+ * Generate the per-writable-table `<table>_sync_state` **view** (ADR-0011 decision 2): a derived
59
+ * projection — never a stored copy — over synced + overlay + journal that answers "what is this
60
+ * entity's convergence state?" with one authoritative, queryable row per entity that has local
61
+ * activity (an overlay or journal row). Keyed on the **real PK columns**, never a generic
62
+ * `entity_key_json` (decision 2).
63
+ *
64
+ * Columns:
65
+ * - `observed_server_version` — the synced row's Server version (NULL when no echo has landed).
66
+ * - `acked_server_version` — the highest Server version the server assigned to our acked writes.
67
+ * - `pending_count` — journal rows still owed to the server (pending/sending/failed).
68
+ * - `has_acked_unobserved_write` — an acked create/update whose echo has not yet caught up. Derived
69
+ * from the **same** {@link buildOverlayResolutionBarrier} predicate the resolver uses (decision 4),
70
+ * so what the UI shows can never drift from what the resolver does.
71
+ * - `local_delete_pending` — an optimistic delete is staged in the overlay.
72
+ * - `conflict_state` — the reason a `conflicted` (stale, reject-if-stale) write was declined, or NULL
73
+ * when the entity has no conflicted mutation (ADR-0015). Surfaced from the journal's
74
+ * `conflict_reason`, scoped to `status = 'conflicted'` so a stale failure reason never leaks in.
75
+ * - `quarantined_count` — terminal local writes the server permanently rejected (ADR-0006): a poison
76
+ * mutation named in a batch rejection, or one that exhausted the attempt cap. Quarantine blocks
77
+ * sync and *keeps* the optimistic overlay, so without this the view would show an entity with
78
+ * `pending_count = 0` and `conflict_state = NULL` yet still carrying un-converged local intent.
79
+ * - `quarantine_state` — the `last_error` of a quarantined write (the rejection reason), or NULL when
80
+ * the entity has none. The reason counterpart to `quarantined_count`, mirroring `conflict_state`.
81
+ *
82
+ * Note `pending_count` is the *retryable* owed set (pending/sending/failed); a quarantined write is
83
+ * terminal, counted separately so a blocked write is never mistaken for one still in flight.
84
+ *
85
+ * The Read model stays lean (it already carries `overlay_kind`); an app that wants per-row
86
+ * convergence status joins this view on the PK.
87
+ */
88
+ export function buildSyncStateView<TTable extends AnyPgTable>(
89
+ entry: SyncTableEntry<TTable>,
90
+ projection: SyncStateViewProjection,
91
+ ): string {
92
+ const serverVersionColumn = resolveServerVersionColumnName(entry);
93
+
94
+ if (!serverVersionColumn) {
95
+ throw new Error(
96
+ `writable table ${getTableConfig(entry.table).name} has no Server version; cannot build the sync-state view (ADR-0011)`,
97
+ );
98
+ }
99
+
100
+ const pkColumns = [...entry.primaryKey.columns];
101
+ const quotedVersion = quoteIdentifier(serverVersionColumn);
102
+ const keyColumnList = pkColumns.map((column) => quoteIdentifier(column)).join(", ");
103
+ const keySelectList = pkColumns.map((column) => `k.${quoteIdentifier(column)}`).join(",\n ");
104
+
105
+ const pkEquality = (left: string, right: string) =>
106
+ pkColumns.map((column) => `${left}.${quoteIdentifier(column)} = ${right}.${quoteIdentifier(column)}`).join(" AND ");
107
+
108
+ // Decision 4: the SAME barrier the resolver's journal-clear DELETE uses. The view asks whether an
109
+ // acked write is *not yet* resolved (`(barrier) IS NOT TRUE`) — NULL (no synced row) counts as
110
+ // unobserved, exactly the create-with-no-echo case. One predicate string, two consumers.
111
+ const barrier = buildOverlayResolutionBarrier(entry, { syncedAlias: "synced", journalAlias: "journal" });
112
+
113
+ return [
114
+ `SELECT`,
115
+ ` ${keySelectList},`,
116
+ ` synced.${quotedVersion} AS observed_server_version,`,
117
+ ` j.acked_server_version,`,
118
+ ` COALESCE(j.pending_count, 0) AS pending_count,`,
119
+ ` COALESCE(j.has_acked_unobserved_write, FALSE) AS has_acked_unobserved_write,`,
120
+ ` COALESCE(o.local_delete_pending, FALSE) AS local_delete_pending,`,
121
+ ` j.conflict_state,`,
122
+ ` COALESCE(j.quarantined_count, 0) AS quarantined_count,`,
123
+ ` j.quarantine_state`,
124
+ `FROM (`,
125
+ ` SELECT DISTINCT ${keyColumnList} FROM ${projection.journalTable}`,
126
+ ` UNION`,
127
+ ` SELECT DISTINCT ${keyColumnList} FROM ${projection.overlayTable}`,
128
+ `) AS k`,
129
+ `LEFT JOIN ${projection.syncedTable} AS synced ON ${pkEquality("synced", "k")}`,
130
+ `LEFT JOIN LATERAL (`,
131
+ ` SELECT`,
132
+ ` MAX(journal.server_updated_at_us) FILTER (WHERE journal.status = 'acked') AS acked_server_version,`,
133
+ ` COUNT(*) FILTER (WHERE journal.status IN ('pending', 'sending', 'failed')) AS pending_count,`,
134
+ ` COALESCE(bool_or(`,
135
+ ` journal.status = 'acked'`,
136
+ ` AND journal.mutation_kind <> 'delete'`,
137
+ ` AND journal.server_updated_at_us IS NOT NULL`,
138
+ ` AND (${barrier}) IS NOT TRUE`,
139
+ ` ), FALSE) AS has_acked_unobserved_write,`,
140
+ ` MAX(journal.conflict_reason) FILTER (WHERE journal.status = 'conflicted') AS conflict_state,`,
141
+ ` COUNT(*) FILTER (WHERE journal.status = 'quarantined') AS quarantined_count,`,
142
+ ` MAX(journal.last_error) FILTER (WHERE journal.status = 'quarantined') AS quarantine_state`,
143
+ ` FROM ${projection.journalTable} AS journal`,
144
+ ` WHERE ${pkEquality("journal", "k")}`,
145
+ `) AS j ON TRUE`,
146
+ `LEFT JOIN LATERAL (`,
147
+ ` SELECT bool_or(overlay.overlay_kind = 'pending_delete') AS local_delete_pending`,
148
+ ` FROM ${projection.overlayTable} AS overlay`,
149
+ ` WHERE ${pkEquality("overlay", "k")}`,
150
+ `) AS o ON TRUE`,
151
+ ].join("\n");
152
+ }
153
+
154
+ /**
155
+ * The event model the Convergence model implements (ADR-0011). The per-entity convergence state is
156
+ * **derived** from synced + overlay + journal — never a mutated row — so this table is the spec the
157
+ * derivation answers to, not a state machine that is stepped. Exported so a test can assert the
158
+ * implemented derivation covers every event.
159
+ */
160
+ export const CONVERGENCE_EVENTS = [
161
+ {
162
+ event: "local create/update/delete enqueued",
163
+ effect: "overlay upserted; a journal mutation appended (records base server version for ADR-0015)",
164
+ },
165
+ { event: "mutation sent", effect: "journal row → sending" },
166
+ {
167
+ event: "mutation acked",
168
+ effect:
169
+ "journal row → acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up",
170
+ },
171
+ {
172
+ event: "Electric insert/update observed",
173
+ effect: "synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal",
174
+ },
175
+ {
176
+ event: "Electric delete observed",
177
+ effect: "resolved by synced-row absence (deletes carry no Server version — ADR-0010)",
178
+ },
179
+ { event: "resolution", effect: "clear overlay/journal only through the shared barrier predicate (decision 4)" },
180
+ { event: "conflict detected", effect: "conflict_state recorded on the journal row (ADR-0015); surfaced in the view" },
181
+ {
182
+ event: "mutation quarantined",
183
+ effect:
184
+ "journal row → quarantined (terminal, ADR-0006), overlay kept; surfaced as quarantined_count/quarantine_state",
185
+ },
186
+ {
187
+ event: "shape must-refetch",
188
+ effect: "subscription reset + re-stream; affected entity state re-derives from the fresh synced rows",
189
+ },
190
+ ] as const;