@pgxsinkit/server 0.2.7 → 0.3.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/dist/index.js CHANGED
@@ -2,248 +2,721 @@
2
2
  // packages/server/src/index.ts
3
3
  import { batchEventPaths, getSyncRegistryStreams as getSyncRegistryStreams4 } from "@pgxsinkit/contracts";
4
4
 
5
- // packages/server/src/electric-proxy.ts
5
+ // packages/server/src/circuits/subscribe.ts
6
6
  import {
7
- buildRowFilterShape,
8
- getOmittedProjectedColumnNames
7
+ readShapeTier as readShapeTier2
9
8
  } from "@pgxsinkit/contracts";
10
9
 
11
- // packages/server/src/cors-origin.ts
12
- function resolveCorsOrigin(request, origins) {
13
- const origin = request.headers.get("origin");
14
- if (!origin) {
15
- return null;
16
- }
17
- return origins.includes("*") || origins.includes(origin) ? origin : null;
10
+ // packages/server/src/circuits/compile.ts
11
+ import { getTableConfig } from "drizzle-orm/pg-core";
12
+ import {
13
+ conjoinPredicates,
14
+ DENY_ALL_PREDICATE,
15
+ isAndPredicate,
16
+ isIsNullPredicate,
17
+ isLeafPredicate,
18
+ readShapeTier
19
+ } from "@pgxsinkit/contracts";
20
+ function resolveEntryByShapeKey(registry, shapeKey) {
21
+ return Object.values(registry).find((entry) => entry?.shape?.shapeKey === shapeKey);
22
+ }
23
+ function resolveShapeTarget(shape) {
24
+ const target = shape.physicalTable ?? shape.tableName;
25
+ if (!target.includes("."))
26
+ return { table: target };
27
+ const [schema] = target.split(".");
28
+ if (schema === "public")
29
+ return { table: target.slice("public.".length) };
30
+ return {
31
+ refusal: `shape "${shape.shapeKey}" reads "${target}", but the engine introspects the public schema ` + `only and names tables bare \u2014 a non-public target has no shape it can be created under.`
32
+ };
18
33
  }
19
-
20
- // packages/server/src/electric-proxy.ts
21
- var perfNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
22
- var ELECTRIC_EXPOSED_HEADERS = "electric-offset,electric-handle,electric-schema,electric-cursor,electric-up-to-date";
23
- async function proxyElectricShapeRequest(request, claims, options) {
24
- if (options.cors && request.method === "OPTIONS") {
25
- return corsPreflightResponse(request, options.cors);
26
- }
27
- const timing = options.logTimings ? { upstreamMs: 0, upstreamStatus: 0 } : undefined;
28
- const start = timing ? perfNow() : 0;
29
- const response = await forwardShapeRequest(request, claims, options, timing);
30
- const finalResponse = options.cors ? withCorsResponseHeaders(request, response, options.cors) : response;
31
- if (timing) {
32
- logShapeTiming(request, timing, perfNow() - start);
33
- }
34
- return finalResponse;
35
- }
36
- function logShapeTiming(request, timing, totalMs) {
37
- const params = new URL(request.url).searchParams;
38
- console.log("[pgxsinkit-timing]", JSON.stringify({
39
- route: "shape",
40
- table: params.get("table") ?? undefined,
41
- live: params.get("live") === "true",
42
- offset: params.get("offset") ?? undefined,
43
- upstreamMs: Math.round(timing.upstreamMs),
44
- upstreamStatus: timing.upstreamStatus,
45
- totalMs: Math.round(totalMs)
46
- }));
34
+ function emittedColumns(entry) {
35
+ const explicit = entry.shape?.rowFilter?.columns;
36
+ if (explicit != null && explicit.length > 0)
37
+ return [...explicit];
38
+ if (entry.clientProjection?.omitColumns == null)
39
+ return;
40
+ return getTableConfig(entry.localTable).columns.map((column) => column.name);
47
41
  }
48
- async function forwardShapeRequest(request, claims, options, timing) {
49
- const decision = decideProxyTarget(request, claims, options);
50
- if (decision.kind === "reject") {
51
- return new Response(JSON.stringify({ message: decision.message }), {
52
- status: decision.status,
53
- headers: { "content-type": "application/json" }
54
- });
55
- }
56
- const upstreamStart = timing ? perfNow() : 0;
57
- const response = await fetch(decision.targetUrl, {
58
- method: "GET",
59
- signal: request.signal
60
- }).catch((error) => {
61
- if (request.signal.aborted || isAbortError(error)) {
62
- return new Response(null, { status: 499, statusText: "Client Closed Request" });
63
- }
64
- throw error;
65
- });
66
- if (timing) {
67
- timing.upstreamMs = perfNow() - upstreamStart;
68
- timing.upstreamStatus = response.status;
69
- }
70
- const responseHeaders = new Headers(response.headers);
71
- responseHeaders.delete("content-encoding");
72
- responseHeaders.delete("content-length");
73
- const shapeKey = new URL(request.url).searchParams.get("table");
74
- const omittedColumns = shapeKey ? getOmittedProjectedColumnsForTable(options.registry, shapeKey) : [];
75
- const rowTransform = shapeKey ? getRowTransformForTable(options.registry, shapeKey) : undefined;
76
- const contentType = responseHeaders.get("content-type") ?? "";
77
- if ((omittedColumns.length > 0 || rowTransform) && contentType.includes("application/json")) {
78
- const payload = await response.clone().json().catch(() => {
79
- return;
80
- });
81
- if (Array.isArray(payload)) {
82
- const context = { claims, ...options.extraParams ? { params: options.extraParams } : {} };
83
- const rewritten = rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context);
84
- return new Response(JSON.stringify(rewritten), {
85
- status: response.status,
86
- statusText: response.statusText,
87
- headers: responseHeaders
88
- });
42
+ function compileShapeRequest(registry, request) {
43
+ const entry = resolveEntryByShapeKey(registry, request.shapeKey);
44
+ const shape = entry?.shape;
45
+ if (entry == null || shape == null) {
46
+ return { outcome: "deny", reason: `no shape declares shapeKey "${request.shapeKey}"` };
47
+ }
48
+ const target = resolveShapeTarget(shape);
49
+ if ("refusal" in target)
50
+ return { outcome: "deny", reason: target.refusal };
51
+ const tier = readShapeTier(shape);
52
+ const subject = tier === "shared" ? scopePredicate(shape, request.scope) : privatePredicate(shape, request.claims, request.params);
53
+ if ("refusal" in subject)
54
+ return { outcome: "deny", reason: subject.refusal };
55
+ const where = conjoinPredicates(subject.predicate, shape.where);
56
+ const narrowing = assertLocalPrimaryKeyIsPinned(entry, where);
57
+ if (narrowing != null)
58
+ return { outcome: "deny", reason: narrowing };
59
+ const columns = emittedColumns(entry);
60
+ return {
61
+ outcome: "create",
62
+ tier,
63
+ request: {
64
+ table: target.table,
65
+ ...where !== undefined ? { where } : {},
66
+ ...columns !== undefined ? { columns } : {}
89
67
  }
68
+ };
69
+ }
70
+ function scopePredicate(shape, values) {
71
+ const columns = shape.scope ?? [];
72
+ if (values == null) {
73
+ return { refusal: `shape "${shape.shapeKey}" is shared-tier and requires ${columns.length} scope value(s)` };
90
74
  }
91
- return new Response(response.body, {
92
- status: response.status,
93
- statusText: response.statusText,
94
- headers: responseHeaders
75
+ if (values.length !== columns.length) {
76
+ return {
77
+ refusal: `shape "${shape.shapeKey}" takes ${columns.length} scope value(s) ` + `(${columns.join(", ")}) but got ${values.length}`
78
+ };
79
+ }
80
+ const equalities = columns.map((col, index) => {
81
+ const value = values[index];
82
+ return value === null ? { col, isNull: true } : { col, op: "eq", value };
95
83
  });
84
+ return { predicate: conjoinPredicates(...equalities) };
96
85
  }
97
- function decideProxyTarget(request, claims, options) {
98
- const requestedShapeKey = new URL(request.url).searchParams.get("table");
99
- if (!requestedShapeKey) {
100
- return { kind: "reject", status: 400, message: "Shape request must specify a table" };
101
- }
102
- if (!resolveEntryByShapeKey(options.registry, requestedShapeKey)) {
103
- return { kind: "reject", status: 403, message: `Shape is not in the sync registry: ${requestedShapeKey}` };
104
- }
105
- return { kind: "forward", targetUrl: buildProxyTargetUrl(request, claims, options) };
106
- }
107
- var ELECTRIC_CONTROL_QUERY_PARAMS = new Set([
108
- "offset",
109
- "handle",
110
- "live",
111
- "cursor",
112
- "cache-buster",
113
- "expired_handle",
114
- "experimental_live_sse",
115
- "live_sse",
116
- "log"
117
- ]);
118
- function buildProxyTargetUrl(request, claims, options) {
119
- const requestUrl = new URL(request.url);
120
- const targetUrl = new URL(options.electricUrl);
121
- targetUrl.searchParams.delete("where");
122
- targetUrl.searchParams.delete("columns");
123
- const entry = resolveEntryByShapeKey(options.registry, requestUrl.searchParams.get("table") ?? "");
124
- const electricTarget = electricTargetForEntry(entry);
125
- if (!electricTarget) {
126
- return targetUrl.toString();
127
- }
128
- targetUrl.searchParams.set("table", electricTarget);
129
- requestUrl.searchParams.forEach((value, key) => {
130
- if (ELECTRIC_CONTROL_QUERY_PARAMS.has(key)) {
131
- targetUrl.searchParams.set(key, value);
132
- }
133
- });
134
- if (options.bustLiveUpstreamCache !== false && targetUrl.searchParams.get("live") === "true") {
135
- targetUrl.searchParams.set("cache-buster", crypto.randomUUID());
136
- }
137
- const rowFilter = entry?.shape?.rowFilter;
138
- if (!rowFilter) {
139
- return targetUrl.toString();
140
- }
141
- const shape = buildRowFilterShape(rowFilter, claims, options.extraParams);
142
- if (shape) {
143
- targetUrl.searchParams.set("where", shape.where);
144
- shape.params.forEach((param, index) => {
145
- targetUrl.searchParams.set(`params[${index + 1}]`, param);
146
- });
86
+ function pinnedColumns(node, into = new Set) {
87
+ if (node == null)
88
+ return into;
89
+ if (isAndPredicate(node)) {
90
+ for (const child of node.and)
91
+ pinnedColumns(child, into);
92
+ return into;
93
+ }
94
+ if (isIsNullPredicate(node)) {
95
+ into.add(node.col);
96
+ return into;
147
97
  }
148
- if (rowFilter.columns && rowFilter.columns.length > 0) {
149
- targetUrl.searchParams.set("columns", rowFilter.columns.join(","));
98
+ if (isLeafPredicate(node) && node.op === "eq") {
99
+ into.add(node.col);
150
100
  }
151
- return targetUrl.toString();
101
+ return into;
152
102
  }
153
- function electricTargetForEntry(entry) {
154
- const shape = entry?.shape;
155
- if (!shape) {
103
+ function assertLocalPrimaryKeyIsPinned(entry, where) {
104
+ const localKey = entry.clientProjection?.localPrimaryKey?.columns;
105
+ if (localKey == null || localKey.length === 0)
106
+ return null;
107
+ const localKeySet = new Set(localKey);
108
+ const dropped = entry.primaryKey.columns.filter((column) => !localKeySet.has(column));
109
+ if (dropped.length === 0)
156
110
  return null;
111
+ const pinned = pinnedColumns(where);
112
+ const unpinned = dropped.filter((column) => !pinned.has(column));
113
+ if (unpinned.length === 0)
114
+ return null;
115
+ return `shape "${entry.shape.shapeKey}" declares clientProjection.localPrimaryKey ` + `(${localKey.join(", ")}), dropping ${unpinned.join(", ")} from the server primary key ` + `(${entry.primaryKey.columns.join(", ")}) \u2014 but this caller's predicate does not pin ` + `${unpinned.length === 1 ? "that column" : "those columns"} to a single value, so two server rows ` + `could collapse onto one local key. Pin it with a top-level equality in the shape's rowFilter (or ` + `its scope), or widen localPrimaryKey to include it.`;
116
+ }
117
+ function privatePredicate(shape, claims, params) {
118
+ const filter = shape.rowFilter?.customPredicate;
119
+ if (filter == null)
120
+ return { predicate: undefined };
121
+ const resolved = filter(claims ?? {}, params);
122
+ if (resolved === DENY_ALL_PREDICATE) {
123
+ return { refusal: `shape "${shape.shapeKey}" denies this caller` };
124
+ }
125
+ return { predicate: resolved ?? undefined };
126
+ }
127
+ function canonicalJson(value) {
128
+ if (value === null || typeof value !== "object")
129
+ return JSON.stringify(value ?? null);
130
+ if (Array.isArray(value))
131
+ return `[${value.map((member) => canonicalJson(member ?? null)).join(",")}]`;
132
+ const entries = Object.entries(value).filter(([, member]) => member !== undefined).sort(([left], [right]) => left < right ? -1 : 1);
133
+ return `{${entries.map(([key, member]) => `${JSON.stringify(key)}:${canonicalJson(member)}`).join(",")}}`;
134
+ }
135
+ async function fingerprintShapeRequest(request) {
136
+ const canonical = canonicalJson({
137
+ table: request.table,
138
+ where: request.where,
139
+ columns: request.columns,
140
+ changesOnly: request.changesOnly
141
+ });
142
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(canonical));
143
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
144
+ }
145
+
146
+ // packages/server/src/circuits/edge.ts
147
+ import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
148
+
149
+ // packages/server/src/circuits/stream-token.ts
150
+ var DEFAULT_STREAM_TOKEN_TTL_SECONDS = 300;
151
+ async function importStreamTokenKey(secret) {
152
+ return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
153
+ "sign",
154
+ "verify"
155
+ ]);
156
+ }
157
+ function base64UrlEncode(bytes) {
158
+ return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
159
+ }
160
+ function base64UrlDecode(value) {
161
+ const padded = value.replaceAll("-", "+").replaceAll("_", "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
162
+ const binary = atob(padded);
163
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
164
+ for (let index = 0;index < binary.length; index += 1)
165
+ bytes[index] = binary.charCodeAt(index);
166
+ return bytes;
167
+ }
168
+ var HEADER = base64UrlEncode(new TextEncoder().encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
169
+ async function mintStreamToken(key, options) {
170
+ const ttl = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
171
+ const claims = {
172
+ sub: options.sub,
173
+ grants: options.grants.map((grant) => ({
174
+ path: grant.path,
175
+ shapeKey: grant.shapeKey,
176
+ shapeId: grant.shapeId,
177
+ claim: grant.claim,
178
+ ...grant.scope !== undefined ? { scope: [...grant.scope] } : {},
179
+ ...grant.fp !== undefined ? { fp: grant.fp } : {}
180
+ })),
181
+ iat: options.now,
182
+ exp: options.now + ttl
183
+ };
184
+ const body = base64UrlEncode(new TextEncoder().encode(JSON.stringify(claims)));
185
+ const signingInput = `${HEADER}.${body}`;
186
+ const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(signingInput));
187
+ return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;
188
+ }
189
+ async function verifyStreamToken(key, token, now, options) {
190
+ const parts = token.split(".");
191
+ if (parts.length !== 3)
192
+ return { ok: false, reason: "malformed token" };
193
+ const [header, body, signature] = parts;
194
+ if (header !== HEADER)
195
+ return { ok: false, reason: "unexpected token header" };
196
+ let valid;
197
+ try {
198
+ valid = await crypto.subtle.verify("HMAC", key, base64UrlDecode(signature), new TextEncoder().encode(`${header}.${body}`));
199
+ } catch {
200
+ return { ok: false, reason: "malformed signature" };
157
201
  }
158
- return shape.electricTable ?? shape.tableName;
202
+ if (!valid)
203
+ return { ok: false, reason: "bad signature" };
204
+ let claims;
205
+ try {
206
+ claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(body)));
207
+ } catch {
208
+ return { ok: false, reason: "malformed payload" };
209
+ }
210
+ if (typeof claims.sub !== "string" || !Array.isArray(claims.grants) || typeof claims.exp !== "number") {
211
+ return { ok: false, reason: "malformed payload" };
212
+ }
213
+ if (claims.exp <= now && options?.allowExpired !== true)
214
+ return { ok: false, reason: "expired" };
215
+ return { ok: true, claims };
159
216
  }
160
- function resolveEntryByShapeKey(registry, requestedShapeKey) {
161
- for (const key of Object.keys(registry)) {
162
- const entry = registry[key];
163
- if (entry?.shape?.shapeKey === requestedShapeKey) {
164
- return entry;
217
+ function findGrant(claims, path) {
218
+ return claims.grants.find((grant) => grant.path === path);
219
+ }
220
+
221
+ // packages/server/src/circuits/edge.ts
222
+ class EntitlementsUnavailableError extends Error {
223
+ constructor() {
224
+ super("[pgxsinkit] the entitlement set is unavailable \u2014 it is catching up, degraded or stale; " + "shared-tier subscriptions cannot be decided right now");
225
+ this.name = "EntitlementsUnavailableError";
226
+ }
227
+ }
228
+ async function authorizeStreamRead(options, token, path, now) {
229
+ if (token == null || token === "")
230
+ return { allow: false, reason: "no stream token" };
231
+ const verified = await verifyStreamToken(options.key, token, now);
232
+ if (!verified.ok)
233
+ return { allow: false, reason: verified.reason };
234
+ const grant = findGrant(verified.claims, path);
235
+ if (grant == null)
236
+ return { allow: false, reason: "token grants no such stream" };
237
+ const subject = verified.claims.sub;
238
+ if (grant.scope === undefined)
239
+ return { allow: true, grant, subject };
240
+ const entitlements = options.entitlements;
241
+ if (entitlements === undefined) {
242
+ return { allow: false, reason: "shared-tier grant, but this deployment configured no entitlement set" };
243
+ }
244
+ if (!entitlements.ready)
245
+ return { allow: false, reason: "entitlements unavailable" };
246
+ if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {
247
+ return { allow: false, reason: "not entitled to this scope" };
248
+ }
249
+ return { allow: true, grant, subject };
250
+ }
251
+ function readStreamToken(request) {
252
+ const header = request.headers.get("authorization");
253
+ if (header == null)
254
+ return null;
255
+ const [scheme, value] = header.split(" ");
256
+ return scheme?.toLowerCase() === "bearer" && value ? value : null;
257
+ }
258
+ var STREAM_READ_EXPOSED_HEADERS = [
259
+ "stream-next-offset",
260
+ "stream-up-to-date",
261
+ "stream-cursor",
262
+ "stream-closed",
263
+ "stream-seq",
264
+ "stream-ttl",
265
+ "stream-expires-at",
266
+ "stream-sse-data-encoding",
267
+ "etag"
268
+ ];
269
+ function rewrittenEgressHeaders(upstream) {
270
+ const headers = new Headers(upstream);
271
+ headers.delete("content-length");
272
+ headers.delete("content-encoding");
273
+ headers.delete("etag");
274
+ headers.set("cache-control", "private, no-store");
275
+ return headers;
276
+ }
277
+ function asksForSse(request) {
278
+ return new URL(request.url).searchParams.get("live") === "sse" || (request.headers.get("accept") ?? "").includes("text/event-stream");
279
+ }
280
+ function createStreamGate(options) {
281
+ const doFetch = options.fetch ?? fetch;
282
+ const base = options.durableStreamsUrl.replace(/\/+$/, "");
283
+ return async function handleStreamRead(request, path, now) {
284
+ const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);
285
+ if (!decision.allow) {
286
+ return new Response(JSON.stringify({ error: decision.reason }), {
287
+ status: 403,
288
+ headers: { "content-type": "application/json" }
289
+ });
165
290
  }
166
- }
167
- return;
291
+ const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);
292
+ const transform = entry?.serverProjection?.rowTransform;
293
+ if (transform != null && asksForSse(request)) {
294
+ return new Response(JSON.stringify({ error: "this shape is rewritten at egress and is served as JSON long-poll only" }), { status: 406, headers: { "content-type": "application/json" } });
295
+ }
296
+ const upstreamUrl = new URL(`${base}/${path}`);
297
+ upstreamUrl.search = new URL(request.url).search;
298
+ const forwarded = new Headers(request.headers);
299
+ forwarded.delete("authorization");
300
+ forwarded.delete("host");
301
+ const init = { method: request.method, headers: forwarded, signal: request.signal };
302
+ if (transform == null || entry == null)
303
+ return doFetch(upstreamUrl, init);
304
+ const upstream = await doFetch(upstreamUrl, init);
305
+ const headers = rewrittenEgressHeaders(upstream.headers);
306
+ if (request.method === "HEAD" || upstream.status !== 200 || !(upstream.headers.get("content-type") ?? "").includes("application/json")) {
307
+ return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });
308
+ }
309
+ const parsed = await upstream.json();
310
+ const isBatch = Array.isArray(parsed);
311
+ const envelopes = isBatch ? parsed : [parsed];
312
+ const keep = new Set(getTableConfig2(entry.localTable).columns.map((column) => column.name));
313
+ const context = {
314
+ claims: { sub: decision.subject },
315
+ ...options.params ? { params: options.params } : {}
316
+ };
317
+ const rewritten = envelopes.map((envelope) => {
318
+ const value = envelope?.value;
319
+ if (value == null || typeof value !== "object")
320
+ return envelope;
321
+ const transformed = transform(value, context);
322
+ const stripped = {};
323
+ for (const [column, cell] of Object.entries(transformed)) {
324
+ if (keep.has(column))
325
+ stripped[column] = cell;
326
+ }
327
+ return { ...envelope, value: stripped };
328
+ });
329
+ return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {
330
+ status: upstream.status,
331
+ statusText: upstream.statusText,
332
+ headers
333
+ });
334
+ };
168
335
  }
169
- function getOmittedProjectedColumnsForTable(registry, shapeKey) {
170
- const entry = resolveEntryByShapeKey(registry, shapeKey);
171
- return entry ? getOmittedProjectedColumnNames(entry) : [];
336
+
337
+ // packages/server/src/circuits/engine-client.ts
338
+ class CircuitsEngineError extends Error {
339
+ status;
340
+ body;
341
+ constructor(status, body, message) {
342
+ super(message);
343
+ this.name = "CircuitsEngineError";
344
+ this.status = status;
345
+ this.body = body;
346
+ }
347
+ }
348
+ function createCircuitsEngineClient(options) {
349
+ const doFetch = options.fetch ?? fetch;
350
+ const base = options.baseUrl.replace(/\/+$/, "");
351
+ async function call(path, init) {
352
+ const headers = new Headers(init.headers);
353
+ headers.set("content-type", "application/json");
354
+ const response = await doFetch(`${base}${path}`, { ...init, headers });
355
+ const body = await response.text();
356
+ if (!response.ok) {
357
+ throw new CircuitsEngineError(response.status, body, `[pgxsinkit] circuits engine ${init.method ?? "GET"} ${path} \u2192 ${response.status}: ${body}`);
358
+ }
359
+ return body === "" ? undefined : JSON.parse(body);
360
+ }
361
+ return {
362
+ async createShape(request) {
363
+ const body = await call("/shapes", {
364
+ method: "POST",
365
+ body: JSON.stringify(request)
366
+ });
367
+ if (body === null || typeof body !== "object")
368
+ throw unusableCreate("the body", body);
369
+ if (typeof body.shapeId !== "string")
370
+ throw unusableCreate("shapeId", body.shapeId);
371
+ if (typeof body.streamPath !== "string")
372
+ throw unusableCreate("streamPath", body.streamPath);
373
+ if (typeof body.subscription !== "string" || body.subscription === "") {
374
+ throw unusableCreate("subscription", body.subscription);
375
+ }
376
+ if (typeof body.leaseSeconds !== "number")
377
+ throw unusableCreate("leaseSeconds", body.leaseSeconds);
378
+ return body;
379
+ },
380
+ async releaseShape(shapeId, subscription) {
381
+ const query = `?subscription=${encodeURIComponent(subscription)}`;
382
+ await call(`/shapes/${encodeURIComponent(shapeId)}${query}`, { method: "DELETE" });
383
+ },
384
+ async replicationState() {
385
+ const body = await call("/replication/lsn", { method: "GET" });
386
+ if (body === null || typeof body !== "object")
387
+ throw unusableBarrier("the body", body);
388
+ if (body.lsn !== null && typeof body.lsn !== "string")
389
+ throw unusableBarrier("lsn", body.lsn);
390
+ if (typeof body.pendingFlips !== "number")
391
+ throw unusableBarrier("pendingFlips", body.pendingFlips);
392
+ if (typeof body.flipFailures !== "number")
393
+ throw unusableBarrier("flipFailures", body.flipFailures);
394
+ return { lsn: body.lsn, pendingFlips: body.pendingFlips, flipFailures: body.flipFailures };
395
+ }
396
+ };
172
397
  }
173
- function getRowTransformForTable(registry, shapeKey) {
174
- return resolveEntryByShapeKey(registry, shapeKey)?.serverProjection?.rowTransform;
398
+ function unusableBarrier(field, value) {
399
+ return new Error(`[pgxsinkit] the engine's GET /replication/lsn answered with an unusable \`${field}\` (${JSON.stringify(value)}). ` + `This client requires an engine reporting the whole convergence barrier \u2014 \`lsn\`, \`pendingFlips\` and ` + `\`flipFailures\` (ADR-0056 decision 3); the engine at this URL is not the one this client targets.`);
175
400
  }
176
- function isObjectRecord(value) {
177
- return typeof value === "object" && value !== null && !Array.isArray(value);
401
+ function unusableCreate(field, value) {
402
+ return new Error(`[pgxsinkit] the engine's POST /shapes answered with an unusable \`${field}\` (${JSON.stringify(value)}). ` + `This client requires an engine that records every shape claim under a named, leased subscription \u2014 ` + `\`shapeId\`, \`streamPath\`, \`subscription\` and \`leaseSeconds\` (fork ADR-0008); the engine at this ` + `URL is not the one this client targets.`);
178
403
  }
179
- function isShapeLogEntry(value) {
180
- return isObjectRecord(value);
404
+
405
+ // packages/server/src/circuits/subscribe.ts
406
+ class CircuitsLeaseConfigError extends Error {
407
+ leaseSeconds;
408
+ ttlSeconds;
409
+ constructor(leaseSeconds, ttlSeconds) {
410
+ super(`[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` + `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` + `(${ttlSeconds}s, the \`ttlSeconds\` option). Claims are renewed on the token re-mint, so a single ` + `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` + `it. Raise ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` + `at most ${Math.floor(leaseSeconds / 2)}, or set ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` + `leases entirely.`);
411
+ this.name = "CircuitsLeaseConfigError";
412
+ this.leaseSeconds = leaseSeconds;
413
+ this.ttlSeconds = ttlSeconds;
414
+ }
415
+ }
416
+ function assertLeaseCoversTtl(leaseSeconds, ttlSeconds) {
417
+ if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds)
418
+ throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);
419
+ }
420
+ function assertClaimRecorded(handle, claim) {
421
+ if (handle.subscription === claim)
422
+ return;
423
+ throw new Error(`[pgxsinkit] the engine recorded this shape claim under \`${handle.subscription}\` rather than the ` + `subscription id it was sent (\`${claim}\`). Renewal and release are BY that id (fork ADR-0008), ` + `so an engine that renames a claim is not the one this client targets.`);
424
+ }
425
+ function compileGrant(options, claims, shapeKey, scope) {
426
+ return compileShapeRequest(options.registry, {
427
+ shapeKey,
428
+ claims,
429
+ ...scope !== undefined ? { scope } : {},
430
+ ...options.params ? { params: options.params } : {}
431
+ });
181
432
  }
182
- function rewriteRow(row, omittedColumns, rowTransform, context) {
183
- const transformed = rowTransform ? rowTransform(row, context) : row;
184
- return omittedColumns.length > 0 ? omitColumnsFromRow(transformed, omittedColumns) : transformed;
433
+ async function renewGrantClaim(engine, request, grant, ttlSeconds) {
434
+ let handle;
435
+ try {
436
+ handle = await engine.createShape({ ...request, subscription: grant.claim });
437
+ } catch (error) {
438
+ if (error instanceof CircuitsEngineError && error.status === 409) {
439
+ return { revoked: "subscription id is held by another shape; re-subscribe" };
440
+ }
441
+ throw error;
442
+ }
443
+ assertClaimRecorded(handle, grant.claim);
444
+ if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {
445
+ await engine.releaseShape(handle.shapeId, grant.claim);
446
+ return { revoked: "shape stream changed; re-subscribe" };
447
+ }
448
+ assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);
449
+ return { renewed: true };
185
450
  }
186
- function rewriteShapeLogEntries(payload, omittedColumns, rowTransform, context) {
187
- return payload.map((entry) => {
188
- if (!isShapeLogEntry(entry)) {
189
- return entry;
451
+ function expandToScopes(options, subject, shapeKey) {
452
+ const entry = resolveEntryByShapeKey(options.registry, shapeKey);
453
+ const shape = entry?.shape;
454
+ if (shape == null)
455
+ return { scopes: [undefined] };
456
+ if (readShapeTier2(shape) === "private")
457
+ return { scopes: [undefined] };
458
+ if (options.entitlements === undefined) {
459
+ return { refusal: "shared-tier shape, but this deployment configured no entitlement set" };
460
+ }
461
+ if (!options.entitlements.ready)
462
+ throw new EntitlementsUnavailableError;
463
+ const held = options.entitlements.scopesFor(subject, shapeKey);
464
+ if (held.length === 0)
465
+ return { refusal: "no entitled scopes" };
466
+ return { scopes: held };
467
+ }
468
+ async function subscribeToShapes(options, claims, requests, now) {
469
+ const subject = typeof claims?.sub === "string" ? claims.sub : null;
470
+ const granted = [];
471
+ const denied = [];
472
+ const grants = [];
473
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
474
+ for (const request of requests) {
475
+ const deny = (reason, scope) => denied.push({ shapeKey: request.shapeKey, ...scope !== undefined ? { scope } : {}, reason });
476
+ if (subject === null) {
477
+ deny("no subject");
478
+ continue;
190
479
  }
191
- let currentEntry = entry;
192
- if (isObjectRecord(entry.value)) {
193
- const nextValue = rewriteRow(entry.value, omittedColumns, rowTransform, context);
194
- if (nextValue !== entry.value) {
195
- currentEntry = { ...currentEntry, value: nextValue };
196
- }
480
+ const expanded = expandToScopes(options, subject, request.shapeKey);
481
+ if ("refusal" in expanded) {
482
+ deny(expanded.refusal);
483
+ continue;
197
484
  }
198
- if (isObjectRecord(currentEntry.old_value)) {
199
- const nextOldValue = rewriteRow(currentEntry.old_value, omittedColumns, rowTransform, context);
200
- if (nextOldValue !== currentEntry.old_value) {
201
- currentEntry = { ...currentEntry, old_value: nextOldValue };
485
+ for (const scope of expanded.scopes) {
486
+ const scoped = scope !== undefined ? { scope } : {};
487
+ const compiled = compileGrant(options, claims, request.shapeKey, scope);
488
+ if (compiled.outcome === "deny") {
489
+ deny(compiled.reason, scope);
490
+ continue;
491
+ }
492
+ if (compiled.tier === "shared" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {
493
+ deny("not entitled to this scope", scope);
494
+ continue;
495
+ }
496
+ const fp = compiled.tier === "private" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};
497
+ const claim = crypto.randomUUID();
498
+ const handle = await options.engine.createShape({ ...compiled.request, subscription: claim });
499
+ assertClaimRecorded(handle, claim);
500
+ try {
501
+ assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);
502
+ } catch (error) {
503
+ await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});
504
+ throw error;
202
505
  }
506
+ granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });
507
+ grants.push({
508
+ path: handle.streamPath,
509
+ shapeKey: request.shapeKey,
510
+ shapeId: handle.shapeId,
511
+ claim,
512
+ ...scoped,
513
+ ...fp
514
+ });
203
515
  }
204
- return currentEntry;
205
- });
206
- }
207
- function isAbortError(error) {
208
- return error instanceof Error && (error.name === "AbortError" || typeof error.code === "number" && error.code === 20);
516
+ }
517
+ if (subject === null || grants.length === 0)
518
+ return { granted, denied };
519
+ const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });
520
+ return { token, expiresAt: now + ttlSeconds, granted, denied };
209
521
  }
210
- function allowedCorsOrigin(request, cors) {
211
- return resolveCorsOrigin(request, cors.origins);
522
+ function createSubscribeHandler(options) {
523
+ return async function handleSubscribe(request) {
524
+ let body;
525
+ try {
526
+ body = await request.json();
527
+ } catch {
528
+ return Response.json({ error: "malformed body" }, { status: 400 });
529
+ }
530
+ if (!Array.isArray(body.subscriptions)) {
531
+ return Response.json({ error: "subscriptions must be an array" }, { status: 400 });
532
+ }
533
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
534
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
535
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
536
+ }
537
+ let result;
538
+ try {
539
+ result = await subscribeToShapes(options, claims, body.subscriptions, Math.floor(Date.now() / 1000));
540
+ } catch (error) {
541
+ if (error instanceof CircuitsEngineError) {
542
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
543
+ }
544
+ if (error instanceof CircuitsLeaseConfigError) {
545
+ return Response.json({ error: "sync engine lease window shorter than the token TTL" }, { status: 503 });
546
+ }
547
+ if (error instanceof EntitlementsUnavailableError) {
548
+ return Response.json({ error: "entitlements unavailable" }, { status: 503 });
549
+ }
550
+ throw error;
551
+ }
552
+ return Response.json(result);
553
+ };
212
554
  }
213
- function corsPreflightResponse(request, cors) {
214
- const headers = new Headers;
215
- const origin = allowedCorsOrigin(request, cors);
216
- if (origin) {
217
- headers.set("Access-Control-Allow-Origin", origin);
218
- headers.append("Vary", "Origin");
555
+ async function refreshStreamToken(options, claims, expiringToken, now) {
556
+ const subject = typeof claims?.sub === "string" ? claims.sub : null;
557
+ const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });
558
+ if (!verified.ok || subject === null)
559
+ return { granted: [], revoked: [] };
560
+ if (verified.claims.sub !== subject)
561
+ return { granted: [], revoked: [] };
562
+ const granted = [];
563
+ const revoked = [];
564
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
565
+ for (const grant of verified.claims.grants) {
566
+ const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};
567
+ if (grant.scope === undefined) {
568
+ const compiled2 = compileGrant(options, claims, grant.shapeKey);
569
+ if (compiled2.outcome === "deny") {
570
+ revoked.push({ shapeKey: grant.shapeKey, reason: compiled2.reason });
571
+ continue;
572
+ }
573
+ if (grant.fp === undefined) {
574
+ revoked.push({
575
+ shapeKey: grant.shapeKey,
576
+ reason: "private grant carries no fingerprint and cannot be re-authorized"
577
+ });
578
+ continue;
579
+ }
580
+ if (await fingerprintShapeRequest(compiled2.request) !== grant.fp) {
581
+ revoked.push({ shapeKey: grant.shapeKey, reason: "shape predicate changed for this subject" });
582
+ continue;
583
+ }
584
+ const renewal2 = await renewGrantClaim(options.engine, compiled2.request, grant, ttlSeconds);
585
+ if ("revoked" in renewal2) {
586
+ revoked.push({ shapeKey: grant.shapeKey, reason: renewal2.revoked });
587
+ continue;
588
+ }
589
+ granted.push(grant);
590
+ continue;
591
+ }
592
+ if (options.entitlements === undefined) {
593
+ revoked.push({
594
+ shapeKey: grant.shapeKey,
595
+ ...scoped,
596
+ reason: "shared-tier grant, but this deployment configured no entitlement set"
597
+ });
598
+ continue;
599
+ }
600
+ if (!options.entitlements.ready)
601
+ throw new EntitlementsUnavailableError;
602
+ if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {
603
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: "not entitled to this scope" });
604
+ continue;
605
+ }
606
+ const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);
607
+ if (compiled.outcome === "deny") {
608
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });
609
+ continue;
610
+ }
611
+ const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);
612
+ if ("revoked" in renewal) {
613
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });
614
+ continue;
615
+ }
616
+ granted.push(grant);
219
617
  }
