@pgxsinkit/contracts 0.2.6 → 0.3.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/src/config.ts CHANGED
@@ -1,8 +1,7 @@
1
- import { sql, type AnyColumn, type SQL } from "drizzle-orm";
2
- import { PgDialect } from "drizzle-orm/pg-core";
1
+ import type { AnyColumn } from "drizzle-orm";
3
2
  import { z } from "zod";
4
3
 
5
- const pgDialect = new PgDialect();
4
+ import { p, type Predicate } from "./predicate";
6
5
 
7
6
  export type TableMode = "readonly" | "writeonly" | "readwrite";
8
7
 
@@ -33,7 +32,7 @@ export function isConflictPolicy(value: unknown): value is ConflictPolicy {
33
32
  }
34
33
 
35
34
  /**
36
- * Subscription timing for a synced table (ADR-0021): **when** its Electric shape subscribes.
35
+ * Subscription timing for a synced table (ADR-0021): **when** its read-path shape subscribes.
37
36
  *
38
37
  * - `eager` (default) — subscribed in the boot set, as today.
39
38
  * - `lazy` — excluded from boot; subscribed on first query-reference. With `persistent` retention,
@@ -41,7 +40,8 @@ export function isConflictPolicy(value: unknown): value is ConflictPolicy {
41
40
  * sessions; with `ephemeral` retention it is session-scoped.
42
41
  *
43
42
  * A property of the **consistency group**: every table sharing a `consistencyGroup` must agree, since
44
- * a group commits atomically on one `MultiShapeStream` and cannot be partly lazy (ADR-0021 §4).
43
+ * a group's streams commit atomically together — all up-to-date, then one transaction (ADR-0056) — so
44
+ * it cannot be partly lazy (ADR-0021 §4).
45
45
  */
46
46
  export type SubscriptionTiming = "eager" | "lazy";
47
47
 
