@pgxsinkit/contracts 0.1.32 → 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +13 -0
  2. package/dist/apply-strategy.d.ts +35 -0
  3. package/dist/apply-strategy.d.ts.map +1 -0
  4. package/dist/config.d.ts +210 -32
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +106 -0
  7. package/dist/convergence-model.d.ts.map +1 -0
  8. package/dist/fingerprint.d.ts +136 -0
  9. package/dist/fingerprint.d.ts.map +1 -0
  10. package/dist/index.d.ts +7 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +5222 -3494
  13. package/dist/index.js.map +37 -30
  14. package/dist/mutation.d.ts +78 -0
  15. package/dist/mutation.d.ts.map +1 -1
  16. package/dist/projection.d.ts +88 -0
  17. package/dist/projection.d.ts.map +1 -0
  18. package/dist/registry-diff.d.ts +50 -0
  19. package/dist/registry-diff.d.ts.map +1 -0
  20. package/dist/registry.d.ts +253 -2
  21. package/dist/registry.d.ts.map +1 -1
  22. package/dist/runtime.d.ts +21 -1
  23. package/dist/runtime.d.ts.map +1 -1
  24. package/dist/sql-defaults.d.ts +27 -0
  25. package/dist/sql-defaults.d.ts.map +1 -0
  26. package/dist/sql-identifier.d.ts +26 -0
  27. package/dist/sql-identifier.d.ts.map +1 -0
  28. package/dist/supabase-rls.d.ts +99 -3
  29. package/dist/supabase-rls.d.ts.map +1 -1
  30. package/package.json +8 -3
  31. package/skills/registry-authoring/SKILL.md +376 -0
  32. package/src/apply-strategy.ts +124 -0
  33. package/src/config.ts +254 -106
  34. package/src/convergence-model.ts +190 -0
  35. package/src/fingerprint.ts +265 -0
  36. package/src/index.ts +7 -0
  37. package/src/mutation.ts +94 -2
  38. package/src/projection.ts +150 -0
  39. package/src/registry-diff.ts +215 -0
  40. package/src/registry.ts +751 -23
  41. package/src/runtime.ts +21 -1
  42. package/src/sql-defaults.ts +29 -0
  43. package/src/sql-identifier.ts +130 -0
  44. package/src/supabase-rls.ts +515 -37