220
- headers.set("Access-Control-Allow-Methods", "GET,OPTIONS");
221
- headers.set("Access-Control-Allow-Headers", request.headers.get("access-control-request-headers") ?? "authorization,apikey,content-type");
222
- headers.set("Access-Control-Max-Age", "3600");
223
- return new Response(null, { status: 204, headers });
618
+ if (granted.length === 0)
619
+ return { granted, revoked };
620
+ const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });
621
+ return { token, expiresAt: now + ttlSeconds, granted, revoked };
224
622
  }
225
- function withCorsResponseHeaders(request, response, cors) {
226
- const origin = allowedCorsOrigin(request, cors);
227
- if (!origin) {
228
- return response;
229
- }
230
- const headers = new Headers(response.headers);
231
- headers.set("Access-Control-Allow-Origin", origin);
232
- headers.append("Vary", "Origin");
233
- headers.set("Access-Control-Expose-Headers", ELECTRIC_EXPOSED_HEADERS);
234
- return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
623
+ function createRefreshHandler(options) {
624
+ return async function handleRefresh(request) {
625
+ let body;
626
+ try {
627
+ body = await request.json();
628
+ } catch {
629
+ return Response.json({ error: "malformed body" }, { status: 400 });
630
+ }
631
+ if (typeof body.token !== "string") {
632
+ return Response.json({ error: "token must be a string" }, { status: 400 });
633
+ }
634
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
635
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
636
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
637
+ }
638
+ let result;
639
+ try {
640
+ result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));
641
+ } catch (error) {
642
+ if (error instanceof EntitlementsUnavailableError) {
643
+ return Response.json({ error: "entitlements unavailable" }, { status: 503 });
644
+ }
645
+ if (error instanceof CircuitsEngineError) {
646
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
647
+ }
648
+ if (error instanceof CircuitsLeaseConfigError) {
649
+ return Response.json({ error: "sync engine lease window shorter than the token TTL" }, { status: 503 });
650
+ }
651
+ throw error;
652
+ }
653
+ return Response.json(result);
654
+ };
235
655
  }
