@pgxsinkit/contracts 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/registry.ts CHANGED
@@ -56,6 +56,14 @@ import {
56
56
  type TableMode,
57
57
  type WriteMode,
58
58
  } from "./config";
59
+ import {
60
+ EVENT_STREAM_NAME_MAX_LENGTH,
61
+ EVENT_STREAM_NAME_PATTERN,
62
+ EVENT_STREAM_QUEUE_PREFIX,
63
+ hasNonStrictObjectRoot,
64
+ isZodSchema,
65
+ type EventStreamRegistry,
66
+ } from "./event-stream";
59
67
 
60
68
  type PgSchemaType = ReturnType<typeof pgSchema>;
61
69
 
@@ -133,6 +141,25 @@ export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTa
133
141
  * local row instead of failing the commit. Resolved to `"insert"` when omitted.
134
142
  */
135
143
  applyMode: "insert" | "upsert";
144
+ /**
145
+ * Consumer-defined ROW CLASSIFICATION (ADR-0052) — documentation-as-code for what KIND of rows this
146
+ * entry carries. The vocabulary is entirely the CONSUMER's: pgxsinkit defines no values and attaches no
147
+ * behaviour to any of them. Its two jobs:
148
+ *
149
+ * - **Fail-closed enumeration.** When the registry declares its vocabulary
150
+ * ({@link SyncRegistryDefinition.rowClasses}), EVERY entry must carry a `rowClass` drawn from that set —
151
+ * validated at `defineSyncRegistry`, i.e. at module eval. A new entry therefore cannot join the registry
152
+ * without its author classifying it, which is what stops a privacy/visibility obligation from being
153
+ * silently inherited by tables nobody remembered to enumerate.
154
+ * - **The binding key for {@link assertRegistryInvariant}.** An invariant binds to `rowClass` values
155
+ * rather than to a hand-maintained table list, so coverage grows with the registry instead of drifting
156
+ * behind it.
157
+ *
158
+ * When the registry declares no `rowClasses`, this field is unconstrained (any string, or none). It is
159
+ * authoring metadata only: it is deliberately absent from the registry fingerprint and the read-contract
160
+ * fingerprint, so classifying a table never shifts a persisted cache key (ADR-0052).
161
+ */
162
+ rowClass?: string;
136
163
  shape?: ShapeSpec;
137
164
  clientProjection?: ClientProjectionSpecForTable<TTable>;
138
165
  serverProjection?: ServerProjectionSpec;
@@ -347,6 +374,12 @@ export type SyncTableInput<
347
374
  * local row. Declare the exception here, where it lives — do not weaken the invariant repo-wide.
348
375
  */
349
376
  applyMode?: "insert" | "upsert";
377
+ /**
378
+ * Consumer-defined row classification (ADR-0052) — see {@link SyncTableEntry.rowClass}. Required (and
379
+ * checked against the declared set) when the registry declares {@link SyncRegistryDefinition.rowClasses};
380
+ * unconstrained otherwise.
381
+ */
382
+ rowClass?: string;
350
383
  shape?: ShapeSpecInputFor<TColumns>;
351
384
  clientProjection?: SyncTableInputProjection<TColumns, TOmittedColumns>;
352
385
  /** Server-side response-path projection (e.g. `rowTransform`). Server authority, not client shape. */