@@ -265,24 +265,109 @@ export interface ShapeSpec {
265
265
  /**
266
266
  * INTERNAL / resolved — the physical Postgres table this shape reads, when it differs from the
267
267
  * shape's own `tableName`. A read PROJECTION (`defineReadProjection`) sets it to the OWNING table's
268
- * name so several shapes can read one physical table under distinct `shapeKey`s; the engine resolves
269
- * an incoming request by `shapeKey` and consults this only on egress, to build the upstream Electric
270
- * `table` param. `attachSyncRegistrySchema` also fills/qualifies it for schema-bound registries.
268
+ * name so several shapes can read one physical table under distinct `shapeKey`s; the control plane
269
+ * resolves an incoming subscription by `shapeKey` and consults this only when it creates the shape, as
270
+ * the source `table` it hands the engine. `attachSyncRegistrySchema` also fills/qualifies it for
271
+ * schema-bound registries.
271
272
  *
272
273
  * Not a consumer input — there is no valid reason to hand-set it (it can only be redundant with, or
273
274
  * wrong about, the table you are reading), so it is omitted from {@link ShapeSpecInput}. The
274
275
  * combinator derives it from the owner; `defineSyncTable` never sets it from input.
275
276
  */
276
- electricTable?: string;
277
+ physicalTable?: string;
277
278
  rowFilter?: RowFilterSpec;
279
+ /**
280
+ * SHARED TIER (ADR-0055) — the scope columns, resolved to column names, whose values key this
281
+ * shape family. The predicate is *generated* as an `AND` of equalities over them, so disjointness
282
+ * is a property of the construction rather than something a checker has to enforce: a row carries
283
+ * exactly one value per scope column, so it falls in exactly one shape of the family, and an
284
+ * overlapping pair is not expressible at all.
285
+ *
286
+ * `NULL` is a legal scope value and compiles to `IS NULL` — which is how an offering-wide row gets
287
+ * its own scope `(O, null)` rather than appearing in every group's shape. The tempting
288
+ * `group_id IS NULL OR group_id = $G` form is not merely disallowed here; it is wrong, because it
289
+ * places one row in every group shape at once.
290
+ *
291
+ * Its presence is what makes this a shared-tier shape. Declaring it alongside `rowFilter` is
292
+ * refused at definition time — see {@link readShapeTier}.
293
+ */
294
+ scope?: readonly string[];
295
+ /**
296
+ * The **static** half of the shape's predicate: subscriber-independent, identical for every
297
+ * reader, and therefore safe in either tier. On the shared tier it is conjoined with the generated
298
+ * scope equalities; on the private tier, with whatever `rowFilter` resolves to for the subject.
299
+ *
300
+ * Native AST, not SQL text — see {@link Predicate}.
301
+ */
302
+ where?: Predicate;
303
+ }
304
+
305
+ /** Which read tier a shape belongs to (ADR-0055 decision 2). */
306
+ export type ShapeTier = "shared" | "private";
307
+
308
+ /**
309
+ * The tier a shape declares, or a refusal.
310
+ *
311
+ * The tier is not configured; it is *read off* which field the author declared — `scope` for shared,
312
+ * `rowFilter` for private. That makes a shape's tier evident from its authoring and impossible to
313
+ * leave ambiguous, which matters because the two differ in whether their bytes are user-independent,
314
+ * and so in whether they may be shared and cached at all.
315
+ *
316
+ * Declaring both is refused rather than resolved by precedence. A `rowFilter` fuses the subject into
317
+ * the predicate, which is exactly what makes a stream unshareable; silently letting it ride along on
318
+ * a shape declared as shared would produce a stream that is cached under a scope key while carrying
319
+ * subject-dependent bytes — a disclosure, not a stale row.
320
+ */
321
+ export function readShapeTier(shape: ShapeSpec): ShapeTier {
322
+ if (shape.scope != null && shape.rowFilter != null) {
323
+ throw new Error(
324
+ `[pgxsinkit] shape "${shape.shapeKey}" declares both scope and rowFilter — a shape is shared ` +
325
+ `(scope: the predicate is a function of scope values only) or private (rowFilter: the subject ` +
326
+ `is fused into the predicate), never both. A rowFilter makes the stream's bytes ` +
327
+ `subject-dependent, so it cannot be served from a scope-keyed shared stream. Move the ` +
328
+ `subject-dependent part into the entitlement rule, or drop scope and keep this private.`,
329
+ );
330
+ }
331
+ return shape.scope != null ? "shared" : "private";
332
+ }
333
+
334
+ /**
335
+ * Refuse a shape whose `rowFilter` cannot actually filter.
336
+ *
337
+ * The control plane compiles a private-tier shape from `customPredicate` alone, so a filter that does
338
+ * not supply one is created with no subject test and streams **every** row to whoever subscribed. That
339
+ * is the precise shape of a silent authorization bypass: the registry says "filtered", the wire says
340
+ * "all rows", and nothing anywhere reports a discrepancy.
341
+ *
342
+ * The way to land there is a `rowFilter` that filters nothing at all — no predicate and no column
343
+ * allow-list — so it asserts a restriction it does not carry. (A filter holding *only* `columns` is
344
+ * legitimate: that is how `defineReadProjection` narrows a projection's wire columns without
345
+ * restricting its rows.)
346
+ *
347
+ * Refused at DEFINITION time, not at the first subscribe: declaring a `rowFilter` asserts that these
348
+ * rows are not for everyone, and there is no input for which a filter that cannot run could later turn
349
+ * out to be fine. A shape that genuinely serves every row omits `rowFilter` entirely — the difference
350
+ * between "no filter" and "a filter that does nothing" is exactly what this keeps expressible.
351
+ */
352
+ export function assertShapeFilterIsEnforceable(shape: ShapeSpec): void {
353
+ const filter = shape.rowFilter;
354
+ if (filter == null || filter.customPredicate != null) return;
355
+
356
+ if (filter.columns == null) {
357
+ throw new Error(
358
+ `[pgxsinkit] shape "${shape.shapeKey}" declares a rowFilter that restricts nothing — no ` +
359
+ `customPredicate and no column allow-list. Declare customPredicate, or drop the rowFilter if ` +
360
+ `the rows really are for everyone (an absent rowFilter is how a shape says so).`,
361
+ );
362
+ }
278
363
  }
279
364
 
280
365
  /** Input variant of {@link ShapeSpec} where `tableName` and `shapeKey` are optional.
281
366
  * When omitted, both default to the top-level `tableName` of the `defineSyncTable` call.
282
- * `electricTable` is deliberately absent — it is a resolved/internal field, never a consumer input
283
- * (see {@link ShapeSpec.electricTable}); a read projection over an existing table is authored with
367
+ * `physicalTable` is deliberately absent — it is a resolved/internal field, never a consumer input
368
+ * (see {@link ShapeSpec.physicalTable}); a read projection over an existing table is authored with
284
369
  * `defineReadProjection`, which derives it from the owner. */