236
- function omitColumnsFromRow(row, omittedColumns) {
237
- let changed = false;
238
- const nextRow = { ...row };
239
- for (const column of omittedColumns) {
240
- if (Object.prototype.hasOwnProperty.call(nextRow, column)) {
241
- delete nextRow[column];
242
- changed = true;
656
+ async function releaseStreamGrants(options, claims, token, now) {
657
+ const subject = typeof claims?.sub === "string" && claims.sub !== "" ? claims.sub : null;
658
+ if (subject === null)
659
+ return { refused: "unauthenticated" };
660
+ const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });
661
+ if (!verified.ok)
662
+ return { refused: verified.reason };
663
+ if (verified.claims.sub !== subject)
664
+ return { refused: "token subject does not match the caller" };
665
+ for (const grant of verified.claims.grants) {
666
+ await options.engine.releaseShape(grant.shapeId, grant.claim);
667
+ }
668
+ return { released: verified.claims.grants.length };
669
+ }
670
+ function createReleaseHandler(options) {
671
+ return async function handleRelease(request) {
672
+ let body;
673
+ try {
674
+ body = await request.json();
675
+ } catch {
676
+ return Response.json({ error: "malformed body" }, { status: 400 });
243
677
  }
244
- }
245
- return changed ? nextRow : row;
678
+ if (typeof body.token !== "string") {
679
+ return Response.json({ error: "token must be a string" }, { status: 400 });
680
+ }
681
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
682
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
683
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
684
+ }
685
+ let result;
686
+ try {
687
+ result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));
688
+ } catch (error) {
689
+ if (error instanceof CircuitsEngineError) {
690
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
691
+ }
692
+ throw error;
693
+ }
694
+ if ("refused" in result)
695
+ return Response.json({ error: result.refused }, { status: 403 });
696
+ return Response.json(result);
697
+ };
698
+ }
699
+ var subscribePath = "/sync/v1/subscribe";
700
+ var refreshPath = "/sync/v1/refresh";
701
+ var releasePath = "/sync/v1/release";
702
+ function createBarrierHandler(options) {
703
+ let cached = null;
704
+ const maxAge = options.maxAgeSeconds ?? 0;
705
+ return async function handleBarrier(request) {
706
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
707
+ if (options.resolveAuthClaims && claims === null) {
708
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
709
+ }
710
+ const now = Date.now() / 1000;
711
+ if (cached && now - cached.at < maxAge)
712
+ return Response.json(cached.body);
713
+ const state = await options.engine.replicationState();
714
+ const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };
715
+ cached = body.flipFailures > 0 ? null : { at: now, body };
716
+ return Response.json(body);
717
+ };
246
718
  }