@@ -392,12 +425,46 @@ export interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {
392
425
  * the returned registry and read back with {@link getSyncRegistryStorage}. See {@link SyncStorageDeclaration}.
393
426
  */
394
427
  storage?: SyncStorageDeclaration;
428
+ /**
429
+ * The registry's CLOSED row-classification vocabulary (ADR-0052) — the consumer's own set of
430
+ * {@link SyncTableEntry.rowClass} values (pgxsinkit defines none). Declaring it turns classification into
431
+ * a fail-closed obligation: EVERY entry must then carry a `rowClass` drawn from this exact set, validated
432
+ * at {@link defineSyncRegistry} (module eval), so a newly added entry cannot join the registry
433
+ * unclassified and silently escape whatever invariants its class enrols it in. The declared set is carried
434
+ * on the returned registry and read back with {@link getSyncRegistryRowClasses}, which
435
+ * {@link assertRegistryInvariant} uses to reject a misspelled class in an invariant's `appliesTo`.
436
+ *
437
+ * Omit it and `rowClass` is unconstrained (the bare-registry-map overload has nowhere to declare a set, so
438
+ * it is always unconstrained). Purely authoring metadata: it never enters the registry fingerprint.
439
+ */
440
+ rowClasses?: readonly string[];
441
+ /**
442
+ * The registry's **Event streams** (ADR-0053 decision 1) — the Event lane's registration surface, keyed by
443
+ * Event-stream NAME (the record key IS the name; {@link defineEventStream} declares the entry). Registration
444
+ * lives here rather than in a parallel artifact so there is ONE contract to lock, diff and thread through
445
+ * `createSyncServer` and `defineSyncWorker`.
446
+ *
447
+ * Validated fail-closed at {@link defineSyncRegistry} (module eval, every offender named at once): the name
448
+ * must match `[a-z][a-z0-9_]*` and fit the pgmq queue-name budget, the payload must be a zod schema, and each
449
+ * identity field must name a non-empty claim path. Carried on the returned registry and read back with
450
+ * {@link getSyncRegistryStreams}.
451
+ *
452
+ * Streams follow the `rowClasses` precedent: they ride the registry LOCK as a sibling (added → `compatible`,
453
+ * removed → `breaking`, payload/identity changed → `risky`) and stay OUT of the canonical fingerprint — an
454
+ * Event stream touches no synced table, no local schema and no apply function, so registering one must never
455
+ * wipe a store's read cache. The bare-registry-map overload has nowhere to declare streams.
456
+ */
457
+ streams?: EventStreamRegistry;
395
458
  }
396
459
 
397
460
  export const syncRegistrySchemaSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistrySchema");
398
461
 
399
462
  export const syncRegistryStorageSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryStorage");
400
463
 
464
+ export const syncRegistryRowClassesSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryRowClasses");
465
+
466
+ export const syncRegistryStreamsSymbol = Symbol.for("@pgxsinkit/contracts/syncRegistryStreams");
467
+
401
468
  export type RegistryTables<TRegistry extends SyncTableRegistry> = {
402
469
  [TKey in keyof TRegistry]: TRegistry[TKey]["table"];
403
470
  };
@@ -436,14 +503,72 @@ type ManagedFieldColumnKeysForOperation<TEntry, TOperation extends ManagedFieldA
436
503
  : never
437
504
  : never;
438
505
 
