@pgxsinkit/contracts 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/config.ts CHANGED
@@ -56,7 +56,7 @@ export function isSubscriptionTiming(value: unknown): value is SubscriptionTimin
56
56
  /**
57
57
  * Retention for a synced table (ADR-0021): **whether** its local copy is durable.
58
58
  *
59
- * - `persistent` (default) — the durable PGlite backend with a resumable subscription-state.
59
+ * - `persistent` (default) — the durable pgwasm backend with a resumable subscription-state.
60
60
  * - `ephemeral` — the table's whole per-table local cluster (read cache, overlay, journal, sequence,
61
61
  * views, reconcile trigger/function) is emitted as `TEMP`, so reads **and** writes leave no durable
62
62
  * trace. Consequence: no durable offline write queue — pair a must-not-lose write with a pessimistic
@@ -137,6 +137,71 @@ export function isStorageDurability(value: unknown): value is StorageDurability
137
137
  return typeof value === "string" && (STORAGE_DURABILITIES as readonly string[]).includes(value);
138
138
  }
139
139
 
140
+ /**
141
+ * The registry-declared store BUILD (ADR-0063): which pgwasm engine build owns the store's data directory.
142
+ * `c` (default) is the C PostgreSQL build; `pgrust` is the Rust one. Like the engine module, it is part of
143
+ * the store's identity — a datadir belongs to the build that wrote it, so a different build is a DIFFERENT
144
+ * store, minted fresh under a fresh path, never a rehome of an existing one.
145
+ *
146
+ * The declaration only NAMES the build. The build itself is always supplied as code at the minting site,
147
+ * never loaded from this string.
148
+ */
149
+ export type StorageBuild = "c" | "pgrust";
150
+
151
+ /** The {@link StorageBuild} values. Source of truth for {@link SyncStorageDeclaration} validation. */
152
+ export const STORAGE_BUILDS = ["c", "pgrust"] as const satisfies readonly StorageBuild[];
153
+
154
+ /** Type guard: is `value` a {@link StorageBuild}? */
155
+ export function isStorageBuild(value: unknown): value is StorageBuild {
156
+ return typeof value === "string" && (STORAGE_BUILDS as readonly string[]).includes(value);
157
+ }
158
+
159
+ /**
160
+ * The declared store ENGINE (ADR-0050 addendum 2026-09-08): the module URL of a store factory that answers
161
+ * for the store instead of the toolkit's own `createPgwasmClient`.
162
+ *
163
+ * `module` is an **absolute or origin-relative module URL** the engine home can `import()`. Its default
164
+ * export — or a named `createStore` — is the toolkit's own `createStore` seam (ADR-0036), unchanged:
165
+ * `(storePath: string, backendOverride?: "memory") => Promise<PgwasmClient>`. The module owns everything
166
+ * this declaration does not carry: its own assets (derivable from `import.meta.url`; there is no asset
167
+ * base and there will not be one), its own storage layout under the store path, and its own environment
168
+ * requirements (a threaded engine that needs a cross-origin-isolated page refuses to construct without
169
+ * one, loudly, from inside the module).
170
+ *
171
+ * Nothing in the toolkit knows, names or imports any particular engine — this field is the whole surface.
172
+ */
173
+ export interface StorageEngineDeclaration {
174
+ module: string;
175
+ }
176
+
177
+ /**
178
+ * Type guard: is `value` a usable {@link StorageEngineDeclaration.module} — a non-blank string that parses
179
+ * as an ABSOLUTE URL (`https://…/factory.js`) or an ORIGIN-RELATIVE one (`/store-engine/factory.js`)?
180
+ *
181
+ * A document-relative specifier (`./factory.js`, `factory.js`) is deliberately rejected: the declaration
182
+ * crosses a bridge into a worker scope whose base URL is the worker chunk's, not the tab's, so a relative
183
+ * URL would resolve differently on either side of the wire. Source of truth for
184
+ * {@link SyncStorageDeclaration} validation.
185
+ */
186
+ export function isStorageEngineModule(value: unknown): value is string {
187
+ if (typeof value !== "string" || value.trim() === "") return false;
188
+ try {
189
+ // The base is only consulted for the origin-relative form; an absolute URL ignores it entirely.
190
+ const url = new URL(value, "https://storage-engine.invalid/");
191
+ return value.startsWith("/") || url.href === new URL(value).href;
192
+ } catch {
193
+ // Not parseable as either form — a hand-typed specifier gone wrong, refused rather than guessed at.
194
+ return false;
195
+ }
196
+ }
197
+
198
+ /** Type guard: is `value` a well-formed {@link StorageEngineDeclaration}? */
199
+ export function isStorageEngineDeclaration(value: unknown): value is StorageEngineDeclaration {
200
+ return (
201
+ typeof value === "object" && value !== null && isStorageEngineModule((value as StorageEngineDeclaration).module)
202
+ );
203
+ }
204
+
140
205
  /**
141
206
  * The registry's storage contract (ADR-0049 decision 1, ADR-0047). Storage is PART OF THE DATA CONTRACT:
142
207
  * whether losing the last not-yet-flushed action is acceptable, and whether OPFS may be used at all, is
@@ -147,20 +212,34 @@ export function isStorageDurability(value: unknown): value is StorageDurability
147
212
  * to contradict it; a capability fallback keeps the declared mode. A no-op on `memory` clones.
148
213
  * - {@link StorageBackend backend} defaults to `"opfs"` and scopes the BROWSER store only; Node/`file` and
149
214
  * `memory` clones are unaffected. `"idbfs"` opts the store out of the capability/election machinery.
215
+ * - {@link StorageBuild build} defaults to `"c"` and names the pgwasm build that owns the store's datadir
216
+ * (ADR-0063). It resolves and binds exactly as `durability` does.
217
+ * - {@link StorageEngineDeclaration engine} defaults to ABSENT — the toolkit's own store. Present, its
218
+ * `module` URL is the store factory that mints this store instead (ADR-0050 addendum 2026-09-08). It is
219
+ * part of the declaration for the same reason the other two are: a store's datadir belongs to the engine
220
+ * that wrote it, so a different `module` is a DIFFERENT store, minted fresh under a fresh path, never a
221
+ * rehome of an existing one.
150
222
  */
