@pgxsinkit/contracts 0.2.7 → 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/dist/apply-strategy.d.ts +13 -1
  3. package/dist/apply-strategy.d.ts.map +1 -1
  4. package/dist/config.d.ts +256 -87
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/convergence-model.d.ts +2 -2
  7. package/dist/convergence-model.d.ts.map +1 -1
  8. package/dist/event-stream.d.ts +1 -1
  9. package/dist/fingerprint.d.ts +31 -11
  10. package/dist/fingerprint.d.ts.map +1 -1
  11. package/dist/index.d.ts +2 -0
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +480 -202
  14. package/dist/index.js.map +16 -14
  15. package/dist/predicate.d.ts +162 -0
  16. package/dist/predicate.d.ts.map +1 -0
  17. package/dist/projection.d.ts +2 -2
  18. package/dist/projection.d.ts.map +1 -1
  19. package/dist/registry-diff.d.ts.map +1 -1
  20. package/dist/registry-invariant.d.ts +26 -14
  21. package/dist/registry-invariant.d.ts.map +1 -1
  22. package/dist/registry.d.ts +74 -48
  23. package/dist/registry.d.ts.map +1 -1
  24. package/dist/sql-role-guard.d.ts +1 -1
  25. package/dist/stream-envelope.d.ts +84 -0
  26. package/dist/stream-envelope.d.ts.map +1 -0
  27. package/dist/supabase-rls.d.ts +32 -36
  28. package/dist/supabase-rls.d.ts.map +1 -1
  29. package/package.json +3 -2
  30. package/skills/registry-authoring/SKILL.md +185 -185
  31. package/skills/registry-authoring/references/storage-engine-and-build.md +29 -0
  32. package/src/apply-strategy.ts +23 -4
  33. package/src/config.ts +340 -116
  34. package/src/convergence-model.ts +2 -2
  35. package/src/event-stream.ts +1 -1
  36. package/src/fingerprint.ts +76 -14
  37. package/src/index.ts +2 -0
  38. package/src/predicate.ts +274 -0
  39. package/src/projection.ts +6 -2
  40. package/src/registry-diff.ts +15 -4
  41. package/src/registry-invariant.ts +34 -19
  42. package/src/registry.ts +324 -78
  43. package/src/sql-role-guard.ts +1 -1
  44. package/src/stream-envelope.ts +91 -0
  45. package/src/supabase-rls.ts +76 -74
package/dist/index.js CHANGED
@@ -44,6 +44,13 @@ function isJsonSafe(column) {
44
44
  const base = normalizeBaseType(column.sqlType);
45
45
  return base === "json" || base === "jsonb";
46
46
  }