719
+ var barrierPath = "/sync/v1/barrier";
247
720
 
248
721
  // packages/server/src/events/pgmq-queue.ts
249
722
  import { sql } from "drizzle-orm";
@@ -490,9 +963,9 @@ function eventIngestRequiresClaims(streams) {
490
963
  function createEventIngestHandler(db, registry, queue, options = {}) {
491
964
  const streams = getSyncRegistryStreams(registry) ?? {};
492
965
  const requiresClaims = eventIngestRequiresClaims(streams);
493
- const perfNow2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
966
+ const perfNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
494
967
  const handle = async (request) => {
495
- const started = options.logTimings ? perfNow2() : 0;
968
+ const started = options.logTimings ? perfNow() : 0;
496
969
  let authMs = 0;
497
970
  let enqueueMs = 0;
498
971
  const finish = (response, eventCount) => {
@@ -501,7 +974,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
501
974
  route: "events",
502
975
  authMs: Math.round(authMs),
503
976
  enqueueMs: Math.round(enqueueMs),
504
- totalMs: Math.round(perfNow2() - started),
977
+ totalMs: Math.round(perfNow() - started),
505
978
  events: eventCount,
506
979
  status: response.status
507
980
  }));
@@ -531,10 +1004,10 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
531
1004
  return finish(errorResponse(`Invalid batch event request: ${framing.error.message}`, 400), 0);
532
1005
  }