151
223
  export interface SyncStorageDeclaration {
152
224
  backend?: StorageBackend;
153
225
  durability?: StorageDurability;
226
+ build?: StorageBuild;
227
+ engine?: StorageEngineDeclaration;
154
228
  }
155
229
 
156
230
  /**
157
231
  * A {@link SyncStorageDeclaration} with every field resolved (ADR-0050) — the store's BOUND declaration.
158
232
  * Produced once per store by {@link resolveStorageDeclaration} and immutable for the store's lifetime: a
159
233
  * preference change mints a fresh store under a fresh path, never rebinds an existing one.
234
+ *
235
+ * `engine` is the one field that stays OPTIONAL after resolution, because the toolkit's own store has no
236
+ * module URL to name: absent IS the resolved value of "the built-in engine".
160
237
  */
161
238
  export interface ResolvedStorageDeclaration {
162
239
  backend: StorageBackend;
163
240
  durability: StorageDurability;
241
+ build: StorageBuild;
242
+ engine?: StorageEngineDeclaration;
164
243
  }
165
244
 
166
245
  /**
@@ -176,6 +255,45 @@ export class StorageDeclarationRefusedError extends Error {
176
255
  }
177
256
  }
178
257
 
258
+ /**
259
+ * Where a store's Postgres build was checked against its declaration (ADR-0063): before a mint by the
260
+ * build a site supplies (`createSyncClient`, `defineSyncWorker`, `createPgwasmClient`), or on an instance a
261
+ * site adopts (`pgwasmInstance`, `precreatedPgwasm`, the result of a worker's `createStore`).
262
+ */
263
+ export type StoreBuildCheckSite =
264
+ | "createSyncClient"
265
+ | "defineSyncWorker"
266
+ | "createPgwasmClient"
267
+ | "pgwasmInstance"
268
+ | "precreatedPgwasm"
269
+ | "createStore";
270
+
271
+ /**
272
+ * The registry declares one Postgres build (`storage.build`, ADR-0063) and the code supplied or adopted
273
+ * another. Thrown before any store is touched. A store's build is code, never a declared string: pass the
274
+ * declared build (e.g. `defineSyncWorker({ build })`, `createSyncClient({ build })`), or fix the declaration.
275
+ * The stable `name` survives bridge serialization (`BridgeErrorWire.name`), and `detail` carries the three
276
+ * fields across it, so a tab can detect the refusal typed.
277
+ */
278
+ export class StorageBuildMismatchError extends Error {
279
+ readonly declared: StorageBuild;
280
+ readonly supplied: string;
281
+ readonly site: StoreBuildCheckSite;
282
+ readonly detail: { readonly declared: StorageBuild; readonly supplied: string; readonly site: StoreBuildCheckSite };
283
+
284
+ constructor(declared: StorageBuild, supplied: string, site: StoreBuildCheckSite) {
285
+ super(
286
+ `storage build mismatch at ${site}: the registry declares the "${declared}" Postgres build but the ` +
287
+ `store's build is "${supplied}" — supply the declared build (a \`build\` option), or fix \`storage.build\``,
288
+ );
289
+ this.name = "StorageBuildMismatchError";
290
+ this.declared = declared;
291
+ this.supplied = supplied;
292
+ this.site = site;
293
+ this.detail = { declared, supplied, site };
294
+ }
295
+ }
296
+
179
297
  /** One field's resolution: explicit-vs-explicit disagreement refuses; otherwise the explicit value, else the default. */