506
+ /**
507
+ * EVERY managed column key, whatever its `applyOn` — the omit set for {@link SyncTableUpdateInput}.
508
+ * `ManagedFieldApplyOn` is a union and the operation parameter is naked, so the conditional distributes
509
+ * and a field managed on either operation contributes its key.
510
+ *
511
+ * The **type-level twin** of {@link isManagedFieldGuarded} at `"update"`: same rule, stated where the
512
+ * compiler can enforce it. Change one only by changing the rule in {@link isManagedFieldGuarded}.
513
+ */
514
+ type ManagedFieldColumnKeys<TEntry> = ManagedFieldColumnKeysForOperation<TEntry, ManagedFieldApplyOn>;
515
+
516
+ /**
517
+ * Whether a managed field is **SERVER-OWNED** for an operation — the ONE definition of the guard rule,
518
+ * so the surfaces that enforce it cannot drift apart:
519
+ *
520
+ * - **create** ⇒ the field is guarded when its `applyOn` includes `"create"`. The server stamps it after
521
+ * validation, so a client value for it is never honoured.
522
+ * - **update** ⇒ **every** managed field is guarded, a **create-only** one included. An update-managed
523
+ * field is stamped by the server on every write; a `applyOn: ["create"]` field is stamped at birth and
524
+ * **inert** on update (the generated apply function offers no UPDATE SET candidate for it). Neither is
525
+ * ever a settable update key, so both are flagged, stripped, and omitted rather than left for consumer
526
+ * RLS to neutralise.
527
+ * - **delete** ⇒ none. A delete carries no payload, so nothing can be owned.
528
+ *
529
+ * "Guarded" is NOT "stamped": stamping is operation-scoped (`applyOn.includes(operation)`) and decides
530
+ * what the applier writes; guarding decides what a client may not send. They coincide on create and
531
+ * deliberately diverge on update.
532
+ *
533
+ * The consuming surfaces, all of which must go through this predicate:
534
+ * - the write route's `getGuardedManagedFields` (`packages/server/src/mutations/route.ts`) — the 400
535
+ * violation check, the sanitizer, and the create/update validation schemas;
536
+ * - the client's `stripManagedFields` (`packages/client/src/mutation.ts`) — the outgoing-payload strip;
537
+ * - the apply-function generator's `buildTableBranch` (`packages/server/src/mutations/plpgsql-apply.ts`) —
538
+ * the INSERT/UPDATE candidate-column exclusions;
539
+ * - {@link ManagedFieldColumnKeys} / `ManagedFieldColumnKeysForOperation` — the type-level twin behind
540
+ * {@link SyncTableCreateInput} / {@link SyncTableUpdateInput}.
541
+ */
542
+ export function isManagedFieldGuarded(
543
+ field: { applyOn: readonly ManagedFieldApplyOn[] },
544
+ operation: "create" | "update" | "delete",
545
+ ): boolean {
546
+ switch (operation) {
547
+ case "create":
548
+ return field.applyOn.includes("create");
549
+ case "update":
550
+ return true;
551
+ case "delete":
552
+ return false;
553
+ }
554
+ }
555
+
439
556
  export type SyncTableCreateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =
440
557
  TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>
441
558
  ? Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], "create">>
442
559
  : never;
443
560
 
561
+ /**
562
+ * The patch type for an update: the insert model made partial, minus **every** managed key — including
563
+ * a **create-only** one. A field declared `applyOn: ["create"]` is stamped at birth and inert on update
564
+ * (the generated apply function offers no UPDATE SET candidate for it), so it is never a settable update
565
+ * key; the write route 400-rejects an update payload that carries one. This omit set is the type-level
566
+ * statement of {@link isManagedFieldGuarded} at `"update"` — that predicate is the single definition of
567
+ * the rule, and every runtime surface derives from it.
568
+ */
444
569
  export type SyncTableUpdateInput<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =
445
570
  TRegistry[TKey] extends SyncTableEntry<AnyPgTable, infer TLocalTable extends AnyPgTable>
446
- ? Partial<Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeysForOperation<TRegistry[TKey], "update">>>
571
+ ? Partial<Omit<InferInsertModel<TLocalTable>, ManagedFieldColumnKeys<TRegistry[TKey]>>>
447
572
  : never;
448
573
 
449
574
  export type SyncTableRecord<TRegistry extends SyncTableRegistry, TKey extends keyof TRegistry> =
@@ -759,6 +884,13 @@ export function defineReadProjection<
759
884
  * `serverProjection.rowTransform` and `columns`; must be disjoint from `columns` and the primary key.
760
885
  */
761
886
  serverOnlyColumns?: readonly TableColumnKey<TOwnerTable>[];
887
+ /**
888
+ * Row classification (ADR-0052) for THIS projection. Defaults to the OWNER's `rowClass` — a projection
889
+ * reads the owner's rows, so it carries the owner's classification (and the invariants bound to it)
890
+ * unless you say otherwise. Override when the narrower shape genuinely changes the KIND of row the
891
+ * client receives (e.g. a redacting window over private rows that egresses only public fields).
892
+ */
893
+ rowClass?: string;
762
894
  consistencyGroup?: string;
763
895
  subscription?: SubscriptionTiming;
764
896
  retention?: Retention;
@@ -935,11 +1067,16 @@ export function defineReadProjection<
935
1067
  // `serverProjection` is attached HERE on the outer object (mirroring `shape`), NOT threaded through the
936
1068
  // inner `defineSyncTable` call — that alone makes the proxy's shapeKey resolution find and run the
