@pgxsinkit/contracts 0.1.51 → 0.2.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/registry.ts CHANGED
@@ -4,6 +4,9 @@ import {
4
4
  getTableConfig,
5
5
  pgTable,
6
6
  pgView,
7
+ primaryKey as pgPrimaryKey,
8
+ PrimaryKeyBuilder,
9
+ type AnyPgColumn,
7
10
  type AnyPgTable,
8
11
  type PgBigInt64Builder,
9
12
  type PgBuildColumns,
@@ -26,9 +29,13 @@ import {
26
29
  CONFLICT_POLICIES,
27
30
  isConflictPolicy,
28
31
  isRetention,
32
+ isStorageBackend,
33
+ isStorageDurability,
29
34
  isSubscriptionTiming,
30
35
  isWriteMode,
31
36
  RETENTIONS,
37
+ STORAGE_BACKENDS,
38
+ STORAGE_DURABILITIES,
32
39
  SUBSCRIPTION_TIMINGS,
33
40
  WRITE_MODES,
34
41
  type ClientProjectionSpec,
@@ -44,6 +51,7 @@ import {
44
51
  type ShapeSpec,
45
52
  type ShapeSpecInput,
46
53
  type SubscriptionTiming,
54
+ type SyncStorageDeclaration,
47
55
  type TableGovernanceSpec as TableGovernanceSpecBase,
48
56
  type TableMode,
49
57
  type WriteMode,
@@ -116,6 +124,15 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
116
124
  view?: AnyPgView | undefined;
117
125
  mode: TableMode;
118
126
  primaryKey: PrimaryKeySpec;
127
+ /**
128
+ * CDC insert-apply policy (ADR-0045). Default `"insert"`: a server CDC `insert` is applied as a plain
129
+ * INSERT, so a genuine primary-key collision surfaces (the ADR-0014 collision-surfacing invariant).
130
+ * `"upsert"`: this table legitimately receives locally-derived provisional rows (e.g. written by a
131
+ * local trigger from another synced table), so server CDC inserts are applied idempotently as
132
+ * `INSERT … ON CONFLICT (pk) DO UPDATE` — the authoritative server row overwrites the provisional
133
+ * local row instead of failing the commit. Resolved to `"insert"` when omitted.
134
+ */
135
+ applyMode: "insert" | "upsert";
119
136
  shape?: ShapeSpec;
120
137
  clientProjection?: ClientProjectionSpecForTable<TTable>;
121
138
  serverProjection?: ServerProjectionSpec;
@@ -130,8 +147,9 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
130
147
  * Consistency group (ADR-0009 decision 2). Tables sharing a `consistencyGroup` are synced on one
131
148
  * `MultiShapeStream` and committed atomically at a shared LSN frontier, so a local reader never
132
149
  * sees one grouped table advanced past another for the same server transaction. Omitted → the
133
- * table is its own singleton group (independent frontier, today's behaviour). The latency cost (a
134
- * group advances only as fast as its slowest shape) is contained to the tables that opt in.
150
+ * table is its own singleton group (independent frontier, no cross-table atomicity — the resolution
151
+ * for a table that declares no group). The latency cost (a group advances only as fast as its
152
+ * slowest shape) is contained to the tables that opt in.
135
153
  */
136
154
  consistencyGroup?: string;
137
155
  /**
@@ -261,17 +279,16 @@ export type SyncTableInputProjection<
261
279
  };
262
280
 
263
281
  /**
264
- * A row filter for {@link defineSyncTable}'s `shape`: either a static {@link RowFilterSpec}, or a
265
- * function of the table's built (typed) columns. The function form is the all-in-one way to author a
266
- * typed-Drizzle row filter inline — reference columns through `c(columns.x)` exactly as `extras`
267
- * does with its `self` argument, so `customWhere` builds parameterized Electric `where`s from real,
268
- * rename-safe column objects instead of hand-written column-name strings.
282
+ * A row filter for {@link defineSyncTable}'s `shape`, authored from the table's built, typed columns.
283
+ * Reference columns through `c(columns.x)` exactly as `extras` does with its `self` argument, so
284
+ * `customWhere` builds parameterized Electric `where`s from real, rename-safe column objects instead
285
+ * of hand-written column-name strings.
269
286
  */
270
- export type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> =
271
- | RowFilterSpec
272
- | ((columns: PgBuildExtraConfigColumns<TColumns>) => RowFilterSpec);
287
+ export type RowFilterInput<TColumns extends Record<string, ColumnBuilderBase>> = (
288
+ columns: PgBuildExtraConfigColumns<TColumns>,
289
+ ) => RowFilterSpec;
273
290
 
274
- /** {@link ShapeSpecInput} whose `rowFilter` may also be a function of the built columns (typed by `TColumns`). */
291
+ /** {@link ShapeSpecInput} whose `rowFilter` is authored from the built columns (typed by `TColumns`). */
275
292
  export type ShapeSpecInputFor<TColumns extends Record<string, ColumnBuilderBase>> = Omit<
276
293
  ShapeSpecInput,
277
294
  "rowFilter"
@@ -305,10 +322,31 @@ export type SyncTableInput<
305
322
  /** @default "readonly" */
306
323
  mode?: TableMode;
307
324
  /**
308
- * Primary key column names. Defaults to `["id"]`.
309
- * Use an array with multiple entries for composite keys.
325
+ * THE primary key of the server table — the single source of truth for its physical
326
+ * `PRIMARY KEY` constraint. `defineSyncTable` emits it as the constraint, named
327
+ * `` `${tableName}_pkey` `` (matching Postgres's inline-PK default, so existing consumer
328
+ * databases see no rename churn) unless the object form overrides `name`.
329
+ *
330
+ * Defaults to `["id"]`. Use an array with multiple entries for composite keys, or the object
331
+ * form `{ name, columns }` to name the constraint.
332
+ *
333
+ * A single-column key MAY equivalently be declared via the column's own `.primaryKey()`
334
+ * (idiomatic drizzle); it must match this spec, and emission is then skipped because the
335
+ * column already carries the constraint. A table-level `primaryKey(...)` in `extras`/`policies`
336
+ * is REJECTED — declare the key here instead.
337
+ */
338
+ primaryKey?: string[] | { name: string; columns: string[] };
339
+ /**
340
+ * CDC insert-apply policy (ADR-0045). **Default `"insert"`** — a CDC insert is a plain INSERT, so a
341
+ * genuine PK collision must surface (the ADR-0014 collision-surfacing invariant; a synced cache table
342
+ * is server-authoritative and a duplicate insert is a real bug). Set `"upsert"` **only** when this
343
+ * table legitimately receives locally-DERIVED provisional rows — e.g. a local trigger on another
344
+ * synced table inserts a provisional row here, and the server independently creates the same row so
345
+ * its CDC insert would collide (23505). With `"upsert"`, server CDC inserts are applied idempotently
346
+ * as `INSERT … ON CONFLICT (pk) DO UPDATE`; the authoritative server row overwrites the provisional
347
+ * local row. Declare the exception here, where it lives — do not weaken the invariant repo-wide.
310
348
  */
311
- primaryKey?: string[];
349
+ applyMode?: "insert" | "upsert";
312
350
  shape?: ShapeSpecInputFor<TColumns>;
313
351
  clientProjection?: SyncTableInputProjection<TColumns, TOmittedColumns>;
314
352
  /** Server-side response-path projection (e.g. `rowTransform`). Server authority, not client shape. */
@@ -346,10 +384,20 @@ export type SyncTableRegistry = Record<string, SyncTableEntry>;
346
384
  export interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {
347
385
  schema?: string;
348
386
  tables: TRegistry;
387
+ /**
388
+ * The storage contract for every store this registry mints (ADR-0049 decision 1, ADR-0047). Part of the
389
+ * DATA contract, not a per-open knob: `durability` binds every toolkit-minted open (relaxed default),
390
+ * and `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones
391
+ * unaffected). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried through on
392
+ * the returned registry and read back with {@link getSyncRegistryStorage}. See {@link SyncStorageDeclaration}.
393
+ */
394
+ storage?: SyncStorageDeclaration;
349
395
  }
350
396
 
351
397
  export const syncRegistrySchemaSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistrySchema");
352
398
 
399
+ export const syncRegistryStorageSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryStorage");
400
+
353
401
  export type RegistryTables<TRegistry extends SyncTableRegistry> = {
354
402
  [TKey in keyof TRegistry]: TRegistry[TKey]["table"];
355
403
  };
@@ -452,6 +500,7 @@ export function defineSyncTable<
452
500
  schema,
453
501
  mode,
454
502
  primaryKey,
503
+ applyMode,
455
504
  governance,
456
505
  clientProjection,
457
506
  serverProjection,
@@ -460,7 +509,55 @@ export function defineSyncTable<
460
509
  } = input;
461
510
 
462
511
  const resolvedMode: TableMode = mode ?? "readonly";
463
- const resolvedPrimaryKey: PrimaryKeySpec = { columns: primaryKey ?? ["id"] };
512
+
513
+ // The `primaryKey` spec is the SINGLE SOURCE OF TRUTH for the server table's physical PRIMARY KEY.
514
+ // It was runtime-only metadata until a consumer (transcrobes) had drizzle-kit DROP a composite PK
515
+ // from a live DB because nothing re-declared it in DDL — so `defineSyncTable` now emits the
516
+ // constraint itself. The default constraint name `${tableName}_pkey` matches Postgres's inline-PK
517
+ // naming, so existing consumer databases see no rename churn; the object form overrides it.
518
+ const primaryKeyColumns = Array.isArray(primaryKey) ? primaryKey : (primaryKey?.columns ?? ["id"]);
519
+ const resolvedPrimaryKey: PrimaryKeySpec = { columns: primaryKeyColumns };
520
+
521
+ // ADR-0045: default to the strict `"insert"` policy (a CDC insert is a plain INSERT — a genuine PK
522
+ // collision must surface). Only tables that legitimately receive locally-derived provisional rows opt
523
+ // into idempotent `"upsert"` apply of server CDC inserts.
524
+ const resolvedApplyMode: "insert" | "upsert" = applyMode ?? "insert";
525
+ const customPrimaryKeyName = !Array.isArray(primaryKey) ? primaryKey?.name : undefined;
526
+ const primaryKeyConstraintName = customPrimaryKeyName ?? `${tableName}_pkey`;
527
+
528
+ // Probe the columns (no extras — cheap) to detect idiomatic column-level `.primaryKey()` flags and
529
+ // to resolve each spec column to its PROPERTY KEY (spec entries may be given as the SQL column name
530
+ // or the property key, matching the omitColumns precedent below).
531
+ const probeColumns = getColumns(pgTable(tableName, makeColumns())) as Record<string, AnyPgColumn>;
532
+ const columnLevelPkKeys = Object.entries(probeColumns)
533
+ .filter(([, col]) => col.primary === true)
534
+ .map(([key]) => key);
535
+ const specPropertyKeys = primaryKeyColumns.map((key) => {
536
+ if (probeColumns[key]) return key;
537
+ const byColumnName = Object.entries(probeColumns).find(([, col]) => col.name === key);
538
+ if (byColumnName) return byColumnName[0];
539
+ throw new Error(`[pgxsinkit] ${tableName}: primaryKey column "${key}" not found among the table's columns`);
540
+ });
541
+
542
+ if (columnLevelPkKeys.length > 1) {
543
+ throw new Error(
544
+ `[pgxsinkit] ${tableName}: multiple columns declare .primaryKey() (${columnLevelPkKeys.join(", ")}) — declare a composite key via the primaryKey option ({ name?, columns }) and remove the column-level .primaryKey() flags; the spec is the single source of truth`,
545
+ );
546
+ }
547
+ if (columnLevelPkKeys.length === 1) {
548
+ const columnLevelPkKey = columnLevelPkKeys[0]!;
549
+ if (specPropertyKeys.length !== 1 || specPropertyKeys[0] !== columnLevelPkKey) {
550
+ throw new Error(
551
+ `[pgxsinkit] ${tableName}: column "${columnLevelPkKey}" declares .primaryKey() but the primaryKey spec is [${resolvedPrimaryKey.columns.join(", ")}] — they must match; the spec is the single source of truth`,
552
+ );
553
+ }
554
+ if (customPrimaryKeyName != null && customPrimaryKeyName !== `${tableName}_pkey`) {
555
+ throw new Error(
556
+ `[pgxsinkit] ${tableName}: a custom primary-key name ("${customPrimaryKeyName}") requires defineSyncTable to emit the constraint — remove .primaryKey() from column "${columnLevelPkKey}" so the named constraint can be emitted`,
557
+ );
558
+ }
559
+ }
560
+ const emitPrimaryKey = columnLevelPkKeys.length === 0;
464
561
 
465
562
  const resolvedClientProjection =
466
563
  resolvedMode !== "writeonly" || clientProjection != null
@@ -477,22 +574,29 @@ export function defineSyncTable<
477
574
  : undefined;
478
575
 
479
576
  const extrasFn =
480
- policies || extras
481
- ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => [
482
- ...(policies ?? []),
483
- ...(extras ? extras(self) : []),
484
- ]
577
+ policies || extras || emitPrimaryKey
578
+ ? (self: PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>) => {
579
+ const consumerExtras = [...(policies ?? []), ...(extras ? extras(self) : [])];
580
+ for (const extra of consumerExtras) {
581
+ if (extra instanceof PrimaryKeyBuilder) {
582
+ throw new Error(
583
+ `[pgxsinkit] ${tableName}: declare the primary key via the primaryKey option (string[] or { name, columns }), not a primaryKey(...) extra — the spec is the single source of truth and defineSyncTable emits the constraint`,
584
+ );
585
+ }
586
+ }
587
+ if (!emitPrimaryKey) return consumerExtras;
588
+ const selfCols = self as unknown as Record<string, AnyPgColumn>;
589
+ const pkColumns = specPropertyKeys.map((k) => selfCols[k]!) as [AnyPgColumn, ...AnyPgColumn[]];
590
+ return [...consumerExtras, pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];
591
+ }
485
592
  : undefined;
486
593
  const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);
487
594
 
488
- // A function-form `shape.rowFilter` is resolved here against the built (typed) columns, so an
489
- // all-in-one `defineSyncTable` can author a row filter with `c(columns.x)` Drizzle fragments — the
490
- // same typed columns `extras` receives — instead of hand-written column-name strings. A static
491
- // `RowFilterSpec` passes through unchanged.
492
- const resolvedRowFilter: RowFilterSpec | undefined =
493
- typeof shape?.rowFilter === "function"
494
- ? shape.rowFilter(getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>)
495
- : (shape?.rowFilter ?? undefined);
595
+ // Resolve `shape.rowFilter` against the built typed columns so all authoring uses rename-safe
596
+ // Drizzle column objects rather than hand-written column-name strings.
597
+ const resolvedRowFilter = shape?.rowFilter?.(
598
+ getColumns(table) as unknown as PgBuildExtraConfigColumns<ReturnType<typeof makeColumns>>,
599
+ );
496
600
  const resolvedShape: ShapeSpec | undefined =
497
601
  resolvedMode !== "writeonly" || shape != null
498
602
  ? {
@@ -525,6 +629,7 @@ export function defineSyncTable<
525
629
  ...otherRest,
526
630
  mode: resolvedMode,
527
631
  primaryKey: resolvedPrimaryKey,
632
+ applyMode: resolvedApplyMode,
528
633
  ...(resolvedShape != null ? { shape: resolvedShape } : {}),
529
634
  // The input specs are typed over the builder columns map (keys of
530
635
  // TColumns); the entry fields demand specs typed over the built table.
@@ -632,7 +737,7 @@ export function defineReadProjection<
632
737
  /** Column keys (of the owner) to sync locally + fetch from Electric. The PK is always kept. Omit → all. */
633
738
  columns?: TColumns;
634
739
  /** Row filter for this shape; the callback form receives the owner's full (physical) columns. */
635
- rowFilter?: RowFilterSpec | ((columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec);
740
+ rowFilter?: (columns: TableColumnsShape<TOwnerTable>) => RowFilterSpec;
636
741
  /**
637
742
  * Server-side egress projection (ADR-0004) for THIS shape — typically a `rowTransform` that redacts a
638
743
  * sub-document of a kept column conditionally on row data. A projection does NOT inherit its owner's
@@ -789,10 +894,7 @@ export function defineReadProjection<
789
894
 
790
895
  // Resolve the row filter against the OWNER's full columns (the customWhere runs in Electric on the
791
896
  // physical table, so it may reference a column the subset omits).
792
- const resolvedRowFilter: RowFilterSpec | undefined =
793
- typeof opts.rowFilter === "function"
794
- ? opts.rowFilter(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>)
795
- : opts.rowFilter;
897
+ const resolvedRowFilter = opts.rowFilter?.(getColumns(owner.table) as unknown as TableColumnsShape<TOwnerTable>);
796
898
 
797
899
  // When a subset is requested, set the Electric `columns` allow-list to the KEPT physical column names
798
900
  // so an omitted (e.g. heavy jsonb) column is never fetched over the wire — not merely stripped after.
@@ -864,8 +966,14 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
864
966
  }
865
967
  validateRegistryTableUniqueness(input.tables);
866
968
  validateRegistryLifecycleGroups(input.tables);
867
-
868
- return attachSyncRegistrySchema(input.tables, input.schema);
969
+ validateStorageDeclaration(input.storage);
970
+
971
+ // Schema first (it may return the same tables object), then stamp the storage declaration on the
972
+ // returned registry as a non-enumerable symbol — the same carrier pattern as the schema symbol — so
973
+ // client code reads the data-contract storage back off the registry value (getSyncRegistrySchema's
974
+ // twin, getSyncRegistryStorage). The bare-registry-map overload carries no storage and reads back
975
+ // `undefined`, which resolves to the ADR-0047 defaults at the mint seam.
976
+ return attachSyncRegistryStorage(attachSyncRegistrySchema(input.tables, input.schema), input.storage);
869
977
  }
870
978
 
871
979
  for (const entry of getRegistryEntries(input)) {
@@ -1008,12 +1116,19 @@ export function getProjectedColumnNames<TTable extends AnyPgTable>(entry: SyncTa
1008
1116
  */
1009
1117
  export function deriveSyncColumnTypes<TTable extends AnyPgTable>(entry: SyncTableEntry<TTable>): SyncColumnType[] {
1010
1118
  return getProjectedColumns(entry).map(({ column, columnName }) => {
1011
- const typedColumn = column as { getSQLType?: () => string; dimensions?: number };
1119
+ const typedColumn = column as { getSQLType?: () => string; dimensions?: number; columnType?: string };
1012
1120
  const sqlType = normalizeCastPositionType(typedColumn.getSQLType?.() ?? "");
1013
1121
  return {
1014
1122
  name: columnName,
1015
1123
  sqlType,
1016
1124
  isArray: (typedColumn.dimensions ?? 0) > 0,
1125
+ // A real Postgres enum column brands as `PgEnumColumn`. `enumValues` is NOT the discriminator:
1126
+ // `text("c", { enum: […] })` / varchar variants expose `enumValues` too but their `getSQLType()` is
1127
+ // a BASE type (`text`, `varchar(255)`) — identifier-quoting that as a cast type would be wrong (and
1128
+ // broken for parameterised types). For a true enum, `getSQLType()` returns the enum TYPE NAME
1129
+ // (usable as a cast type once quoted) — the flag lets the ladder classify it as COPY/JSON-safe
1130
+ // instead of falling to the `insert` floor on the unrecognised type name.
1131
+ isEnum: typedColumn.columnType?.startsWith("PgEnum") === true,
1017
1132
  } satisfies SyncColumnType;
1018
1133
  });
1019
1134
  }
@@ -1073,15 +1188,10 @@ export function resolveServerVersionColumnName<TTable extends AnyPgTable>(
1073
1188
  return undefined;
1074
1189
  }
1075
1190
 
1191
+ // `field.column` is the drizzle property key (registry validation rejects a column-name declaration —
1192
+ // ADR-0012); resolve it to the underlying SQL column name.
1076
1193
  const columns = getColumns(entry.table);
1077
- // `field.column` is the drizzle property key; resolve it to the underlying column name.
1078
- const byProperty = (columns as Record<string, { name: string } | undefined>)[field.column as string];
1079
- if (byProperty) {
1080
- return byProperty.name;
1081
- }
1082
-
1083
- // Defensive: a managed field declared by column name rather than property key.
1084
- return Object.values(columns).find((column) => column.name === field.column)?.name;
1194
+ return (columns as Record<string, { name: string } | undefined>)[field.column as string]?.name;
1085
1195
  }
1086
1196
 
1087
1197
  export function attachSyncRegistrySchema<TRegistry extends SyncTableRegistry>(registry: TRegistry, schema?: string) {
@@ -1131,6 +1241,77 @@ export function getSyncRegistrySchema<TRegistry extends SyncTableRegistry>(regis
1131
1241
  return typeof schema === "string" && schema.length > 0 ? schema : "public";
1132
1242
  }
1133
1243
 
1244
+ /**
1245
+ * Stamp the registry's storage declaration (ADR-0049 decision 1, ADR-0047) onto the registry value as a
1246
+ * non-enumerable symbol — the storage twin of {@link attachSyncRegistrySchema}. Carries the data-contract
1247
+ * storage through {@link defineSyncRegistry} so client code reads it back via {@link getSyncRegistryStorage}.
1248
+ * A `null`/`undefined` declaration attaches nothing (the bare-registry-map overload), leaving the reader to
1249
+ * resolve the ADR-0047 defaults at the mint seam.
1250
+ */
1251
+ export function attachSyncRegistryStorage<TRegistry extends SyncTableRegistry>(
1252
+ registry: TRegistry,
1253
+ storage: SyncStorageDeclaration | undefined,
1254
+ ) {
1255
+ if (storage == null) {
1256
+ return registry;
1257
+ }
1258
+ // Idempotent for an EQUAL declaration (a registry value reused across constructions may be re-stamped with
1259
+ // the same contract) but fail-closed on a CONFLICT — two different storage contracts over one registry is a
1260
+ // definition error, never silently resolved. `backend`/`durability` are the only fields, so a shallow
1261
+ // compare is exhaustive.
1262
+ const existing = getSyncRegistryStorage(registry);
1263
+ if (existing != null) {
1264
+ if (existing.backend !== storage.backend || existing.durability !== storage.durability) {
1265
+ throw new Error(
1266
+ `conflicting storage declaration for registry: already ${JSON.stringify(existing)}, cannot re-declare ` +
1267
+ `${JSON.stringify(storage)}`,
1268
+ );
1269
+ }
1270
+ return registry;
1271
+ }
1272
+ Object.defineProperty(registry, syncRegistryStorageSymbol, {
1273
+ value: storage,
1274
+ enumerable: false,
1275
+ configurable: false,
1276
+ writable: false,
1277
+ });
1278
+ return registry;
1279
+ }
1280
+
1281
+ /**
1282
+ * Read the storage declaration (ADR-0049 decision 1, ADR-0047) a registry was built with, or `undefined`
1283
+ * when none was declared (a bare registry map, or a definition with no `storage`). The client resolves the
1284
+ * effective mint durability as `getSyncRegistryStorage(registry)?.durability ?? "relaxed"` at its single
1285
+ * mint seam — the storage twin of {@link getSyncRegistrySchema}.
1286
+ */
1287
+ export function getSyncRegistryStorage<TRegistry extends SyncTableRegistry>(
1288
+ registry: TRegistry,
1289
+ ): SyncStorageDeclaration | undefined {
1290
+ const storage = Reflect.get(registry, syncRegistryStorageSymbol) as unknown;
1291
+ return storage != null && typeof storage === "object" ? (storage as SyncStorageDeclaration) : undefined;
1292
+ }
1293
+
1294
+ /**
1295
+ * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` must
1296
+ * be a known value, matching how the other registry axes reject bad input at `defineSyncRegistry`. An absent
1297
+ * declaration or absent field is fine — it resolves to the ADR-0047 defaults (`opfs` / `relaxed`).
1298
+ */
1299
+ function validateStorageDeclaration(storage: SyncStorageDeclaration | undefined) {
1300
+ if (storage == null) {
1301
+ return;
1302
+ }
1303
+ if (storage.backend !== undefined && !isStorageBackend(storage.backend)) {
1304
+ throw new Error(
1305
+ `invalid storage.backend "${String(storage.backend)}": must be one of ${STORAGE_BACKENDS.join(", ")}`,
1306
+ );
1307
+ }
1308
+ if (storage.durability !== undefined && !isStorageDurability(storage.durability)) {
1309
+ throw new Error(
1310
+ `invalid storage.durability "${String(storage.durability)}": must be one of ${STORAGE_DURABILITIES.join(", ")}`,
1311
+ );
1312
+ }
1313
+ }
1314
+
1134
1315
  function isSyncRegistryDefinition<TRegistry extends SyncTableRegistry>(
1135
1316
  input: TRegistry | SyncRegistryDefinition<TRegistry>,
1136
1317
  ): input is SyncRegistryDefinition<TRegistry> {
@@ -1226,11 +1407,25 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
1226
1407
  );
1227
1408
  }
1228
1409
 
1410
+ // A managed field's `column` is the drizzle PROPERTY KEY of the target column, never its SQL column
1411
+ // name — ADR-0012 keeps the two distinct. Both consumers resolve by property key and canonicalise to
1412
+ // it (the client stamp in mutation.ts, the Server-version resolve in resolveServerVersionColumnName);
1413
+ // neither tolerates a column-name spelling. So a declaration that names the SQL column instead of the
1414
+ // property must fail HERE, at the boundary where declarations enter, rather than silently
1415
+ // half-resolving downstream.
1416
+ const managedFieldPropertyKeys = new Set(Object.keys(getColumns(entry.table)));
1417
+
1229
1418
  // The single claim-stamping strategy (ADR-0026): an `authClaim` managed field reads a value from the
1230
1419
  // verified request claims at a JSON path, emitted into the apply-function DDL — so the path segments
1231
1420
  // must be plain identifiers and any cast a plain type name (never a value-injection surface). A
1232
1421
  // non-authClaim field carrying claimPath/cast is an authoring slip; reject it rather than ignore it.
1233
1422
  for (const field of entry.governance?.managedFields ?? []) {
1423
+ if (!managedFieldPropertyKeys.has(field.column as string)) {
1424
+ throw new Error(
1425
+ `managed field ${tableName}.${String(field.column)} names an unknown column: field.column must be the ` +
1426
+ `drizzle PROPERTY KEY of the target column, not its SQL column name (ADR-0012)`,
1427
+ );
1428
+ }
1234
1429
  if (field.strategy === "authClaim") {
1235
1430
  if (!Array.isArray(field.claimPath) || field.claimPath.length === 0) {
1236
1431
  throw new Error(
package/src/runtime.ts CHANGED
@@ -47,7 +47,7 @@ export interface MutationDiagnostics {
47
47
  }
48
48
 
49
49
  /**
50
- * A registry-wide mutation-journal summary (warm-persisted-store-startup slice 4 / proposal §5): the
50
+ * A registry-wide mutation-journal summary for warm-store observability: the
51
51
  * per-status counts across EVERY writable table's journal, folded from one aggregate query/subscription over
52
52
  * the `pgxsinkit_all_mutations` view — so a consumer renders a global sync indicator with ONE subscription
53
53
  * instead of one live query per writable journal. Cheap enough to mount permanently.