@@ -0,0 +1,265 @@
1
+ import { getTableConfig, type AnyPgTable } from "drizzle-orm/pg-core";
2
+
3
+ import type { RowFilterSpec } from "./config";
4
+ import type { SyncTableEntry, SyncTableRegistry } from "./registry";
5
+
6
+ /**
7
+ * The registry fingerprint (ADR-0004): a stable, order-independent description of
8
+ * the shape-relevant registry metadata, plus a hash of it.
9
+ *
10
+ * This is the single source of "has the shape changed" — consumed as the local-DB
11
+ * 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
13
+ * *presence* and the surrounding **static** filter structure (the projected columns)
14
+ * 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
16
+ * fingerprint (and so rebuild the cache + reset the subscription).
17
+ */
18
+
19
+ export interface CanonicalColumn {
20
+ name: string;
21
+ type: string;
22
+ notNull: boolean;
23
+ hasDefault: boolean;
24
+ primary: boolean;
25
+ }
26
+
27
+ export interface CanonicalTable {
28
+ key: string;
29
+ mode: string;
30
+ primaryKey: string[];
31
+ localPrimaryKey: string[] | null;
32
+ columns: CanonicalColumn[];
33
+ projection: {
34
+ syncedTable: string | null;
35
+ overlayTable: string | null;
36
+ journalTable: string | null;
37
+ omitColumns: string[];
38
+ } | null;
39
+ shape: {
40
+ tableName: string;
41
+ shapeKey: string;
42
+ electricTable: string | null;
43
+ rowFilter: CanonicalRowFilter | null;
44
+ } | null;
45
+ managedFields: Array<{ field: string; strategy: string; applyOn: string[] }>;
46
+ /**
47
+ * Consistency group (ADR-0009 decision 2). Part of the fingerprint because it decides which
48
+ * subscription-state row a table persists under: moving a table between groups must shift the
49
+ * fingerprint (forcing a cache rebuild + subscription reset) and surface in the diff gate. `null`
50
+ * = the default singleton group.
51
+ */
52
+ consistencyGroup: string | null;
53
+ /**
54
+ * Retention (ADR-0021). Part of the fingerprint because it changes the cluster DDL — an `ephemeral`
55
+ * table's whole cluster is emitted as `TEMP`/`pg_temp` — so flipping persistent↔ephemeral must force a
56
+ * cache rebuild + subscription reset. (Subscription timing is NOT included: it is pure runtime
57
+ * orchestration over identical tables and needs no rebuild.)
58
+ */
59
+ retention: string;
60
+ }
61
+
62
+ /**
63
+ * 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
66
+ * is surfaced only by bumping `revision`.
67
+ */
68
+ export interface CanonicalRowFilter {
69
+ hasCustomWhere: boolean;
70
+ columns: string[] | null;
71
+ /**
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
74
+ * forces a cache + subscription reset.
75
+ */
76
+ revision: string | null;
77
+ }
78
+
79
+ const byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
80
+ const asString = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
81
+
82
+ function canonicalizeColumns(table: AnyPgTable): CanonicalColumn[] {
83
+ return getTableConfig(table)
84
+ .columns.map((column) => ({
85
+ name: column.name,
86
+ type: column.getSQLType(),
87
+ notNull: column.notNull,
88
+ hasDefault: column.hasDefault,
89
+ primary: column.primary,
90
+ }))
91
+ .sort(byName);
92
+ }
93
+
94
+ function canonicalizeManagedFields(entry: SyncTableEntry): CanonicalTable["managedFields"] {
95
+ return (entry.governance?.managedFields ?? [])
96
+ .map((field) => {
97
+ const record = field as { propertyKey?: unknown; column?: unknown; strategy?: unknown; applyOn?: unknown };
98
+ const name =
99
+ typeof record.propertyKey === "string"
100
+ ? record.propertyKey
101
+ : typeof record.column === "string"
102
+ ? record.column
103
+ : "";
104
+ const applyOn = Array.isArray(record.applyOn) ? [...record.applyOn].map(String).sort(asString) : [];
105
+ const strategy = typeof record.strategy === "string" ? record.strategy : "";
106
+ return { field: name, strategy, applyOn };
107
+ })
108
+ .sort((a, b) => asString(a.field, b.field));
109
+ }
110
+
111
+ function canonicalizeRowFilter(filter: RowFilterSpec | undefined): CanonicalRowFilter | null {
112
+ if (!filter) {
113
+ return null;
114
+ }
115
+ return {
116
+ hasCustomWhere: filter.customWhere != null,
117
+ columns: filter.columns ? [...filter.columns].sort(asString) : null,
118
+ revision: filter.revision != null ? String(filter.revision) : null,
119
+ };
120
+ }
121
+
122
+ function canonicalizeTable(key: string, entry: SyncTableEntry): CanonicalTable {
123
+ const projection = entry.clientProjection
124
+ ? {
125
+ syncedTable: entry.clientProjection.syncedTable ?? null,
126
+ overlayTable: entry.clientProjection.overlayTable ?? null,
127
+ journalTable: entry.clientProjection.journalTable ?? null,
128
+ omitColumns: [...(entry.clientProjection.omitColumns ?? [])].map(String).sort(asString),
129
+ }
130
+ : null;
131
+
132
+ const shape = entry.shape
133
+ ? {
134
+ tableName: entry.shape.tableName,
135
+ shapeKey: entry.shape.shapeKey,
136
+ electricTable: entry.shape.electricTable ?? null,
137
+ rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
138
+ }
139
+ : null;
140
+
141
+ return {
142
+ key,
143
+ mode: entry.mode,
144
+ primaryKey: [...entry.primaryKey.columns].sort(asString),
145
+ localPrimaryKey: entry.clientProjection?.localPrimaryKey
146
+ ? [...entry.clientProjection.localPrimaryKey.columns].sort(asString)
147
+ : null,
148
+ columns: canonicalizeColumns(entry.table),
149
+ projection,
150
+ shape,
151
+ managedFields: canonicalizeManagedFields(entry),
152
+ consistencyGroup: entry.consistencyGroup ?? null,
153
+ retention: entry.retention ?? "persistent",
154
+ };
155
+ }
156
+
157
+ /**
158
+ * The canonical, order-independent shape of a registry. Tables are sorted by key so
159
+ * declaration order never affects the result.
160
+ */
161
+ export function canonicalizeRegistry(registry: SyncTableRegistry): CanonicalTable[] {
162
+ return Object.entries(registry)
163
+ .map(([key, entry]) => canonicalizeTable(key, entry))
164
+ .sort((a, b) => asString(a.key, b.key));
165
+ }
166
+
167
+ /** A stable string serialization of the canonical registry shape. */
168
+ export function canonicalRegistryString(registry: SyncTableRegistry): string {
169
+ return JSON.stringify(canonicalizeRegistry(registry));
170
+ }
171
+
172
+ /**
173
+ * A stable fingerprint (hex) of the registry's shape. Identical shapes — even with
174
+ * tables declared in a different order — produce the same fingerprint; any
175
+ * structural change produces a different one.
176
+ */
177
+ export function fingerprintRegistry(registry: SyncTableRegistry): string {
178
+ return hashString(canonicalRegistryString(registry));
179
+ }
180
+
181
+ /**
182
+ * The **read contract** of a single sync table: the subset of its canonical shape that decides what
183
+ * data streams down and how a row is identified and filtered — synced-table name, columns, primary key
184
+ * (and any local-PK override), column omission, and the shape (electric table + row filter). It is the
185
+ * stable identity a writable entry shares with its {@link asReadonly} projection.
186
+ *
187
+ * Deliberately EXCLUDES the two axes a per-client projection may legitimately differ on:
188
+ * - **write capability** — `mode`, the overlay/journal projection, `managedFields`, `conflictPolicy`,
189
+ * `writeMode` (one client writes the table, another only reads it);
190
+ * - **lifecycle orchestration** — `consistencyGroup`, `subscription`, `retention` (a client may
191
+ * eager- or lazy-load, or group differently, without changing the data it sees).
192
+ *
193
+ * What it pins is the data itself: two registries that present "the same" logical table to different
194
+ * clients must agree here, or those clients are silently seeing different rows/columns. As with the
195
+ * full registry fingerprint, the `customWhere` *body* is invisible — only its presence and the
196
+ * consumer-bumped {@link RowFilterSpec.revision} participate, so bump `revision` to force a divergence
197
+ * a logic-only change would otherwise hide.
198
+ */
199
+ export interface CanonicalReadContract {
200
+ syncedTable: string;
201
+ primaryKey: string[];
202
+ localPrimaryKey: string[] | null;
203
+ columns: CanonicalColumn[];
204
+ omitColumns: string[];
205
+ shape: {
206
+ tableName: string;
207
+ shapeKey: string;
208
+ electricTable: string | null;
209
+ rowFilter: CanonicalRowFilter | null;
210
+ } | null;
211
+ }
212
+
213
+ /** The canonical {@link CanonicalReadContract} of a sync table entry (see the interface for what it omits). */
214
+ export function canonicalizeReadContract(entry: SyncTableEntry): CanonicalReadContract {
215
+ const shape = entry.shape
216
+ ? {
217
+ tableName: entry.shape.tableName,
218
+ shapeKey: entry.shape.shapeKey,
219
+ electricTable: entry.shape.electricTable ?? null,
220
+ rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
221
+ }
222
+ : null;
223
+
224
+ return {
225
+ syncedTable: entry.clientProjection?.syncedTable ?? getTableConfig(entry.table).name,
226
+ primaryKey: [...entry.primaryKey.columns].sort(asString),
227
+ localPrimaryKey: entry.clientProjection?.localPrimaryKey
228
+ ? [...entry.clientProjection.localPrimaryKey.columns].sort(asString)
229
+ : null,
230
+ columns: canonicalizeColumns(entry.table),
231
+ omitColumns: [...(entry.clientProjection?.omitColumns ?? [])].map(String).sort(asString),
232
+ shape,
233
+ };
234
+ }
235
+
236
+ /** A stable string serialization of a table's {@link CanonicalReadContract}. */
237
+ export function canonicalReadContractString(entry: SyncTableEntry): string {
238
+ return JSON.stringify(canonicalizeReadContract(entry));
239
+ }
240
+
241
+ /**
242
+ * A stable fingerprint (hex) of a table's {@link CanonicalReadContract}. Equal for a writable entry and
243
+ * its {@link asReadonly} projection; the basis of the projection-consistency invariant
244
+ * (`assertReadContractPreserved`).
245
+ */
246
+ export function fingerprintReadContract(entry: SyncTableEntry): string {
247
+ return hashString(canonicalReadContractString(entry));
248
+ }
249
+
250
+ /**
251
+ * FNV-1a over UTF-8 bytes, returned as 16 hex chars. Pure and dependency-free so it runs
252
+ * identically in the browser and in Bun (no crypto import). A fingerprint, not a security
253
+ * primitive — used both for the registry shape fingerprint (ADR-0004) and for the apply-function
254
+ * DDL fingerprint embedded in the generated migration (ADR-0018).
255
+ */
256
+ export function hashString(input: string): string {
257
+ const bytes = new TextEncoder().encode(input);
258
+ const prime = 0x100000001b3n;
259
+ const mask = (1n << 64n) - 1n;
260
+ let hash = 0xcbf29ce484222325n;
261
+ for (const byte of bytes) {
262
+ hash = ((hash ^ BigInt(byte)) * prime) & mask;
263
+ }
264
+ return hash.toString(16).padStart(16, "0");
265
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,13 @@
1
+ export * from "./apply-strategy";
1
2
  export * from "./common";
2
3
  export * from "./config";
4
+ export * from "./convergence-model";
5
+ export * from "./fingerprint";
3
6
  export * from "./registry";
7
+ export * from "./registry-diff";
4
8
  export * from "./mutation";
9
+ export * from "./projection";
5
10
  export * from "./runtime";
11
+ export * from "./sql-defaults";
12
+ export * from "./sql-identifier";
6
13
  export * from "./supabase-rls";
package/src/mutation.ts CHANGED
@@ -3,8 +3,29 @@ import { z } from "zod";
3
3
  import { unixMicrosecondsSchema } from "./common";
4
4
 
5
5
  export const mutationKindSchema = z.enum(["create", "update", "delete"]);
6
- export const mutationStatusSchema = z.enum(["pending", "sending", "acked", "failed"]);
7
- export const mutationAckStatusSchema = z.enum(["acked", "failed", "conflicted"]);
6
+ /**
7
+ * The full Mutation-journal status machine — every status a journal row can hold, including the two
8
+ * terminal states (`quarantined`, ADR-0006; `conflicted`, ADR-0015). Kept in lockstep with the
9
+ * client's `MutationStatus` (packages/client/src/mutation-state.ts). Distinct from
10
+ * {@link mutationAckStatusSchema}, the narrower *transport* subset a server ack may carry.
11
+ */
12
+ export const mutationStatusSchema = z.enum([
13
+ "pending",
14
+ "sending",
15
+ "acked",
16
+ "failed",
17
+ "quarantined",
18
+ "conflicted",
19
+ "rejected",
20
+ ]);
21
+ /**
22
+ * The *transport* statuses a server ack may carry. `acked` (applied), `failed` (transient, retry),
23
+ * `conflicted` (ADR-0015 stale write — overlay KEPT, resolve as a new write), and `rejected` (ADR-0022 —
24
+ * a business rejection from the authoritative endpoint: a server-side invariant the client cannot evaluate
25
+ * said no, so the optimistic overlay is auto-discarded for the whole write-unit and the typed reason is
26
+ * surfaced).
27
+ */
28
+ export const mutationAckStatusSchema = z.enum(["acked", "failed", "conflicted", "rejected"]);
8
29
 
9
30
  export const entityKeySchema = z.record(z.string().trim().min(1), z.string().trim().min(1));
10
31
 
@@ -12,11 +33,26 @@ export const mutationEnvelopeSchema = z
12
33
  .object({
13
34
  tableName: z.string().trim().min(1),
14
35
  entityKey: entityKeySchema,
36
+ // INVARIANT — the public mutation surface is UUID-only by contract (this schema, the ack/rejection
37
+ // schemas below, and the client's `mutation_id UUID` journal). The generated apply function and the
38
+ // `operations_log` accept an OPAQUE TEXT id for one narrow case: a DIRECT server-side caller that
39
+ // derives child envelopes (composite `${parentId}:<tag>:<n>` ids) and calls the apply function
40
+ // itself, never crossing this HTTP route or the client journal. So a non-UUID id can never enter a
41
+ // request that this schema validates. See packages/server/src/mutations/plpgsql-apply.ts.
15
42
  mutationId: z.uuid(),
16
43
  mutationSeq: z.number().int().nonnegative(),
17
44
  kind: mutationKindSchema,
18
45
  payload: z.unknown(),
19
46
  clientTimestampUs: unixMicrosecondsSchema,
47
+ /**
48
+ * The Base server version this write was authored against (ADR-0015): the row's Server version
49
+ * at enqueue for a chain head, or its predecessor's resolved version for a chained write. The
50
+ * applier compares the row's *current* Server version to it — `current > base` ⇒ a stale write
51
+ * (an external write interleaved). Absent on a `create` (its conflict is a PK collision, a
52
+ * separate concern) and on any write whose table predates the policy; absence means no stale
53
+ * check runs.
54
+ */
55
+ baseServerVersion: unixMicrosecondsSchema.optional(),
20
56
  })
21
57
  .strict();
22
58
 
@@ -24,11 +60,21 @@ export const mutationAckSchema = z
24
60
  .object({
25
61
  tableName: z.string().trim().min(1),
26
62
  entityKey: entityKeySchema,
63
+ // UUID-only (public-surface invariant; see mutationEnvelopeSchema). The route builds every ack from
64
+ // the request envelope's own UUID `mutationId` — never from the apply function's returned conflict
65
+ // rows (which are TEXT and, for a direct caller's derived child, non-UUID) — so a text id can never
66
+ // reach this ack: the conflict map is keyed by returned text ids but only looked up by request UUIDs.
27
67
  mutationId: z.uuid(),
28
68
  mutationSeq: z.number().int().nonnegative(),
29
69
  status: mutationAckStatusSchema,
30
70
  serverUpdatedAtUs: unixMicrosecondsSchema.optional(),
31
71
  conflictReason: z.string().trim().min(1).optional(),
72
+ /**
73
+ * The typed reason a `rejected` ack carries (ADR-0022): the authoritative endpoint's account of why the
74
+ * write-unit was declined (a capacity/quota/uniqueness rule — e.g. the DB constraint or trigger message).
75
+ * Surfaced to the app when the optimistic overlay is auto-discarded.
76
+ */
77
+ rejectionReason: z.string().trim().min(1).optional(),
32
78
  httpStatus: z.number().int().min(100).max(599).optional(),
33
79
  })
34
80
  .strict();
@@ -39,12 +85,55 @@ export const batchMutationRequestSchema = z
39
85
  })