937
1069
  // projection's egress transform (getRowTransformForTable → resolveEntryByShapeKey(…)?.serverProjection).
1070
+ // Row classification (ADR-0052) is INHERITED from the owner by default — a projection streams the owner's
1071
+ // rows, so it belongs to the owner's class (and to every invariant bound to it) unless the projection's
1072
+ // narrower shape genuinely changes the kind of row a client receives, which `opts.rowClass` overrides.
1073
+ const rowClass = opts.rowClass ?? owner.rowClass;
938
1074
  const projection = {
939
1075
  ...built,
940
1076
  table: owner.table,
941
1077
  shape,
942
1078
  readProjection: true as const,
1079
+ ...(rowClass != null ? { rowClass } : {}),
943
1080
  ...(serverProjection != null ? { serverProjection } : {}),
944
1081
  };
945
1082
  // The local table carries the OWNER's real column types restricted to the kept keys (`TColumns[number]`
@@ -967,13 +1104,23 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
967
1104
  validateRegistryTableUniqueness(input.tables);
968
1105
  validateRegistryLifecycleGroups(input.tables);
969
1106
  validateStorageDeclaration(input.storage);
1107
+ validateRowClassification(input.tables, input.rowClasses);
1108
+ validateEventStreams(input.streams);
970
1109
 
971
1110
  // Schema first (it may return the same tables object), then stamp the storage declaration on the
972
1111
  // returned registry as a non-enumerable symbol — the same carrier pattern as the schema symbol — so
973
1112
  // client code reads the data-contract storage back off the registry value (getSyncRegistrySchema's
974
1113
  // 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);
1114
+ // `undefined`, which resolves to the ADR-0047 defaults at the mint seam. The declared row-class
1115
+ // vocabulary rides the same way (ADR-0052), for getSyncRegistryRowClasses, and so do the registered
1116
+ // Event streams (ADR-0053), for getSyncRegistryStreams.
1117
+ return attachSyncRegistryStreams(
1118
+ attachSyncRegistryRowClasses(
1119
+ attachSyncRegistryStorage(attachSyncRegistrySchema(input.tables, input.schema), input.storage),
1120
+ input.rowClasses,
1121
+ ),
1122
+ input.streams,
1123
+ );
977
1124
  }
978
1125
 