180
298
  function resolveDeclarationField<TValue>(
181
299
  field: keyof SyncStorageDeclaration,
@@ -199,12 +317,21 @@ function resolveDeclarationField<TValue>(
199
317
  * declaration (authoritative) and the tab's WIRE declaration (honoured only where the registry is silent).
200
318
  * Per field: an unset field is "no opinion" and can never conflict; both explicit and disagreeing is a
201
319
  * {@link StorageDeclarationRefusedError}; unresolved fields take the capability defaults
202
- * (`backend: "opfs"`, `durability: "relaxed"`).
320
+ * (`backend: "opfs"`, `durability: "relaxed"`, `build: "c"`, and NO engine module — the toolkit's own store).
321
+ *
322
+ * The `engine` field resolves on its `module` URL, which is the identity that matters: two declarations
323
+ * naming the same module are the same engine, and a disagreement refuses exactly as the other fields do.
203
324
  */
204
325
  export function resolveStorageDeclaration(
205
326
  staticDeclaration: SyncStorageDeclaration | undefined,
206
327
  wireDeclaration: SyncStorageDeclaration | undefined,
207
328
  ): ResolvedStorageDeclaration {
329
+ const engineModule = resolveDeclarationField<string | undefined>(
330
+ "engine",
331
+ staticDeclaration?.engine?.module,
332
+ wireDeclaration?.engine?.module,
333
+ undefined,
334
+ );
208
335
  return {
209
336
  backend: resolveDeclarationField("backend", staticDeclaration?.backend, wireDeclaration?.backend, "opfs"),
210
337
  durability: resolveDeclarationField(
@@ -213,6 +340,8 @@ export function resolveStorageDeclaration(
213
340
  wireDeclaration?.durability,
214
341
  "relaxed",
215
342
  ),
343
+ build: resolveDeclarationField("build", staticDeclaration?.build, wireDeclaration?.build, "c"),
344
+ ...(engineModule === undefined ? {} : { engine: { module: engineModule } }),
216
345
  };
217
346
  }
218
347
 
@@ -220,13 +349,18 @@ export function resolveStorageDeclaration(
220
349
  * Check a LATER declaration against a store's bound resolution (ADR-0050): an unset or equal field is
221
350
  * idempotent; an explicit field disagreeing with the bound value is a {@link StorageDeclarationRefusedError}.
222
351
  * The bound declaration is immutable — first arrival binds, later arrivals only confirm.
352
+ *
353
+ * `engine` is checked on its `module` URL, and only when the incoming declaration names one: an incoming
354
+ * declaration with NO engine is "no opinion" exactly like an unset `backend`, never an assertion that the
355
+ * store is on the built-in engine. (Absence is how the built-in engine is spelled, so it cannot double as
356
+ * an explicit contradiction; a consumer switching back mints a fresh store rather than redeclaring one.)
223
357
  */
224
358
  export function assertStorageDeclarationCompatible(
225
359
  bound: ResolvedStorageDeclaration,
226
360
  incoming: SyncStorageDeclaration | undefined,
227
361
  ): void {
228
362
  if (incoming === undefined) return;
229
- for (const field of ["backend", "durability"] as const) {
363
+ for (const field of ["backend", "durability", "build"] as const) {
230
364
  const value = incoming[field];
231
365
  if (value !== undefined && value !== bound[field]) {
232
366
  throw new StorageDeclarationRefusedError(
@@ -236,6 +370,15 @@ export function assertStorageDeclarationCompatible(
236
370
  );
237
371
  }
238
372
  }
373
+ const incomingEngine = incoming.engine?.module;
374
+ if (incomingEngine !== undefined && incomingEngine !== bound.engine?.module) {
375
+ throw new StorageDeclarationRefusedError(
376
+ `storage declaration disagreement on "engine": the store is bound to ` +
377
+ `${bound.engine === undefined ? "the built-in store engine" : `"${bound.engine.module}"`} but a later ` +
378
+ `declaration says "${incomingEngine}" — a store's declaration is immutable; a store's datadir belongs ` +
379
+ `to the engine that wrote it, so an engine change mints a fresh store under a fresh path`,
380
+ );
381
+ }
239
382
  }
240
383
 
241
384
  /**
@@ -385,24 +528,63 @@ export interface RowTransformContext {
385
528
  * jsonb column, or otherwise rewrite a value, *conditionally on row data*. This expresses
386
529
  * what a static, whole-column `omitColumns` cannot.
387
530
  *
388
- * Server authority only: it never alters the local PGlite schema and never alters the shape
531
+ * Server authority only: it never alters the local pgwasm schema and never alters the shape
389
532
  * definition — the engine ref-counts shapes by definition (ADR-0055), so a transform can
390
533
  * neither change which stream a subject reads nor split one that would otherwise be shared.
391
534
  * Return the same `row` reference to signal "no change".
392
535
  */
393
536
  export type RowTransform = (row: Record<string, unknown>, context: RowTransformContext) => Record<string, unknown>;
394
537
 
538
+ /**
539
+ * One index the LOCAL store should carry on a synced table (see {@link ClientProjectionSpec.localIndexes}).
540
+ * A plain ascending btree over projected columns — deliberately the same expressiveness the local schema
541
+ * generator's shared `CREATE INDEX` core has for the journal indexes, and no more.
542
+ */
543
+ export interface LocalIndexSpec {
544
+ /** The index's name. Unique within the entry, and a plain identifier — it is emitted into DDL. */
545
+ name: string;
546
+ /**
547
+ * The indexed columns, in order. Each names a column of the entry's table by DB column name or by
548
+ * Drizzle property key (the same either/or the primary-key specs accept), and must survive the client
549
+ * projection: naming an `omitColumns` column is a registry error, because the local table has no such
550
+ * column to index.
551
+ */
552
+ columns: readonly string[];
553
+ /**
554
+ * Emit `CREATE UNIQUE INDEX`. Note what that means for a synced cache: uniqueness is the SERVER's
555
+ * guarantee, and a local unique index turns a violation into a failed apply rather than a rejected
556
+ * write. Declare it only where the server constraint genuinely holds for the projected rows.
557
+ */
558
+ unique?: boolean;
559
+ }
560
+
395
561
  export interface ClientProjectionSpec {
396
562
  syncedTable?: string;
397
563
  overlayTable?: string;
398
564
  journalTable?: string;
399
565
  omitColumns?: readonly string[];
400
566
  localPrimaryKey?: PrimaryKeySpec;
567
+ /**
568
+ * OPT-IN local indexes for this entry's synced table (ADR-0029 D3's renderer, consumer-declared).
569
+ *
570
+ * The local store renders a table's PRIMARY KEY and nothing else — a synced table's server-side indexes
571
+ * are NOT mirrored, deliberately: they serve server loads, and half of them cover columns a client
572
+ * projection omits. So a local read path that needs an index has to say so here, and only here.
573
+ *
574
+ * Declare what the CLIENT's queries need, not what the server has: a scan the app runs on every render
575
+ * over a large synced table (the motivating case: a `due_at` window over 100k rows — ~13 ms sequential
576
+ * vs ~0.1 ms indexed on pgwasm, logged by `tests/unit/read-model-overlay-plan`). Each index costs write
577
+ * time on every applied batch and space in the user's store, so an index nothing queries is a straight loss.
578
+ *
579
+ * Rendered on the synced table ONLY — never on the overlay, whose primary key is already its index and
580
+ * whose plan problem is not an index problem (see the read model's non-membership test).
581
+ */
582
+ localIndexes?: readonly LocalIndexSpec[];
401
583
  }
402
584
 
403
585
  /**
404
586
  * Server-side projection applied on the read egress path. This is server
405
- * authority, not client shape — it never alters the local PGlite schema or the
587
+ * authority, not client shape — it never alters the local pgwasm schema or the
406
588
  * shape definition — so it lives apart from {@link ClientProjectionSpec} (ADR-0004).
407
589
  */
408
590
  export interface ServerProjectionSpec {
package/src/projection.ts CHANGED
@@ -43,6 +43,10 @@ export function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgT
43
43
  ...(clientProjection.syncedTable != null ? { syncedTable: clientProjection.syncedTable } : {}),
44
44
  ...(clientProjection.omitColumns != null ? { omitColumns: clientProjection.omitColumns } : {}),
45
45
  ...(clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {}),
46
+ // Read-relevant: a local index serves the CLIENT's reads, and a readonly client reads the same
47
+ // rows through the same columns. Dropping it would leave the projected store scanning where the
48
+ // authoritative one seeks — silently, since nothing else would differ.
49
+ ...(clientProjection.localIndexes != null ? { localIndexes: clientProjection.localIndexes } : {}),
46
50
  }
47
51
  : undefined;
48
52
 
@@ -74,7 +78,7 @@ export function asReadonly<TTable extends AnyPgTable, TLocalTable extends AnyPgT
74
78
 
75
79
  /**
76
80
  * Project an entry onto a different **retention** (ADR-0021) — the per-table local-persistence axis:
77
- * `persistent` (the durable PGlite/OPFS backend) | `ephemeral` (the table's whole local cluster — read
81
+ * `persistent` (the durable pgwasm/OPFS backend) | `ephemeral` (the table's whole local cluster — read
78
82
  * cache, overlay, journal, sequence, views, reconcile function — emitted as `TEMP`/`pg_temp`, leaving no
79
83
  * durable trace). Returns a copy of `entry` with `retention` overridden and **everything else preserved
80
84
  * verbatim** (table, columns, mode, write contract, shape/row filter, the other lifecycle axes).
package/src/registry.ts CHANGED
@@ -30,13 +30,16 @@ import {
30
30
  isConflictPolicy,
31
31
  isRetention,
32
32
  isStorageBackend,
33
+ isStorageBuild,
33
34
  isStorageDurability,
35
+ isStorageEngineDeclaration,
34
36
  isSubscriptionTiming,
35
37
  isWriteMode,
36
38
  assertShapeFilterIsEnforceable,
37
39
  readShapeTier,
38
40
  RETENTIONS,
39
41
  STORAGE_BACKENDS,
42
+ STORAGE_BUILDS,
40
43
  STORAGE_DURABILITIES,
41
44
  SUBSCRIPTION_TIMINGS,
42
45
  WRITE_MODES,
@@ -125,7 +128,7 @@ type SyncTableInputGovernanceMarker<TGovernance> = {
125
128
  export interface SyncTableEntry<TTable extends AnyPgTable = AnyPgTable, TLocalTable extends AnyPgTable = TTable> {
126
129
  table: TTable;
127
130
  /**
128
- * Projected client-side table for PGlite use. Columns listed in
131
+ * Projected client-side table for pgwasm use. Columns listed in
129
132
  * `clientProjection.omitColumns` (e.g. `created_by_id`) are absent from
130
133
  * both the runtime table definition and the TypeScript shape of this table.
131
134
  */
@@ -451,9 +454,11 @@ export interface SyncRegistryDefinition<TRegistry extends SyncTableRegistry> {
451
454
  /**
452
455
  * The storage contract for every store this registry mints (ADR-0049 decision 1, ADR-0047). Part of the
453
456
  * DATA contract, not a per-open knob: `durability` binds every toolkit-minted open (relaxed default),
454
- * and `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones
455
- * unaffected). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried through on
456
- * the returned registry and read back with {@link getSyncRegistryStorage}. See {@link SyncStorageDeclaration}.
457
+ * `backend` scopes the BROWSER store only (`opfs` default; Node/`file` and `memory` clones
458
+ * unaffected), and `engine` names the store-factory module that mints the store at all (absent default —
459
+ * the toolkit's own). Validated at {@link defineSyncRegistry} (fail-closed at module-eval); carried
460
+ * through on the returned registry and read back with {@link getSyncRegistryStorage}. See
461
+ * {@link SyncStorageDeclaration}.
457
462
  */
458
463
  storage?: SyncStorageDeclaration;
459
464
  /**
@@ -924,7 +929,7 @@ export function defineReadProjection<
924
929
  // accepted — `TOwnerTable` (the physical table) is what `columns`/`rowFilter` are typed against.
925
930
  owner: SyncTableEntry<TOwnerTable, TOwnerLocal>,
926
931
  opts: {
927
- /** The projection's distinct local identity — its PGlite table name AND its `shapeKey`. */
932
+ /** The projection's distinct local identity — its pgwasm table name AND its `shapeKey`. */
928
933
  as: TAs;
929
934
  /** Column keys (of the owner) to sync locally + fetch on the shape. The PK is always kept. Omit → all. */
930
935
  columns?: TColumns;
@@ -1177,6 +1182,7 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
1177
1182
  }
1178
1183
  validateRegistryTableUniqueness(input.tables);
1179
1184
  validateRegistryShapeKeyUniqueness(input.tables);
1185
+ validateRegistryLocalIndexNames(input.tables);
1180
1186
  validateRegistryLifecycleGroups(input.tables);
1181
1187
  validateStorageDeclaration(input.storage);
1182
1188
  validateRowClassification(input.tables, input.rowClasses);
@@ -1203,13 +1209,14 @@ export function defineSyncRegistry<const TRegistry extends { [TKey in keyof TReg
1203
1209
  }
1204
1210
  validateRegistryTableUniqueness(input);
1205
1211
  validateRegistryShapeKeyUniqueness(input);
1212
+ validateRegistryLocalIndexNames(input);
1206
1213
  validateRegistryLifecycleGroups(input);
1207
1214
 
1208
1215
  return input;
1209
1216
  }
1210
1217
 
1211
1218
  /** The local/shape identity an entry resolves to: its `shape.tableName` (the unique shape key a client
1212
- * requests and the local PGlite table), falling back to the Drizzle table name when an entry has no
1219
+ * requests and the local pgwasm table), falling back to the Drizzle table name when an entry has no
1213
1220
  * shape (a write-only table). A read projection carries a distinct `shape.tableName` (`as`) even though
1214
1221
  * its `table` is the owner's, so it is identified here by `as`, never by the shared physical table. */
1215
1222
  function localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {
@@ -1218,7 +1225,7 @@ function localShapeIdentity(entry: SyncTableEntry<AnyPgTable>): string {
1218
1225
 
1219
1226
  /**
1220
1227
  * A registry must not declare the same local table twice. Every entry resolves to one local identity
1221
- * ({@link localShapeIdentity}) — the PGlite table a client reads and the `shapeKey` the proxy resolves a
1228
+ * ({@link localShapeIdentity}) — the pgwasm table a client reads and the `shapeKey` the proxy resolves a
1222
1229
  * request by — so two entries sharing it would collide locally (one shadows the other) and make the
1223
1230
  * shape unresolvable. A read PROJECTION over a shared physical table does NOT trip this: it carries a
1224
1231
  * DISTINCT local identity (`as`) and points at the owning table via the derived `shape.physicalTable`,
@@ -1244,11 +1251,37 @@ function validateRegistryTableUniqueness(registry: SyncTableRegistry) {
1244
1251
  }
1245
1252
  }
1246
1253
 
1254
+ /**
1255
+ * A local index NAME is a SCHEMA-level object name, so two entries declaring the same
1256
+ * `clientProjection.localIndexes` name collide across tables — and the collision is SILENT: the generator
1257
+ * emits `CREATE INDEX IF NOT EXISTS`, which matches on the name alone, so the second table simply never
1258
+ * gets its index and the read it was declared for quietly scans. Per-entry uniqueness (checked with the
1259
+ * rest of the declaration in `validateSyncTableEntry`) cannot see that, so it is checked here, once per
1260
+ * registry, at module eval.
1261
+ */
1262
+ function validateRegistryLocalIndexNames(registry: SyncTableRegistry) {
1263
+ const declaredBy = new Map<string, string>();
1264
+
1265
+ for (const [key, entry] of Object.entries(registry)) {
1266
+ for (const index of (entry as SyncTableEntry<AnyPgTable>).clientProjection?.localIndexes ?? []) {
1267
+ const firstKey = declaredBy.get(index.name);
1268
+ if (firstKey !== undefined) {
1269
+ throw new Error(
1270
+ `local index "${index.name}" is declared by two registry entries ("${firstKey}" and "${key}"): ` +
1271
+ `an index name is a schema-level object name, and the generator's CREATE INDEX IF NOT EXISTS ` +
1272
+ `would silently skip the second one. Name each local index after its own table.`,
1273
+ );
1274
+ }
1275
+ declaredBy.set(index.name, key);
1276
+ }
1277
+ }
1278
+ }
1279
+
1247
1280
  /**
1248
1281
  * A registry must not expose the same PUBLIC `shapeKey` twice. This is a DISTINCT identity from the
1249
1282
  * local table checked by {@link validateRegistryTableUniqueness}: `shapeKey` is what a subscription
1250
1283
  * request names on the wire and what the control plane resolves an entry by (`resolveEntryByShapeKey`
1251
- * is first-match), while the local identity is the PGlite table a client reads into. They coincide by
1284
+ * is first-match), while the local identity is the pgwasm table a client reads into. They coincide by
1252
1285
  * default (`shapeKey` falls back to `tableName`), so the local check already covers the common case,
1253
1286
  * and read projections over one physical table stay legal because `as` yields a distinct value for
1254
1287
  * BOTH identities. The only way to collide here is an EXPLICIT `shape.shapeKey` that diverges from the
@@ -1514,11 +1547,15 @@ export function attachSyncRegistryStorage<TRegistry extends SyncTableRegistry>(
1514
1547
  }
1515
1548
  // Idempotent for an EQUAL declaration (a registry value reused across constructions may be re-stamped with
1516
1549
  // the same contract) but fail-closed on a CONFLICT — two different storage contracts over one registry is a
1517
- // definition error, never silently resolved. `backend`/`durability` are the only fields, so a shallow
1518
- // compare is exhaustive.
1550
+ // definition error, never silently resolved. `backend`/`durability`/`engine` are the only fields, and
1551
+ // `engine`'s identity is its module URL, so comparing those three is exhaustive.
1519
1552
  const existing = getSyncRegistryStorage(registry);
1520
1553
  if (existing != null) {
1521
- if (existing.backend !== storage.backend || existing.durability !== storage.durability) {
1554
+ if (
1555
+ existing.backend !== storage.backend ||
1556
+ existing.durability !== storage.durability ||
1557
+ existing.engine?.module !== storage.engine?.module
1558
+ ) {
1522
1559
  throw new Error(
1523
1560
  `conflicting storage declaration for registry: already ${JSON.stringify(existing)}, cannot re-declare ` +
1524
1561
  `${JSON.stringify(storage)}`,
@@ -1812,9 +1849,10 @@ function validateRowClassification(registry: SyncTableRegistry, rowClasses: read
1812
1849
  }
1813
1850
 
1814
1851
  /**
1815
- * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` must
1816
- * be a known value, matching how the other registry axes reject bad input at `defineSyncRegistry`. An absent
1817
- * declaration or absent field is fine — it resolves to the ADR-0047 defaults (`opfs` / `relaxed`).
1852
+ * Fail-closed at module-eval (ADR-0049 decision 1): a declared `storage.backend` / `storage.durability` /
1853
+ * `storage.build` / `storage.engine` must be a known value, matching how the other registry axes reject bad
1854
+ * input at `defineSyncRegistry`. An absent declaration or absent field is fine — it resolves to the
1855
+ * defaults (`opfs` / `relaxed` / `c`) and, for `engine`, to the toolkit's own store.
1818
1856
  */
1819
1857
  function validateStorageDeclaration(storage: SyncStorageDeclaration | undefined) {
1820
1858
  if (storage == null) {
@@ -1830,6 +1868,16 @@ function validateStorageDeclaration(storage: SyncStorageDeclaration | undefined)
1830
1868
  `invalid storage.durability "${String(storage.durability)}": must be one of ${STORAGE_DURABILITIES.join(", ")}`,
1831
1869
  );
1832
1870
  }
1871
+ if (storage.build !== undefined && !isStorageBuild(storage.build)) {
1872
+ throw new Error(`invalid storage.build "${String(storage.build)}": must be one of ${STORAGE_BUILDS.join(", ")}`);
1873
+ }
1874
+ if (storage.engine !== undefined && !isStorageEngineDeclaration(storage.engine)) {
1875
+ throw new Error(
1876
+ `invalid storage.engine ${JSON.stringify(storage.engine)}: must be { module } naming an ABSOLUTE ` +
1877
+ `("https://host/factory.js") or ORIGIN-RELATIVE ("/store-engine/factory.js") module URL the engine ` +
1878
+ `home can import — a document-relative specifier resolves differently in a worker scope`,
1879
+ );
1880
+ }
1833
1881
  }
1834
1882
 
1835
1883
  function isSyncRegistryDefinition<TRegistry extends SyncTableRegistry>(
@@ -2004,6 +2052,8 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
2004
2052
  const omitColumns = entry.clientProjection?.omitColumns ?? [];
2005
2053
  const localPrimaryKeyColumns = entry.clientProjection?.localPrimaryKey?.columns ?? [];
2006
2054
 
2055
+ validateLocalIndexes(entry, tableName, columnsByPropertyKey, columnsByColumnName, omitColumns);
2056
+
2007
2057
  if (omitColumns.length === 0 && localPrimaryKeyColumns.length === 0) {
2008
2058
  return;
2009
2059
  }
@@ -2084,3 +2134,71 @@ function validateSyncTableEntry(entry: SyncTableEntry<AnyPgTable>) {
2084
2134
  );
2085
2135
  }
2086
2136
  }
2137
+
2138
+ /**
2139
+ * Refuse a `clientProjection.localIndexes` declaration the local schema generator could not render
2140
+ * faithfully — at REGISTRY-BUILD time (module eval), never at boot: a store that has already been created
2141
+ * cannot report a typo in a column name in any useful way, and a half-rendered index set is worse than a
2142
+ * refused registry.
2143
+ *
2144
+ * Four refusals, each with the thing the author has to change in the message: an unknown column, a column
2145
+ * the client projection omits (the local table has no such column — the index would target a column that
2146
+ * exists only on the server), a duplicate index name within the entry, and a name that is not a plain
2147
+ * identifier (it is emitted into DDL). An empty column list is refused for the same reason.
2148
+ */
2149
+ function validateLocalIndexes(
2150
+ entry: SyncTableEntry<AnyPgTable>,
2151
+ tableName: string,
2152
+ columnsByPropertyKey: Map<string, { propertyKey: string; columnName: string }>,
2153
+ columnsByColumnName: Map<string, { propertyKey: string; columnName: string }>,
2154
+ omitColumns: readonly string[],
2155
+ ): void {
2156
+ const localIndexes = entry.clientProjection?.localIndexes ?? [];
2157
+ if (localIndexes.length === 0) {
2158
+ return;
2159
+ }
2160
+
2161
+ // Omission is declared by property key; a column may be named either way in an index, so both keys of
2162
+ // an omitted column are refused.
2163
+ const omitted = new Set<string>();
2164
+ for (const propertyKey of omitColumns) {
2165
+ omitted.add(propertyKey);
2166
+ const column = columnsByPropertyKey.get(propertyKey);
2167
+ if (column) omitted.add(column.columnName);
2168
+ }
2169
+
2170
+ const seenNames = new Set<string>();
2171
+ for (const index of localIndexes) {
2172
+ if (typeof index.name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(index.name)) {
2173
+ throw new Error(
2174
+ `clientProjection.localIndexes on ${tableName} declares an invalid index name ${JSON.stringify(index.name)}: ` +
2175
+ `it is emitted into DDL, so it must be a plain identifier ([A-Za-z_][A-Za-z0-9_]*)`,
2176
+ );
2177
+ }
2178
+ if (seenNames.has(index.name)) {
2179
+ throw new Error(
2180
+ `clientProjection.localIndexes on ${tableName} declares the index name "${index.name}" twice: ` +
2181
+ `an index name must be unique (it is a schema-level object name)`,
2182
+ );
2183
+ }
2184
+ seenNames.add(index.name);
2185
+
2186
+ if (index.columns.length === 0) {
2187
+ throw new Error(`clientProjection.localIndexes on ${tableName}: index "${index.name}" declares no columns`);
2188
+ }
2189
+
2190
+ for (const column of index.columns) {
2191
+ if (omitted.has(column)) {
2192
+ throw new Error(
2193
+ `clientProjection.localIndexes on ${tableName}: index "${index.name}" names column "${column}", which ` +
2194
+ `clientProjection.omitColumns removes from the local table — index only projected columns`,
2195
+ );
2196
+ }
2197
+ if (!columnsByPropertyKey.has(column) && !columnsByColumnName.has(column)) {
2198
+ throw new Error(
2199
+ `clientProjection.localIndexes on ${tableName}: index "${index.name}" names unknown column "${column}"`,
2200
+ );
2201
+ }
2202
+ }
2203
+ }
2204
+ }
@@ -2,7 +2,7 @@
2
2
  * The single role-existence guard used by every pgxsinkit-emitted GRANT/REVOKE.
3
3
  *
4
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
5
+ * `anon`/`authenticated`/`service_role` exist), on a plain Postgres, and on a pgwasm test lane
6
6
  * (where none of them do). A bare `REVOKE … FROM anon` is a hard error where the role is absent, so
7
7
  * every role-scoped grant/revoke is wrapped in a `DO $$ … IF EXISTS (SELECT 1 FROM pg_roles …)`
8
8
  * block and simply does nothing there.