40
86
  .strict();
41
87
 
88
+ /**
89
+ * The body of an **authoritative write** (ADR-0022 §3, mechanism c): one pessimistic write-**unit** — a set
90
+ * of co-committed mutations the server applies in its **own isolated transaction**, atomically, returning a
91
+ * per-mutation ack. `writeUnit` is the client's unit id (the dynamic `transaction` tag, or the static
92
+ * consistency-group key), carried for attribution. Distinct from `batchMutationRequestSchema` only in
93
+ * *semantics* (atomic unit + a constraint exception → a clean `rejected` ack, never a whole-batch 500) and
94
+ * its endpoint path; the mutation envelope is identical.
95
+ */
96
+ export const authoritativeWriteRequestSchema = z
97
+ .object({
98
+ writeUnit: z.string().trim().min(1).optional(),
99
+ mutations: z.array(mutationEnvelopeSchema).min(1),
100
+ })
101
+ .strict();
102
+
42
103
  export const batchMutationAckSchema = z
43
104
  .object({
44
105
  acks: z.array(mutationAckSchema),
45
106
  })
46
107
  .strict();
47
108
 
109
+ /**
110
+ * Per-mutation attribution for a structural batch rejection. The batch write is atomic —
111
+ * one structurally-invalid mutation rejects the whole POST with a single non-2xx — so the
112
+ * server names the offending mutation(s) here. That lets the client quarantine exactly those
113
+ * and keep the innocent siblings retryable, instead of dragging the whole offline queue to
114
+ * quarantine at the shared attempt cap.
115
+ */
116
+ export const mutationRejectionSchema = z
117
+ .object({
118
+ tableName: z.string().trim().min(1),
119
+ // UUID-only (public-surface invariant; see mutationEnvelopeSchema). Attribution names an offending
120
+ // request mutation, whose id this same contract already validated as a UUID.
121
+ mutationId: z.uuid(),
122
+ mutationSeq: z.number().int().nonnegative(),
123
+ reason: z.string().trim().min(1),
124
+ })
125
+ .strict();
126
+
127
+ /**
128
+ * The body of a non-2xx batch-mutation response. `rejections` is present only when the fault
129
+ * is attributable to specific mutations (payload validation); whole-batch faults (execution
130
+ * 5xx, auth, malformed envelope) carry just a `message`. Unknown extra fields are stripped.
131
+ */
132
+ export const batchMutationErrorSchema = z.object({
133
+ message: z.string().optional(),
134
+ rejections: z.array(mutationRejectionSchema).optional(),
135
+ });
136
+
48
137
  export type MutationKind = z.infer<typeof mutationKindSchema>;