979
1126
  for (const entry of getRegistryEntries(input)) {
@@ -1291,6 +1438,269 @@ export function getSyncRegistryStorage<TRegistry extends SyncTableRegistry>(
1291
1438
  return storage != null && typeof storage === "object" ? (storage as SyncStorageDeclaration) : undefined;
1292
1439
  }
1293
1440
 
1441
+ /**
1442
+ * Stamp the registry's declared row-class vocabulary (ADR-0052) onto the registry value as a non-enumerable
1443
+ * symbol — the classification twin of {@link attachSyncRegistryStorage}. An absent/empty declaration attaches
1444
+ * nothing (the bare-registry-map overload, and any definition that declares no vocabulary), so
1445
+ * {@link getSyncRegistryRowClasses} reads back `undefined` and classification stays unconstrained.
1446
+ */
1447
+ export function attachSyncRegistryRowClasses<TRegistry extends SyncTableRegistry>(
1448
+ registry: TRegistry,
1449
+ rowClasses: readonly string[] | undefined,
1450
+ ) {
1451
+ if (rowClasses == null) {
1452
+ return registry;
1453
+ }
1454
+ // Idempotent for an EQUAL vocabulary (a registry value reused across constructions may be re-stamped with
1455
+ // the same set) but fail-closed on a CONFLICT — two different vocabularies over one registry is a
1456
+ // definition error, never silently resolved.
1457
+ const existing = getSyncRegistryRowClasses(registry);
1458
+ if (existing != null) {
1459
+ if (existing.length !== rowClasses.length || existing.some((value, index) => value !== rowClasses[index])) {
1460
+ throw new Error(
1461
+ `conflicting rowClasses declaration for registry: already [${existing.join(", ")}], cannot re-declare ` +
1462
+ `[${rowClasses.join(", ")}]`,
1463
+ );
1464
+ }
1465
+ return registry;
1466
+ }
1467
+ Object.defineProperty(registry, syncRegistryRowClassesSymbol, {
1468
+ value: Object.freeze([...rowClasses]),
1469
+ enumerable: false,
1470
+ configurable: false,
1471
+ writable: false,
1472
+ });
1473
+ return registry;
1474
+ }
1475
+
1476
+ /**
1477
+ * Read the row-class vocabulary (ADR-0052) a registry was built with, or `undefined` when none was declared
1478
+ * (a bare registry map, or a definition with no `rowClasses`) — the classification twin of
1479
+ * {@link getSyncRegistryStorage}. {@link assertRegistryInvariant} consults it to reject an invariant whose
1480
+ * `appliesTo` names a class this registry does not define (a typo that would otherwise bind nothing).
1481
+ */
1482
+ export function getSyncRegistryRowClasses<TRegistry extends SyncTableRegistry>(
1483
+ registry: TRegistry,
1484
+ ): readonly string[] | undefined {
1485
+ const rowClasses = Reflect.get(registry, syncRegistryRowClassesSymbol) as unknown;
1486
+ return Array.isArray(rowClasses) ? (rowClasses as readonly string[]) : undefined;
1487
+ }
1488
+
1489
+ /**
1490
+ * Stamp the registry's registered Event streams (ADR-0053 decision 1) onto the registry value as a
1491
+ * non-enumerable symbol — the Event-lane twin of {@link attachSyncRegistryRowClasses}. An absent declaration
1492
+ * attaches nothing (the bare-registry-map overload, and any definition that registers no Event stream), so
1493
+ * {@link getSyncRegistryStreams} reads back `undefined` and the registry simply has no Event lane.
1494
+ *
1495
+ * Non-enumerable is load-bearing beyond tidiness: `canonicalizeRegistry` walks the registry's own enumerable
1496
+ * keys, so riding a symbol is what keeps Event streams OUT of the persisted fingerprint.
1497
+ */
1498
+ export function attachSyncRegistryStreams<TRegistry extends SyncTableRegistry>(
1499
+ registry: TRegistry,
1500
+ streams: EventStreamRegistry | undefined,
1501
+ ) {
1502
+ if (streams == null) {
1503
+ return registry;
1504
+ }
1505
+ // Idempotent for the SAME registration (one tables object may be reused across per-client registries built
1506
+ // from one definition) but fail-closed on a CONFLICT — two different Event-lane contracts over one registry
1507
+ // is a definition error, never silently resolved. Entries are compared by identity: a payload schema is an
1508
+ // opaque object, so structural equality here would be a worse promise than none.
1509
+ const existing = getSyncRegistryStreams(registry);
1510
+ if (existing != null) {
1511
+ const existingNames = Object.keys(existing).sort();
1512
+ const nextNames = Object.keys(streams).sort();
1513
+ const same =
1514
+ existingNames.length === nextNames.length &&
1515
+ existingNames.every((name, index) => name === nextNames[index] && existing[name] === streams[name]);
1516
+ if (!same) {
1517
+ throw new Error(
1518
+ `conflicting streams declaration for registry: already [${existingNames.join(", ")}], cannot re-declare ` +
1519
+ `[${nextNames.join(", ")}]`,
1520
+ );
1521
+ }
1522
+ return registry;
1523
+ }
1524
+ Object.defineProperty(registry, syncRegistryStreamsSymbol, {
1525
+ value: Object.freeze({ ...streams }),
1526
+ enumerable: false,
1527
+ configurable: false,
1528
+ writable: false,
1529
+ });
1530
+ return registry;
1531
+ }
1532
+
1533
+ /**
1534
+ * Read the Event streams (ADR-0053 decision 1) a registry was built with, or `undefined` when none were
1535
+ * registered — the Event-lane twin of {@link getSyncRegistryRowClasses}. The server mounts the ingestion route
1536
+ * and provisions one pgmq queue per entry from this; the client resolves an `appendEvent` payload schema
1537
+ * through it.
1538
+ */
1539
+ export function getSyncRegistryStreams<TRegistry extends SyncTableRegistry>(
1540
+ registry: TRegistry,
1541
+ ): EventStreamRegistry | undefined {
1542
+ const streams = Reflect.get(registry, syncRegistryStreamsSymbol) as unknown;
1543
+ return streams != null && typeof streams === "object" ? (streams as EventStreamRegistry) : undefined;
1544
+ }
1545
+
1546
+ /**
1547
+ * Fail-closed at module-eval (ADR-0053 decision 1): every registered Event stream must be nameable as a pgmq
1548
+ * queue and must declare a usable payload contract and identity-stamping rule. A bad Event-stream name has to
1549
+ * fail at DEFINITION — failing at deployment DDL, when `pgxsinkit-generate` emits the per-stream queues, is
1550
+ * far too late.
1551
+ *
1552
+ * Rejection-only, and it names EVERY offender in one error (same posture as {@link validateRowClassification}:
1553
+ * an author fixing a batch of streams should not have to re-run the build once per stream).
1554
+ */
1555
+ function validateEventStreams(streams: EventStreamRegistry | undefined) {
1556
+ if (streams == null) {
1557
+ return;
1558
+ }
1559
+
1560
+ const problems: string[] = [];
1561
+
1562
+ for (const [name, entry] of Object.entries(streams)) {
1563
+ if (!EVENT_STREAM_NAME_PATTERN.test(name)) {
1564
+ problems.push(
1565
+ `"${name}": invalid Event-stream name — must match ${EVENT_STREAM_NAME_PATTERN.source} ` +
1566
+ `(lowercase letters, digits and underscores, starting with a letter)`,
1567
+ );
1568
+ } else if (name.length > EVENT_STREAM_NAME_MAX_LENGTH) {
1569
+ problems.push(
1570
+ `"${name}": Event-stream name is ${name.length} characters — at most ${EVENT_STREAM_NAME_MAX_LENGTH} ` +
1571
+ `are allowed, because each stream is provisioned as the pgmq queue ` +
1572
+ `"${EVENT_STREAM_QUEUE_PREFIX}${name}" and pgmq's queue-name limit is 47 characters, of which the ` +
1573
+ `"${EVENT_STREAM_QUEUE_PREFIX}" prefix consumes ${EVENT_STREAM_QUEUE_PREFIX.length}`,
1574
+ );
1575
+ }
1576
+
1577
+ if (entry == null || typeof entry !== "object") {
1578
+ problems.push(`"${name}": not an Event-stream entry — declare it with defineEventStream({ payload, identity })`);
1579
+ continue;
1580
+ }
1581
+
1582
+ if (!isZodSchema(entry.payload)) {
1583
+ problems.push(`"${name}": payload is not a zod schema — declare a strict zod schema for the event payload`);
1584
+ } else if (hasNonStrictObjectRoot(entry.payload)) {
1585
+ // The strict promise is ENFORCED, not advertised. A stripping `z.object({…})` would drop a misspelled
1586
+ // or newly-added key between the caller and the consumer with no verdict anywhere — the exact silence
1587
+ // the lane's "everything in the Outbox is well-formed" invariant exists to prevent. Non-object roots
1588
+ // (string, array, record, transform pipelines) are untouched by this rule.
1589
+ problems.push(
1590
+ `"${name}": the payload's object schema is not strict — declare it with \`.strict()\` or ` +
1591
+ `\`z.strictObject()\` (every object inside a union payload too), so an unknown key is REJECTED at ` +
1592
+ `\`appendEvent\` instead of being silently stripped on the way to the consumer`,
1593
+ );
1594
+ }
1595
+
1596
+ if (entry.revision != null && (!Number.isInteger(entry.revision) || entry.revision <= 0)) {
1597
+ problems.push(
1598
+ `"${name}": revision must be a positive integer (it is the opaque counter you bump when acceptance ` +
1599
+ `logic the JSON-Schema hash cannot see — a refinement threshold, a transform — changes)`,
1600
+ );
1601
+ }
1602
+
1603
+ if (entry.identity == null || typeof entry.identity !== "object") {
1604
+ problems.push(`"${name}": identity must be a record of field name -> { claimPath }`);
1605
+ continue;
1606
+ }
1607
+
1608
+ for (const [field, spec] of Object.entries(entry.identity)) {
1609
+ if (field.trim().length === 0) {
1610
+ problems.push(`"${name}": an identity field name is empty`);
1611
+ continue;
1612
+ }
1613
+ const claimPath = spec?.claimPath;
1614
+ if (!Array.isArray(claimPath) || claimPath.length === 0) {
1615
+ problems.push(
1616
+ `"${name}".identity.${field}: claimPath must be a non-empty JSON path into the verified claims ` +
1617
+ `(e.g. ["sub"] or ["app_metadata", "person_id"])`,
1618
+ );
1619
+ continue;
1620
+ }
1621
+ if (claimPath.some((segment) => typeof segment !== "string" || segment.trim().length === 0)) {
1622
+ problems.push(`"${name}".identity.${field}: every claimPath segment must be a non-empty string`);
1623
+ }
1624
+ }
1625
+ }
1626
+
1627
+ if (problems.length === 0) {
1628
+ return;
1629
+ }
1630
+
1631
+ throw new Error(
1632
+ `invalid Event-stream registration (ADR-0053). The record key IS the Event-stream name, and each entry ` +
1633
+ `must be a defineEventStream({ payload, identity }) — ${problems.join("; ")}.`,
1634
+ );
1635
+ }
1636
+
1637
+ /**
1638
+ * Fail-closed at module-eval (ADR-0052): when a registry declares a `rowClasses` vocabulary, EVERY entry
1639
+ * must carry a {@link SyncTableEntry.rowClass} drawn from it. This is the whole point of the field — a new
1640
+ * entry added tomorrow cannot join the registry without its author classifying it, so an invariant that
1641
+ * binds by class can never quietly under-enumerate the tables it is supposed to cover.
1642
+ *
1643
+ * Rejection-only, and it names EVERY offender in one error (an author fixing a batch of entries should not
1644
+ * have to re-run the build once per entry). An undeclared vocabulary constrains nothing — the entries may
1645
+ * carry any `rowClass`, or none.
1646
+ */
1647
+ function validateRowClassification(registry: SyncTableRegistry, rowClasses: readonly string[] | undefined) {
1648
+ if (rowClasses == null) {
1649
+ return;
1650
+ }
1651
+
1652
+ if (rowClasses.length === 0) {
1653
+ throw new Error(
1654
+ `rowClasses is declared but empty: a declared vocabulary makes classification mandatory, so an empty ` +
1655
+ `set can never be satisfied. Declare the classes this registry uses, or omit rowClasses entirely.`,
1656
+ );
1657
+ }
1658
+
1659
+ const seen = new Set<string>();
1660
+ const duplicates = new Set<string>();
1661
+ for (const rowClass of rowClasses) {
1662
+ if (typeof rowClass !== "string" || rowClass.length === 0) {
1663
+ throw new Error(
1664
+ `rowClasses contains an invalid value ${JSON.stringify(rowClass)}: each class must be a non-empty string`,
1665
+ );
1666
+ }
1667
+ if (seen.has(rowClass)) {
1668
+ duplicates.add(rowClass);
1669
+ }
1670
+ seen.add(rowClass);
1671
+ }
1672
+ if (duplicates.size > 0) {
1673
+ throw new Error(`rowClasses declares duplicate classes: ${[...duplicates].join(", ")}`);
1674
+ }
1675
+
1676
+ const unclassified: string[] = [];
1677
+ const unknown: string[] = [];
1678
+ for (const [key, entry] of Object.entries(registry)) {
1679
+ const rowClass = (entry as SyncTableEntry<AnyPgTable>).rowClass;
1680
+ if (rowClass == null) {
1681
+ unclassified.push(key);
1682
+ continue;
1683
+ }
1684
+ if (!seen.has(rowClass)) {
1685
+ unknown.push(`${key} (rowClass "${rowClass}")`);
1686
+ }
1687
+ }
1688
+
1689
+ if (unclassified.length === 0 && unknown.length === 0) {
1690
+ return;
1691
+ }
1692
+
1693
+ const problems = [
1694
+ ...(unclassified.length > 0 ? [`unclassified entries: ${unclassified.join(", ")}`] : []),
1695
+ ...(unknown.length > 0 ? [`entries with an undeclared class: ${unknown.join(", ")}`] : []),
1696
+ ];
1697
+ throw new Error(
1698
+ `row classification is incomplete (ADR-0052). This registry declares rowClasses ` +
1699
+ `[${rowClasses.join(", ")}], so every entry must carry a rowClass from that set — ${problems.join("; ")}. ` +
1700
+ `Classify each entry (or widen rowClasses if a genuinely new kind of row has arrived).`,
1701
+ );
1702
+ }
1703
+
1294
1704
  /**
1295
1705
  * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` must
1296
1706
  * be a known value, matching how the other registry axes reject bad input at `defineSyncRegistry`. An absent
package/src/runtime.ts CHANGED
@@ -3,9 +3,10 @@ export type SyncRuntimePhase = "booting" | "syncing" | "ready" | "degraded" | "a
3
3
  export interface SyncRuntimeStatus {
4
4
  /**
5
5
  * `auth-needed` (ADR-0013): the read path is hitting auth errors (401/403) and is retrying
6
- * forever with backoff — distinct from `degraded` (a sync commit exhausted its retries). The app
7
- * should prompt re-login; sync auto-resumes (phase returns to `ready`/`syncing`) the instant
8
- * re-authentication makes the token valid again. It never silently wedges or permanently stops.
6
+ * forever with backoff — distinct from `degraded`, which covers the read path not being SERVED (a
7
+ * shape stream erroring, or unable to reach the server at all) and a sync commit that exhausted its
8
+ * retries. The app should prompt re-login; sync auto-resumes (phase returns to `ready`/`syncing`) the
9
+ * instant re-authentication makes the token valid again. It never silently wedges or permanently stops.
9
10
  */
10
11
  phase: SyncRuntimePhase;
11
12
  isRunning: boolean;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The single role-existence guard used by every pgxsinkit-emitted GRANT/REVOKE.
3
+ *
4
+ * pgxsinkit artifacts are portable: the same migration runs on a Supabase-shaped cluster (where
5
+ * `anon`/`authenticated`/`service_role` exist), on a plain Postgres, and on a PGlite test lane
6
+ * (where none of them do). A bare `REVOKE … FROM anon` is a hard error where the role is absent, so
7
+ * every role-scoped grant/revoke is wrapped in a `DO $$ … IF EXISTS (SELECT 1 FROM pg_roles …)`
8
+ * block and simply does nothing there.
9
+ *
10
+ * Two callers share this one definition — `buildRegistryGovernanceSql` (@pgxsinkit/schema, table
11
+ * grants) and the apply-function ACL (@pgxsinkit/server, ADR-0054) — so the guard idiom cannot
12
+ * drift between the artifacts that carry a deployment's authorization posture.
13
+ */
14
+
15
+ import { escapeSqlLiteral } from "./sql-identifier";
16
+
17
+ /**
18
+ * Wrap one already-rendered SQL statement (no trailing semicolon) in the role-existence guard.
19
+ *
20
+ * `statementSql` is embedded as a PL/pgSQL string literal, so it is escaped as a whole — callers pass
21
+ * ordinary SQL with real single quotes and real double-quoted identifiers.
22
+ */
23
+ export function buildRoleGuardedStatement(roleName: string, statementSql: string): string {
24
+ return [
25
+ "DO $$",
26
+ "BEGIN",
27
+ ` IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = '${escapeSqlLiteral(roleName)}') THEN`,
28
+ ` EXECUTE '${escapeSqlLiteral(statementSql)}';`,
29
+ " END IF;",
30
+ "END;",
31
+ "$$;",
32
+ ].join("\n");
33
+ }