285
- export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "electricTable"> & {
370
+ export type ShapeSpecInput = Omit<ShapeSpec, "tableName" | "shapeKey" | "physicalTable"> & {
286
371
  tableName?: string;
287
372
  shapeKey?: string;
288
373
  };
@@ -294,15 +379,16 @@ export interface RowTransformContext {
294
379
  }
295
380
 
296
381
  /**
297
- * Per-row rewrite applied in the proxy response path (after the row filter, before
298
- * column omission). Receives a shape-log row's column map (keys are wire/column names)
382
+ * Per-row rewrite applied on the server's read egress path (after the row filter, before
383
+ * column omission). Receives a streamed row's column map (keys are wire/column names)
299
384
  * and returns a possibly-rewritten one — letting the server strip a *sub-document* of a
300
385
  * jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses
301
386
  * what a static, whole-column `omitColumns` cannot.
302
387
  *
303
- * It runs only in the proxy's per-response path: it never alters the local PGlite schema,
304
- * never changes the Electric shape URL, and so never pollutes Electric's shared shape
305
- * cache. Return the same `row` reference to signal "no change".
388
+ * Server authority only: it never alters the local PGlite schema and never alters the shape
389
+ * definition — the engine ref-counts shapes by definition (ADR-0055), so a transform can
390
+ * neither change which stream a subject reads nor split one that would otherwise be shared.
391
+ * Return the same `row` reference to signal "no change".
306
392
  */
307
393
  export type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;
308
394
 
@@ -315,13 +401,13 @@ export interface ClientProjectionSpec {
315
401
  }
316
402
 
317
403
  /**
318
- * Server-side projection applied in the proxy response path. This is server
404
+ * Server-side projection applied on the read egress path. This is server
319
405
  * authority, not client shape — it never alters the local PGlite schema or the
320
- * Electric shape URL — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).
406
+ * shape definition — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).
321
407
  */
322
408
  export interface ServerProjectionSpec {
323
409
  /**
324
- * Optional per-row rewrite applied in the proxy response path. Runs before column
410
+ * Optional per-row rewrite applied on the read egress path. Runs before column
325
411
  * omission, so it may read a column (e.g. a control flag) that
326
412
  * `clientProjection.omitColumns` then removes from the client-visible row. See
327
413
  * {@link RowTransform}.
@@ -382,8 +468,9 @@ export interface TableSpecInput {
382
468
  clientProjection?: ClientProjectionSpec;
383
469
  governance?: TableGovernanceSpec;
384
470
  /**
385
- * Consistency group (ADR-0009 decision 2): tables sharing a group sync on one `MultiShapeStream`
386
- * and commit atomically at a shared LSN frontier. Absent → the table is its own singleton group.
471
+ * Consistency group (ADR-0009 decision 2): tables sharing a group sync on one set of streams and
472
+ * commit atomically — every stream up-to-date, then one transaction (ADR-0056). Absent → the table is
473
+ * its own singleton group.
387
474
  */
388
475
  consistencyGroup?: string;
389
476
  /**
@@ -404,12 +491,6 @@ export interface TableSpecInput {
404
491
  writeMode?: WriteMode;
405
492
  }
406
493
 
407
- export interface SyncConfigInput<TTables extends Record<string, TableSpecInput> = Record<string, TableSpecInput>> {
408
- electricUrl: string;
409
- localSchema?: string;
410
- tables: TTables;
411
- }
412
-
413
494
  export function getLocalSyncPrimaryKey(source: {
414
495
  primaryKey: PrimaryKeySpec;
415
496
  clientProjection?: Pick<ClientProjectionSpec, "localPrimaryKey">;
@@ -426,56 +507,47 @@ export function getLocalSyncPrimaryKeyColumns(source: {
426
507
 
427
508
  export interface RowFilterSpec {
428
509
  /**
429
- * The row filter: returns the Electric shape `where` for this request, or `null` to bypass
430
- * filtering (e.g. admin access). **Prefer returning a Drizzle `SQL` fragment** built from the
431
- * table's columns: reference each column through {@link c} (a bare, rename-safe identifier) and
432
- * embed request-derived values directly — they become **bound `$n` params**, never hand-escaped
433
- * literals. Enum columns must be cast to text (`${c(col)}::text = 'x'`) for Electric's grammar,
434
- * and subqueries must be self-contained (not correlated), since Electric needs plain column refs.
510
+ * The PRIVATE-TIER row filter (ADR-0055): the predicate fused with the caller's claims, compiled
511
+ * into the shape at subscribe. `null` bypasses filtering (all rows); {@link DENY_ALL_PREDICATE}
512
+ * denies.
435
513
  *
436
- * Returning a raw **string** is the escape hatch for a predicate Drizzle can't express. SECURITY:
437
- * a string is interpolated verbatim into the `where` — it is NOT escaped, so any request-derived
438
- * value you embed must be escaped/validated (`escapeSqlLiteral`) inside this function, or it is a
439
- * SQL-injection vector. Reach for the string form only when the Drizzle fragment cannot express it.
514
+ * Authored with the `p.*` builders over real Drizzle column objects, so a comparison is checked
515
+ * against the column's own TypeScript type — a mistyped enum label, a `null` against a NOT NULL
516
+ * column, or a `jsonb`/`Date` column with no scalar wire form are all compile errors rather than
517
+ * silently-wrong filters.
440
518
  *
441
- * **Must be pure.** The proxy already calls this fresh on every shape request; the client also
442
- * *probes* it with empty claims (`{}`) to detect claims-dependence (ADR-0039 —
443
- * {@link isClaimsDependentRowFilter}). Do not memoize, mutate external state, or assume it runs once.
519
+ * **Must be pure**: it is called fresh per shape creation, and probed with empty claims to detect
520
+ * claims-dependence (ADR-0039 — {@link isClaimsDependentRowFilter}).
444
521
  */
445
- customWhere?: (claims: JwtClaims, params?: Record<string, unknown>) => string | SQL | null;
522
+ customPredicate?: (claims: JwtClaims, params?: Record<string, unknown>) => Predicate | null;
446
523
  /** Column projection for the shape URL (e.g. ["id", "source_text"]). */
447
524
  columns?: string[];
448
525
  /**
449
- * An opaque version tag for the part of this filter the fingerprint cannot see — the `customWhere`
450
- * body (you cannot hash a closure; only its *presence* is fingerprinted). Bump this (any new
451
- * string/number) whenever you change that logic so the fingerprint shifts and the local read cache
452
- * rebuilds + the shape subscription resets. Leaving it unchanged after a `customWhere`
453
- * authorization change would silently serve the stale shape.
526
+ * An opaque version tag for the part of this filter the fingerprint cannot see — the
527
+ * `customPredicate` body (you cannot hash a closure; only its *presence* is fingerprinted). Bump
528
+ * this (any new string/number) whenever you change that logic so the fingerprint shifts and the
529
+ * local read cache rebuilds + the shape subscription resets. Leaving it unchanged after a
530
+ * `customPredicate` authorization change would silently serve the stale shape.
454
531
  */
455
532
  revision?: string | number;
456
533
  }
457
534
 
458
535
  /**
459
- * A **bare** (table-unqualified) quoted identifier for a Drizzle column — `"workspace_id"`, never
460
- * `"work_items"."workspace_id"`. Electric's shape `where` grammar requires *plain* column references
461
- * (it rejects a qualified one with "Expected a plain column reference"), and Drizzle qualifies columns
462
- * by default — so reference columns through `c()` when authoring a `customWhere` Drizzle fragment. The
463
- * column object keeps the reference rename-safe and existence-checked at compile time; only the bare
464
- * name reaches the wire. Subqueries must stay self-contained (not correlated), since bare names then
465
- * resolve unambiguously to each FROM — a correlated subquery would need qualification Electric rejects.
466
- */
467
- export function c(column: AnyColumn): SQL {
468
- return sql`${sql.identifier(column.name)}`;
469
- }
470
-
471
- /**
472
- * The deny-all row filter: a `customWhere` returns this to make **no** rows visible (e.g. an
536
+ * The deny-all predicate: a `customPredicate` returns this to make **no** rows visible (e.g. an
473
537
  * unauthenticated request), the counterpart to returning `null` (which bypasses filtering — all rows
474
- * visible). It is a Drizzle `SQL` fragment (`false`), so it stays on the typed/parameterized path
475
- * with the rest of the filter rather than being a hand-written `"1 = 0"` string. `WHERE false`
476
- * matches nothing; Electric accepts it (verified) exactly as it accepts `1 = 0`.
538
+ * visible).
539
+ *
540
+ * An empty `OR` rather than a synthetic always-false comparison: the engine evaluates it as FALSE by
541
+ * construction (`Or` starts at FALSE and only TRUE dominates), it needs no column to name, and it
542
+ * cannot be made accidentally true by a NULL cell the way `col <> col` can.
543
+ *
544
+ * The control plane recognises it **by reference identity** and declines to create the shape at all,
545
+ * so a denied subject holds no handle and no stream is materialised — a stronger outcome than an
546
+ * empty stream, and the reason this is a frozen singleton rather than a shape a caller might
547
+ * reconstruct. A structurally equal but distinct `{ or: [] }` is still correct on the wire; it just
548
+ * costs an empty shape instead of a refusal.
477
549
  */
478
- export const DENY_ALL: SQL = sql`false`;
550
+ export const DENY_ALL_PREDICATE: Predicate = Object.freeze({ or: [] as Predicate[] });
479
551
 
480
552
  /**
481
553
  * Whether a row filter denies (or cannot serve) an unauthenticated caller — a *claims-dependent*
@@ -483,65 +555,35 @@ export const DENY_ALL: SQL = sql`false`;
483
555
  * claims-dependent, activated with no auth token, opens an empty subscription by construction, so
484
556
  * the client warns.
485
557
  *
486
- * A filter is claims-dependent when its `customWhere`, evaluated with **empty claims** (`{}` —
487
- * exactly what the proxy passes for an unauthenticated request) and no params, either **throws** or
488
- * returns the {@link DENY_ALL} sentinel by **reference identity** (which every contracts helper —
489
- * {@link buildOwnershipShapeWhere} and friends — returns for a missing subject, and which is already
490
- * the documented deny-anonymous pattern). Any other result — `null` (no filtering), a string, or a
491
- * different `SQL` fragment — is not claims-dependent as far as this probe can tell.
558
+ * A filter is claims-dependent when its `customPredicate`, evaluated with **empty claims** (`{}` —
559
+ * exactly what the control plane passes for an unauthenticated request) and no params, either
560
+ * **throws** or returns the {@link DENY_ALL_PREDICATE} sentinel by **reference identity** (which every
561
+ * contracts helper — {@link buildOwnershipShapePredicate} and friends — returns for a missing subject,
562
+ * and which is already the documented deny-anonymous pattern). Any other result — `null` (no
563
+ * filtering) or a different predicate — is not claims-dependent as far as this probe can tell.
492
564
  *
493
- * Requires `customWhere` to be pure (its contract; see {@link RowFilterSpec.customWhere}).
565
+ * Requires `customPredicate` to be pure (its contract; see {@link RowFilterSpec.customPredicate}).
494
566
  */
495
567
  export function isClaimsDependentRowFilter(filter: RowFilterSpec | undefined): boolean {
496
- if (!filter?.customWhere) {
568
+ if (!filter?.customPredicate) {
497
569
  return false;
498
570
  }
499
571
 
500
572
  try {
501
- return filter.customWhere({}, undefined) === DENY_ALL;
573
+ return filter.customPredicate({}, undefined) === DENY_ALL_PREDICATE;
502
574
  } catch {
503
575
  return true;
504
576
  }
505
577
  }
506
578
 
507
579
  /**
508
- * The ownership shape `where` — the read-path mirror of an owner-column RLS policy: rows whose owner
509
- * column equals the caller's subject, {@link DENY_ALL} for an unauthenticated caller. Takes the real
510
- * Drizzle owner column (bare via {@link c}, rename-safe); the subject rides as a typed interpolation —
511
- * a bound param through `buildRowFilterShape`, or a drizzle-escaped literal when a proxy renders it
512
- * inline for a shape URL.
513
- */
514
- export function buildOwnershipShapeWhere(ownerColumn: AnyColumn, subject: string | null | undefined): SQL {
515
- return subject == null || subject === "" ? DENY_ALL : sql`${c(ownerColumn)} = ${subject}`;
516
- }
517
-
518
- /** The parameterized shape filter the proxy sends to Electric: a `where` and its positional params. */
519
- export interface RowFilterShape {
520
- where: string;
521
- params: string[];
522
- }
523
-
524
- /**
525
- * The shape filter the proxy sends to Electric: the `where` plus its positional `params` (`$1`, `$2`,
526
- * …). A `customWhere` returning a Drizzle `SQL` fragment is serialized here, so request-derived values
527
- * become **bound params** — never hand-escaped literals; a string `customWhere` is the raw escape
528
- * hatch (no params). Returns `null` when there is no filter (all rows visible).
580
+ * The ownership **predicate** the read path filters on: rows whose owner column equals the caller's
581
+ * subject, {@link DENY_ALL_PREDICATE} for an unauthenticated caller (by reference, so a
582
+ * `customPredicate` built on it probes claims-dependent).
583
+ *
584
+ * Takes the real Drizzle owner column, so the reference is rename-safe, and the subject rides as a
585
+ * typed JSON scalar rather than text that has to be escaped and re-parsed.
529
586
  */
530
- export function buildRowFilterShape(
531
- filter: RowFilterSpec,
532
- claims: JwtClaims | null,
533
- params?: Record<string, unknown>,
534
- ): RowFilterShape | null {
535
- const custom = filter.customWhere?.(claims ?? {}, params);
536
-
537
- if (custom == null) {
538
- return null;
539
- }
540
-
541
- if (typeof custom === "string") {
542
- return custom ? { where: custom, params: [] } : null;
543
- }
544
-
545
- const compiled = pgDialect.sqlToQuery(custom);
546
- return { where: compiled.sql, params: compiled.params.map((value) => String(value)) };
587
+ export function buildOwnershipShapePredicate(ownerColumn: AnyColumn, subject: string | null | undefined): Predicate {
588
+ return subject == null || subject === "" ? DENY_ALL_PREDICATE : p.eq(ownerColumn, subject);
547
589
  }
@@ -169,11 +169,11 @@ export const CONVERGENCE_EVENTS = [
169
169
  "journal row → acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up",
170
170
  },
171
171
  {
172
- event: "Electric insert/update observed",
172
+ event: "synced upsert observed",
173
173
  effect: "synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal",
174
174
  },
175
175
  {
176
- event: "Electric delete observed",
176
+ event: "synced delete observed",
177
177
  effect: "resolved by synced-row absence (deletes carry no Server version — ADR-0010)",
178
178
  },
179
179
  { event: "resolution", effect: "clear overlay/journal only through the shared barrier predicate (decision 4)" },
@@ -72,7 +72,7 @@ export interface EventStreamEntry<TPayload extends z.ZodType = z.ZodType> {
72
72
  identity: Record<string, EventStreamIdentityField>;
73
73
  /**
74
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
75
+ * role `RowFilterSpec.revision` plays for a `customPredicate` closure. The lock hashes the payload schema as
76
76
  * a **JSON Schema**, and refinements/transforms are simply not representable there: a reviewer
77
77
  * demonstrated that `z.string().refine(v => v.length >= 3)` and the INCOMPATIBLE `>= 10` version produce
78
78
  * the identical stream hash, so the `risky` diff the ADR relies on never fires.
@@ -1,6 +1,14 @@
1
1
  import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
2
 
3
3
  import type { RowFilterSpec } from "./config";
4
+ import {
5
+ isAndPredicate,
6
+ isInSubqueryPredicate,
7
+ isIsNullPredicate,
8
+ isNotPredicate,
9
+ isOrPredicate,
10
+ type Predicate,
11
+ } from "./predicate";
4
12
  import type { SyncTableEntry, SyncTableRegistry } from "./registry";
5
13
 
6
14
  /**
@@ -9,10 +17,10 @@ import type { SyncTableEntry, SyncTableRegistry } from "./registry";
9
17
  *
10
18
  * This is the single source of "has the shape changed" — consumed as the local-DB
11
19
  * version key and as the basis of the registry-diff gate (ADR-0006). Function *bodies*
12
- * (`rowTransform`, `customWhere`) cannot be fingerprinted and are excluded — but their
20
+ * (`rowTransform`, `customPredicate`) cannot be fingerprinted and are excluded — but their
13
21
  * *presence* and the surrounding **static** filter structure (the projected columns)
14
22
  * participate. For the invisible *logic* itself, a consumer-bumped `rowFilter.revision` is
15
- * folded in: changing it is how a `customWhere` authorization change is forced to shift the
23
+ * folded in: changing it is how a `customPredicate` authorization change is forced to shift the
16
24
  * fingerprint (and so rebuild the cache + reset the subscription).
17
25
  */
18
26
 
@@ -39,8 +47,18 @@ export interface CanonicalTable {
39
47
  shape: {
40
48
  tableName: string;
41
49
  shapeKey: string;
42
- electricTable: string | null;
50
+ physicalTable: string | null;
43
51
  rowFilter: CanonicalRowFilter | null;
52
+ /** Shared-tier scope columns, in declaration order — the order parameterizes the family. */
53
+ scope: string[] | null;
54
+ /**
55
+ * The native static predicate, canonicalized in full.
56
+ *
57
+ * Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only
58
+ * ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing
59
+ * a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.
60
+ */
61
+ where: string | null;
44
62
  } | null;
45
63
  managedFields: Array<{ field: string; strategy: string; applyOn: string[] }>;
46
64
  /**
@@ -61,16 +79,16 @@ export interface CanonicalTable {
61
79
 
62
80
  /**
63
81
  * The static, fingerprint-able structure of a row filter. A changed projection shifts the
64
- * fingerprint, so the local store rebuilds and the diff gate flags it. `customWhere`'s body is
65
- * invisible — only its presence (`hasCustomWhere`) is recorded — so a `customWhere` *logic* change
82
+ * fingerprint, so the local store rebuilds and the diff gate flags it. `customPredicate`'s body is
83
+ * invisible — only its presence (`hasCustomPredicate`) is recorded — so a `customPredicate` *logic* change
66
84
  * is surfaced only by bumping `revision`.
67
85
  */
68
86
  export interface CanonicalRowFilter {
69
- hasCustomWhere: boolean;
87
+ hasCustomPredicate: boolean;
70
88
  columns: string[] | null;
71
89
  /**
72
- * The consumer-supplied version tag for the non-fingerprintable filter logic (the `customWhere`
73
- * body). Changing it shifts the fingerprint, which is the only way a `customWhere` *logic* change
90
+ * The consumer-supplied version tag for the non-fingerprintable filter logic (the `customPredicate`
91
+ * body). Changing it shifts the fingerprint, which is the only way a `customPredicate` *logic* change
74
92
  * forces a cache + subscription reset.
75
93
  */
76
94
  revision: string | null;
@@ -108,12 +126,42 @@ function canonicalizeManagedFields(entry: SyncTableEntry): CanonicalTable["manag
108
126
  .sort((a, b) => asString(a.field, b.field));
109
127
  }
110
128
 
129
+ /**
130
+ * A stable string form of a native predicate.
131
+ *
132
+ * Keys are emitted in a fixed order rather than serialized as authored, so two predicates that
133
+ * differ only in how their object literals were written fingerprint identically — otherwise a
134
+ * cosmetic edit would force every client to rebuild its local cache.
135
+ */
136
+ function canonicalizePredicate(node: Predicate | undefined): string | null {
137
+ if (node === undefined) return null;
138
+ const render = (current: Predicate): unknown => {
139
+ if (isAndPredicate(current)) return { and: current.and.map(render) };
140
+ if (isOrPredicate(current)) return { or: current.or.map(render) };
141
+ if (isNotPredicate(current)) return { not: render(current.not) };
142
+ if (isInSubqueryPredicate(current)) {
143
+ return {
144
+ col: current.col,
145
+ in: {
146
+ table: current.in.table,
147
+ project: current.in.project,
148
+ where: current.in.where ? render(current.in.where) : null,
149
+ },
150
+ negated: current.negated === true,
151
+ };
152
+ }
153
+ if (isIsNullPredicate(current)) return { col: current.col, isNull: current.isNull };
154
+ return { col: current.col, op: current.op, value: current.value };
155
+ };
156
+ return JSON.stringify(render(node));
157
+ }
158
+
111
159
  function canonicalizeRowFilter(filter: RowFilterSpec | undefined): CanonicalRowFilter | null {
112
160
  if (!filter) {
113
161
  return null;
114
162
  }
115
163
  return {
116
- hasCustomWhere: filter.customWhere != null,
164
+ hasCustomPredicate: filter.customPredicate != null,
117
165
  columns: filter.columns ? [...filter.columns].sort(asString) : null,
118
166
  revision: filter.revision != null ? String(filter.revision) : null,
119
167
  };
@@ -133,8 +181,10 @@ function canonicalizeTable(key: string, entry: SyncTableEntry): CanonicalTable {
133
181
  ? {
134
182
  tableName: entry.shape.tableName,
135
183
  shapeKey: entry.shape.shapeKey,
136
- electricTable: entry.shape.electricTable ?? null,
184
+ physicalTable: entry.shape.physicalTable ?? null,
137
185
  rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
186
+ scope: entry.shape.scope ? [...entry.shape.scope] : null,
187
+ where: canonicalizePredicate(entry.shape.where),
138
188
  }
139
189
  : null;
140
190
 
@@ -198,7 +248,7 @@ export function fingerprintRegistry(registry: SyncTableRegistry): string {
198
248
  /**
199
249
  * The **read contract** of a single sync table: the subset of its canonical shape that decides what
200
250
  * data streams down and how a row is identified and filtered — synced-table name, columns, primary key
201
- * (and any local-PK override), column omission, and the shape (electric table + row filter). It is the
251
+ * (and any local-PK override), column omission, and the shape (physical table + row filter). It is the
202
252
  * stable identity a writable entry shares with its {@link asReadonly} projection.
203
253
  *
204
254
  * Deliberately EXCLUDES the two axes a per-client projection may legitimately differ on:
@@ -209,7 +259,7 @@ export function fingerprintRegistry(registry: SyncTableRegistry): string {
209
259
  *
210
260
  * What it pins is the data itself: two registries that present "the same" logical table to different
211
261
  * clients must agree here, or those clients are silently seeing different rows/columns. As with the
212
- * full registry fingerprint, the `customWhere` *body* is invisible — only its presence and the
262
+ * full registry fingerprint, the `customPredicate` *body* is invisible — only its presence and the
213
263
  * consumer-bumped {@link RowFilterSpec.revision} participate, so bump `revision` to force a divergence
214
264
  * a logic-only change would otherwise hide.
215
265
  */
@@ -222,8 +272,18 @@ export interface CanonicalReadContract {
222
272
  shape: {
223
273
  tableName: string;
224
274
  shapeKey: string;
225
- electricTable: string | null;
275
+ physicalTable: string | null;
226
276
  rowFilter: CanonicalRowFilter | null;
277
+ /** Shared-tier scope columns, in declaration order — the order parameterizes the family. */
278
+ scope: string[] | null;
279
+ /**
280
+ * The native static predicate, canonicalized in full.
281
+ *
282
+ * Unlike `customPredicate`, this one is *visible*: an AST can be hashed, where a closure could only
283
+ * ever be fingerprinted by its presence. So the `revision` footgun does not apply here — editing
284
+ * a native `where` shifts the fingerprint by itself, and a consumer cannot forget to say so.
285
+ */
286
+ where: string | null;
227
287
  } | null;
228
288
  }
229
289
 
@@ -233,8 +293,10 @@ export function canonicalizeReadContract(entry: SyncTableEntry): CanonicalReadCo
233
293
  ? {
234
294
  tableName: entry.shape.tableName,
235
295
  shapeKey: entry.shape.shapeKey,
236
- electricTable: entry.shape.electricTable ?? null,
296
+ physicalTable: entry.shape.physicalTable ?? null,
237
297
  rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
298
+ scope: entry.shape.scope ? [...entry.shape.scope] : null,
299
+ where: canonicalizePredicate(entry.shape.where),
238
300
  }
239
301
  : null;
240
302
 
package/src/index.ts CHANGED
@@ -9,9 +9,11 @@ export * from "./registry";
9
9
  export * from "./registry-diff";
10
10
  export * from "./registry-invariant";
11
11
  export * from "./mutation";
12
+ export * from "./predicate";
12
13
  export * from "./projection";
13
14
  export * from "./runtime";
14
15
  export * from "./sql-defaults";
16
+ export * from "./stream-envelope";
15
17
  export * from "./sql-identifier";
16
18
  export * from "./sql-role-guard";
17
19
  export * from "./supabase-rls";