533
1006
  const events = framing.data.events;
534
- const authStart = options.logTimings ? perfNow2() : 0;
1007
+ const authStart = options.logTimings ? perfNow() : 0;
535
1008
  const resolvedClaims = await options.resolveAuthClaims?.(request);
536
1009
  if (options.logTimings)
537
- authMs = perfNow2() - authStart;
1010
+ authMs = perfNow() - authStart;
538
1011
  if (requiresClaims && !isPlainObject(resolvedClaims)) {
539
1012
  return finish(errorResponse("Event streams with claim-stamped identity require validated JWT claims", 401), events.length);
540
1013
  }
@@ -645,7 +1118,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
645
1118
  events: streamEvents
646
1119
  }));
647
1120
  if (messages.length > 0) {
648
- const enqueueStart = options.logTimings ? perfNow2() : 0;
1121
+ const enqueueStart = options.logTimings ? perfNow() : 0;
649
1122
  try {
650
1123
  await db.transaction(async (tx) => {
651
1124
  await queue.enqueueBatch(messages, tx);
@@ -657,7 +1130,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
657
1130
  }), events.length);
658
1131
  }
659
1132
  if (options.logTimings)
660
- enqueueMs = perfNow2() - enqueueStart;
1133
+ enqueueMs = perfNow() - enqueueStart;
661
1134
  if (options.onEventsEnqueued) {
662
1135
  try {
663
1136
  options.onEventsEnqueued({ streams: [...byStream.keys()] });
@@ -673,7 +1146,7 @@ function createEventIngestHandler(db, registry, queue, options = {}) {
673
1146
 
674
1147
  // packages/server/src/mutations/route.ts
675
1148
  import { and, eq, sql as sql3 } from "drizzle-orm";
676
- import { getTableConfig as getTableConfig2 } from "drizzle-orm/pg-core";
1149
+ import { getTableConfig as getTableConfig4 } from "drizzle-orm/pg-core";
677
1150
  import { getColumns as getColumns2 } from "drizzle-orm/utils";
678
1151
  import { createSchemaFactory } from "drizzle-orm/zod";
679
1152
  import {
@@ -780,7 +1253,7 @@ function asSqlState(value) {
780
1253
 
781
1254
  // packages/server/src/mutations/plpgsql-apply.ts
782
1255
  import { getTableName, sql as sql2 } from "drizzle-orm";
783
- import { getTableConfig } from "drizzle-orm/pg-core";
1256
+ import { getTableConfig as getTableConfig3 } from "drizzle-orm/pg-core";
784
1257
  import { getColumns } from "drizzle-orm/utils";
785
1258
  import {
786
1259
  buildRoleGuardedStatement,
@@ -860,7 +1333,7 @@ function resolveManagedFields(entry) {
860
1333
  }
861
1334
  function buildTableBranch(entry) {
862
1335
  const tableName = getTableName(entry.table);
863
- const { schema } = getTableConfig(entry.table);
1336
+ const { schema } = getTableConfig3(entry.table);
864
1337
  const qualifiedTableName = qualifyIdent(schema, tableName);
865
1338
  const columns = getColumns(entry.table);
866
1339
  const projectedColumns = getProjectedColumns(entry);
@@ -1328,13 +1801,13 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1328
1801
  const resolvedApplyFunctionSchema = resolveApplyFunctionSchema(applyFunctionRenderOptions.functionSchema);
1329
1802
  const applyInvocationOptions = resolvedApplyFunctionSchema ? { functionSchema: resolvedApplyFunctionSchema } : {};
1330
1803
  const expectedFingerprint = expectedApplyFingerprint(registry, applyFunctionRenderOptions);
1331
- const perfNow2 = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1804
+ const perfNow = () => typeof performance !== "undefined" ? performance.now() : Date.now();
1332
1805
  const withTiming = (route, handler) => {
1333
1806
  if (!logTimings) {
1334
1807
  return (request) => handler(request);
1335
1808
  }
1336
1809
  return async (request) => {
1337
- const start = perfNow2();
1810
+ const start = perfNow();
1338
1811
  const timing = {
1339
1812
  handlerStart: start,
1340
1813
  preTxMs: 0,
@@ -1350,7 +1823,7 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1350
1823
  txOpenMs: Math.round(timing.txOpenMs),
1351
1824
  authMs: Math.round(timing.authMs),
1352
1825
  applyMs: Math.round(timing.applyMs),
1353
- totalMs: Math.round(perfNow2() - start),
1826
+ totalMs: Math.round(perfNow() - start),
1354
1827
  mutations: timing.mutations,
1355
1828
  status: response.status
1356
1829
  }));
@@ -1359,12 +1832,12 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1359
1832
  };
1360
1833
  const stampPreTx = (timing) => {
1361
1834
  if (timing)
1362
- timing.preTxMs = perfNow2() - timing.handlerStart;
1363
- return timing ? perfNow2() : 0;
1835
+ timing.preTxMs = perfNow() - timing.handlerStart;
1836
+ return timing ? perfNow() : 0;
1364
1837
  };
1365
1838
  const stampTxOpen = (timing, txCallAt) => {
1366
1839
  if (timing)
1367
- timing.txOpenMs = perfNow2() - txCallAt;
1840
+ timing.txOpenMs = perfNow() - txCallAt;
1368
1841
  };
1369
1842
  const startupReady = () => {
1370
1843
  if (!startupReadyPromise) {
@@ -1502,10 +1975,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1502
1975
  const shouldApplyRlsContext = rlsAuthContextRequired;
1503
1976
  let userClaims = {};
1504
1977
  if (shouldApplyRlsContext) {
1505
- const authStart = timing ? perfNow2() : 0;
1978
+ const authStart = timing ? perfNow() : 0;
1506
1979
  const resolvedClaims = await resolveAuthClaims?.(request);
1507
1980
  if (timing)
1508
- timing.authMs = perfNow2() - authStart;
1981
+ timing.authMs = perfNow() - authStart;
1509
1982
  if (!isPlainObject2(resolvedClaims)) {
1510
1983
  await logOperationSafely(db, operationsLogConfig, {
1511
1984
  tableName: null,
@@ -1524,10 +1997,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1524
1997
  }
1525
1998
  const batchRequest = sanitizeRestrictedFields(body, registry);
1526
1999
  await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
1527
- const applyStart = timing ? perfNow2() : 0;
2000
+ const applyStart = timing ? perfNow() : 0;
1528
2001
  const conflicts = await executePlpgsqlBatch(tx, batchRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint, applyInvocationOptions);
1529
2002
  if (timing)
1530
- timing.applyMs = perfNow2() - applyStart;
2003
+ timing.applyMs = perfNow() - applyStart;
1531
2004
  if (shouldApplyRlsContext) {
1532
2005
  await tx.execute(sql3`RESET ROLE`);
1533
2006
  }
@@ -1666,10 +2139,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1666
2139
  const shouldApplyRlsContext = rlsAuthContextRequired;
1667
2140
  let userClaims = {};
1668
2141
  if (shouldApplyRlsContext) {
1669
- const authStart = timing ? perfNow2() : 0;
2142
+ const authStart = timing ? perfNow() : 0;
1670
2143
  const resolvedClaims = await resolveAuthClaims?.(request);
1671
2144
  if (timing)
1672
- timing.authMs = perfNow2() - authStart;
2145
+ timing.authMs = perfNow() - authStart;
1673
2146
  if (!isPlainObject2(resolvedClaims)) {
1674
2147
  await logOperationSafely(db, operationsLogConfig, {
1675
2148
  tableName: null,
@@ -1688,10 +2161,10 @@ function createMutationHandler(db, registry, operationsLogConfig, operationsLogR
1688
2161
  }
1689
2162
  const unitRequest = sanitizeRestrictedFields(body, registry);
1690
2163
  await tx.execute(sql3`SET CONSTRAINTS ALL DEFERRED`);
1691
- const applyStart = timing ? perfNow2() : 0;
2164
+ const applyStart = timing ? perfNow() : 0;
1692
2165
  const conflicts = await executePlpgsqlBatch(tx, unitRequest, requestPath, false, shouldApplyRlsContext, userClaims, expectedFingerprint, applyInvocationOptions);
1693
2166
  if (timing)
1694
- timing.applyMs = perfNow2() - applyStart;
2167
+ timing.applyMs = perfNow() - applyStart;
1695
2168
  if (shouldApplyRlsContext) {
1696
2169
  await tx.execute(sql3`RESET ROLE`);
1697
2170
  }
@@ -1880,7 +2353,7 @@ function getErrorStringProperty(error, key) {
1880
2353
  return typeof value === "string" && value.length > 0 ? value : null;
1881
2354
  }
1882
2355
  function isRlsAuthContextRequired(registry) {
1883
- return Object.values(registry).some((entry) => getTableConfig2(entry.table).policies.length > 0 || (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authClaim"));
2356
+ return Object.values(registry).some((entry) => getTableConfig4(entry.table).policies.length > 0 || (entry.governance?.managedFields ?? []).some((field) => field.strategy === "authClaim"));
1884
2357
  }
1885
2358
 
1886
2359
  class UnauthorizedBatchMutationError extends Error {
@@ -2100,6 +2573,15 @@ async function ensureOperationsLogSchema(db, config) {
2100
2573
  }
2101
2574
  }
2102
2575
 
2576
+ // packages/server/src/cors-origin.ts
2577
+ function resolveCorsOrigin(request, origins) {
2578
+ const origin = request.headers.get("origin");
2579
+ if (!origin) {
2580
+ return null;
2581
+ }
2582
+ return origins.includes("*") || origins.includes(origin) ? origin : null;
2583
+ }
2584
+
2103
2585
  // packages/server/src/router.ts
2104
2586
  class FetchRouter {
2105
2587
  #routes = new Map;
@@ -2568,10 +3050,9 @@ function createSyncServer(options) {
2568
3050
  }
2569
3051
  operationsLogReady = Promise.resolve();
2570
3052
  }
2571
- const shapeProxyPath = options.shapeProxyPath ?? "/api/shape";
2572
3053
  const corsScopes = [{ prefix: "/api/" }];
2573
- if (options.electricUrl) {
2574
- corsScopes.push({ exact: shapeProxyPath });
3054
+ if (options.readPath) {
3055
+ corsScopes.push({ prefix: "/sync/v1/" });
2575
3056
  }
2576
3057
  router.setCors({
2577
3058
  origins: options.allowedOrigins ?? defaultAllowedOrigins,
@@ -2611,20 +3092,28 @@ function createSyncServer(options) {
2611
3092
  router.post(path, eventHandler);
2612
3093
  }
2613
3094
  }
2614
- if (options.electricUrl) {
2615
- const electricUrl = options.electricUrl;
3095
+ if (options.readPath) {
3096
+ const readPath = options.readPath;
2616
3097
  const resolveAuthClaims = options.resolveAuthClaims;
2617
- const resolveShapeParams = options.resolveShapeParams;
2618
- router.get(shapeProxyPath, async (request) => {
2619
- const claims = resolveAuthClaims ? await resolveAuthClaims(request) : null;
2620
- const extraParams = resolveShapeParams?.(request);
2621
- return proxyElectricShapeRequest(request, claims, {
2622
- registry: options.registry,
2623
- electricUrl,
2624
- ...extraParams ? { extraParams } : {},
2625
- ...options.logTimings ? { logTimings: true } : {}
2626
- });
2627
- });
3098
+ if (resolveAuthClaims === undefined) {
3099
+ throw new Error("[pgxsinkit] createSyncServer: `readPath` was configured without `resolveAuthClaims`. The native " + "read path mints a per-subject stream token, so it cannot serve a deployment that has no way to " + "resolve a subject. Provide `resolveAuthClaims`, or drop `readPath` for a write-only deployment.");
3100
+ }
3101
+ const subscribeOptions = {
3102
+ registry: options.registry,
3103
+ engine: readPath.engine,
3104
+ ...readPath.entitlements ? { entitlements: readPath.entitlements } : {},
3105
+ key: readPath.key,
3106
+ ...readPath.ttlSeconds !== undefined ? { ttlSeconds: readPath.ttlSeconds } : {},
3107
+ resolveAuthClaims
3108
+ };
3109
+ router.post(subscribePath, createSubscribeHandler(subscribeOptions));
3110
+ router.post(refreshPath, createRefreshHandler(subscribeOptions));
3111
+ router.post(releasePath, createReleaseHandler({ engine: readPath.engine, key: readPath.key, resolveAuthClaims }));
3112
+ router.get(barrierPath, createBarrierHandler({
3113
+ engine: readPath.engine,
3114
+ resolveAuthClaims,
3115
+ ...readPath.barrierMaxAgeSeconds !== undefined ? { maxAgeSeconds: readPath.barrierMaxAgeSeconds } : {}
3116
+ }));
2628
3117
  }
2629
3118
  const fetch2 = router.fetch;
2630
3119
  return {
@@ -2701,42 +3190,68 @@ function resolveOperationsLogConfig(options) {
2701
3190
  };
2702
3191
  }
2703
3192
  export {
2704
- resolveEventIdentity,
2705
- renderPgxsinkitUtilitiesMigration,
2706
- renderEventLaneMigration,
2707
- readSqlState,
2708
- proxyElectricShapeRequest,
2709
- operationsLogTable,
2710
- operationsLogRegclassTarget,
2711
- expectedApplyFingerprint,
2712
- eventStreamQueueName,
2713
- eventLaneStreamNames,
2714
- eventLaneDdlFingerprint,
2715
- eventIngestRequiresClaims,
2716
- ensureOperationsLogSchema,
2717
- defineEventConsumer,
2718
- createSyncServer,
2719
- createPgmqEventQueue,
2720
- createMutationHandler,
2721
- createEventIngestHandler,
2722
- computeEventPollWaitMs,
2723
- buildRegistrySchema,
2724
- buildPlpgsqlBatchFunctionDdl,
2725
- batchMutationPaths,
2726
- authoritativeMutationPaths,
2727
- assertEventQueueReceipts,
2728
- PGMQ_DEAD_LETTER_KEY,
2729
- MalformedEventQueueMessageError,
2730
- FetchRouter,
2731
- EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,
2732
- EVENT_LANE_FINGERPRINT_PREFIX,
2733
- DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
2734
- DEFAULT_EVENT_POLL_FLOOR_MS,
2735
- DEFAULT_EVENT_POLL_FACTOR,
2736
- DEFAULT_EVENT_POLL_CEILING_MS,
2737
- DEFAULT_EVENT_MAX_ATTEMPTS,
3193
+ CircuitsEngineError,
3194
+ CircuitsLeaseConfigError,
3195
+ DEFAULT_EVENT_CONSUMER_BATCH_SIZE,
2738
3196
  DEFAULT_EVENT_DRAIN_BUDGET_MS,
2739
- DEFAULT_EVENT_CONSUMER_BATCH_SIZE
3197
+ DEFAULT_EVENT_MAX_ATTEMPTS,
3198
+ DEFAULT_EVENT_POLL_CEILING_MS,
3199
+ DEFAULT_EVENT_POLL_FACTOR,
3200
+ DEFAULT_EVENT_POLL_FLOOR_MS,
3201
+ DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,
3202
+ DEFAULT_STREAM_TOKEN_TTL_SECONDS,
3203
+ EVENT_LANE_FINGERPRINT_PREFIX,
3204
+ EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,
3205
+ EntitlementsUnavailableError,
3206
+ FetchRouter,
3207
+ MalformedEventQueueMessageError,
3208
+ PGMQ_DEAD_LETTER_KEY,
3209
+ STREAM_READ_EXPOSED_HEADERS,
3210
+ assertEventQueueReceipts,
3211
+ authoritativeMutationPaths,
3212
+ authorizeStreamRead,
3213
+ barrierPath,
3214
+ batchMutationPaths,
3215
+ buildPlpgsqlBatchFunctionDdl,
3216
+ buildRegistrySchema,
3217
+ compileShapeRequest,
3218
+ computeEventPollWaitMs,
3219
+ createBarrierHandler,
3220
+ createCircuitsEngineClient,
3221
+ createEventIngestHandler,
3222
+ createMutationHandler,
3223
+ createPgmqEventQueue,
3224
+ createRefreshHandler,
3225
+ createReleaseHandler,
3226
+ createStreamGate,
3227
+ createSubscribeHandler,
3228
+ createSyncServer,
3229
+ defineEventConsumer,
3230
+ ensureOperationsLogSchema,
3231
+ eventIngestRequiresClaims,
3232
+ eventLaneDdlFingerprint,
3233
+ eventLaneStreamNames,
3234
+ eventStreamQueueName,
3235
+ expectedApplyFingerprint,
3236
+ findGrant,
3237
+ fingerprintShapeRequest,
3238
+ importStreamTokenKey,
3239
+ mintStreamToken,
3240
+ operationsLogRegclassTarget,
3241
+ operationsLogTable,
3242
+ readSqlState,
3243
+ readStreamToken,
3244
+ refreshPath,
3245
+ refreshStreamToken,
3246
+ releasePath,
3247
+ releaseStreamGrants,
3248
+ renderEventLaneMigration,
3249
+ renderPgxsinkitUtilitiesMigration,
3250
+ resolveEntryByShapeKey,
3251
+ resolveEventIdentity,
3252
+ subscribePath,
3253
+ subscribeToShapes,
3254
+ verifyStreamToken
2740
3255
  };
2741
3256
 
2742
- //# debugId=5CEE23A5C2F9E5C264756E2164756E21
3257
+ //# debugId=D6ED29C75B567CF464756E2164756E21