49
138
  export type MutationStatus = z.infer<typeof mutationStatusSchema>;
50
139
  export type MutationAckStatus = z.infer<typeof mutationAckStatusSchema>;
@@ -52,4 +141,7 @@ export type EntityKey = z.infer<typeof entityKeySchema>;
52
141
  export type MutationEnvelope = z.infer<typeof mutationEnvelopeSchema>;
53
142
  export type MutationAck = z.infer<typeof mutationAckSchema>;
54
143
  export type BatchMutationRequest = z.infer<typeof batchMutationRequestSchema>;
144
+ export type AuthoritativeWriteRequest = z.infer<typeof authoritativeWriteRequestSchema>;
55
145
  export type BatchMutationAck = z.infer<typeof batchMutationAckSchema>;
146
+ export type MutationRejection = z.infer<typeof mutationRejectionSchema>;
147
+ export type BatchMutationError = z.infer<typeof batchMutationErrorSchema>;
@@ -0,0 +1,150 @@
1
+ import type { AnyPgTable } from "drizzle-orm/pg-core";
2
+
3
+ import type { Retention } from "./config";
4
+ import { fingerprintReadContract } from "./fingerprint";
5
+ import type { ClientProjectionSpecForTable, SyncTableEntry, SyncTableRegistry } from "./registry";
6
+
7
+ /**
8
+ * Per-client mode projection (ADR-0025). The authoritative (server) registry defines a table once with
9
+ * its full write contract; a client that must only *read* that table consumes the same entry through
10
+ * `asReadonly`. The read/identity contract — table, columns, primary key, synced-table name, column
11
+ * omission, the shape/row filter, AND the column-builder factory (`makeColumns`) — is preserved
12
+ * verbatim; the write-capability metadata is dropped:
13
+ *
14
+ * - `mode` flips to `readonly`;
15
+ * - the overlay-merged read-model `view` and the overlay/journal client projection (the local write
16
+ * machinery `@pgxsinkit/client` provisions for a writable table) are removed — a readonly client reads
17
+ * the synced base table directly;
18
+ * - `conflictPolicy`, `governance` (managed fields), and `writeMode` are removed — a readonly table has
19
+ * no write path, and `defineSyncRegistry` would otherwise still treat them as a writable declaration.
20
+ *
21
+ * The result is the same entry `defineSyncTable` would have produced for this table with
22
+ * `mode: "readonly"`, so `defineSyncRegistry` accepts it without the writable-table requirements
23
+ * (server-version field + `conflictPolicy`).
24
+ *
25
+ * Lifecycle axes (`consistencyGroup`, `subscription`, `retention`) are preserved — a projection may keep
26
+ * the authoritative grouping/timing/durability; change them on the projected entry if a client needs to.
27
+ *
28
+ * `makeColumns` (the column-builder factory `defineSyncTable` stashes) is carried too: since ADR-0029 P1
29
+ * the client derives EVERY synced-table object from it (`getSyncedLocalTable` → `projectedColumnBuilders`),
30
+ * so a readonly projection that dropped it could not build its own local synced read cache — the member-boot
31
+ * failure this keep-list's NOTE below predicted. It is read-derivation machinery, not a write handle.
32
+ *
33
+ * NOTE: if a new *read-relevant* field is added to {@link SyncTableEntry}, carry it here too (this builds
34
+ * the readonly entry by listing what to keep, so a new field is otherwise silently dropped).
35
+ */
36
+ export function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgTable>(
37
+ entry: SyncTableEntry<TTable, TLocalTable>,
38
+ ): SyncTableEntry<TTable, TLocalTable> {
39
+ const { clientProjection } = entry;
40
+ const readonlyProjection: ClientProjectionSpecForTable<TTable> | undefined =
41
+ clientProjection != null
42
+ ? {
43
+ ...(clientProjection.syncedTable != null ? { syncedTable: clientProjection.syncedTable } : {}),
44
+ ...(clientProjection.omitColumns != null ? { omitColumns: clientProjection.omitColumns } : {}),
45
+ ...(clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {}),
46
+ }
47
+ : undefined;
48
+
49
+ return {
50
+ table: entry.table,
51
+ localTable: entry.localTable,
52
+ mode: "readonly",
53
+ primaryKey: entry.primaryKey,
54
+ ...(entry.shape != null ? { shape: entry.shape } : {}),
55
+ ...(readonlyProjection != null ? { clientProjection: readonlyProjection } : {}),
56
+ ...(entry.serverProjection != null ? { serverProjection: entry.serverProjection } : {}),
57
+ ...(entry.consistencyGroup != null ? { consistencyGroup: entry.consistencyGroup } : {}),
58
+ ...(entry.subscription != null ? { subscription: entry.subscription } : {}),
59
+ ...(entry.retention != null ? { retention: entry.retention } : {}),
60
+ ...(entry.readProjection ? { readProjection: true } : {}),
61
+ // Read-derivation machinery, not a write handle: the client rebuilds the readonly table's own local
62
+ // synced object from this factory (ADR-0029 P1). Dropping it would break member-mode boot.
63
+ ...(entry.makeColumns != null ? { makeColumns: entry.makeColumns } : {}),
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Project an entry onto a different **retention** (ADR-0021) — the per-table local-persistence axis:
69
+ * `persistent` (the durable PGlite/OPFS backend) | `ephemeral` (the table's whole local cluster — read
70
+ * cache, overlay, journal, sequence, views, reconcile function — emitted as `TEMP`/`pg_temp`, leaving no
71
+ * durable trace). Returns a copy of `entry` with `retention` overridden and **everything else preserved
72
+ * verbatim** (table, columns, mode, write contract, shape/row filter, the other lifecycle axes).
73
+ *
74
+ * Retention is a **lifecycle** axis, not a read-contract one, so a per-client registry may legitimately
75
+ * differ on it: {@link fingerprintReadContract} excludes retention, so a `withRetention(...)` of an
76
+ * authoritative entry still satisfies {@link assertReadContractPreserved}. This is how one authoritative
77
+ * registry yields a table that is durable for one client and ephemeral for another, e.g.
78
+ * `withRetention(asReadonly(authoritative.exam), "ephemeral")`.
79
+ *
80
+ * Unlike `mode` (whose overlay/journal/view fields {@link asReadonly} must re-resolve), retention has **no
81
+ * entry-derived fields** — the durable-vs-`TEMP` decision is taken by the client's schema generator at
82
+ * runtime from this scalar — so overriding it needs no re-resolution and a plain copy is correct. The
83
+ * return type is the input entry's exact type (write handles, create/update typing, governance marker all
84
+ * carry through); the cast restates what a generic object spread cannot prove.
85
+ *
86
+ * Two constraints carry over (enforced elsewhere, not by this helper):
87
+ * - **Consistency-group uniformity** (ADR-0021 §4): every table sharing a `consistencyGroup` must agree on
88
+ * retention — override the whole group, not one member, or `defineSyncRegistry` rejects the mixed group.
89
+ * A singleton-group table can be flipped alone.
90
+ * - **No durable offline write queue for `ephemeral`** (ADR-0021 composition rule): an ephemeral writable
91
+ * table's journal is `TEMP`, so a write staged offline does not survive session end — pair a must-not-lose
92
+ * write with a `pessimistic` write-mode (ADR-0022) or a prompt flush.
93
+ */
94
+ export function withRetention<TEntry extends SyncTableEntry>(entry: TEntry, retention: Retention): TEntry {
95
+ return { ...entry, retention } as TEntry;
96
+ }
97
+
98
+ /**
99
+ * The named `ephemeral` lifecycle projection — `withRetention(entry, "ephemeral")` — the lifecycle twin of
100
+ * {@link asReadonly}, for the common direction (a client wants no durable trace of a table the authoritative
101
+ * registry keeps `persistent`). Composes with `asReadonly`: `asEphemeral(asReadonly(authoritative.exam))`
102
+ * is a read-only, no-durable-trace projection. The reverse direction (an ephemeral authoritative table a
103
+ * client wants durable) is the bidirectional {@link withRetention} with `"persistent"`. See
104
+ * {@link withRetention} for the constraints that carry over (group uniformity; no durable offline queue).
105
+ */
106
+ export function asEphemeral<TEntry extends SyncTableEntry>(entry: TEntry): TEntry {
107
+ return withRetention(entry, "ephemeral");
108
+ }
109
+
110
+ /**
111
+ * Assert that a per-client `projection` registry preserves the **read contract** (ADR-0025) of the
112
+ * `authoritative` registry it projects from. For every table the projection declares, its
113
+ * {@link fingerprintReadContract} must equal the authoritative entry's: a projection may differ only in
114
+ * write capability and lifecycle orchestration, never in the data it syncs (columns, primary key,
115
+ * row-filter shape). A table present in the authoritative registry but absent from the projection is a
116
+ * permitted subset; a table in the projection with no authoritative source is an error (no contract to
117
+ * project from).
118
+ *
119
+ * Throws, naming the divergent tables, on any mismatch. Call it where the client registries are assembled
120
+ * (module-eval or a test) so a drifted projection fails closed instead of silently serving different rows
121
+ * to different clients. The `customWhere` body is invisible to the fingerprint — bump
122
+ * {@link RowFilterSpec.revision} so a logic-only divergence is caught.
123
+ */
124
+ export function assertReadContractPreserved(
125
+ authoritative: SyncTableRegistry,
126
+ projection: SyncTableRegistry,
127
+ options?: { label?: string },
128
+ ): void {
129
+ const divergent: string[] = [];
130
+
131
+ for (const [key, projectedEntry] of Object.entries(projection)) {
132
+ const authoritativeEntry = authoritative[key];
133
+ if (authoritativeEntry == null) {
134
+ divergent.push(`${key} (absent from the authoritative registry)`);
135
+ continue;
136
+ }
137
+ if (fingerprintReadContract(authoritativeEntry) !== fingerprintReadContract(projectedEntry)) {
138
+ divergent.push(key);
139
+ }
140
+ }
141
+
142
+ if (divergent.length > 0) {
143
+ const where = options?.label ? ` (${options.label})` : "";
144
+ throw new Error(
145
+ `read-contract divergence${where}: a per-client projection must preserve its authoritative table's ` +
146
+ `read contract (synced columns, primary key, row-filter shape) and differ only in write capability ` +
147
+ `and lifecycle. Divergent tables: ${divergent.join(", ")}.`,
148
+ );
149
+ }
150
+ }