@pgxsinkit/contracts 0.1.32 → 0.1.36

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,376 @@
1
+ ---
2
+ name: registry-authoring
3
+ description: >-
4
+ Load when defining or changing a pgxsinkit sync registry with @pgxsinkit/contracts —
5
+ defineSyncRegistry / defineSyncTable, table sync modes, managed fields, conflict policy, read-path row
6
+ filters, and RLS. Teaches the rules that throw or fail closed if missed: every readwrite table needs a
7
+ server-version managed field plus a conflictPolicy (no default), authClaim/nowMicroseconds managed
8
+ fields are server-assigned and rejected in client payloads, enum columns must be cast to text,
9
+ the read filter and the RLS policy must derive from one predicate, and the in-database apply function
10
+ is provisioned by the pgxsinkit-generate CLI as a drizzle-kit migration. Also covers per-client mode
11
+ projection (ADR-0025): one authoritative registry with `asReadonly` projections when a table is
12
+ readwrite for one client and readonly for another, guarded by `assertReadContractPreserved`. Load before
13
+ authoring a registry, adding a writable table, presenting a table read-only to one client, or wiring
14
+ row-level security.
15
+ metadata:
16
+ type: core
17
+ library: "@pgxsinkit/contracts"
18
+ library_version: "0.1.32"
19
+ source: https://pgxsinkit.github.io/start/getting-started/
20
+ ---
21
+
22
+ # Authoring a pgxsinkit registry
23
+
24
+ The registry (`defineSyncRegistry` over `defineSyncTable`) is the single source of truth both paths read
25
+ from — the read proxy and the write apply function are generated from it, so getting the registry right
26
+ is what keeps read and write authorization from drifting.
27
+
28
+ ## Writable tables have two hard requirements (or it throws)
29
+
30
+ `defineSyncRegistry` **throws** unless every `mode: "readwrite"` table declares **both**:
31
+
32
+ 1. A **server version** — a `nowMicroseconds`-on-`update` managed field, conventionally `updated_at_us`
33
+ (a `bigint` microsecond column). Optimistic convergence keys on it; the `reject-if-stale` conflict
34
+ policy compares the write's base version against it.
35
+ 2. A **`conflictPolicy`** — `"reject-if-stale"` or `"last-write-wins"`. There is **no silent default**,
36
+ because a silent last-write-wins is exactly the data loss the choice exists to surface.
37
+
38
+ ```ts
39
+ widgets: defineSyncTable({
40
+ tableName: "widgets",
41
+ mode: "readwrite",
42
+ makeColumns: () => ({
43
+ id: uuid("id").primaryKey(),
44
+ label: varchar("label", { length: 120 }).notNull(),
45
+ ownerId: uuid("owner_id"),
46
+ updatedAtUs: bigint("updated_at_us", { mode: "bigint" }).notNull().default(clockMicrosecondsSql),
47
+ }),
48
+ conflictPolicy: "reject-if-stale", // REQUIRED — no default
49
+ governance: {
50
+ managedFields: [
51
+ { column: "updatedAtUs", applyOn: ["create", "update"], strategy: "nowMicroseconds" },
52
+ // Stamp the owner from the verified `sub` claim. (`auth.uid()` is just claimPath: ["sub"].)
53
+ { column: "ownerId", applyOn: ["create"], strategy: "authClaim", claimPath: ["sub"] },
54
+ ],
55
+ },
56
+ }),
57
+ ```
58
+
59
+ ## Managed fields are server-assigned — never send them
60
+
61
+ A managed field is stamped by the apply function under the verified request claims. Two strategies:
62
+
63
+ - **`nowMicroseconds`** — `clock_timestamp()` microseconds (the audit columns; the `updated_at_us`-on-update
64
+ field is the strictly-monotonic server version). The stamp is the canonical `public.pgxsinkit_clock_us()`
65
+ database function (one home for the clock semantics — `clock_timestamp()`, never `now()`), installed by the
66
+ **utilities migration** (`renderPgxsinkitUtilitiesMigration` / `pgxsinkit-generate --utilities`) which must
67
+ be the **first folder** in your migration chain, before the schema and the generated sync-artifact.
68
+ - **`authClaim`** — a value read from a verified JWT claim at a JSON `claimPath`. This is the **single**
69
+ claim-stamping strategy: `["sub"]` is the auth subject (the old `auth.uid()` owner idiom), and
70
+ `["app_metadata", "person_id"]` (etc.) is any app-minted identity — one mechanism, not a `sub`-only
71
+ special case. `cast` is optional and **defaults to the target column's own SQL type** (a `uuid` column
72
+ needs none); the path segments must be plain identifiers (they are emitted into the apply-function DDL).
73
+
74
+ The write API **rejects** a client write payload that _includes_ a managed field, and the create-validation
75
+ schema **omits** managed-on-create fields. So: do not put `updated_at_us` or a claim-stamped owner column in
76
+ a client `create`/`update` payload; let the server assign them. (The apply function independently stamps
77
+ these, so a client value would either be overwritten or rejected. The optimistic overlay still fills an
78
+ `authClaim` create field locally from the decoded claim, so the row renders attributed immediately.)
79
+
80
+ ## Omitted columns are invisible to the write path — by design
81
+
82
+ `clientProjection.omitColumns` columns are **server-only**: they exist on the Postgres table but not on the
83
+ client, and the apply function reads **only a table's projected columns** from a write payload. A payload key
84
+ that is not a writable (projected) column splits into exactly two cases:
85
+
86
+ - **A projected-away / server-only column** (one you listed in `clientProjection.omitColumns`) sent
87
+ _explicitly_ in a `create`/`update` payload is **400-rejected** by the write route's projected-field check.
88
+ It is _not_ silently dropped, and the write does **not** succeed.
89
+ - **An unknown non-column key** (a typo, a stale field the table no longer has) is **silently ignored by the
90
+ apply function** — that write collapses to a bare server-version (`updated_at_us`) bump and still acks
91
+ `succeeded`. To make that silence observable, the write API emits **one structured `console.warn` per
92
+ (table, key) per process** naming the dropped key — a diagnostic, not a rejection. It fires _only_ for this
93
+ unknown-key case, never for a projected-away column (which is rejected, not dropped).
94
+
95
+ The rule that follows: **write a server-only (omitted) column outside the sync rail** — a server-side
96
+ `UPDATE`, a trigger, or a managed field (`governance.managedFields`, stamped by the apply function). Do not
97
+ try to set it from a client `create`/`update` payload; the route rejects it.
98
+
99
+ ## Read-path filtering: `customWhere` runs in Electric, not Postgres
100
+
101
+ A table's `shape.rowFilter.customWhere` builds the Electric shape `where`. **Electric** evaluates it (not
102
+ Postgres), so **return a Drizzle `SQL` fragment built from the table's columns** — reference each column
103
+ through `c(column)` and embed request-derived values directly: they become **bound `$n` params**, never
104
+ hand-escaped literals.
105
+
106
+ ```ts
107
+ import { c, DENY_ALL } from "@pgxsinkit/contracts";
108
+
109
+ function widgetsReadFilter(claims) {
110
+ if (isAdmin(claims)) return null; // null = no filter (all rows visible)
111
+ if (!claims.sub) return DENY_ALL; // sql`false` — the deny-all sentinel (no rows visible)
112
+ return sql`${c(widgets.ownerId)} = ${claims.sub}`; // claims.sub is a bound $1 param
113
+ }
114
+ ```
115
+
116
+ Two Electric where-grammar rules: columns must be **plain** (unqualified) — `c()` emits the bare name
117
+ (`"owner_id"`), never the Drizzle-default qualified `"widgets"."owner_id"` (Electric rejects that); and an
118
+ **enum column must be cast to text** — `${c(widgets.role)}::text = 'manager'`. Subqueries must be
119
+ self-contained (not correlated). Returning a raw **string** is the escape hatch — escape any embedded
120
+ value yourself with `escapeSqlLiteral` (a string is NOT escaped for you); return `DENY_ALL` (not `"1 = 0"`)
121
+ to block all rows.
122
+
123
+ **Inline (all-in-one `defineSyncTable`) — `rowFilter` as a function of the columns.** The example above
124
+ references `widgets.ownerId`, which assumes the table is built _elsewhere_ (e.g. a separate schema file the
125
+ registry imports). When you declare a table and its filter together in **one** `defineSyncTable` call, the
126
+ table object doesn't exist yet at the call site — so don't fall back to hand-written column-name strings.
127
+ Give `shape.rowFilter` a **function of the built columns** (the same typed columns `extras` receives) and
128
+ keep using `c()`:
129
+
130
+ ```ts
131
+ defineSyncTable({
132
+ tableName: "widgets",
133
+ makeColumns: () => ({ id: uuid("id").primaryKey(), ownerId: uuid("owner_id") }),
134
+ shape: {
135
+ rowFilter: (columns) => ({
136
+ customWhere: (claims) => (claims.sub ? sql`${c(columns.ownerId)} = ${claims.sub}` : DENY_ALL),
137
+ }),
138
+ },
139
+ });
140
+ ```
141
+
142
+ A static `RowFilterSpec` (`rowFilter: { customWhere }`) still works unchanged — reach for the function form
143
+ only when you need typed, rename-safe column refs inside an all-in-one definition. **Prefer it over the
144
+ string escape hatch:** a `customWhere` that returns `null`/`""` means _no filter — all rows visible_, so a
145
+ hand-built owner filter that returns `null` for "no claim" silently exposes every row; the typed form makes
146
+ `DENY_ALL` the obvious deny.
147
+
148
+ ## Cross-table filters: compose a self-contained subquery from the typed columns, never a string
149
+
150
+ A **membership fan-out** — "sync a row only if the subject belongs to its container" — is a `customWhere`
151
+ whose predicate is a **subquery over another table** (`container_id IN (SELECT … FROM memberships …)`).
152
+ Author it the same typed way as an owner filter, never as a hand-built string: `c()` for every column
153
+ (bare, as Electric needs), the **table object** for the `FROM`, and the subject as a **bound param**.
154
+ Factor the subquery into a small helper so the read filter — and any narrower variant — share one
155
+ definition (the read-path twin of the membership RLS predicate):
156
+
157
+ ```ts
158
+ import { c, DENY_ALL, type JwtClaims } from "@pgxsinkit/contracts";
159
+ import { sql, type SQL } from "drizzle-orm";
160
+
161
+ // The containers a subject belongs to, as a self-contained subquery: bare columns via c(), the FROM
162
+ // from the table object, the subject bound as $n. The subquery references `membership`'s OWN columns,
163
+ // so its bare names resolve to its own FROM — it is self-contained, not correlated.
164
+ function memberContainers(subject: string): SQL {
165
+ return sql`select ${c(membership.containerId)} from ${membership} where ${c(membership.memberId)} = ${subject}`;
166
+ }
167
+
168
+ function widgetsReadFilter(claims: JwtClaims): SQL {
169
+ if (!claims.sub) return DENY_ALL; // no claim → deny (NOT null, which would expose every row)
170
+ return sql`${c(widgets.containerId)} in (${memberContainers(claims.sub)})`;
171
+ }
172
+ ```
173
+
174
+ What the typed form buys over a string: the columns stay rename-safe and existence-checked, and the
175
+ subject is a `$n` param (`params: ["…"]`), never an escaped literal — so a quote in the value can't break
176
+ or inject the predicate. **Subqueries nest by interpolation** — wrap one `sql` fragment in another to
177
+ narrow a fan-out (e.g. a group _within_ an offering): `` sql`${c(post.offeringId)} in (${memberOfferings(sub)}) and (${c(post.groupId)} is null or ${c(post.groupId)} in (${memberGroups(sub)}))` `` (each `${sub}`
178
+ is its own bound param). Two constraints hold: the subquery must stay **self-contained** (not correlated —
179
+ it gets its own `FROM`, so bare names resolve to it), and the subquery `where` is the **flagged Electric
180
+ preview** — run Electric with `allow_subqueries,tagged_subqueries` or the shape fails closed (no rows).
181
+ On **managed Electric Cloud** that preview is activated per source by Electric staff on request (no
182
+ self-serve toggle yet; default-on intended) — ask Electric to enable it, or self-host Electric.
183
+ Combine with the function form when the table is defined all-in-one: the row's own column comes from
184
+ `(columns) => …`, the foreign table + its columns are imported already-built.
185
+
186
+ ## RLS: derive read and write from the same Drizzle columns
187
+
188
+ Authorization runs in two engines (Postgres RLS for writes; the Electric `where` for reads). Build both
189
+ from the **same Drizzle columns** so a row can never be readable-but-unwritable (or the reverse) through a
190
+ column rename or a typo:
191
+
192
+ - Common shapes: `buildSupabaseOwnerOrAdminNativePolicies({ role, ownerColumn })` and
193
+ `buildSupabaseMembershipNativePolicies({ role, containerColumn, membershipTable, … })` (from
194
+ `@pgxsinkit/contracts`). They take **real Drizzle columns** and derive the governed table name from
195
+ them, so call them inside `defineSyncTable`'s `extras: (t) => …` callback (where the columns carry their
196
+ table), not the `policies:` array.
197
+ - Beyond them (e.g. collaborative any-member writes): compose your own with `pgPolicy` + Drizzle operators
198
+ (`and`/`or`/`eq`) over the columns. Use the official `drizzle-orm/supabase` helpers for the auth leaves —
199
+ `authUid` (emits `(select auth.uid())`, the Supabase per-statement-eval performance idiom, not a per-row
200
+ bare `auth.uid()`), `authenticatedRole`, etc. Inline a literal with `eq(col, value).inlineParams()` (the
201
+ value stays type-checked against the column and is inlined into the DDL — a bare `$n` is something
202
+ `CREATE POLICY` cannot carry). Drop to raw `sql` only for things with no Drizzle equivalent: a SECURITY
203
+ DEFINER membership helper or a `current_setting('request.jwt.claims')` admin check. Inline such a
204
+ predicate rather than referencing a not-yet-created SQL function — `CREATE POLICY` needs it to exist
205
+ first. For "compare OLD vs NEW" rules (column immutability), RLS cannot help (`WITH CHECK` sees only NEW,
206
+ `USING` only OLD) —
207
+ use a `BEFORE UPDATE` trigger.
208
+
209
+ Give drizzle-kit `entities: { roles: { provider: "supabase" } }` in `drizzle.config.ts` so it treats the
210
+ Supabase roles (`authenticated`/`anon`/`service_role`/…) as externally managed — referenced in a policy's
211
+ `to:` but never created or dropped.
212
+
213
+ ## Provision the apply function from the registry
214
+
215
+ The write path applies through one in-database PL/pgSQL function, `pgxsinkit_apply_mutations`. Generate
216
+ the drizzle-kit migration that installs it with the published `pgxsinkit-generate` CLI (a `bin` of
217
+ `@pgxsinkit/server`), run from your project, then apply it through your normal migration flow:
218
+
219
+ ```bash
220
+ bun run pgxsinkit-generate --registry ./sync-registry.ts --export registry \
221
+ --project-dir ./db --config drizzle.config.ts --name sync_artifact
222
+ ```
223
+
224
+ The apply function and the audit/version column DEFAULTs both **call** the canonical
225
+ `public.pgxsinkit_clock_us()` microsecond clock, so its **utilities migration must be the first folder in
226
+ the chain** — generate it once with `--utilities`, passing an early-sorting folder name:
227
+
228
+ ```bash
229
+ bun run pgxsinkit-generate --utilities \
230
+ --project-dir ./db --config drizzle.config.ts --name 20200101000000_pgxsinkit_utilities
231
+ ```
232
+
233
+ ## Multi-client: one authoritative registry, readonly projections (ADR-0025)
234
+
235
+ When the same table is `readwrite` for one client and `readonly` for another (a teacher writes a row a
236
+ learner only reads, or the reverse), `mode` is **per-client**, not a property of the table. Define it
237
+ **once** in an authoritative registry at its writable capability and project it per client. `mode` is baked
238
+ at `defineSyncTable` time and drives the overlay/journal machinery + the `_read_model` view, so a
239
+ hand-spread `{ ...entry, mode: "readonly" }` is **broken** (it keeps a view over overlay state the readonly
240
+ client never creates). Use `asReadonly`, which re-derives a true readonly entry — drops the overlay/journal
241
+ projection, the view, and `conflictPolicy`/`governance`/`writeMode`; keeps columns, primary key, synced
242
+ table, and the shape/row filter.
243
+
244
+ ```ts
245
+ import { asReadonly, assertReadContractPreserved } from "@pgxsinkit/contracts";
246
+
247
+ const authoritativeRegistry = defineSyncRegistry({ posting_restriction: postingRestrictionEntry }); // readwrite
248
+ const teacherRegistry = defineSyncRegistry({ posting_restriction: postingRestrictionEntry });
249
+ const learnerRegistry = defineSyncRegistry({ posting_restriction: asReadonly(postingRestrictionEntry) });
250
+
251
+ // Fail closed if a projection ever diverges the data it syncs (columns / pk / row-filter shape):
252
+ assertReadContractPreserved(authoritativeRegistry, teacherRegistry, { label: "teacher" });
253
+ assertReadContractPreserved(authoritativeRegistry, learnerRegistry, { label: "learner" });
254
+ ```
255
+
256
+ - **Generate the server (apply function + proxy) from the authoritative registry** — the apply function
257
+ emits a branch for every table and stamps managed fields / reject-if-stale from the entry's write
258
+ contract, so it must see the writable entry. A claims-branching `customWhere` then serves every client.
259
+ - A projection may differ **only** in write capability and lifecycle (`subscription`/`retention`/group),
260
+ never in the read contract — `assertReadContractPreserved` enforces it (it can't see the `customWhere`
261
+ body, so bump `rowFilter.revision` on a logic change).
262
+ - The full registry fingerprint differs between the writable and readonly variants — expected and fine:
263
+ it is client-local (guards each client's own store rebuild) and the server never sees it.
264
+
265
+ ## A second shape over one table: read projections (ADR-0027)
266
+
267
+ `asReadonly` reuses the **same** table+columns for another client. When you instead need a **different,
268
+ narrower shape over an existing physical table** — a light column subset and/or a different row filter,
269
+ under a distinct local identity — use `defineReadProjection(owner, …)`. The first use: a learner reads the
270
+ full `assessment_definition` (heavy QTI jsonb) while an admin reads only titles, admin-scoped.
271
+
272
+ ```ts
273
+ import { defineReadProjection } from "@pgxsinkit/contracts";
274
+
275
+ export const assessmentDefinition = defineSyncTable({ tableName: "assessment_definition", makeColumns /* … */ });
276
+
277
+ export const assessmentDefinitionAdminSummary = defineReadProjection(assessmentDefinition, {
278
+ as: "assessment_definition_admin_summary", // distinct local table + shapeKey
279
+ columns: ["offeringId", "assessmentType", "title", "state"], // typed subset of owner keys; PK always kept
280
+ rowFilter: (c) => ({ customWhere: adminOrgFilter(c.offeringId), revision: "admin-summary-1" }),
281
+ });
282
+ ```
283
+
284
+ - It **owns no table**: its `table` IS the owner's, so nothing new is migrated and there is nothing to
285
+ leak into a drizzle-kit schema barrel. Only its `localTable` (named `as`) and shape are its own.
286
+ - `columns` is a typed subset of the owner's keys; the projection's local table carries the owner's **real
287
+ per-column types restricted to exactly the listed keys** (Picked down from the owner), so a projection row
288
+ typechecks by property key with no casts. The PK is always kept **at runtime**, but the type is a safe
289
+ **under-claim**: a PK column you don't put in `columns` is still synced, yet is **absent from the type** —
290
+ list it in `columns` when you need to read it typed. The owner's column definitions are reused (never
291
+ restated), and the subset becomes the Electric `columns` allow-list so an omitted (heavy) column is
292
+ **never fetched**, not merely stripped.
293
+ - The physical Electric table is **derived** from the owner — you never name a source string (the old
294
+ `shape.electricTable` is internal-only and not a consumer input). The `rowFilter` callback receives the
295
+ OWNER's full columns (the `customWhere` runs in Electric on the physical table, so it may reference a
296
+ column the subset omits).
297
+ - It is **readonly**; put it in the authoritative registry under its own key and in the reading client's
298
+ registry. RLS for its reads lives on the **owner** (a projection adds no DDL to a table it doesn't own);
299
+ its `customWhere` must be a subset of what that RLS allows. The proxy resolves each shape by its unique
300
+ `shapeKey`, so the owner and the projection coexist over one physical table.
301
+
302
+ ### Redacting projection: a secure "window" over a keyed table
303
+
304
+ A projection can carry its own `serverProjection` (an egress `rowTransform`, resolved by the projection's
305
+ `shapeKey`) — e.g. stream a `jsonb` item body while stripping the answer key per row. When the transform
306
+ must READ a column that is not in the client shape (a `keysWithheld` control flag), list it in
307
+ `serverOnlyColumns`: it is added to the Electric fetch allow-list (so the transform sees it) yet stays
308
+ omitted from the client keep-set. Egress order is **transform first, then omission** — the flag is
309
+ stripped after the transform runs.
310
+
311
+ ```ts
312
+ export const secureItemWindow = defineReadProjection(secureItem, {
313
+ as: "secure_item_window",
314
+ columns: ["payload", "metadata"], // client keep-set (PK always kept)
315
+ serverProjection: {
316
+ rowTransform: (row) => (row.keys_withheld === true ? { ...row, payload: stripKey(row.payload) } : row),
317
+ },
318
+ serverOnlyColumns: ["keysWithheld"], // fetched for the transform, never on the client wire
319
+ });
320
+ ```
321
+
322
+ `serverOnlyColumns` requires BOTH `serverProjection.rowTransform` and `columns`, and must be disjoint from
323
+ `columns` and the PK — each is a loud error.
324
+
325
+ **No inheritance — enforced.** A projection does NOT inherit its owner's `serverProjection`. An inherited
326
+ transform whose input column is absent from the projection's fetch list would read `undefined` and
327
+ silently fail OPEN (serving the un-redacted body). Because a bare projection over a redacting owner would
328
+ therefore egress the RAW owner row, `defineReadProjection` THROWS at definition time when the owner
329
+ declares an egress `rowTransform` unless the projection declares its posture — either your own
330
+ `serverProjection` (usually the same fn) + `serverOnlyColumns` for its control inputs, or the explicit
331
+ opt-out `serverProjection: "unredacted"` (only after confirming the kept columns leak nothing; it attaches
332
+ no transform but records the raw-egress decision at the definition site). `"unredacted"` over a
333
+ transform-less owner is itself rejected — a stale opt-out would silently pre-authorize a leak if the owner
334
+ later gains a transform.
335
+
336
+ ## Consistency groups: scope them to the joined cluster
337
+
338
+ `consistencyGroup` binds tables onto one shape stream committing **atomically** at a shared LSN
339
+ frontier — a reader never sees one grouped table advanced past another for the same server
340
+ transaction. Default is none (per-table singleton, independent frontier). Three scoping rules:
341
+
342
+ 1. **Group the transactionally-joined cluster** — tables written together in one server transaction
343
+ and rendered joined (FK parent + children). That is what the atomic frontier protects; if the app
344
+ otherwise needs post-ack re-reads to hide half-applied transactions, the tables belong in a group.
345
+ 2. **Quiet members are affordable.** Pre-ADR-0033 a rarely-written reference table could hold its
346
+ whole group for a full long-poll cycle (~41s on CDN-fronted Electric); the live-tail sibling nudge
347
+ now caps that at ~one catch-up round trip per gated commit. Don't keep a lookup table out of its
348
+ natural group for cost reasons.
349
+ 3. **Don't group "everything".** Every gated commit nudges each lagging member — scope a group to the
350
+ joined cluster; unrelated clusters go in separate groups or stay singletons.
351
+
352
+ All members of a group must agree on `subscription`, `retention`, and `writeMode` (the registry
353
+ rejects disagreement).
354
+
355
+ ## Common mistakes
356
+
357
+ - Omitting `conflictPolicy` or the server-version field on a `readwrite` table (throws).
358
+ - Putting a managed field (`updated_at_us`, owner) in a client write payload (rejected).
359
+ - Trying to write an `omitColumns` (server-only) column from a client payload — the write route
360
+ **400-rejects** it (an unknown non-column typo is instead silently dropped and surfaced by a per-process
361
+ `console.warn`); write server-only columns outside the sync rail (a server `UPDATE`, a trigger, or a
362
+ managed field).
363
+ - In a `customWhere`: comparing an enum without `::text`, qualifying a column (use `c()` for a bare ref),
364
+ or hand-escaping a value into a string instead of binding it via a Drizzle `sql` fragment.
365
+ - Letting the read filter and RLS policy diverge instead of building both from the same Drizzle columns.
366
+ - Declaring a _second_ owning `defineSyncTable` to read an existing physical table (a phantom table, and
367
+ the registry rejects the duplicate local identity) — use `defineReadProjection` for a second shape.
368
+ - Calling the native policy builders in the `policies:` array (they need `extras: (t) => …` to derive the
369
+ table from the columns), or referencing a custom SQL function in `CREATE POLICY` before it exists.
370
+ - In a hand-written policy: bare `auth.uid()` instead of `authUid` (per-row vs per-statement), or a bound
371
+ literal (`eq(col, x)`) where `CREATE POLICY` needs an inlined one (`eq(col, x).inlineParams()`).
372
+ - Hand-spreading `{ ...entry, mode: "readonly" }` to downgrade a writable table for a read-only client
373
+ (keeps a `_read_model` view over overlay state that client never creates) — use `asReadonly`.
374
+
375
+ For the surrounding model (two paths, one write path, fail-closed subquery flag), load the `core` skill
376
+ from `@pgxsinkit/client`. Full prose: <https://pgxsinkit.github.io/start/getting-started/>.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Static, type-driven read-path apply ladder (ADR-0009 decision 3).
3
+ *
4
+ * We own the registry's column types ahead of time and only ever target the latest PGlite, so the
5
+ * bulk-insert strategy for a synced table is chosen **once, statically** from its column types —
6
+ * never by probing `information_schema` at runtime. This module is the pure, dependency-free core
7
+ * (no registry, no Drizzle import) so it stays in the fast unit lane; {@link deriveSyncColumnTypes}
8
+ * in `registry.ts` bridges a `SyncTableEntry`'s Drizzle columns into {@link SyncColumnType}s.
9
+ */
10
+
11
+ /** The bulk-insert path the engine uses for a fresh subscription's initial backfill. */
12
+ export type ApplyStrategy = "copy" | "json" | "insert";
13
+
14
+ /** Resolved column type descriptor for the apply ladder — derived from the registry, not the DB. */
15
+ export interface SyncColumnType {
16
+ /** SQL column name (not the Drizzle property key). */
17
+ name: string;
18
+ /**
19
+ * The column's base SQL type from Drizzle's `getSQLType()` (e.g. `"uuid"`, `"text"`, `"jsonb"`,
20
+ * `"bigint"`, `"timestamp with time zone"`). Array-ness is carried separately in {@link isArray};
21
+ * this string is the element/base type and is usable verbatim as a `json_to_recordset` cast type
22
+ * (with `[]` appended when `isArray`).
23
+ */
24
+ sqlType: string;
25
+ /** True when the column is an array of any dimension. */
26
+ isArray: boolean;
27
+ }
28
+
29
+ /**
30
+ * Postgres scalar types whose JS→CSV-text rendering is unambiguous, so PGlite `COPY ... FROM`
31
+ * round-trips them losslessly. Deliberately **conservative** (ADR-0009 decision 3): never add a
32
+ * type here unless `COPY` truly handles it. Notably EXCLUDES timestamps/dates (format nuances),
33
+ * `numeric` (precision/format), `bytea`, `interval`, enums, `json`/`jsonb`, and arrays — those
34
+ * route to the `json` tier (if json-representable) or the always-correct `insert` floor.
35
+ */
36
+ const COPY_SAFE_BASE_TYPES = new Set<string>([
37
+ "text",
38
+ "varchar",
39
+ "character varying",
40
+ "char",
41
+ "character",
42
+ "bpchar",
43
+ "uuid",
44
+ "boolean",
45
+ "bool",
46
+ "smallint",
47
+ "int2",
48
+ "integer",
49
+ "int",
50
+ "int4",
51
+ "bigint",
52
+ "int8",
53
+ "real",
54
+ "float4",
55
+ "double precision",
56
+ "float8",
57
+ ]);
58
+
59
+ /**
60
+ * Normalises a Drizzle `getSQLType()` string to a bare base type for whitelist comparison: strips
61
+ * array markers and type arguments (`varchar(255)` → `varchar`, `numeric(10, 2)` → `numeric`),
62
+ * collapses whitespace, and lowercases.
63
+ */
64
+ function normalizeBaseType(sqlType: string): string {
65
+ return sqlType
66
+ .replace(/\[\]/g, "")
67
+ .replace(/\(.*\)/g, "")
68
+ .replace(/\s+/g, " ")
69
+ .trim()
70
+ .toLowerCase();
71
+ }
72
+
73
+ function isCopySafe(column: SyncColumnType): boolean {
74
+ return !column.isArray && COPY_SAFE_BASE_TYPES.has(normalizeBaseType(column.sqlType));
75
+ }
76
+
77
+ /**
78
+ * `json_to_recordset` extends the COPY-safe set with arrays, `json`, and `jsonb` — viable now that
79
+ * the latest PGlite round-trips bigint and bigint[] correctly (ADR-0009 decision 3).
80
+ */
81
+ function isJsonSafe(column: SyncColumnType): boolean {
82
+ if (isCopySafe(column)) {
83
+ return true;
84
+ }
85
+ if (column.isArray) {
86
+ return true;
87
+ }
88
+ const base = normalizeBaseType(column.sqlType);
89
+ return base === "json" || base === "jsonb";
90
+ }
91
+
92
+ /**
93
+ * Chooses the bulk-insert strategy for a table from its column types (ADR-0009 decision 3):
94
+ * - every column COPY-safe → `copy`;
95
+ * - else every column COPY-safe ∪ array/json/jsonb → `json`;
96
+ * - else → `insert` (the always-correct floor for anything not positively whitelisted).
97
+ *
98
+ * Pure and total: an empty column list falls to `insert`.
99
+ */
100
+ export function classifyApplyStrategy(columns: readonly SyncColumnType[]): ApplyStrategy {
101
+ if (columns.length === 0) {
102
+ return "insert";
103
+ }
104
+
105
+ let allCopySafe = true;
106
+ let allJsonSafe = true;
107
+
108
+ for (const column of columns) {
109
+ if (!isCopySafe(column)) {
110
+ allCopySafe = false;
111
+ }
112
+ if (!isJsonSafe(column)) {
113
+ allJsonSafe = false;
114
+ }
115
+ }
116
+
117
+ if (allCopySafe) {
118
+ return "copy";
119
+ }
120
+ if (allJsonSafe) {
121
+ return "json";
122
+ }
123
+ return "insert";
124
+ }