47
+ function jsonUdtName(column) {
48
+ const base = normalizeBaseType(column.sqlType);
49
+ if (base !== "json" && base !== "jsonb") {
50
+ return;
51
+ }
52
+ return column.isArray ? `_${base}` : base;
53
+ }
47
54
  function classifyApplyStrategy(columns) {
48
55
  if (columns.length === 0) {
49
56
  return "insert";
@@ -70,10 +77,88 @@ function classifyApplyStrategy(columns) {
70
77
  import { z } from "zod";
71
78
  var unixMicrosecondsSchema = z.string().regex(/^[0-9]+$/);
72
79
  // packages/contracts/src/config.ts
73
- import { sql } from "drizzle-orm";
74
- import { PgDialect } from "drizzle-orm/pg-core";
75
80
  import { z as z2 } from "zod";
76
- var pgDialect = new PgDialect;
81
+
82
+ // packages/contracts/src/predicate.ts
83
+ import { getColumnTable, getTableName } from "drizzle-orm";
84
+ function isLeafPredicate(node) {
85
+ return "col" in node && "op" in node;
86
+ }
87
+ function isIsNullPredicate(node) {
88
+ return "col" in node && "isNull" in node;
89
+ }
90
+ function isAndPredicate(node) {
91
+ return "and" in node;
92
+ }
93
+ function isOrPredicate(node) {
94
+ return "or" in node;
95
+ }
96
+ function isNotPredicate(node) {
97
+ return "not" in node;
98
+ }
99
+ function isInSubqueryPredicate(node) {
100
+ return "in" in node && "col" in node;
101
+ }
102
+ function assertPredicateValue(column, value) {
103
+ if (value === null)
104
+ return;
105
+ const kind = typeof value;
106
+ if (kind === "string" || kind === "number" || kind === "boolean")
107
+ return;
108
+ const shown = value instanceof Date ? "Date" : kind === "object" ? "object" : kind;
109
+ throw new Error(`[pgxsinkit] predicate on "${column.name}": ${shown} is not a predicate value \u2014 the wire form ` + `carries JSON scalars (string | number | boolean | null). Render it to the text form the ` + `column itself stores and pass that, rather than relying on a coercion that may not match.`);
110
+ }
111
+ function toWireValue(column, value) {
112
+ if (typeof value !== "bigint") {
113
+ assertPredicateValue(column, value);
114
+ return value;
115
+ }
116
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
117
+ throw new Error(`[pgxsinkit] predicate on "${column.name}": ${value}n is outside the exactly-representable ` + `integer range, so serializing it would silently round to a different value. Compare against ` + `a value inside the safe-integer range, or split the test.`);
118
+ }
119
+ return Number(value);
120
+ }
121
+ function leaf(column, op, value) {
122
+ return { col: column.name, op, value: toWireValue(column, value) };
123
+ }
124
+ var p = {
125
+ eq: (column, value) => leaf(column, "eq", value),
126
+ ne: (column, value) => leaf(column, "neq", value),
127
+ lt: (column, value) => leaf(column, "lt", value),
128
+ lte: (column, value) => leaf(column, "lte", value),
129
+ gt: (column, value) => leaf(column, "gt", value),
130
+ gte: (column, value) => leaf(column, "gte", value),
131
+ like: (column, pattern) => leaf(column, "like", pattern),
132
+ notLike: (column, pattern) => ({
133
+ not: leaf(column, "like", pattern)
134
+ }),
135
+ isNull: (column) => ({ col: column.name, isNull: true }),
136
+ isNotNull: (column) => ({ col: column.name, isNull: false }),
137
+ and: (...nodes) => ({ and: nodes }),
138
+ or: (...nodes) => ({ or: nodes }),
139
+ not: (node) => ({ not: node }),
140
+ subquery: (projected, where) => ({
141
+ table: getTableName(getColumnTable(projected)),
142
+ project: projected.name,
143
+ ...where !== undefined ? { where } : {}
144
+ }),
145
+ in: (column, ref) => ({ col: column.name, in: ref }),
146
+ notIn: (column, ref) => ({
147
+ col: column.name,
148
+ in: ref,
149
+ negated: true
150
+ })
151
+ };
152
+ function conjoinPredicates(...nodes) {
153
+ const present = nodes.filter((node) => node !== undefined);
154
+ if (present.length === 0)
155
+ return;
156
+ if (present.length === 1)
157
+ return present[0];
158
+ return { and: present };
159
+ }
160
+
161
+ // packages/contracts/src/config.ts
77
162
  var CONFLICT_POLICIES = ["last-write-wins", "reject-if-stale"];
78
163
  function isConflictPolicy(value) {
79
164
  return typeof value === "string" && CONFLICT_POLICIES.includes(value);
@@ -98,6 +183,23 @@ var STORAGE_DURABILITIES = ["relaxed", "strict"];
98
183
  function isStorageDurability(value) {
99
184
  return typeof value === "string" && STORAGE_DURABILITIES.includes(value);
100
185
  }
186
+ var STORAGE_BUILDS = ["c", "pgrust"];
187
+ function isStorageBuild(value) {
188
+ return typeof value === "string" && STORAGE_BUILDS.includes(value);
189
+ }
190
+ function isStorageEngineModule(value) {
191
+ if (typeof value !== "string" || value.trim() === "")
192
+ return false;
193
+ try {
194
+ const url = new URL(value, "https://storage-engine.invalid/");
195
+ return value.startsWith("/") || url.href === new URL(value).href;
196
+ } catch {
197
+ return false;
198
+ }
199
+ }
200
+ function isStorageEngineDeclaration(value) {
201
+ return typeof value === "object" && value !== null && isStorageEngineModule(value.module);
202
+ }
101
203
 
102
204
  class StorageDeclarationRefusedError extends Error {
103
205
  constructor(message) {
@@ -105,6 +207,21 @@ class StorageDeclarationRefusedError extends Error {
105
207
  this.name = "StorageDeclarationRefusedError";
106
208
  }
107
209
  }
210
+
211
+ class StorageBuildMismatchError extends Error {
212
+ declared;
213
+ supplied;
214
+ site;
215
+ detail;
216
+ constructor(declared, supplied, site) {
217
+ super(`storage build mismatch at ${site}: the registry declares the "${declared}" Postgres build but the ` + `store's build is "${supplied}" \u2014 supply the declared build (a \`build\` option), or fix \`storage.build\``);
218
+ this.name = "StorageBuildMismatchError";
219
+ this.declared = declared;
220
+ this.supplied = supplied;
221
+ this.site = site;
222
+ this.detail = { declared, supplied, site };
223
+ }
224
+ }
108
225
  function resolveDeclarationField(field, staticValue, wireValue, defaultValue) {
109
226
  if (staticValue !== undefined && wireValue !== undefined && staticValue !== wireValue) {
110
227
  throw new StorageDeclarationRefusedError(`storage declaration disagreement on "${field}": the registry-attached declaration says ` + `"${String(staticValue)}" but the wire declaration says "${String(wireValue)}" \u2014 a store's storage ` + `contract has one value per field; fix the declaring side (a preference change mints a fresh store, ` + `it never redeclares an existing one)`);
@@ -112,20 +229,27 @@ function resolveDeclarationField(field, staticValue, wireValue, defaultValue) {
112
229
  return staticValue ?? wireValue ?? defaultValue;
113
230
  }
114
231
  function resolveStorageDeclaration(staticDeclaration, wireDeclaration) {
232
+ const engineModule = resolveDeclarationField("engine", staticDeclaration?.engine?.module, wireDeclaration?.engine?.module, undefined);
115
233
  return {
116
234
  backend: resolveDeclarationField("backend", staticDeclaration?.backend, wireDeclaration?.backend, "opfs"),
117
- durability: resolveDeclarationField("durability", staticDeclaration?.durability, wireDeclaration?.durability, "relaxed")
235
+ durability: resolveDeclarationField("durability", staticDeclaration?.durability, wireDeclaration?.durability, "relaxed"),
236
+ build: resolveDeclarationField("build", staticDeclaration?.build, wireDeclaration?.build, "c"),
237
+ ...engineModule === undefined ? {} : { engine: { module: engineModule } }
118
238
  };
119
239
  }
120
240
  function assertStorageDeclarationCompatible(bound, incoming) {
121
241
  if (incoming === undefined)
122
242
  return;
123
- for (const field of ["backend", "durability"]) {
243
+ for (const field of ["backend", "durability", "build"]) {
124
244
  const value = incoming[field];
125
245
  if (value !== undefined && value !== bound[field]) {
126
246
  throw new StorageDeclarationRefusedError(`storage declaration disagreement on "${field}": the store is bound to "${bound[field]}" but a later ` + `declaration says "${value}" \u2014 a store's declaration is immutable; a preference change mints a ` + `fresh store under a fresh path`);
127
247
  }
128
248
  }
249
+ const incomingEngine = incoming.engine?.module;
250
+ if (incomingEngine !== undefined && incomingEngine !== bound.engine?.module) {
251
+ throw new StorageDeclarationRefusedError(`storage declaration disagreement on "engine": the store is bound to ` + `${bound.engine === undefined ? "the built-in store engine" : `"${bound.engine.module}"`} but a later ` + `declaration says "${incomingEngine}" \u2014 a store's declaration is immutable; a store's datadir belongs ` + `to the engine that wrote it, so an engine change mints a fresh store under a fresh path`);
252
+ }
129
253
  }
130
254
  var jwtClaimsSchema = z2.looseObject({
131
255
  sub: z2.string().optional(),
@@ -133,39 +257,39 @@ var jwtClaimsSchema = z2.looseObject({
133
257
  roles: z2.array(z2.string()).optional()
134
258
  }).optional()
135
259
  });
260
+ function readShapeTier(shape) {
261
+ if (shape.scope != null && shape.rowFilter != null) {
262
+ throw new Error(`[pgxsinkit] shape "${shape.shapeKey}" declares both scope and rowFilter \u2014 a shape is shared ` + `(scope: the predicate is a function of scope values only) or private (rowFilter: the subject ` + `is fused into the predicate), never both. A rowFilter makes the stream's bytes ` + `subject-dependent, so it cannot be served from a scope-keyed shared stream. Move the ` + `subject-dependent part into the entitlement rule, or drop scope and keep this private.`);
263
+ }
264
+ return shape.scope != null ? "shared" : "private";
265
+ }
266
+ function assertShapeFilterIsEnforceable(shape) {
267
+ const filter = shape.rowFilter;
268
+ if (filter == null || filter.customPredicate != null)
269
+ return;
270
+ if (filter.columns == null) {
271
+ throw new Error(`[pgxsinkit] shape "${shape.shapeKey}" declares a rowFilter that restricts nothing \u2014 no ` + `customPredicate and no column allow-list. Declare customPredicate, or drop the rowFilter if ` + `the rows really are for everyone (an absent rowFilter is how a shape says so).`);
272
+ }
273
+ }
136
274
  function getLocalSyncPrimaryKey(source) {
137
275
  return source.clientProjection?.localPrimaryKey ?? source.primaryKey;
138
276
  }
139
277
  function getLocalSyncPrimaryKeyColumns(source) {
140
278
  return [...getLocalSyncPrimaryKey(source).columns];
141
279
  }
142
- function c(column) {
143
- return sql`${sql.identifier(column.name)}`;
144
- }
145
- var DENY_ALL = sql`false`;
280
+ var DENY_ALL_PREDICATE = Object.freeze({ or: [] });
146
281
  function isClaimsDependentRowFilter(filter) {
147
- if (!filter?.customWhere) {
282
+ if (!filter?.customPredicate) {
148
283
  return false;
149
284
  }
150
285
  try {
151
- return filter.customWhere({}, undefined) === DENY_ALL;
286
+ return filter.customPredicate({}, undefined) === DENY_ALL_PREDICATE;
152
287
  } catch {
153
288
  return true;
154
289
  }
155
290
  }
156
- function buildOwnershipShapeWhere(ownerColumn, subject) {
157
- return subject == null || subject === "" ? DENY_ALL : sql`${c(ownerColumn)} = ${subject}`;
158
- }
159
- function buildRowFilterShape(filter, claims, params) {
160
- const custom = filter.customWhere?.(claims ?? {}, params);
161
- if (custom == null) {
162
- return null;
163
- }
164
- if (typeof custom === "string") {
165
- return custom ? { where: custom, params: [] } : null;
166
- }
167
- const compiled = pgDialect.sqlToQuery(custom);
168
- return { where: compiled.sql, params: compiled.params.map((value) => String(value)) };
291
+ function buildOwnershipShapePredicate(ownerColumn, subject) {
292
+ return subject == null || subject === "" ? DENY_ALL_PREDICATE : p.eq(ownerColumn, subject);
169
293
  }
170
294
  // packages/contracts/src/convergence-model.ts
171
295
  import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
@@ -268,14 +392,15 @@ function defineSyncTable(input) {
268
392
  const primaryKeyConstraintName = customPrimaryKeyName ?? `${tableName}_pkey`;
269
393
  const probeColumns = getColumns(pgTable(tableName, makeColumns()));
270
394
  const columnLevelPkKeys = Object.entries(probeColumns).filter(([, col]) => col.primary === true).map(([key]) => key);
271
- const specPropertyKeys = primaryKeyColumns.map((key) => {
395
+ const toPropertyKey = (key, label) => {
272
396
  if (probeColumns[key])
273
397
  return key;
274
398
  const byColumnName = Object.entries(probeColumns).find(([, col]) => col.name === key);
275
399
  if (byColumnName)
276
400
  return byColumnName[0];
277
- throw new Error(`[pgxsinkit] ${tableName}: primaryKey column "${key}" not found among the table's columns`);
278
- });
401
+ throw new Error(`[pgxsinkit] ${tableName}: ${label} column "${key}" not found among the table's columns`);
402
+ };
403
+ const specPropertyKeys = primaryKeyColumns.map((key) => toPropertyKey(key, "primaryKey"));
279
404
  if (columnLevelPkKeys.length > 1) {
280
405
  throw new Error(`[pgxsinkit] ${tableName}: multiple columns declare .primaryKey() (${columnLevelPkKeys.join(", ")}) \u2014 declare a composite key via the primaryKey option ({ name?, columns }) and remove the column-level .primaryKey() flags; the spec is the single source of truth`);
281
406
  }
@@ -311,15 +436,31 @@ function defineSyncTable(input) {
311
436
  return [...consumerExtras, pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];
312
437
  } : undefined;
313
438
  const table = schema ? schema.table(tableName, makeColumns(), extrasFn) : pgTable(tableName, makeColumns(), extrasFn);
314
- const resolvedRowFilter = shape?.rowFilter?.(getColumns(table));
439
+ const shapeColumns = getColumns(table);
440
+ const resolvedRowFilter = shape?.rowFilter?.(shapeColumns);
441
+ const resolvedScope = shape?.scope?.(shapeColumns).map((column) => column.name);
442
+ const resolvedWhere = shape?.where?.(shapeColumns);
315
443
  const resolvedShape = resolvedMode !== "writeonly" || shape != null ? {
316
444
  tableName: shape?.tableName ?? tableName,
317
445
  shapeKey: shape?.shapeKey ?? shape?.tableName ?? tableName,
318
- ...resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {}
446
+ ...resolvedRowFilter != null ? { rowFilter: resolvedRowFilter } : {},
447
+ ...resolvedScope != null ? { scope: resolvedScope } : {},
448
+ ...resolvedWhere != null ? { where: resolvedWhere } : {}
319
449
  } : undefined;
450
+ if (resolvedShape != null) {
451
+ readShapeTier(resolvedShape);
452
+ assertShapeFilterIsEnforceable(resolvedShape);
453
+ }
320
454
  const omittedColumns = clientProjection?.omitColumns ?? [];
321
455
  const projectedCols = viewColumnsForProjection(makeColumns(), omittedColumns);
322
- const localTable = schema ? schema.table(tableName, projectedCols) : pgTable(tableName, projectedCols);
456
+ const localPkPropertyKeys = (clientProjection?.localPrimaryKey?.columns ?? primaryKeyColumns).map((key) => toPropertyKey(key, "localPrimaryKey"));
457
+ const localPkIsColumnLevel = localPkPropertyKeys.length === 1 && probeColumns[localPkPropertyKeys[0]]?.primary === true;
458
+ const localExtrasFn = localPkIsColumnLevel ? undefined : (self) => {
459
+ const selfCols = self;
460
+ const pkColumns = localPkPropertyKeys.map((k) => selfCols[k]);
461
+ return [pgPrimaryKey({ name: primaryKeyConstraintName, columns: pkColumns })];
462
+ };
463
+ const localTable = schema ? schema.table(tableName, projectedCols, localExtrasFn) : pgTable(tableName, projectedCols, localExtrasFn);
323
464
  const viewColumns = viewColumnsForProjection(makeColumns(), omittedColumns);
324
465
  const view = resolvedMode === "readwrite" ? pgView(`${tableName}_read_model`, {
325
466
  ...viewColumns,
@@ -379,7 +520,7 @@ function defineReadProjection(owner, opts) {
379
520
  const clientKept = new Set([...opts.columns, ...pkKeys]);
380
521
  for (const key of serverOnlyColumns) {
381
522
  if (!allKeys.includes(key)) {
382
- throw new Error(`defineReadProjection: projection "${opts.as}" serverOnlyColumns names "${key}", which is not a ` + `column of owner "${physicalTable}". It feeds the Electric fetch allow-list, so a typo would ` + `silently mis-fetch \u2014 name an existing owner column key.`);
523
+ throw new Error(`defineReadProjection: projection "${opts.as}" serverOnlyColumns names "${key}", which is not a ` + `column of owner "${physicalTable}". It feeds the shape's "columns" allow-list, so a typo would ` + `silently mis-fetch \u2014 name an existing owner column key.`);
383
524
  }
384
525
  if (clientKept.has(key)) {
385
526
  throw new Error(`defineReadProjection: projection "${opts.as}" lists "${key}" in BOTH serverOnlyColumns and the ` + `client shape (columns or primary key) \u2014 it is already fetched and kept client-side, so ` + `declaring it server-only is contradictory. Remove it from serverOnlyColumns.`);
@@ -407,9 +548,10 @@ function defineReadProjection(owner, opts) {
407
548
  const shape = {
408
549
  tableName: opts.as,
409
550
  shapeKey: opts.as,
410
- electricTable: physicalTable,
551
+ physicalTable,
411
552
  ...rowFilter != null ? { rowFilter } : {}
412
553
  };
554
+ assertShapeFilterIsEnforceable(shape);
413
555
  const rowClass = opts.rowClass ?? owner.rowClass;
414
556
  const projection = {
415
557
  ...built,
@@ -427,6 +569,8 @@ function defineSyncRegistry(input) {
427
569
  validateSyncTableEntry(entry);
428
570
  }
429
571
  validateRegistryTableUniqueness(input.tables);
572
+ validateRegistryShapeKeyUniqueness(input.tables);
573
+ validateRegistryLocalIndexNames(input.tables);
430
574
  validateRegistryLifecycleGroups(input.tables);
431
575
  validateStorageDeclaration(input.storage);
432
576
  validateRowClassification(input.tables, input.rowClasses);
@@ -437,6 +581,8 @@ function defineSyncRegistry(input) {
437
581
  validateSyncTableEntry(entry);
438
582
  }
439
583
  validateRegistryTableUniqueness(input);
584
+ validateRegistryShapeKeyUniqueness(input);
585
+ validateRegistryLocalIndexNames(input);
440
586
  validateRegistryLifecycleGroups(input);
441
587
  return input;
442
588
  }
@@ -454,6 +600,31 @@ function validateRegistryTableUniqueness(registry) {
454
600
  declaredBy.set(identity, key);
455
601
  }
456
602
  }
603
+ function validateRegistryLocalIndexNames(registry) {
604
+ const declaredBy = new Map;
605
+ for (const [key, entry] of Object.entries(registry)) {
606
+ for (const index of entry.clientProjection?.localIndexes ?? []) {
607
+ const firstKey = declaredBy.get(index.name);
608
+ if (firstKey !== undefined) {
609
+ throw new Error(`local index "${index.name}" is declared by two registry entries ("${firstKey}" and "${key}"): ` + `an index name is a schema-level object name, and the generator's CREATE INDEX IF NOT EXISTS ` + `would silently skip the second one. Name each local index after its own table.`);
610
+ }
611
+ declaredBy.set(index.name, key);
612
+ }
613
+ }
614
+ }
615
+ function validateRegistryShapeKeyUniqueness(registry) {
616
+ const declaredBy = new Map;
617
+ for (const [key, entry] of Object.entries(registry)) {
618
+ const shape = entry.shape;
619
+ if (shape === undefined)
620
+ continue;
621
+ const firstKey = declaredBy.get(shape.shapeKey);
622
+ if (firstKey !== undefined) {
623
+ throw new Error(`shapeKey "${shape.shapeKey}" is declared by two registry entries ("${firstKey}" and "${key}"): ` + `a duplicate shapeKey makes the second entry unreachable \u2014 the control plane resolves a ` + `subscription by shapeKey and would serve the first entry's shape. Give each entry a unique ` + `shape.shapeKey, or use defineReadProjection (a distinct "as") for a second shape over one table.`);
624
+ }
625
+ declaredBy.set(shape.shapeKey, key);
626
+ }
627
+ }
457
628
  function validateRegistryLifecycleGroups(registry) {
458
629
  const groups = new Map;
459
630
  for (const entry of getRegistryEntries(registry)) {
@@ -569,7 +740,7 @@ function attachSyncRegistrySchema(registry, schema) {
569
740
  const qualifiedTableName = `${normalizedSchema}.${entry.shape.tableName}`;
570
741
  entry.shape = {
571
742
  ...entry.shape,
572
- electricTable: entry.shape.electricTable ? qualify(entry.shape.electricTable) : qualifiedTableName,
743
+ physicalTable: entry.shape.physicalTable ? qualify(entry.shape.physicalTable) : qualifiedTableName,
573
744
  ...entry.shape.shapeKey === entry.shape.tableName ? { shapeKey: qualifiedTableName } : {}
574
745
  };
575
746
  }
@@ -591,7 +762,7 @@ function attachSyncRegistryStorage(registry, storage) {
591
762
  }
592
763
  const existing = getSyncRegistryStorage(registry);
593
764
  if (existing != null) {
594
- if (existing.backend !== storage.backend || existing.durability !== storage.durability) {
765
+ if (existing.backend !== storage.backend || existing.durability !== storage.durability || existing.engine?.module !== storage.engine?.module) {
595
766
  throw new Error(`conflicting storage declaration for registry: already ${JSON.stringify(existing)}, cannot re-declare ` + `${JSON.stringify(storage)}`);
596
767
  }
597
768
  return registry;
@@ -756,6 +927,12 @@ function validateStorageDeclaration(storage) {
756
927
  if (storage.durability !== undefined && !isStorageDurability(storage.durability)) {
757
928
  throw new Error(`invalid storage.durability "${String(storage.durability)}": must be one of ${STORAGE_DURABILITIES.join(", ")}`);
758
929
  }
930
+ if (storage.build !== undefined && !isStorageBuild(storage.build)) {
931
+ throw new Error(`invalid storage.build "${String(storage.build)}": must be one of ${STORAGE_BUILDS.join(", ")}`);
932
+ }
933
+ if (storage.engine !== undefined && !isStorageEngineDeclaration(storage.engine)) {
934
+ throw new Error(`invalid storage.engine ${JSON.stringify(storage.engine)}: must be { module } naming an ABSOLUTE ` + `("https://host/factory.js") or ORIGIN-RELATIVE ("/store-engine/factory.js") module URL the engine ` + `home can import \u2014 a document-relative specifier resolves differently in a worker scope`);
935
+ }
759
936
  }
760
937
  function isSyncRegistryDefinition(input) {
761
938
  return typeof input === "object" && input !== null && "tables" in input && typeof input.tables === "object" && input.tables !== null;
@@ -772,6 +949,9 @@ function validateSyncTableEntry(entry) {
772
949
  if (typeof entry.makeColumns !== "function") {
773
950
  throw new Error(`sync table ${tableName} has no makeColumns factory: every registered entry must be built by ` + `defineSyncTable (or a projection of one \u2014 asReadonly / asEphemeral / defineReadProjection), which ` + `stashes the column-builder factory the client requires (ADR-0029 P1) to derive its local ` + `synced/overlay/journal objects. Hand-assembled entries are unsupported.`);
774
951
  }
952
+ if (entry.serverProjection?.rowTransform != null && entry.shape?.scope != null) {
953
+ throw new Error(`[pgxsinkit] shape "${entry.shape.shapeKey}" declares both scope and a serverProjection.rowTransform ` + `\u2014 an egress transform rewrites the stream's bytes per request with the reader's subject, so the ` + `shape is private-tier by construction (ADR-0055 decision 5) and cannot be served from a ` + `scope-keyed shared stream. Drop the transform and pre-compute the redaction into a column the ` + `shape projects, or drop scope and keep this shape private.`);
954
+ }
775
955
  if (entry.mode !== "readonly" && resolveServerVersionColumnName(entry) === undefined) {
776
956
  throw new Error(`writable table ${tableName} must declare a Server version: a managed field with strategy ` + `"nowMicroseconds" and applyOn including "update" (conventionally updated_at_us) \u2014 ADR-0010`);
777
957
  }
@@ -820,6 +1000,7 @@ function validateSyncTableEntry(entry) {
820
1000
  const columnsByColumnName = new Map(columns.map((column) => [column.columnName, column]));
821
1001
  const omitColumns = entry.clientProjection?.omitColumns ?? [];
822
1002
  const localPrimaryKeyColumns = entry.clientProjection?.localPrimaryKey?.columns ?? [];
1003
+ validateLocalIndexes(entry, tableName, columnsByPropertyKey, columnsByColumnName, omitColumns);
823
1004
  if (omitColumns.length === 0 && localPrimaryKeyColumns.length === 0) {
824
1005
  return;
825
1006
  }
@@ -864,6 +1045,40 @@ function validateSyncTableEntry(entry) {
864
1045
  throw new Error(`clientProjection.omitColumns must only omit create-safe columns for writable table ${tableName}: ${createRequiredOmissions.join(", ")}`);
865
1046
  }
866
1047
  }
1048
+ function validateLocalIndexes(entry, tableName, columnsByPropertyKey, columnsByColumnName, omitColumns) {
1049
+ const localIndexes = entry.clientProjection?.localIndexes ?? [];
1050
+ if (localIndexes.length === 0) {
1051
+ return;
1052
+ }
1053
+ const omitted = new Set;
1054
+ for (const propertyKey of omitColumns) {
1055
+ omitted.add(propertyKey);
1056
+ const column = columnsByPropertyKey.get(propertyKey);
1057
+ if (column)
1058
+ omitted.add(column.columnName);
1059
+ }
1060
+ const seenNames = new Set;
1061
+ for (const index of localIndexes) {
1062
+ if (typeof index.name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(index.name)) {
1063
+ throw new Error(`clientProjection.localIndexes on ${tableName} declares an invalid index name ${JSON.stringify(index.name)}: ` + `it is emitted into DDL, so it must be a plain identifier ([A-Za-z_][A-Za-z0-9_]*)`);
1064
+ }
1065
+ if (seenNames.has(index.name)) {
1066
+ throw new Error(`clientProjection.localIndexes on ${tableName} declares the index name "${index.name}" twice: ` + `an index name must be unique (it is a schema-level object name)`);
1067
+ }
1068
+ seenNames.add(index.name);
1069
+ if (index.columns.length === 0) {
1070
+ throw new Error(`clientProjection.localIndexes on ${tableName}: index "${index.name}" declares no columns`);
1071
+ }
1072
+ for (const column of index.columns) {
1073
+ if (omitted.has(column)) {
1074
+ throw new Error(`clientProjection.localIndexes on ${tableName}: index "${index.name}" names column "${column}", which ` + `clientProjection.omitColumns removes from the local table \u2014 index only projected columns`);
1075
+ }
1076
+ if (!columnsByPropertyKey.has(column) && !columnsByColumnName.has(column)) {
1077
+ throw new Error(`clientProjection.localIndexes on ${tableName}: index "${index.name}" names unknown column "${column}"`);
1078
+ }
1079
+ }
1080
+ }
1081
+ }
867
1082
 
868
1083
  // packages/contracts/src/sql-identifier.ts
869
1084
  var RESERVED_SQL_KEYWORDS = new Set([
@@ -1037,11 +1252,11 @@ var CONVERGENCE_EVENTS = [
1037
1252
  effect: "journal row \u2192 acked, server_updated_at_us stamped; entity shows acked_unobserved until the echo catches up"
1038
1253
  },
1039
1254
  {
1040
- event: "Electric insert/update observed",
1255
+ event: "synced upsert observed",
1041
1256
  effect: "synced row applied; the barrier predicate runs; resolved entities clear overlay + acked journal"
1042
1257
  },
1043
1258
  {
1044
- event: "Electric delete observed",
1259
+ event: "synced delete observed",
1045
1260
  effect: "resolved by synced-row absence (deletes carry no Server version \u2014 ADR-0010)"
1046
1261
  },
1047
1262
  { event: "resolution", effect: "clear overlay/journal only through the shared barrier predicate (decision 4)" },
@@ -1114,12 +1329,39 @@ function canonicalizeManagedFields(entry) {
1114
1329
  return { field: name, strategy, applyOn };
1115
1330
  }).sort((a, b) => asString(a.field, b.field));
1116
1331
  }
1332
+ function canonicalizePredicate(node) {
1333
+ if (node === undefined)
1334
+ return null;
1335
+ const render = (current) => {
1336
+ if (isAndPredicate(current))
1337
+ return { and: current.and.map(render) };
1338
+ if (isOrPredicate(current))
1339
+ return { or: current.or.map(render) };
1340
+ if (isNotPredicate(current))
1341
+ return { not: render(current.not) };
1342
+ if (isInSubqueryPredicate(current)) {
1343
+ return {
1344
+ col: current.col,
1345
+ in: {
1346
+ table: current.in.table,
1347
+ project: current.in.project,
1348
+ where: current.in.where ? render(current.in.where) : null
1349
+ },
1350
+ negated: current.negated === true
1351
+ };
1352
+ }
1353
+ if (isIsNullPredicate(current))
1354
+ return { col: current.col, isNull: current.isNull };
1355
+ return { col: current.col, op: current.op, value: current.value };
1356
+ };
1357
+ return JSON.stringify(render(node));
1358
+ }
1117
1359
  function canonicalizeRowFilter(filter) {
1118
1360
  if (!filter) {
1119
1361
  return null;
1120
1362
  }
1121
1363
  return {
1122
- hasCustomWhere: filter.customWhere != null,
1364
+ hasCustomPredicate: filter.customPredicate != null,
1123
1365
  columns: filter.columns ? [...filter.columns].sort(asString) : null,
1124
1366
  revision: filter.revision != null ? String(filter.revision) : null
1125
1367
  };
@@ -1134,8 +1376,10 @@ function canonicalizeTable(key, entry) {
1134
1376
  const shape = entry.shape ? {
1135
1377
  tableName: entry.shape.tableName,
1136
1378
  shapeKey: entry.shape.shapeKey,
1137
- electricTable: entry.shape.electricTable ?? null,
1138
- rowFilter: canonicalizeRowFilter(entry.shape.rowFilter)
1379
+ physicalTable: entry.shape.physicalTable ?? null,
1380
+ rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
1381
+ scope: entry.shape.scope ? [...entry.shape.scope] : null,
1382
+ where: canonicalizePredicate(entry.shape.where)
1139
1383
  } : null;
1140
1384
  return {
1141
1385
  key,
@@ -1169,8 +1413,10 @@ function canonicalizeReadContract(entry) {
1169
1413
  const shape = entry.shape ? {
1170
1414
  tableName: entry.shape.tableName,
1171
1415
  shapeKey: entry.shape.shapeKey,
1172
- electricTable: entry.shape.electricTable ?? null,
1173
- rowFilter: canonicalizeRowFilter(entry.shape.rowFilter)
1416
+ physicalTable: entry.shape.physicalTable ?? null,
1417
+ rowFilter: canonicalizeRowFilter(entry.shape.rowFilter),
1418
+ scope: entry.shape.scope ? [...entry.shape.scope] : null,
1419
+ where: canonicalizePredicate(entry.shape.where)
1174
1420
  } : null;
1175
1421
  return {
1176
1422
  syncedTable: entry.clientProjection?.syncedTable ?? getTableConfig3(entry.table).name,
@@ -1326,13 +1572,19 @@ function diffProjection(table, previous, next, changes) {
1326
1572
  }
1327
1573
  }
1328
1574
  function diffShape(table, previous, next, changes) {
1329
- const target = (shape) => shape ? `${shape.tableName}|${shape.shapeKey}|${shape.electricTable ?? ""}` : null;
1575
+ const target = (shape) => shape ? `${shape.tableName}|${shape.shapeKey}|${shape.physicalTable ?? ""}` : null;
1330
1576
  if (target(previous) !== target(next)) {
1331
1577
  changes.push({ severity: "risky", table, detail: "shape target changed (re-sync required)" });
1332
1578
  }
1333
1579
  if (JSON.stringify(previous?.rowFilter ?? null) !== JSON.stringify(next?.rowFilter ?? null)) {
1334
1580
  changes.push({ severity: "risky", table, detail: "row filter changed (re-sync required)" });
1335
1581
  }
1582
+ if (JSON.stringify(previous?.scope ?? null) !== JSON.stringify(next?.scope ?? null)) {
1583
+ changes.push({ severity: "risky", table, detail: "shape scope changed (re-sync required)" });
1584
+ }
1585
+ if ((previous?.where ?? null) !== (next?.where ?? null)) {
1586
+ changes.push({ severity: "risky", table, detail: "shape predicate changed (re-sync required)" });
1587
+ }
1336
1588
  }
1337
1589
  function diffRowClass(table, previous, next, changes) {
1338
1590
  if (previous === next) {
@@ -1422,8 +1674,13 @@ function summarizeRegistryDiff(diff) {
1422
1674
  `);
1423
1675
  }
1424
1676
  // packages/contracts/src/registry-invariant.ts
1425
- import { getTableConfig as getTableConfig4, PgDialect as PgDialect2 } from "drizzle-orm/pg-core";
1426
- var policyDialect = new PgDialect2;
1677
+ import { getTableConfig as getTableConfig4, PgDialect } from "drizzle-orm/pg-core";
1678
+ function deniesAllRows(predicate) {
1679
+ if (predicate === DENY_ALL_PREDICATE)
1680
+ return true;
1681
+ return predicate != null && isOrPredicate(predicate) && predicate.or.length === 0;
1682
+ }
1683
+ var policyDialect = new PgDialect;
1427
1684
  function renderPolicyPredicate(fragment) {
1428
1685
  return fragment == null ? null : policyDialect.sqlToQuery(fragment.inlineParams()).sql;
1429
1686
  }
@@ -1435,9 +1692,8 @@ function renderPolicies(entry) {
1435
1692
  withCheck: renderPolicyPredicate(policy.withCheck)
1436
1693
  }));
1437
1694
  }
1438
- function renderWhere(entry, claims) {
1439
- const rowFilter = entry.shape?.rowFilter;
1440
- return rowFilter == null ? null : buildRowFilterShape(rowFilter, claims);
1695
+ function resolvePredicate(entry, claims) {
1696
+ return entry.shape?.rowFilter?.customPredicate?.(claims) ?? null;
1441
1697
  }
1442
1698
  function boundEntries(registry, appliesTo) {
1443
1699
  const entries = Object.entries(registry);
@@ -1474,7 +1730,7 @@ function assertRegistryInvariant(registry, spec) {
1474
1730
  rowClass: entry.rowClass,
1475
1731
  fixtureName,
1476
1732
  claims,
1477
- renderedWhere: renderWhere(entry, claims),
1733
+ readPredicate: resolvePredicate(entry, claims),
1478
1734
  renderedPolicies
1479
1735
  });
1480
1736
  if (verdict === true) {
@@ -1550,7 +1806,8 @@ function asReadonly(entry) {
1550
1806
  const readonlyProjection = clientProjection != null ? {
1551
1807
  ...clientProjection.syncedTable != null ? { syncedTable: clientProjection.syncedTable } : {},
1552
1808
  ...clientProjection.omitColumns != null ? { omitColumns: clientProjection.omitColumns } : {},
1553
- ...clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {}
1809
+ ...clientProjection.localPrimaryKey != null ? { localPrimaryKey: clientProjection.localPrimaryKey } : {},
1810
+ ...clientProjection.localIndexes != null ? { localIndexes: clientProjection.localIndexes } : {}
1554
1811
  } : undefined;
1555
1812
  return {
1556
1813
  table: entry.table,
@@ -1593,10 +1850,14 @@ function assertReadContractPreserved(authoritative, projection, options) {
1593
1850
  }
1594
1851
  }
1595
1852
  // packages/contracts/src/sql-defaults.ts
1596
- import { sql as sql2 } from "drizzle-orm";
1853
+ import { sql } from "drizzle-orm";
1597
1854
  var NOW_MICROSECONDS_SQL_TEXT = "CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000000) AS BIGINT)";
1598
1855
  var CLOCK_US_CALL_SQL_TEXT = "public.pgxsinkit_clock_us()";
1599
- var clockMicrosecondsSql = sql2.raw(CLOCK_US_CALL_SQL_TEXT);
1856
+ var clockMicrosecondsSql = sql.raw(CLOCK_US_CALL_SQL_TEXT);
1857
+ // packages/contracts/src/stream-envelope.ts
1858
+ function isDeleteEnvelope(envelope) {
1859
+ return envelope.headers.operation === "delete";
1860
+ }
1600
1861
  // packages/contracts/src/sql-role-guard.ts
1601
1862
  function buildRoleGuardedStatement(roleName, statementSql) {
1602
1863
  return [
@@ -1611,9 +1872,9 @@ function buildRoleGuardedStatement(roleName, statementSql) {
1611
1872
  `);
1612
1873
  }
1613
1874
  // packages/contracts/src/supabase-rls.ts
1614
- import { and, eq, getTableName, or, sql as sql3 } from "drizzle-orm";
1615
- import { PgDialect as PgDialect3, pgPolicy } from "drizzle-orm/pg-core";
1616
- var textDialect = new PgDialect3;
1875
+ import { and, eq, getTableName as getTableName2, or, sql as sql2 } from "drizzle-orm";
1876
+ import { PgDialect as PgDialect2, pgPolicy } from "drizzle-orm/pg-core";
1877
+ var textDialect = new PgDialect2;
1617
1878
  function renderInlineSql(fragment) {
1618
1879
  return textDialect.sqlToQuery(fragment.inlineParams()).sql;
1619
1880
  }
@@ -1677,11 +1938,11 @@ function tableNameForColumn(column, label) {
1677
1938
  if (!table) {
1678
1939
  throw new Error(`${label} must be a built Drizzle column carrying its table \u2014 call this builder inside defineSyncTable's \`extras\` callback`);
1679
1940
  }
1680
- return getTableName(table);
1941
+ return getTableName2(table);
1681
1942
  }
1682
1943
  function buildSubjectSql(subjectCastType) {
1683
1944
  assertTypeName(subjectCastType, "subjectCastType");
1684
- return sql3.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);
1945
+ return sql2.raw(`(select ${buildSubjectSqlText(subjectCastType)})`);
1685
1946
  }
1686
1947
  function buildSubjectSqlText(subjectCastType) {
1687
1948
  return `coalesce(
@@ -1697,22 +1958,22 @@ function resolveAdminRolesClaimPath(path) {
1697
1958
  return segments;
1698
1959
  }
1699
1960
  function buildClaimPathChainSql(path) {
1700
- return sql3.join(path.map((segment) => sql3` -> ${segment}`), sql3``);
1961
+ return sql2.join(path.map((segment) => sql2` -> ${segment}`), sql2``);
1701
1962
  }
1702
1963
  function buildClaimArraySqlText(claimSqlText) {
1703
1964
  return `case jsonb_typeof(${claimSqlText}) when 'array' then ${claimSqlText} else '[]'::jsonb end`;
1704
1965
  }
1705
1966
  function buildAdminRoleExistsSqlText(adminRoleName, claimPath) {
1706
- const rolesClaim = renderInlineSql(sql3`(
1967
+ const rolesClaim = renderInlineSql(sql2`(
1707
1968
  coalesce(
1708
1969
  nullif(current_setting('request.jwt.claim', true), ''),
1709
1970
  nullif(current_setting('request.jwt.claims', true), '')
1710
1971
  )::jsonb${buildClaimPathChainSql(claimPath)}
1711
1972
  )`);
1712
- return renderInlineSql(sql3`EXISTS (
1973
+ return renderInlineSql(sql2`EXISTS (
1713
1974
  SELECT 1
1714
1975
  FROM jsonb_array_elements_text(
1715
- ${sql3.raw(buildClaimArraySqlText(rolesClaim))}
1976
+ ${sql2.raw(buildClaimArraySqlText(rolesClaim))}
1716
1977
  ) AS assigned_role(role_name_value)
1717
1978
  WHERE assigned_role.role_name_value = ${adminRoleName}
1718
1979
  )`);
@@ -1740,7 +2001,7 @@ function buildSupabaseOwnerOrAdminPredicateSqlText(options = {}) {
1740
2001
  function buildSupabaseOwnerOrAdminNativePolicies(options) {
1741
2002
  const adminRoleName = options.adminRoleName ?? defaultAdminRoleName;
1742
2003
  const subject = buildSubjectSql(options.subjectCastType ?? defaultSubjectCastType);
1743
- const adminExists = sql3.raw(buildAdminRoleExistsSqlText(adminRoleName, resolveAdminRolesClaimPath(options.adminRolesClaimPath)));
2004
+ const adminExists = sql2.raw(buildAdminRoleExistsSqlText(adminRoleName, resolveAdminRolesClaimPath(options.adminRolesClaimPath)));
1744
2005
  const predicate = or(eq(options.ownerColumn, subject), adminExists);
1745
2006
  const tableName = tableNameForColumn(options.ownerColumn, "ownerColumn");
1746
2007
  return ownerOrAdminPolicyShapes.map((shape) => pgPolicy(buildOwnerOrAdminPolicyName(tableName, shape.command), {
@@ -1764,9 +2025,9 @@ function resolveOwnerOrAdminAccess(claims, options = {}) {
1764
2025
  const admin = Array.isArray(roles) && roles.some((role) => typeof role === "string" && role === adminRoleName);
1765
2026
  return { admin, subject: readSubjectClaim(claims) };
1766
2027
  }
1767
- function buildOwnerOrAdminShapeWhere(ownerColumn, claims, options = {}) {
2028
+ function buildOwnerOrAdminShapePredicate(ownerColumn, claims, options = {}) {
1768
2029
  const access = resolveOwnerOrAdminAccess(claims, options);
1769
- return access.admin ? null : buildOwnershipShapeWhere(ownerColumn, access.subject);
2030
+ return access.admin ? null : buildOwnershipShapePredicate(ownerColumn, access.subject);
1770
2031
  }
1771
2032
  var defaultManagerRoleValue = "manager";
1772
2033
  var membershipPolicyShapes = [
@@ -1785,15 +2046,15 @@ function normalizeMembershipColumns(options) {
1785
2046
  function membershipMatch(cols, subject, requireManager) {
1786
2047
  const subjectIsMember = eq(cols.membershipSubjectColumn, subject);
1787
2048
  const where = requireManager && cols.managerRoleColumn ? and(subjectIsMember, eq(cols.managerRoleColumn, cols.managerRoleValue).inlineParams()) : subjectIsMember;
1788
- return sql3`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;
2049
+ return sql2`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${where}))`;
1789
2050
  }
1790
2051
  function ownerOrManager(cols, subject) {
1791
2052
  const owner = eq(cols.ownerColumn, subject);
1792
2053
  return cols.managerRoleColumn ? or(owner, membershipMatch(cols, subject, true)) : owner;
1793
2054
  }
1794
2055
  function membershipWriteGate(cols, gate, subject) {
1795
- const unlocked = sql3`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;
1796
- const notMuted = sql3`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;
2056
+ const unlocked = sql2`${cols.containerColumn} = any(array(select ${gate.containerPkColumn} from ${gate.containerTable} where ${eq(gate.containerLockColumn, false).inlineParams()}))`;
2057
+ const notMuted = sql2`${cols.containerColumn} = any(array(select ${cols.membershipContainerColumn} from ${cols.membershipTable} where ${and(eq(cols.membershipSubjectColumn, subject), eq(gate.membershipMutedColumn, false).inlineParams())}))`;
1797
2058
  return and(or(unlocked, membershipMatch(cols, subject, true)), notMuted);
1798
2059
  }
1799
2060
  function buildSupabaseMembershipNativePolicies(options) {
@@ -1834,12 +2095,12 @@ function buildSupabaseMembershipNativePolicies(options) {
1834
2095
  });
1835
2096
  });
1836
2097
  }
1837
- function buildMembershipShapeWhere(columns, claims) {
2098
+ function buildMembershipShapePredicate(columns, claims) {
1838
2099
  const subject = readSubjectClaim(claims);
1839
2100
  if (subject === null) {
1840
- return DENY_ALL;
2101
+ return DENY_ALL_PREDICATE;
1841
2102
  }
1842
- return sql3`${c(columns.containerColumn)} in (select ${c(columns.membershipContainerColumn)} from ${columns.membershipTable} where ${c(columns.membershipSubjectColumn)} = ${subject})`;
2103
+ return p.in(columns.containerColumn, p.subquery(columns.membershipContainerColumn, p.eq(columns.membershipSubjectColumn, subject)));
1843
2104
  }
1844
2105
  var defaultGrantsClaimPath = ["app_metadata", "authorization", "grants"];
1845
2106
  var defaultGrantScopeCastType = "uuid";
@@ -1869,7 +2130,7 @@ function buildRoleInListSqlText(roleValues) {
1869
2130
  if (roleValues.length === 0) {
1870
2131
  throw new Error("grant-scope policy requires at least one role value");
1871
2132
  }
1872
- return renderInlineSql(sql3.join(roleValues.map((role) => sql3`${role}`), sql3`, `));
2133
+ return renderInlineSql(sql2.join(roleValues.map((role) => sql2`${role}`), sql2`, `));
1873
2134
  }
1874
2135
  function resolveGrantScopeIdField(options) {
1875
2136
  const field = options.scopeIdField ?? `${options.scopeKind}Id`;
@@ -1881,7 +2142,7 @@ function buildBypassExistsSqlText(bypass, grantsText) {
1881
2142
  return `exists (
1882
2143
  select 1
1883
2144
  from jsonb_array_elements(${grantsText}) as bypass_grant
1884
- where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql3`${scopeKind}`)}
2145
+ where bypass_grant -> 'scope' ->> 'kind' = ${renderInlineSql(sql2`${scopeKind}`)}
1885
2146
  and bypass_grant ->> 'role' in (${buildRoleInListSqlText(bypass.roleValues)})
1886
2147
  )`;
1887
2148
  }
@@ -1893,13 +2154,13 @@ function buildGrantScopePredicate(options) {
1893
2154
  assertTypeName(castType, "scopeCastType");
1894
2155
  const grantsText = buildGrantsArraySqlText(resolveGrantsClaimPath(options.grantsClaimPath));
1895
2156
  const roleIn = buildRoleInListSqlText(options.roleValues);
1896
- const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql3`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;
1897
- const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql3`${scopeIdField}`)})::${castType}`;
1898
- const base = options.naive ? sql3`exists (select 1 from jsonb_array_elements(${sql3.raw(grantsText)}) as grant_elem where ${sql3.raw(kindMatch)} and ${sql3.raw(idExpr)} = ${options.scopeColumn})` : sql3`${options.scopeColumn} = any(array(select ${sql3.raw(idExpr)} from jsonb_array_elements(${sql3.raw(grantsText)}) as grant_elem where ${sql3.raw(kindMatch)}))`;
2157
+ const kindMatch = `grant_elem -> 'scope' ->> 'kind' = ${renderInlineSql(sql2`${scopeKind}`)} and grant_elem ->> 'role' in (${roleIn})`;
2158
+ const idExpr = `(grant_elem -> 'scope' ->> ${renderInlineSql(sql2`${scopeIdField}`)})::${castType}`;
2159
+ const base = options.naive ? sql2`exists (select 1 from jsonb_array_elements(${sql2.raw(grantsText)}) as grant_elem where ${sql2.raw(kindMatch)} and ${sql2.raw(idExpr)} = ${options.scopeColumn})` : sql2`${options.scopeColumn} = any(array(select ${sql2.raw(idExpr)} from jsonb_array_elements(${sql2.raw(grantsText)}) as grant_elem where ${sql2.raw(kindMatch)}))`;
1899
2160
  if (!options.bypass) {
1900
2161
  return base;
1901
2162
  }
1902
- return or(base, sql3.raw(buildBypassExistsSqlText(options.bypass, grantsText)));
2163
+ return or(base, sql2.raw(buildBypassExistsSqlText(options.bypass, grantsText)));
1903
2164
  }
1904
2165
  function buildSupabaseGrantScopeNativePolicies(options) {
1905
2166
  const predicate = buildGrantScopePredicate(options);
@@ -1944,11 +2205,12 @@ function resolveGrantScopeIds(claims, options) {
1944
2205
  }
1945
2206
  return [...ids];
1946
2207
  }
1947
- function buildGrantScopeShapeWhere(scopeColumn, ids) {
2208
+ function buildGrantScopeShapePredicate(scopeColumn, ids) {
1948
2209
  if (ids.length === 0) {
1949
- return DENY_ALL;
2210
+ return DENY_ALL_PREDICATE;
1950
2211
  }
1951
- return sql3`${c(scopeColumn)} in (${sql3.join(ids.map((id) => sql3`${id}`), sql3`, `)})`;
2212
+ const equalities = ids.map((id) => p.eq(scopeColumn, id));
2213
+ return equalities.length === 1 ? equalities[0] : p.or(...equalities);
1952
2214
  }
1953
2215
  function hasGrantScopeBypass(claims, options) {
1954
2216
  const bypass = options.bypass;
@@ -1985,133 +2247,149 @@ function resolveGrantScopeAccess(claims, options) {
1985
2247
  ids: resolveGrantScopeIds(claims, options)
1986
2248
  };
1987
2249
  }
1988
- function buildGrantScopeAccessShapeWhere(scopeColumn, claims, options) {
2250
+ function buildGrantScopeAccessShapePredicate(scopeColumn, claims, options) {
1989
2251
  const access = resolveGrantScopeAccess(claims, options);
1990
- return access.bypass ? null : buildGrantScopeShapeWhere(scopeColumn, access.ids);
2252
+ return access.bypass ? null : buildGrantScopeShapePredicate(scopeColumn, access.ids);
1991
2253
  }
1992
2254
  export {
1993
- withRetention,
1994
- unixMicrosecondsSchema,
1995
- syncRegistryStreamsSymbol,
1996
- syncRegistryStorageSymbol,
1997
- syncRegistrySchemaSymbol,
1998
- syncRegistryRowClassesSymbol,
1999
- supabaseOwnerOrAdminDefaults,
2000
- summarizeRegistryDiff,
2001
- stampedEventSchema,
2002
- runRegistryCheck,
2003
- resolveStorageDeclaration,
2004
- resolveServerVersionColumnName,
2005
- resolveOwnerOrAdminAccess,
2006
- resolveGrantScopeIds,
2007
- resolveGrantScopeAccess,
2008
- registryRowClasses,
2009
- registryEventStreams,
2010
- quoteSqlLiteral,
2011
- quoteIdentifier,
2012
- normalizeCastPositionType,
2013
- mutationStatusSchema,
2014
- mutationRejectionSchema,
2015
- mutationKindSchema,
2016
- mutationEnvelopeSchema,
2017
- mutationAckStatusSchema,
2018
- mutationAckSchema,
2019
- maybeQuoteIdentifier,
2020
- jwtClaimsSchema,
2021
- isZodSchema,
2022
- isWriteMode,
2023
- isSubscriptionTiming,
2024
- isStorageDurability,
2025
- isStorageBackend,
2026
- isRetention,
2027
- isManagedFieldGuarded,
2028
- isConflictPolicy,
2029
- isClaimsDependentRowFilter,
2030
- hashString,
2031
- hasNonStrictObjectRoot,
2032
- getSyncRegistryStreams,
2033
- getSyncRegistryStorage,
2034
- getSyncRegistrySchema,
2035
- getSyncRegistryRowClasses,
2036
- getProjectedColumns,
2037
- getProjectedColumnNames,
2038
- getOmittedProjectedColumns,
2039
- getOmittedProjectedColumnNames,
2040
- getLocalSyncedTablePrimaryKeyColumns,
2041
- getLocalSyncPrimaryKeyColumns,
2042
- getLocalSyncPrimaryKey,
2043
- fingerprintRegistry,
2044
- fingerprintReadContract,
2045
- eventQueueMessageSchema,
2046
- eventEnvelopeSchema,
2047
- eventAckStatusSchema,
2048
- eventAckSchema,
2049
- escapeSqlLiteral,
2050
- entityKeySchema,
2051
- diffRegistryAgainstLock,
2052
- diffCanonicalRegistries,
2053
- deriveSyncColumnTypes,
2054
- defineSyncTable,
2055
- defineSyncRegistry,
2056
- defineReadProjection,
2057
- defineEventStream,
2058
- compareRegistries,
2059
- clockMicrosecondsSql,
2060
- classifyTableApplyStrategy,
2061
- classifyApplyStrategy,
2062
- canonicalizeRegistry,
2063
- canonicalizeReadContract,
2064
- canonicalRegistryString,
2065
- canonicalReadContractString,
2066
- c,
2067
- buildSyncStateView,
2068
- buildSupabaseOwnerOrAdminPredicateSqlText,
2069
- buildSupabaseOwnerOrAdminNativePolicies,
2070
- buildSupabaseMembershipNativePolicies,
2071
- buildSupabaseGrantScopeNativePolicies,
2072
- buildRowFilterShape,
2073
- buildRoleGuardedStatement,
2074
- buildRegistryLock,
2075
- buildOwnershipShapeWhere,
2076
- buildOwnerOrAdminShapeWhere,
2077
- buildOverlayResolutionBarrier,
2078
- buildMembershipShapeWhere,
2079
- buildGrantScopeShapeWhere,
2080
- buildGrantScopeAccessShapeWhere,
2081
- batchMutationRequestSchema,
2082
- batchMutationErrorSchema,
2083
- batchMutationAckSchema,
2084
- batchEventRequestSchema,
2085
- batchEventPaths,
2086
- batchEventErrorSchema,
2087
- batchEventAckSchema,
2088
- authoritativeWriteRequestSchema,
2089
- attachSyncRegistryStreams,
2090
- attachSyncRegistryStorage,
2091
- attachSyncRegistrySchema,
2092
- attachSyncRegistryRowClasses,
2093
- assertStorageDeclarationCompatible,
2094
- assertRegistryInvariant,
2095
- assertReadContractPreserved,
2096
- asReadonly,
2097
- asEphemeral,
2098
- WRITE_MODES,
2099
- StorageDeclarationRefusedError,
2100
- SUBSCRIPTION_TIMINGS,
2101
- STORAGE_DURABILITIES,
2102
- STORAGE_BACKENDS,
2103
- RETENTIONS,
2104
- NOW_MICROSECONDS_SQL_TEXT,
2105
- MAX_EVENT_REQUEST_BYTES,
2106
- MAX_EVENT_PAYLOAD_BYTES,
2107
- MAX_EVENTS_PER_BATCH,
2108
- EVENT_STREAM_QUEUE_PREFIX,
2109
- EVENT_STREAM_NAME_PATTERN,
2110
- EVENT_STREAM_NAME_MAX_LENGTH,
2111
- DENY_ALL,
2112
- CONVERGENCE_EVENTS,
2255
+ CLOCK_US_CALL_SQL_TEXT,
2113
2256
  CONFLICT_POLICIES,
2114
- CLOCK_US_CALL_SQL_TEXT
2257
+ CONVERGENCE_EVENTS,
2258
+ DENY_ALL_PREDICATE,
2259
+ EVENT_STREAM_NAME_MAX_LENGTH,
2260
+ EVENT_STREAM_NAME_PATTERN,
2261
+ EVENT_STREAM_QUEUE_PREFIX,
2262
+ MAX_EVENTS_PER_BATCH,
2263
+ MAX_EVENT_PAYLOAD_BYTES,
2264
+ MAX_EVENT_REQUEST_BYTES,
2265
+ NOW_MICROSECONDS_SQL_TEXT,
2266
+ RETENTIONS,
2267
+ STORAGE_BACKENDS,
2268
+ STORAGE_BUILDS,
2269
+ STORAGE_DURABILITIES,
2270
+ SUBSCRIPTION_TIMINGS,
2271
+ StorageBuildMismatchError,
2272
+ StorageDeclarationRefusedError,
2273
+ WRITE_MODES,
2274
+ asEphemeral,
2275
+ asReadonly,
2276
+ assertReadContractPreserved,
2277
+ assertRegistryInvariant,
2278
+ assertShapeFilterIsEnforceable,
2279
+ assertStorageDeclarationCompatible,
2280
+ attachSyncRegistryRowClasses,
2281
+ attachSyncRegistrySchema,
2282
+ attachSyncRegistryStorage,
2283
+ attachSyncRegistryStreams,
2284
+ authoritativeWriteRequestSchema,
2285
+ batchEventAckSchema,
2286
+ batchEventErrorSchema,
2287
+ batchEventPaths,
2288
+ batchEventRequestSchema,
2289
+ batchMutationAckSchema,
2290
+ batchMutationErrorSchema,
2291
+ batchMutationRequestSchema,
2292
+ buildGrantScopeAccessShapePredicate,
2293
+ buildGrantScopeShapePredicate,
2294
+ buildMembershipShapePredicate,
2295
+ buildOverlayResolutionBarrier,
2296
+ buildOwnerOrAdminShapePredicate,
2297
+ buildOwnershipShapePredicate,
2298
+ buildRegistryLock,
2299
+ buildRoleGuardedStatement,
2300
+ buildSupabaseGrantScopeNativePolicies,
2301
+ buildSupabaseMembershipNativePolicies,
2302
+ buildSupabaseOwnerOrAdminNativePolicies,
2303
+ buildSupabaseOwnerOrAdminPredicateSqlText,
2304
+ buildSyncStateView,
2305
+ canonicalReadContractString,
2306
+ canonicalRegistryString,
2307
+ canonicalizeReadContract,
2308
+ canonicalizeRegistry,
2309
+ classifyApplyStrategy,
2310
+ classifyTableApplyStrategy,
2311
+ clockMicrosecondsSql,
2312
+ compareRegistries,
2313
+ conjoinPredicates,
2314
+ defineEventStream,
2315
+ defineReadProjection,
2316
+ defineSyncRegistry,
2317
+ defineSyncTable,
2318
+ deniesAllRows,
2319
+ deriveSyncColumnTypes,
2320
+ diffCanonicalRegistries,
2321
+ diffRegistryAgainstLock,
2322
+ entityKeySchema,
2323
+ escapeSqlLiteral,
2324
+ eventAckSchema,
2325
+ eventAckStatusSchema,
2326
+ eventEnvelopeSchema,
2327
+ eventQueueMessageSchema,
2328
+ fingerprintReadContract,
2329
+ fingerprintRegistry,
2330
+ getLocalSyncPrimaryKey,
2331
+ getLocalSyncPrimaryKeyColumns,
2332
+ getLocalSyncedTablePrimaryKeyColumns,
2333
+ getOmittedProjectedColumnNames,
2334
+ getOmittedProjectedColumns,
2335
+ getProjectedColumnNames,
2336
+ getProjectedColumns,
2337
+ getSyncRegistryRowClasses,
2338
+ getSyncRegistrySchema,
2339
+ getSyncRegistryStorage,
2340
+ getSyncRegistryStreams,
2341
+ hasNonStrictObjectRoot,
2342
+ hashString,
2343
+ isAndPredicate,
2344
+ isClaimsDependentRowFilter,
2345
+ isConflictPolicy,
2346
+ isDeleteEnvelope,
2347
+ isInSubqueryPredicate,
2348
+ isIsNullPredicate,
2349
+ isLeafPredicate,
2350
+ isManagedFieldGuarded,
2351
+ isNotPredicate,
2352
+ isOrPredicate,
2353
+ isRetention,
2354
+ isStorageBackend,
2355
+ isStorageBuild,
2356
+ isStorageDurability,
2357
+ isStorageEngineDeclaration,
2358
+ isStorageEngineModule,
2359
+ isSubscriptionTiming,
2360
+ isWriteMode,
2361
+ isZodSchema,
2362
+ jsonUdtName,
2363
+ jwtClaimsSchema,
2364
+ maybeQuoteIdentifier,
2365
+ mutationAckSchema,
2366
+ mutationAckStatusSchema,
2367
+ mutationEnvelopeSchema,
2368
+ mutationKindSchema,
2369
+ mutationRejectionSchema,
2370
+ mutationStatusSchema,
2371
+ normalizeCastPositionType,
2372
+ p,
2373
+ quoteIdentifier,
2374
+ quoteSqlLiteral,
2375
+ readShapeTier,
2376
+ registryEventStreams,
2377
+ registryRowClasses,
2378
+ resolveGrantScopeAccess,
2379
+ resolveGrantScopeIds,
2380
+ resolveOwnerOrAdminAccess,
2381
+ resolveServerVersionColumnName,
2382
+ resolveStorageDeclaration,
2383
+ runRegistryCheck,
2384
+ stampedEventSchema,
2385
+ summarizeRegistryDiff,
2386
+ supabaseOwnerOrAdminDefaults,
2387
+ syncRegistryRowClassesSymbol,
2388
+ syncRegistrySchemaSymbol,
2389
+ syncRegistryStorageSymbol,
2390
+ syncRegistryStreamsSymbol,
2391
+ unixMicrosecondsSchema,
2392
+ withRetention
2115
2393
  };
2116
2394
 
2117
- //# debugId=7B2607AF400BBBC364756E2164756E21
2395
+ //# debugId=68C3BDD5068DEA1A64756E2164756E21