@pgxsinkit/server 0.5.1 → 0.5.2

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.
@@ -72,7 +72,7 @@ export interface StreamGateOptions {
72
72
  entitlements?: EntitlementSet;
73
73
  /**
74
74
  * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the
75
- * same value the engine is given as `ELECTRIC_CIRCUITS_DS_URL`, since both address the same paths.
75
+ * same value the engine is given as `CIRCUITS_DS_URL`, since both address the same paths.
76
76
  */
77
77
  durableStreamsUrl: string;
78
78
  /**
@@ -61,7 +61,7 @@ export interface SubscribeOptions {
61
61
  *
62
62
  * The control plane renews every live claim on exactly one cadence: the token re-mint, which the
63
63
  * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The
64
- * engine releases a claim not renewed within `leaseSeconds` (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`).
64
+ * engine releases a claim not renewed within `leaseSeconds` (`CIRCUITS_SHAPE_IDLE_SECS`).
65
65
  * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a
66
66
  * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The
67
67
  * factor of two is the margin for exactly one missed refresh.
@@ -71,7 +71,7 @@ export interface SubscribeOptions {
71
71
  * you" — and never a denial: a client told it lost entitlement truncates its rows.
72
72
  */
73
73
  export declare class CircuitsLeaseConfigError extends Error {
74
- /** The engine's `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
74
+ /** The engine's `CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
75
75
  readonly leaseSeconds: number;
76
76
  /** The stream-token TTL this control plane is configured with. */
77
77
  readonly ttlSeconds: number;
@@ -1 +1 @@
1
- {"version":3,"file":"subscribe.d.ts","sourceRoot":"","sources":["../../src/circuits/subscribe.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,SAAS,EACd,KAAK,cAAc,EAEnB,KAAK,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S,CAAC;CAChB,GAAG;IACF,iBAAiB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,CAAC;CACxF,aAE4C,OAAO,KAAG,OAAO,CAAC,QAAQ,CAAC,CAkCzE;AAED,2DAA2D;AAC3D,eAAO,MAAM,aAAa,uBAAuB,CAAC;AAClD,eAAO,MAAM,WAAW,qBAAqB,CAAC;AAC9C,eAAO,MAAM,WAAW,qBAAqB,CAAC;AAE9C;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE;IAC5C,MAAM,EAAE,oBAAoB,CAAC;IAC7B,iBAAiB,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,SAAS,GAAG,IAAI,CAAC;IACvF,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB,aAI8C,OAAO,KAAG,OAAO,CAAC,QAAQ,CAAC,CAgBzE;AAED,eAAO,MAAM,WAAW,qBAAqB,CAAC"}
@@ -56,7 +56,7 @@ export interface CircuitsShapeHandle {
56
56
  subscription: string;
57
57
  /**
58
58
  * How long this subscription may go unrenewed before the engine releases it
59
- * (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, default 1800). `0` means leases never lapse, because that
59
+ * (`CIRCUITS_SHAPE_IDLE_SECS`, default 1800). `0` means leases never lapse, because that
60
60
  * setting also disables dormancy.
61
61
  *
62
62
  * Reported rather than guessed: the renewal cadence is the deployment's to set, and a control plane
package/dist/index.js CHANGED
@@ -425,7 +425,7 @@ class CircuitsLeaseConfigError extends Error {
425
425
  leaseSeconds;
426
426
  ttlSeconds;
427
427
  constructor(leaseSeconds, ttlSeconds) {
428
- 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.`);
428
+ super(`[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` + `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 CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` + `at most ${Math.floor(leaseSeconds / 2)}, or set CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` + `leases entirely.`);
429
429
  this.name = "CircuitsLeaseConfigError";
430
430
  this.leaseSeconds = leaseSeconds;
431
431
  this.ttlSeconds = ttlSeconds;
@@ -3290,4 +3290,4 @@ export {
3290
3290
  verifyStreamToken
3291
3291
  };
3292
3292
 
3293
- //# debugId=51F8EC2D39BDA31B64756E2164756E21
3293
+ //# debugId=A99B60012F83C2B064756E2164756E21
package/dist/index.js.map CHANGED
@@ -3,9 +3,9 @@
3
3
  "sources": ["../src/index.ts", "../src/circuits/subscribe.ts", "../src/circuits/compile.ts", "../src/circuits/edge.ts", "../src/circuits/stream-token.ts", "../src/circuits/engine-client.ts", "../src/events/pgmq-queue.ts", "../src/events/queue.ts", "../src/events/route.ts", "../src/events/identity.ts", "../src/mutations/route.ts", "../src/operations-log/schema.ts", "../src/operations-log/writer.ts", "../src/sql-state.ts", "../src/mutations/plpgsql-apply.ts", "../src/operations-log/ddl.ts", "../src/cors-origin.ts", "../src/router.ts", "../src/migrations/utilities.ts", "../src/events/consumer.ts", "../src/events/ddl.ts"],
4
4
  "sourcesContent": [
5
5
  "import type { PgAsyncDatabase, PgQueryResultHKT } from \"drizzle-orm/pg-core\";\n\nimport type {\n JwtClaims,\n RegistryRelations,\n RegistryTables,\n SyncRuntimeStatus,\n SyncServerAddress,\n SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\nimport { batchEventPaths, getSyncRegistryStreams } from \"@pgxsinkit/contracts\";\n\nimport type { EntitlementSet } from \"./circuits/edge\";\nimport type { CircuitsEngineClient } from \"./circuits/engine-client\";\nimport {\n barrierPath,\n createBarrierHandler,\n createRefreshHandler,\n createReleaseHandler,\n createSubscribeHandler,\n refreshPath,\n releasePath,\n subscribePath,\n} from \"./circuits/subscribe\";\nimport { createPgmqEventQueue } from \"./events/pgmq-queue\";\nimport type { EventQueue } from \"./events/queue\";\nimport { createEventIngestHandler, type EventGate, type EventsEnqueuedHook } from \"./events/route\";\nimport {\n authoritativeMutationPaths,\n batchMutationPaths,\n createMutationHandler,\n type StartupVerificationMode,\n} from \"./mutations/route\";\nimport { ensureOperationsLogSchema } from \"./operations-log/ddl\";\nimport type { OperationsLogConfig } from \"./operations-log/types\";\nimport { FetchRouter, type CorsScope } from \"./router\";\n\nconst defaultAllowedOrigins = [\"http://localhost:5173\", \"http://localhost:5174\"];\n\ninterface BunServerHandle {\n stop: () => void;\n}\n\ninterface BunNamespace {\n serve: (options: {\n port: number;\n hostname?: string;\n idleTimeout?: number;\n fetch: (request: Request) => Response | Promise<Response>;\n }) => BunServerHandle;\n}\n\n/**\n * How the operations-log table's presence is resolved at startup (ADR-0030 decision 3):\n * - `\"probe\"` (default): the safe degradation posture (ADR-0030) — one query ensures/confirms the table,\n * and logging is disabled at runtime (with a warning) if it is absent, so a missing table degrades\n * gracefully instead of failing writes.\n * - `\"enabled\"`: assume the table exists — NO query. If it is actually absent, writes then fail loudly.\n * - `\"disabled\"`: turn logging off with NO query.\n *\n * `\"enabled\" | \"disabled\"` are the serverless posture: paired with `startupVerification: \"deploy-time\"`,\n * a fresh worker sends zero queries before the mutation transaction itself.\n */\nexport type OperationsLogStartupMode = \"probe\" | \"enabled\" | \"disabled\";\n\n/**\n * The `deployment` profile owns the server's startup query posture (ADR-0030 decision 3). Its defaults\n * are the safe degradation posture — probe-and-verify at startup — so a long-lived host that never sets\n * it still verifies and degrades gracefully; serverless / per-request workers set\n * `{ startupVerification: \"deploy-time\", operationsLog: \"enabled\" | \"disabled\" }` for a\n * zero-startup-query first write.\n */\nexport interface DeploymentProfile {\n /** Governs ONLY the RLS auth-helper verify now (apply-fn drift is self-verifying). Default `\"in-process\"`. */\n startupVerification?: StartupVerificationMode;\n /** How the operations-log table presence is resolved. Default `\"probe\"`. */\n operationsLog?: OperationsLogStartupMode;\n}\n\nexport interface CreateSyncServerOptions<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n registry: TRegistry;\n db: TDb;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n /**\n * When set, the server serves the NATIVE read path's control plane (ADR-0055): subscribe, stream-token\n * re-mint, and the engine convergence barrier. Without it, none of those routes is registered and the\n * deployment is write-only.\n *\n * They share the single `resolveAuthClaims` adapter with the write path (ADR-0003), so read and write\n * authorization cannot diverge.\n */\n readPath?: {\n /** The Circuits engine's control API — never client-reachable; only this process calls it. */\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the shared tier. Omit when the registry declares no shared\n * shape — a shared subscription is then refused with that reason rather than silently allowed.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute token lifetime. */\n ttlSeconds?: number;\n /** How long the barrier answer may be cached. Default 0 — see `createBarrierHandler`. */\n barrierMaxAgeSeconds?: number;\n /** Optional per-request extra params passed to the private tier's row filters. */\n resolveShapeParams?: (request: Request) => Record<string, unknown> | undefined;\n };\n operationsLog?: {\n enabled?: boolean;\n };\n /** Health check endpoint. Enabled by default at `/health`; `false` disables it, `{ path }` relocates it. */\n healthCheck?: boolean | { path: string };\n port?: number;\n host?: string;\n idleTimeoutSeconds?: number;\n allowedOrigins?: string[];\n onStatusChange?: (status: SyncRuntimeStatus) => void;\n /**\n * The startup query posture (ADR-0030). The apply function now verifies its own ADR-0018 fingerprint\n * in-body on every call (SQLSTATE `PXS01` on drift), so there is no startup drift check to configure;\n * this governs only the RLS auth-helper verify and the operations-log presence resolution. Defaults\n * are the safe degradation posture (ADR-0030). See {@link DeploymentProfile}.\n */\n deployment?: DeploymentProfile;\n /**\n * The **Event lane**'s consent/entitlement gate (ADR-0053 decision 1): the lane's one function, and so an\n * option here rather than a registry field (the registry stays declarative data only). Called once per\n * event, after its payload validated and its identity resolved, and before anything is enqueued; a refusal\n * is a per-event `refused` verdict. Absent → every well-formed event is allowed. See {@link EventGate}.\n */\n eventGate?: EventGate;\n /**\n * Fired after an ingest request ENQUEUED at least one sub-batch (ADR-0053 amendment, 2026-08-02): the\n * deployment-agnostic seam a SERVERLESS deployment uses to nudge whatever endpoint runs the consumer's\n * `drainOnce()`, so an interactive append drains in milliseconds instead of waiting for the next\n * scheduled tick. Fire-and-forget — it is called after the commit, its throw is caught and warn-logged,\n * and the scheduled sweep (not the nudge) is the delivery guarantee. Absent → nothing is nudged, which is\n * right for a deployment hosting the long-lived runner. See {@link EventsEnqueuedHook}.\n */\n onEventsEnqueued?: EventsEnqueuedHook;\n /**\n * The Event lane's queue backend. Defaults to the shipped pgmq backend over this server's own `db`\n * (`createPgmqEventQueue`), which is what makes an enqueue join the endpoint's transaction. Override it to\n * run the lane on another backend, or to substitute a fake in tests.\n */\n eventQueue?: EventQueue;\n /**\n * Opt-in per-request timing log (default false). When on, each mutation and shape-proxy request emits\n * one compact `[pgxsinkit-timing]` line with an ISO-8601(ms, UTC) timestamp and phase durations, for\n * attributing wall-clock latency against the client's `syncDebug` lines. Off by default — a pure\n * diagnostic surface that adds no standing query or latency when unset.\n */\n logTimings?: boolean;\n /**\n * The roles the INSTALLED apply function was generated with (`pgxsinkit-generate\n * --grant-execute-to <role>`, ADR-0054). Default `[]` — owner-only, the default the CLI generates.\n *\n * It is not a grant this server performs; it is how the server reproduces the artifact's ADR-0018\n * fingerprint, which hashes the ACL along with the rest of the body. Generate with a grant and leave\n * this unset and every write fails `PXS01` (stale artifact) — so the two lists must stay identical.\n */\n applyFunctionGrantExecuteTo?: readonly string[];\n /**\n * The schema the INSTALLED apply function lives in (`pgxsinkit-generate --function-schema <schema>`).\n * Default: unset — the artifact is generated unqualified and resolved through the connection's\n * `search_path`.\n *\n * It does two things at once, which is why one option drives both: the schema is part of the\n * fingerprinted body (the function names itself in its own self-check), AND it is how this server\n * QUALIFIES the call. Generate with `--function-schema` and leave this unset and the call goes out\n * unqualified — which either finds nothing (`42883`) or, worse, finds a same-named function elsewhere\n * on the `search_path` that then fails `PXS01` against a fingerprint it does not carry. The two must\n * name the same schema.\n */\n applyFunctionSchema?: string;\n}\n\nexport interface ServerDiagnostics<TRegistry extends SyncTableRegistry> {\n tables: Array<keyof TRegistry & string>;\n modes: Record<string, TRegistry[keyof TRegistry][\"mode\"]>;\n}\n\nexport interface SyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n> {\n drizzle: TDb;\n fetch: (request: Request) => Promise<Response>;\n request: (path: string, init?: RequestInit) => Promise<Response>;\n start: () => Promise<void>;\n stop: () => Promise<void>;\n status: SyncRuntimeStatus;\n address: SyncServerAddress | null;\n diagnostics: () => ServerDiagnostics<TRegistry>;\n}\n\nexport function createSyncServer<\n TRegistry extends SyncTableRegistry,\n TDb extends PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>> = PgAsyncDatabase<\n PgQueryResultHKT,\n RegistryRelations<TRegistry>\n >,\n>(options: CreateSyncServerOptions<TRegistry, TDb>): SyncServer<TRegistry, TDb> {\n const db = options.db;\n const router = new FetchRouter();\n let bunServer: BunServerHandle | undefined;\n\n const status: SyncRuntimeStatus = {\n phase: \"ready\",\n isRunning: false,\n };\n\n let address: SyncServerAddress | null = null;\n const operationsLogConfig = resolveOperationsLogConfig(options.operationsLog);\n const operationsLogStartup = options.deployment?.operationsLog ?? \"probe\";\n // ADR-0030: how operations_log presence is resolved decides whether startup issues a query at all.\n // - \"probe\" (default): thread the presence probe into the effective config. operations_log is an\n // *optional* feature (default-enabled), so if logging was requested but the table is absent, disable\n // it at runtime rather than letting every write fail on a missing table — the documented degradation\n // (ensureOperationsLogSchema warns and returns `false`). The route awaits `operationsLogReady` before\n // any logOperation, so the corrected flag is in effect by the time logging runs, and the route holds\n // this same config object. (Board dogfooding: discarding this boolean 500'd every mutation on a\n // missing optional table.)\n // - \"enabled\": assume the table exists — NO query; logging stays on (an actual absence then fails\n // writes loudly, by design). \"disabled\": logging off — NO query.\n let operationsLogReady: Promise<void>;\n if (operationsLogStartup === \"probe\") {\n operationsLogReady = ensureOperationsLogSchema(db, operationsLogConfig).then((present) => {\n operationsLogConfig.enabled = operationsLogConfig.enabled && present;\n });\n } else {\n if (operationsLogStartup === \"disabled\") {\n operationsLogConfig.enabled = false;\n }\n operationsLogReady = Promise.resolve();\n }\n\n // CORS covers the canonical /api/* routes, plus the native control plane's own /sync/v1/* prefix.\n const corsScopes: CorsScope[] = [{ prefix: \"/api/\" }];\n if (options.readPath) {\n corsScopes.push({ prefix: \"/sync/v1/\" });\n }\n router.setCors(\n {\n origins: options.allowedOrigins ?? defaultAllowedOrigins,\n allowMethods: [\"GET\", \"POST\", \"OPTIONS\"],\n // `apikey`: a deployment gateway (Supabase) expects it on every request, so the browser client\n // sends it; it must be allowed in the preflight even though the server itself ignores it.\n allowHeaders: [\"Content-Type\", \"Authorization\", \"apikey\"],\n },\n corsScopes,\n );\n\n router.setErrorHandler((error) => {\n status.phase = \"degraded\";\n status.lastError = error instanceof Error ? error.message : \"Unexpected error\";\n options.onStatusChange?.(status);\n\n if (isValidationError(error)) {\n return Response.json({ message: \"Validation failed\", issues: error.issues }, { status: 400 });\n }\n\n return Response.json({ message: error instanceof Error ? error.message : \"Unexpected error\" }, { status: 500 });\n });\n\n const healthCheckPath = resolveHealthCheckPath(options.healthCheck, true);\n if (healthCheckPath) {\n router.get(healthCheckPath, () => Response.json({ ok: true }));\n }\n\n // The single mutation ingress point — all writes go through POST /api/mutations.\n const mutationHandlers = createMutationHandler(\n db,\n options.registry,\n operationsLogConfig,\n operationsLogReady,\n options.resolveAuthClaims,\n options.deployment?.startupVerification ?? \"in-process\",\n options.logTimings ?? false,\n options.applyFunctionGrantExecuteTo ?? [],\n options.applyFunctionSchema,\n );\n for (const path of batchMutationPaths) {\n router.post(path, mutationHandlers.batch);\n }\n for (const path of authoritativeMutationPaths) {\n router.post(path, mutationHandlers.authoritative);\n }\n\n // The Event lane's ingestion endpoint (ADR-0053 decision 3), mounted ONLY when the registry registers at\n // least one Event stream — a registry without streams has no event lane, and the path stays a 404. Nothing\n // is probed or provisioned here: the queues are deploy-time DDL (`pgxsinkit-generate --events`), so the\n // route preserves the zero-startup-query posture.\n const eventStreams = getSyncRegistryStreams(options.registry);\n if (eventStreams && Object.keys(eventStreams).length > 0) {\n const eventQueue = options.eventQueue ?? createPgmqEventQueue({ db });\n const eventHandler = createEventIngestHandler(db, options.registry, eventQueue, {\n ...(options.resolveAuthClaims ? { resolveAuthClaims: options.resolveAuthClaims } : {}),\n ...(options.eventGate ? { eventGate: options.eventGate } : {}),\n ...(options.onEventsEnqueued ? { onEventsEnqueued: options.onEventsEnqueued } : {}),\n logTimings: options.logTimings ?? false,\n });\n for (const path of batchEventPaths) {\n router.post(path, eventHandler);\n }\n }\n\n // The native control plane (ADR-0055). It shares the same resolveAuthClaims adapter as the write\n // path, so read and write authorization can never diverge (ADR-0003).\n //\n // Note what is NOT here: any route that serves shape DATA. Reads terminate on durable-streams\n // through the edge, which is the whole point of the topology — this process is asked once, at\n // subscribe time, and is then out of the read path entirely.\n if (options.readPath) {\n const readPath = options.readPath;\n const resolveAuthClaims = options.resolveAuthClaims;\n // Refused at construction, not at the first subscribe. Every read is bound to a subject in both\n // tiers (ADR-0055): the private tier fuses it into the predicate and the shared tier checks it\n // against the entitlement set, and a stream token with no subject would name a bearer no\n // revocation could ever reach. So a read path with no way to resolve a subject cannot grant\n // anything — it is a contradiction, and the only useful moment to say so is now, rather than as\n // a 401 every client then sits in.\n if (resolveAuthClaims === undefined) {\n throw new Error(\n \"[pgxsinkit] createSyncServer: `readPath` was configured without `resolveAuthClaims`. The native \" +\n \"read path mints a per-subject stream token, so it cannot serve a deployment that has no way to \" +\n \"resolve a subject. Provide `resolveAuthClaims`, or drop `readPath` for a write-only deployment.\",\n );\n }\n const subscribeOptions = {\n registry: options.registry,\n engine: readPath.engine,\n ...(readPath.entitlements ? { entitlements: readPath.entitlements } : {}),\n key: readPath.key,\n ...(readPath.ttlSeconds !== undefined ? { ttlSeconds: readPath.ttlSeconds } : {}),\n resolveAuthClaims,\n };\n\n router.post(subscribePath, createSubscribeHandler(subscribeOptions));\n router.post(refreshPath, createRefreshHandler(subscribeOptions));\n // The close half of subscribe. Every grant subscribe handed out is a named claim on an engine\n // shape, and a live claim blocks dormancy and eviction — so without this route every shape waits\n // out its full lease window before it can be reclaimed. The release is idempotent (each grant\n // names its own claim), and a release that never arrives is reclaimed by the lease anyway; see\n // `releaseStreamGrants`.\n router.post(releasePath, createReleaseHandler({ engine: readPath.engine, key: readPath.key, resolveAuthClaims }));\n router.get(\n barrierPath,\n createBarrierHandler({\n engine: readPath.engine,\n resolveAuthClaims,\n ...(readPath.barrierMaxAgeSeconds !== undefined ? { maxAgeSeconds: readPath.barrierMaxAgeSeconds } : {}),\n }),\n );\n }\n\n const fetch = router.fetch;\n\n return {\n drizzle: db,\n fetch,\n request: (path, init) => {\n const baseUrl = address === null ? \"http://localhost\" : `http://${address.host}:${address.port}`;\n return fetch(new Request(new URL(path, baseUrl).toString(), init));\n },\n start: async () => {\n if (bunServer) {\n return;\n }\n\n const bun = getBunNamespace();\n if (!bun) {\n throw new Error(\"createSyncServer.start() requires the Bun runtime\");\n }\n\n const host = options.host ?? \"0.0.0.0\";\n const port = options.port ?? 3001;\n const idleTimeout = options.idleTimeoutSeconds;\n\n bunServer = bun.serve({\n hostname: host,\n port,\n ...(idleTimeout !== undefined ? { idleTimeout } : {}),\n fetch,\n });\n\n status.isRunning = true;\n status.phase = \"ready\";\n delete status.lastError;\n address = { host, port };\n options.onStatusChange?.(status);\n },\n stop: async () => {\n bunServer?.stop();\n bunServer = undefined;\n status.isRunning = false;\n options.onStatusChange?.(status);\n },\n status,\n get address() {\n return address;\n },\n diagnostics: () => ({\n tables: Object.keys(options.registry) as Array<keyof TRegistry & string>,\n modes: Object.fromEntries(Object.entries(options.registry).map(([key, entry]) => [key, entry.mode])),\n }),\n };\n}\n\nexport function buildRegistrySchema<TRegistry extends SyncTableRegistry>(\n registry: TRegistry,\n): RegistryTables<TRegistry> {\n return Object.fromEntries(\n Object.entries(registry).map(([key, entry]) => [key, entry.table]),\n ) as RegistryTables<TRegistry>;\n}\n\nfunction resolveHealthCheckPath(config?: boolean | { path: string }, defaultEnabled = false): string | null {\n if (config === false) {\n return null;\n }\n\n if (config === undefined && !defaultEnabled) {\n return null;\n }\n\n if (typeof config === \"object\" && \"path\" in config) {\n return config.path;\n }\n\n return \"/health\";\n}\n\nfunction getBunNamespace(): BunNamespace | undefined {\n const maybeBun = (globalThis as { Bun?: BunNamespace }).Bun;\n return maybeBun;\n}\n\nfunction isValidationError(error: unknown): error is { issues: unknown[] } {\n return typeof error === \"object\" && error !== null && \"issues\" in error && Array.isArray(error.issues);\n}\n\nfunction resolveOperationsLogConfig(options?: { enabled?: boolean }): OperationsLogConfig {\n return {\n enabled: options?.enabled ?? true,\n };\n}\n\nexport { authoritativeMutationPaths, batchMutationPaths, createMutationHandler } from \"./mutations/route\";\nexport type { StartupVerificationMode } from \"./mutations/route\";\nexport type { CorsConfig, CorsScope, FetchHandler, RouterErrorHandler } from \"./router\";\nexport { FetchRouter } from \"./router\";\nexport { buildPlpgsqlBatchFunctionDdl, expectedApplyFingerprint } from \"./mutations/plpgsql-apply\";\nexport type { ApplyFunctionRenderOptions } from \"./mutations/plpgsql-apply\";\nexport { renderPgxsinkitUtilitiesMigration } from \"./migrations/utilities\";\nexport { ensureOperationsLogSchema, operationsLogRegclassTarget } from \"./operations-log/ddl\";\nexport { operationsLogTable } from \"./operations-log/schema\";\nexport { readSqlState } from \"./sql-state\";\nexport {\n createEventIngestHandler,\n eventIngestRequiresClaims,\n EVENT_QUEUE_UNAVAILABLE_RETRY_AFTER_SECONDS,\n} from \"./events/route\";\nexport type {\n CreateEventIngestHandlerOptions,\n EventGate,\n EventGateDecision,\n EventGateInput,\n EventIngestDb,\n EventsEnqueuedHook,\n EventsEnqueuedInfo,\n} from \"./events/route\";\nexport { assertEventQueueReceipts, eventStreamQueueName, MalformedEventQueueMessageError } from \"./events/queue\";\nexport type {\n DeadLetteredEventMessage,\n DeliveredEventMessage,\n EventQueue,\n EventQueueExecutor,\n EventQueueReadOptions,\n EventQueueReceipt,\n} from \"./events/queue\";\nexport { createPgmqEventQueue, PGMQ_DEAD_LETTER_KEY } from \"./events/pgmq-queue\";\nexport type { CreatePgmqEventQueueOptions } from \"./events/pgmq-queue\";\nexport {\n computeEventPollWaitMs,\n defineEventConsumer,\n DEFAULT_EVENT_CONSUMER_BATCH_SIZE,\n DEFAULT_EVENT_DRAIN_BUDGET_MS,\n DEFAULT_EVENT_MAX_ATTEMPTS,\n DEFAULT_EVENT_POLL_CEILING_MS,\n DEFAULT_EVENT_POLL_FACTOR,\n DEFAULT_EVENT_POLL_FLOOR_MS,\n DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n} from \"./events/consumer\";\nexport type {\n DefineEventConsumerOptions,\n EventConsumer,\n EventConsumerBatch,\n EventConsumerCallback,\n EventConsumerPollOptions,\n EventConsumerSleep,\n EventDeadLetterReport,\n EventDrainOptions,\n EventDrainSummary,\n EventPollReport,\n} from \"./events/consumer\";\nexport {\n EVENT_LANE_FINGERPRINT_PREFIX,\n eventLaneDdlFingerprint,\n eventLaneStreamNames,\n renderEventLaneMigration,\n} from \"./events/ddl\";\nexport { resolveEventIdentity } from \"./events/identity\";\nexport type { IdentityResolution } from \"./events/identity\";\n\n// The Circuits-native read path (ADR-0055) — shape lifecycle only. Reads terminate on\n// durable-streams and never traverse the engine.\nexport { compileShapeRequest, fingerprintShapeRequest, resolveEntryByShapeKey } from \"./circuits/compile\";\nexport type { CompiledShapeRequest, ShapeRequest } from \"./circuits/compile\";\nexport { CircuitsEngineError, createCircuitsEngineClient } from \"./circuits/engine-client\";\nexport type { CircuitsEngineClient, CircuitsEngineOptions } from \"./circuits/engine-client\";\nexport type { CircuitsShapeHandle, CreateShapeRequest } from \"./circuits/wire\";\nexport {\n DEFAULT_STREAM_TOKEN_TTL_SECONDS,\n findGrant,\n importStreamTokenKey,\n mintStreamToken,\n verifyStreamToken,\n} from \"./circuits/stream-token\";\nexport type {\n MintStreamTokenOptions,\n VerifyStreamTokenOptions,\n StreamGrant,\n StreamTokenClaims,\n StreamTokenVerification,\n} from \"./circuits/stream-token\";\nexport {\n authorizeStreamRead,\n createStreamGate,\n EntitlementsUnavailableError,\n readStreamToken,\n STREAM_READ_EXPOSED_HEADERS,\n} from \"./circuits/edge\";\nexport type { EntitlementSet, GateDecision, StreamAuthorizationOptions, StreamGateOptions } from \"./circuits/edge\";\nexport {\n barrierPath,\n CircuitsLeaseConfigError,\n createBarrierHandler,\n createRefreshHandler,\n createReleaseHandler,\n createSubscribeHandler,\n refreshPath,\n refreshStreamToken,\n releasePath,\n releaseStreamGrants,\n subscribePath,\n subscribeToShapes,\n} from \"./circuits/subscribe\";\nexport type {\n DeniedSubscription,\n GrantedSubscription,\n RefreshResult,\n SubscribeOptions,\n SubscribeResult,\n SubscriptionRequest,\n} from \"./circuits/subscribe\";\n",
6
- "import {\n readShapeTier,\n type JwtClaims,\n type PredicateValue,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n compileShapeRequest,\n fingerprintShapeRequest,\n resolveEntryByShapeKey,\n type CompiledShapeRequest,\n} from \"./compile\";\nimport { EntitlementsUnavailableError, type EntitlementSet } from \"./edge\";\nimport { CircuitsEngineError, type CircuitsEngineClient } from \"./engine-client\";\nimport { DEFAULT_STREAM_TOKEN_TTL_SECONDS, mintStreamToken, verifyStreamToken, type StreamGrant } from \"./stream-token\";\nimport type { CircuitsShapeHandle, CreateShapeRequest } from \"./wire\";\n\n/**\n * One shape a client wants to follow.\n *\n * A shape KEY and nothing else — deliberately (ADR-0055 decision 6). A shared-tier shape fans out to\n * one stream per scope the subject holds, and the control plane does that expansion because it is\n * the only side that knows the answer: it holds the entitlement set. A client naming its own scopes\n * could only ever restate that set redundantly or contradict it, and every contradiction is a\n * denial it then has to reconcile at boot.\n */\nexport interface SubscriptionRequest {\n shapeKey: string;\n}\n\n/** A subscription the control plane granted: what to read, and where. */\nexport interface GrantedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n shapeId: string;\n /** The durable-streams path, which is what the client follows through the edge. */\n streamPath: string;\n}\n\n/** A subscription the control plane declined, with why. */\nexport interface DeniedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n reason: string;\n}\n\nexport interface SubscribeResult {\n /** The stream token covering every granted subscription. Absent when nothing was granted. */\n token?: string;\n /** Seconds since the epoch. The client re-mints before this, in one request for the whole batch. */\n expiresAt?: number;\n granted: GrantedSubscription[];\n denied: DeniedSubscription[];\n}\n\nexport interface SubscribeOptions {\n registry: SyncTableRegistry;\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the SHARED tier.\n *\n * Optional, because a registry with no shared-tier shape has nothing to ask it. Omitting it is a\n * statement that this deployment has none: a shared-tier subscription is then refused with that\n * reason rather than silently permitted, so adding the first shared shape fails loudly instead of\n * serving one subject's rows to everyone.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge — the same process holds both. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute default. */\n ttlSeconds?: number;\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n}\n\n/**\n * The engine's subscription lease is shorter than this deployment's token TTL — a **configuration**\n * fault, not a request one.\n *\n * The control plane renews every live claim on exactly one cadence: the token re-mint, which the\n * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The\n * engine releases a claim not renewed within `leaseSeconds` (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`).\n * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a\n * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The\n * factor of two is the margin for exactly one missed refresh.\n *\n * Refused loudly rather than papered over, because both numbers are the operator's and neither the\n * subject nor the client can do anything about either. The routes answer 503 — \"this deployment, not\n * you\" — and never a denial: a client told it lost entitlement truncates its rows.\n */\nexport class CircuitsLeaseConfigError extends Error {\n /** The engine's `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */\n readonly leaseSeconds: number;\n /** The stream-token TTL this control plane is configured with. */\n readonly ttlSeconds: number;\n\n constructor(leaseSeconds: number, ttlSeconds: number) {\n super(\n `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +\n `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +\n `(${ttlSeconds}s, the \\`ttlSeconds\\` option). Claims are renewed on the token re-mint, so a single ` +\n `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +\n `it. Raise ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \\`ttlSeconds\\` to ` +\n `at most ${Math.floor(leaseSeconds / 2)}, or set ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +\n `leases entirely.`,\n );\n this.name = \"CircuitsLeaseConfigError\";\n this.leaseSeconds = leaseSeconds;\n this.ttlSeconds = ttlSeconds;\n }\n}\n\n/**\n * `leaseSeconds === 0` means the engine has dormancy — and with it leases — switched off, so there is\n * no window to fall out of and nothing to check. Anything else must cover two re-mints.\n */\nfunction assertLeaseCoversTtl(leaseSeconds: number, ttlSeconds: number): void {\n if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds) throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);\n}\n\n/**\n * The engine must record a claim under the name it was given — on the create that TAKES it and on\n * every create that RENEWS it alike.\n *\n * An engine that renames a claim is one this control plane can neither renew nor release by id, which\n * is the whole protocol (fork ADR-0008): the renewal would take a second claim every time, and the\n * release would name something the engine never held. That is the wrong engine, not a degraded one,\n * so it throws rather than degrading — there is no answer this client could go on to give.\n */\nfunction assertClaimRecorded(handle: CircuitsShapeHandle, claim: string): void {\n if (handle.subscription === claim) return;\n throw new Error(\n `[pgxsinkit] the engine recorded this shape claim under \\`${handle.subscription}\\` rather than the ` +\n `subscription id it was sent (\\`${claim}\\`). Renewal and release are BY that id (fork ADR-0008), ` +\n `so an engine that renames a claim is not the one this client targets.`,\n );\n}\n\n/**\n * Compile one shape for one scope — the single form both the subscribe and the re-mint paths use.\n *\n * Shared between them on purpose: the re-mint RENEWS each grant's engine claim by repeating the create\n * that took it, so the request it sends has to be the request subscribe would build today. Two\n * spellings of \"compile this grant\" would be two chances for a renew to name a different definition\n * than the grant it is renewing — which the engine would answer with a different handle, and this\n * route would read as a revocation.\n */\nfunction compileGrant(\n options: Pick<SubscribeOptions, \"registry\" | \"params\">,\n claims: JwtClaims | null,\n shapeKey: string,\n scope?: readonly PredicateValue[],\n): CompiledShapeRequest {\n return compileShapeRequest(options.registry, {\n shapeKey,\n claims,\n ...(scope !== undefined ? { scope } : {}),\n ...(options.params ? { params: options.params } : {}),\n });\n}\n\n/** What a renewal attempt came to. `renewed` is the only outcome that keeps the grant. */\ntype RenewalOutcome = { renewed: true } | { revoked: string };\n\n/**\n * Renew one grant's engine claim: the SAME create, repeated with the SAME subscription id.\n *\n * This is the whole of the lease protocol on our side (fork ADR-0008). The engine has no separate\n * renew route because it needs none — a create naming a claim the shape already holds returns the same\n * handle, counts nothing, and moves the lease. So the re-mint, which already re-authorizes every grant\n * on the client's own refresh cadence, renews for free and renews exactly the grants that survived.\n *\n * The two failure outcomes are both \"this is no longer the stream the client follows\", and both end in\n * `revoked` rather than an error, because the client's answer to a revocation — truncate and\n * re-subscribe — is precisely the right one:\n *\n * - **A different handle.** The claim lapsed, or the shape was evicted, so this call re-subscribed\n * instead of renewing (ADR-0007) and the engine handed back a fresh shape on a fresh path. The\n * grant names the old one. The claim just taken is released immediately: nothing is following that\n * new stream, and the client's re-subscribe will take its own.\n * - **409.** The id names a different shape. Nothing was taken, so there is nothing to give back.\n *\n * Anything else the engine says is an OUTAGE and propagates — the route answers 503. A revocation\n * would tell the client it lost the scope, and a client told that clears the rows. An engine that\n * renames the claim propagates too, through {@link assertClaimRecorded}: that one is not an outage\n * either, it is the wrong engine.\n */\nasync function renewGrantClaim(\n engine: CircuitsEngineClient,\n request: CreateShapeRequest,\n grant: StreamGrant,\n ttlSeconds: number,\n): Promise<RenewalOutcome> {\n let handle;\n try {\n handle = await engine.createShape({ ...request, subscription: grant.claim });\n } catch (error) {\n if (error instanceof CircuitsEngineError && error.status === 409) {\n return { revoked: \"subscription id is held by another shape; re-subscribe\" };\n }\n throw error;\n }\n assertClaimRecorded(handle, grant.claim);\n // The handle comparison and the release of a fresh claim come BEFORE the lease guard, deliberately:\n // a misconfigured window is fatal to this request, and throwing it first would strand the claim\n // this very call just took.\n if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {\n await engine.releaseShape(handle.shapeId, grant.claim);\n return { revoked: \"shape stream changed; re-subscribe\" };\n }\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n return { renewed: true };\n}\n\n/**\n * What one requested shape expands to: the scopes to compile it at.\n *\n * `[undefined]` — a single scope-less compile — is the private tier, whose subject arrives in the\n * claims instead. A shared-tier shape expands to one entry per entitled scope, and none is a\n * refusal rather than an empty success: a subject with no scopes has nothing to read, and returning\n * zero grants silently would leave the client waiting on streams that were never created.\n *\n * An unknown shapeKey deliberately expands to `[undefined]` and is refused downstream by\n * `compileShapeRequest`, so the message for \"no such shape\" has exactly one author.\n *\n * Throws {@link EntitlementsUnavailableError} when the set exists but cannot be trusted yet — an\n * outage, not a refusal, and the route turns it into a 503.\n */\nfunction expandToScopes(\n options: Pick<SubscribeOptions, \"registry\" | \"entitlements\">,\n subject: string,\n shapeKey: string,\n): { scopes: readonly (readonly PredicateValue[] | undefined)[] } | { refusal: string } {\n const entry: SyncTableEntry | undefined = resolveEntryByShapeKey(options.registry, shapeKey);\n const shape = entry?.shape;\n if (shape == null) return { scopes: [undefined] };\n if (readShapeTier(shape) === \"private\") return { scopes: [undefined] };\n\n if (options.entitlements === undefined) {\n return { refusal: \"shared-tier shape, but this deployment configured no entitlement set\" };\n }\n // A refusal above, a THROW here, and the difference is permanence. \"No entitlement set configured\"\n // is a statement about this deployment that will read the same on every future request. \"Not ready\"\n // is a statement about this instant, and answering it with a denial would tell the client it lost\n // the scope — which makes it clear those rows. See {@link EntitlementsUnavailableError}.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n const held = options.entitlements.scopesFor(subject, shapeKey);\n if (held.length === 0) return { refusal: \"no entitled scopes\" };\n return { scopes: held };\n}\n\n/**\n * Subscribe to a batch of shapes: compile each against the registry, check entitlement, register it\n * with the engine, and mint ONE token covering all of them.\n *\n * A shared-tier shape FANS OUT: one stream per scope the subject holds, so K requested shapes yield\n * however many grants their entitlements come to. Expansion happens here rather than on the client\n * because this is the side holding the entitlement set — see {@link SubscriptionRequest}.\n *\n * A partial result rather than an all-or-nothing one. A subject holding K scopes at boot may\n * legitimately have lost one of them, and failing the whole batch on that would deny them the K-1\n * they still hold — so a denial is reported per subscription and the rest proceed.\n *\n * That partiality covers AUTHORIZATION only. An engine that cannot answer — degraded, unreachable —\n * is not a denial and must never be reported as one: a client told \"not entitled\" truncates that\n * scope and unsubscribes, so reporting an outage that way would turn a transient engine fault into\n * client-side data loss. Engine failures propagate, and the route answers 503.\n *\n * An entitlement set that is not `ready` joins it. It is the same shape of failure — a dependency\n * that cannot answer right now — and the client's response to a denial is the same clear, so it\n * propagates as {@link EntitlementsUnavailableError} and the route answers 503 too. What stays a\n * denial is the set being absent altogether: that is a deployment's permanent configuration.\n *\n * Entitlement is checked HERE as well as at the edge, and the duplication is deliberate: this is\n * what stops a shape being created and a capability minted for a scope the subject never held. The\n * edge's check bounds how long an already-minted one keeps working.\n */\nexport async function subscribeToShapes(\n options: SubscribeOptions,\n claims: JwtClaims | null,\n requests: readonly SubscriptionRequest[],\n now: number,\n): Promise<SubscribeResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const granted: GrantedSubscription[] = [];\n const denied: DeniedSubscription[] = [];\n const grants: StreamGrant[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const request of requests) {\n const deny = (reason: string, scope?: readonly PredicateValue[]) =>\n denied.push({ shapeKey: request.shapeKey, ...(scope !== undefined ? { scope } : {}), reason });\n\n // Every read is bound to a subject, both tiers. The private tier fuses the subject into the\n // predicate and the shared tier checks it against the entitlement set, but neither has an\n // anonymous form — a token with no subject would name a bearer no revocation could reach.\n if (subject === null) {\n deny(\"no subject\");\n continue;\n }\n\n const expanded = expandToScopes(options, subject, request.shapeKey);\n if (\"refusal\" in expanded) {\n deny(expanded.refusal);\n continue;\n }\n\n for (const scope of expanded.scopes) {\n const scoped = scope !== undefined ? { scope } : {};\n const compiled = compileGrant(options, claims, request.shapeKey, scope);\n if (compiled.outcome === \"deny\") {\n deny(compiled.reason, scope);\n continue;\n }\n\n // Enumeration said yes; ask the predicate too. The two are required to agree, and when they do\n // not it is this side that must catch it: the edge checks `permits` on EVERY read, so a scope\n // only `scopesFor` believes in would mint a capability for a stream the client can never\n // actually read. Better a denial it can see now than a stream that 403s forever.\n if (compiled.tier === \"shared\" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {\n deny(\"not entitled to this scope\", scope);\n continue;\n }\n\n // The private tier's grant records WHAT was authorized, not merely that something was. Its\n // predicate is a function of this subject's claims, and those change under the client's feet —\n // a role removed mid-session — so the re-mint has to be able to ask whether the shape this\n // grant points at is still the shape these claims compile to. The fingerprint is how it asks\n // without storing anything (ADR-0055 decision 6). The shared tier needs none: its predicate is\n // generated from the scope values, which the entitlement re-check already covers.\n const fp = compiled.tier === \"private\" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};\n\n // The claim is NAMED before it is taken, and the name is ours (fork ADR-0008). That is what\n // makes this create idempotent — a repeat with the same id renews rather than joining twice —\n // and what makes the release retry-safe: `DELETE ?subscription=…` drops this claim and only\n // this one. A uuid per grant, never per shape: two grants that deduplicate onto one shapeId are\n // two joins, and one id could only ever release one of them.\n const claim = crypto.randomUUID();\n\n // Deliberately unguarded: see the note above on why an engine fault is not a denial.\n const handle = await options.engine.createShape({ ...compiled.request, subscription: claim });\n assertClaimRecorded(handle, claim);\n // Checked per create rather than once at boot: the lease window is the engine's to report, and\n // this is the only place it is reported. A misconfigured pairing must surface as a 503 on the\n // very first subscribe, not as sessions quietly lapsing an idle window later.\n //\n // The claim is already taken by the time this can trip, so it is handed back before the error\n // leaves — nobody will ever follow this stream. Best effort, and the failure is SWALLOWED: the\n // configuration fault is what the operator has to see, and a release that also fails must not\n // mask it. An unreleased claim lapses on its own.\n try {\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n } catch (error) {\n await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});\n throw error;\n }\n\n granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });\n // The grant carries the shapeId this `createShape` returned AND the claim it was taken under,\n // and together they are what make the renew and release routes possible at all: both are\n // stateless, so the signed token is the only record of what this session holds.\n grants.push({\n path: handle.streamPath,\n shapeKey: request.shapeKey,\n shapeId: handle.shapeId,\n claim,\n ...scoped,\n ...fp,\n });\n }\n }\n\n if (subject === null || grants.length === 0) return { granted, denied };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, denied };\n}\n\n/**\n * The subscribe route: verified claims in, a token and stream paths out.\n *\n * Deliberately a POST that returns paths rather than a redirect to them. The client needs the whole\n * batch to open K long-polls and to know when to re-mint, and a redirect would give it one stream\n * and no expiry.\n */\nexport function createSubscribeHandler(\n options: SubscribeOptions & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleSubscribe(request: Request): Promise<Response> {\n let body: { subscriptions?: SubscriptionRequest[] };\n try {\n body = (await request.json()) as { subscriptions?: SubscriptionRequest[] };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (!Array.isArray(body.subscriptions)) {\n return Response.json({ error: \"subscriptions must be an array\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n\n // Unauthenticated is NOT a denial, for the same reason an engine outage is not: a client told\n // \"not entitled\" truncates the scope and unsubscribes, so answering an expired JWT that way\n // turns a re-login into data loss. 401 is what makes it a distinct, recoverable status the\n // client can retry through (ADR-0013).\n //\n // The check is on the SUBJECT, not on the claims object: a verified token with no `sub` names a\n // bearer no revocation could ever reach, so it is exactly as unusable as no token at all. A\n // deployment with no auth adapter never reaches here — `createSyncServer` refuses that pairing\n // at construction.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: SubscribeResult;\n try {\n result = await subscribeToShapes(options, claims, body.subscriptions, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer is an OUTAGE, and 503 is what keeps the client retrying.\n // Relaying it as a per-subscription denial would tell the client it lost entitlement, and a\n // client told that truncates the scope and unsubscribes — turning a transient fault into data\n // loss.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n // A lease window shorter than the token TTL is an operator's misconfiguration, and it joins the\n // 503s for the same reason: it is a statement about this deployment, never about this subject's\n // entitlements. Denying instead would make an unserviceable pairing look like lost access.\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n // 200 even when everything was denied: the per-subscription reasons ARE the response, and\n // collapsing them to a status code would tell a client that lost one scope out of K nothing\n // about which one.\n return Response.json(result);\n };\n}\n\nexport interface RefreshResult {\n token?: string;\n expiresAt?: number;\n /** Grants that survived re-authorization — see {@link refreshStreamToken} for what that is per tier. */\n granted: StreamGrant[];\n /**\n * Grants the subject may no longer read as granted: a shared scope they have lost, or a private\n * shape their current claims no longer compile to. The client truncates each and unsubscribes,\n * then re-subscribes for whatever it is entitled to now.\n */\n revoked: DeniedSubscription[];\n}\n\n/**\n * Re-mint a stream token from an existing one (ADR-0055 decision 6).\n *\n * The expiring token IS the request: its signature proves this control plane issued those grants, so\n * nothing has to be stored server-side to know what the subject held, and the edge stays stateless on\n * both halves. Expiry is deliberately not enforced here — a token is presented for re-mint precisely\n * because it is at or past its TTL — but the signature is, and **every grant is re-authorized**.\n * That re-check is what makes the TTL a revocation bound rather than a formality.\n *\n * BOTH TIERS are re-authorized, by the question each tier's authorization actually turns on.\n *\n * - Shared: the live entitlement set. Its predicate is generated from the scope values, so it cannot\n * drift with the subject; what can change is whether the subject still holds the scope.\n * - Private: **recompile the shape with the subject's CURRENT claims** and compare the fingerprint\n * the grant carries. A private predicate may read ANY verified claim, not only `sub`, so a subject\n * demoted mid-session — a role dropped, a tenant changed — is still the same authenticated subject\n * and would sail through a check that only re-verified the JWT. Re-verifying the JWT proves the\n * bearer is still who they were; it says nothing about whether the shape they hold is still the\n * shape their claims compile to, and only recompiling answers that.\n *\n * A fingerprint mismatch is a REVOCATION by design, including when the recompiled predicate would\n * still permit the subject something. The grant names one stream, that stream serves the old\n * predicate, and this route may not hand out a new one — the client's re-subscribe is where a new\n * shape is created, and this route is not that. So the grant is revoked, the client re-subscribes, the\n * control plane creates the shape its current claims compile to, and because the handle differs the\n * client re-snapshots through ADR-0056 decision 7's must-refetch.\n *\n * **This is also where every surviving grant's engine claim is RENEWED** (fork ADR-0008). A claim is a\n * lease: the engine releases one not renewed within `leaseSeconds`, because native reads terminate on\n * durable-streams and the renewal is the only liveness signal it has. Renewing here rather than on a\n * timer is what makes the cadence honest — this route already runs once per subject per TTL window and\n * already decides which grants are still authorized, so the renewal covers exactly the grants that\n * survived and costs no extra round trip. A revoked grant is deliberately NOT renewed: its lease\n * lapses and the engine reclaims the shape.\n *\n * The renewal is the same create, repeated with the grant's own `claim` id. Its outcomes are in\n * {@link renewGrantClaim}; a renewal that comes back a different handle, or 409s, revokes the grant\n * with a re-subscribe reason rather than failing the whole re-mint.\n *\n * `registry` is therefore REQUIRED rather than optional: a refresh route that cannot recompile cannot\n * re-authorize the private tier — and now cannot renew either, since the renewal IS the compiled\n * create. `engine` is required for the same reason.\n *\n * Throws {@link EntitlementsUnavailableError} rather than revoking when the set cannot be consulted —\n * the same outage-is-not-a-denial rule {@link subscribeToShapes} follows, and it matters more here:\n * `revoked` is the wire's clear-this-scope instruction, and this route runs every few minutes for\n * the life of every subscription. An engine that cannot answer a renewal joins it, as does a lease\n * window this deployment's TTL does not fit inside ({@link CircuitsLeaseConfigError}).\n */\nexport async function refreshStreamToken(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\">,\n claims: JwtClaims | null,\n expiringToken: string,\n now: number,\n): Promise<RefreshResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });\n if (!verified.ok || subject === null) return { granted: [], revoked: [] };\n\n // The token names its subject; a token presented by anyone else is not a re-mint, it is a theft.\n if (verified.claims.sub !== subject) return { granted: [], revoked: [] };\n\n const granted: StreamGrant[] = [];\n const revoked: DeniedSubscription[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const grant of verified.claims.grants) {\n const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};\n if (grant.scope === undefined) {\n // Private tier: re-authorize by recompiling. See the note above on why the signed grant alone\n // is not the entitlement — the predicate is a function of claims that may have changed since\n // it was issued.\n const compiled = compileGrant(options, claims, grant.shapeKey);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, reason: compiled.reason });\n continue;\n }\n if (grant.fp === undefined) {\n // Nothing to compare against, so nothing that could establish this grant is still the right\n // one. Fail closed rather than trust it: the recovery is a re-subscribe, which costs the\n // client a re-snapshot and costs the subject nothing they are still entitled to.\n revoked.push({\n shapeKey: grant.shapeKey,\n reason: \"private grant carries no fingerprint and cannot be re-authorized\",\n });\n continue;\n }\n if ((await fingerprintShapeRequest(compiled.request)) !== grant.fp) {\n revoked.push({ shapeKey: grant.shapeKey, reason: \"shape predicate changed for this subject\" });\n continue;\n }\n // Re-authorized, so renew the claim it holds — the recompiled request is exactly the one that\n // took it, which the fingerprint just proved.\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n continue;\n }\n if (options.entitlements === undefined) {\n // Permanent, and therefore a real revocation: this deployment has no entitlement set, so a\n // shared grant can never be re-minted and the scope is not coming back.\n //\n // Worded as the EDGE words the same condition, and deliberately not as \"entitlements\n // unavailable\" — that string is now the 503 outage body, which means the exact opposite here:\n // an outage says nothing about this subject's scopes and must never clear a row.\n revoked.push({\n shapeKey: grant.shapeKey,\n ...scoped,\n reason: \"shared-tier grant, but this deployment configured no entitlement set\",\n });\n continue;\n }\n // Transient, and therefore NOT a revocation. `revoked` is an instruction to clear the scope, and\n // a re-mint is the most routine request on this route — an entitlement subscription that is a few\n // seconds behind would otherwise empty a subject's store every time it reconnected.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: \"not entitled to this scope\" });\n continue;\n }\n // Still entitled, so renew. The shared tier carries no fingerprint — its predicate is generated\n // from the scope values, which is why the entitlement check above is the whole question — so the\n // request is recompiled here, through the same {@link compileGrant} subscribe used.\n const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });\n continue;\n }\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n }\n\n if (granted.length === 0) return { granted, revoked };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, revoked };\n}\n\n/**\n * The re-mint route. Takes the expiring token, answers with a fresh one and the list of grants that\n * did not survive re-authorization — the shared tier's against the live entitlement set, the private\n * tier's against a recompile with the subject's current claims — and **renews the engine claim of\n * every grant that did survive** (fork ADR-0008).\n *\n * `registry` for that recompile and `engine` for that renewal, both required for the reasons\n * {@link refreshStreamToken} gives.\n *\n * 200 even when everything was revoked, for the same reason subscribe answers 200 on a full denial:\n * the per-grant reasons ARE the response, and a client that lost one scope of K needs to know which.\n */\nexport function createRefreshHandler(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\"> & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRefresh(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // Same as subscribe: an unauthenticated re-mint is a credential problem, not a revocation. The\n // difference matters more here — a `revoked` answer makes the client truncate, and a token\n // expiring is the single most ordinary thing that happens on this route.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: RefreshResult;\n try {\n result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // 503, never a `revoked` list: an entitlement set that cannot answer has said nothing about\n // this subject's scopes, and a client that read it as a revocation would clear rows it still\n // holds. The client retries with the token it already has, which the edge keeps honouring\n // until its TTL lapses.\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n // An engine that could not answer a RENEWAL is the same case: the claim is still held (a lease\n // outlives a failed renewal by the rest of its window), the token the client holds still works,\n // and a `revoked` answer would clear rows over a transient fault.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n throw error;\n }\n return Response.json(result);\n };\n}\n\n/**\n * Give back the engine claims a token's grants acquired — the close half of subscribe.\n *\n * **Why this route exists.** A native `POST /shapes` with a definition the engine already holds does\n * not create a second shape: it JOINS the existing one, under a claim of its own. Live claims are\n * load-bearing rather than bookkeeping — one live claim blocks both dormancy and eviction, precisely\n * because native durable-streams reads bypass the engine entirely, so a claim is the only thing that\n * tells it a reader it cannot see still exists. Without a release, a shape waits out its whole lease\n * window before it can go dormant, every time.\n *\n * **The token IS the request**, exactly as on the re-mint path: its signature proves this control\n * plane minted these grants, so nothing has to be stored server-side to know what was acquired.\n * Verified with `allowExpired`, and that is not a weakening — a session releases at CLOSE, which is\n * routinely past a 5-minute TTL, and expiry bounds how long a grant keeps *working*, not what it\n * proves was issued. A release grants its bearer nothing; the only thing it can do is give away\n * claims that this token's own subject holds.\n *\n * **ONE release per GRANT, deliberately not deduplicated by `shapeId`.** Two grants naming one shape\n * are two joins — the engine deduplicated identical definitions and counted both (ADR-0055 decision\n * 6) — so collapsing them here would return one of two claims and leak the other permanently. Each\n * grant releases its OWN claim (`DELETE /shapes/{id}?subscription=<claim>`), which is what makes one\n * release distinguishable from the other at all.\n *\n * **Idempotent and retry-safe** (fork ADR-0008). A claim is named, so releasing it twice is releasing\n * it once: the second `DELETE` is a no-op `200` and cannot touch another subscriber's claim. That is\n * a change in kind from the anonymous refcount decrement this route was first written against, and it\n * collapses the old asymmetry — a client, a proxy or an operator may repeat a release freely. A\n * release that never arrives at all is not a permanent leak either: the claim is a LEASE, renewed on\n * the token re-mint, so a session that crashed or was unloaded has its claims reclaimed by the engine\n * within `leaseSeconds`. What this route buys is promptness, not correctness.\n *\n * Refusals are refusals, not no-ops: a bad signature or a mismatched subject answers an error rather\n * than `{ released: 0 }`, because a token presented by anyone but its own subject is not a release,\n * it is an attempt to drop the victim's claims.\n */\nexport async function releaseStreamGrants(\n options: { engine: CircuitsEngineClient; key: CryptoKey },\n claims: JwtClaims | null,\n token: string,\n now: number,\n): Promise<{ released: number } | { refused: string }> {\n const subject = typeof claims?.sub === \"string\" && claims.sub !== \"\" ? claims.sub : null;\n if (subject === null) return { refused: \"unauthenticated\" };\n\n const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });\n if (!verified.ok) return { refused: verified.reason };\n if (verified.claims.sub !== subject) return { refused: \"token subject does not match the caller\" };\n\n for (const grant of verified.claims.grants) {\n await options.engine.releaseShape(grant.shapeId, grant.claim);\n }\n return { released: verified.claims.grants.length };\n}\n\n/**\n * The release route: the token a session was given, back at its close.\n *\n * **Safe to call more than once.** Every grant releases a NAMED claim, so a repeat is the same act\n * once (fork ADR-0008) — a duplicate close, a proxy retry or an operator replaying a request all\n * answer 200 and change nothing. The client still sends it at most once, but that is now a matter of\n * not making a pointless request rather than of correctness.\n *\n * 403 rather than 200 on a refusal — see {@link releaseStreamGrants} for why a refused release must\n * be visible. 401 when the caller has no subject, the same rule subscribe and re-mint follow: an\n * unauthenticated call is a credential problem, and it is the one thing here a client could fix.\n */\nexport function createReleaseHandler(\n options: {\n engine: CircuitsEngineClient;\n key: CryptoKey;\n } & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRelease(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: { released: number } | { refused: string };\n try {\n result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer has not dropped the claims. 503 says \"this deployment, not\n // you\", and a client is free to come back: releases are named and therefore idempotent (fork\n // ADR-0008), so a retry that races a release which actually landed is a no-op rather than a\n // theft. Whether it retries or not, the residue is bounded by the lease — an unreleased claim\n // lapses within `leaseSeconds` of its last renewal.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n if (\"refused\" in result) return Response.json({ error: result.refused }, { status: 403 });\n return Response.json(result);\n };\n}\n\n/** The control-plane paths the native read path mounts. */\nexport const subscribePath = \"/sync/v1/subscribe\";\nexport const refreshPath = \"/sync/v1/refresh\";\nexport const releasePath = \"/sync/v1/release\";\n\n/**\n * The convergence-barrier route (ADR-0056 decision 4).\n *\n * Proxied rather than exposed: the engine's control plane is unauthenticated by design and is not\n * client-reachable, so surfacing the barrier on our own authenticated endpoint costs nothing and\n * keeps the trust boundary intact.\n *\n * `maxAgeSeconds` may cache the answer briefly, but only a HEALTHY one. For the `pendingFlips` term\n * staleness is safe in exactly one direction — it moves the barrier backwards, so a stale reading can\n * only DELAY an alignment, never satisfy one falsely. `flipFailures` inverts that: a cached\n * pre-degradation zero would let a group align against an engine that has already\n * lost membership effects, which is precisely the alignment the term exists to refuse. So a degraded\n * reading is never cached and never served from cache, and the cache window is exactly the bound on\n * how long a client may align against a freshly-degraded engine — which is why the default is 0.\n */\nexport function createBarrierHandler(options: {\n engine: CircuitsEngineClient;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n maxAgeSeconds?: number;\n}) {\n let cached: { at: number; body: BarrierBody } | null = null;\n const maxAge = options.maxAgeSeconds ?? 0;\n\n return async function handleBarrier(request: Request): Promise<Response> {\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // The barrier says nothing about any subject's data — only whether the engine has finished\n // propagating — but it is still engine internals, so it needs a caller we recognise.\n if (options.resolveAuthClaims && claims === null) {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n const now = Date.now() / 1000;\n if (cached && now - cached.at < maxAge) return Response.json(cached.body);\n\n const state = await options.engine.replicationState();\n const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };\n cached = body.flipFailures > 0 ? null : { at: now, body };\n return Response.json(body);\n };\n}\n\nexport const barrierPath = \"/sync/v1/barrier\";\n\n/** The barrier as the client reads it — the engine's LSN is operator detail and stays server-side. */\ninterface BarrierBody {\n pendingFlips: number;\n /** Abandoned flip batches. Non-zero is terminal for a group reading it, and is never cached. */\n flipFailures: number;\n}\n",
6
+ "import {\n readShapeTier,\n type JwtClaims,\n type PredicateValue,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n compileShapeRequest,\n fingerprintShapeRequest,\n resolveEntryByShapeKey,\n type CompiledShapeRequest,\n} from \"./compile\";\nimport { EntitlementsUnavailableError, type EntitlementSet } from \"./edge\";\nimport { CircuitsEngineError, type CircuitsEngineClient } from \"./engine-client\";\nimport { DEFAULT_STREAM_TOKEN_TTL_SECONDS, mintStreamToken, verifyStreamToken, type StreamGrant } from \"./stream-token\";\nimport type { CircuitsShapeHandle, CreateShapeRequest } from \"./wire\";\n\n/**\n * One shape a client wants to follow.\n *\n * A shape KEY and nothing else — deliberately (ADR-0055 decision 6). A shared-tier shape fans out to\n * one stream per scope the subject holds, and the control plane does that expansion because it is\n * the only side that knows the answer: it holds the entitlement set. A client naming its own scopes\n * could only ever restate that set redundantly or contradict it, and every contradiction is a\n * denial it then has to reconcile at boot.\n */\nexport interface SubscriptionRequest {\n shapeKey: string;\n}\n\n/** A subscription the control plane granted: what to read, and where. */\nexport interface GrantedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n shapeId: string;\n /** The durable-streams path, which is what the client follows through the edge. */\n streamPath: string;\n}\n\n/** A subscription the control plane declined, with why. */\nexport interface DeniedSubscription {\n shapeKey: string;\n scope?: readonly PredicateValue[];\n reason: string;\n}\n\nexport interface SubscribeResult {\n /** The stream token covering every granted subscription. Absent when nothing was granted. */\n token?: string;\n /** Seconds since the epoch. The client re-mints before this, in one request for the whole batch. */\n expiresAt?: number;\n granted: GrantedSubscription[];\n denied: DeniedSubscription[];\n}\n\nexport interface SubscribeOptions {\n registry: SyncTableRegistry;\n engine: CircuitsEngineClient;\n /**\n * The live entitlement set backing the SHARED tier.\n *\n * Optional, because a registry with no shared-tier shape has nothing to ask it. Omitting it is a\n * statement that this deployment has none: a shared-tier subscription is then refused with that\n * reason rather than silently permitted, so adding the first shared shape fails loudly instead of\n * serving one subject's rows to everyone.\n */\n entitlements?: EntitlementSet;\n /** The stream-token signing key, shared with the edge — the same process holds both. */\n key: CryptoKey;\n /** Per-deployment override of ADR-0055's 5-minute default. */\n ttlSeconds?: number;\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n}\n\n/**\n * The engine's subscription lease is shorter than this deployment's token TTL — a **configuration**\n * fault, not a request one.\n *\n * The control plane renews every live claim on exactly one cadence: the token re-mint, which the\n * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The\n * engine releases a claim not renewed within `leaseSeconds` (`CIRCUITS_SHAPE_IDLE_SECS`).\n * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a\n * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The\n * factor of two is the margin for exactly one missed refresh.\n *\n * Refused loudly rather than papered over, because both numbers are the operator's and neither the\n * subject nor the client can do anything about either. The routes answer 503 — \"this deployment, not\n * you\" — and never a denial: a client told it lost entitlement truncates its rows.\n */\nexport class CircuitsLeaseConfigError extends Error {\n /** The engine's `CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */\n readonly leaseSeconds: number;\n /** The stream-token TTL this control plane is configured with. */\n readonly ttlSeconds: number;\n\n constructor(leaseSeconds: number, ttlSeconds: number) {\n super(\n `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +\n `CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +\n `(${ttlSeconds}s, the \\`ttlSeconds\\` option). Claims are renewed on the token re-mint, so a single ` +\n `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +\n `it. Raise CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \\`ttlSeconds\\` to ` +\n `at most ${Math.floor(leaseSeconds / 2)}, or set CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +\n `leases entirely.`,\n );\n this.name = \"CircuitsLeaseConfigError\";\n this.leaseSeconds = leaseSeconds;\n this.ttlSeconds = ttlSeconds;\n }\n}\n\n/**\n * `leaseSeconds === 0` means the engine has dormancy — and with it leases — switched off, so there is\n * no window to fall out of and nothing to check. Anything else must cover two re-mints.\n */\nfunction assertLeaseCoversTtl(leaseSeconds: number, ttlSeconds: number): void {\n if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds) throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);\n}\n\n/**\n * The engine must record a claim under the name it was given — on the create that TAKES it and on\n * every create that RENEWS it alike.\n *\n * An engine that renames a claim is one this control plane can neither renew nor release by id, which\n * is the whole protocol (fork ADR-0008): the renewal would take a second claim every time, and the\n * release would name something the engine never held. That is the wrong engine, not a degraded one,\n * so it throws rather than degrading — there is no answer this client could go on to give.\n */\nfunction assertClaimRecorded(handle: CircuitsShapeHandle, claim: string): void {\n if (handle.subscription === claim) return;\n throw new Error(\n `[pgxsinkit] the engine recorded this shape claim under \\`${handle.subscription}\\` rather than the ` +\n `subscription id it was sent (\\`${claim}\\`). Renewal and release are BY that id (fork ADR-0008), ` +\n `so an engine that renames a claim is not the one this client targets.`,\n );\n}\n\n/**\n * Compile one shape for one scope — the single form both the subscribe and the re-mint paths use.\n *\n * Shared between them on purpose: the re-mint RENEWS each grant's engine claim by repeating the create\n * that took it, so the request it sends has to be the request subscribe would build today. Two\n * spellings of \"compile this grant\" would be two chances for a renew to name a different definition\n * than the grant it is renewing — which the engine would answer with a different handle, and this\n * route would read as a revocation.\n */\nfunction compileGrant(\n options: Pick<SubscribeOptions, \"registry\" | \"params\">,\n claims: JwtClaims | null,\n shapeKey: string,\n scope?: readonly PredicateValue[],\n): CompiledShapeRequest {\n return compileShapeRequest(options.registry, {\n shapeKey,\n claims,\n ...(scope !== undefined ? { scope } : {}),\n ...(options.params ? { params: options.params } : {}),\n });\n}\n\n/** What a renewal attempt came to. `renewed` is the only outcome that keeps the grant. */\ntype RenewalOutcome = { renewed: true } | { revoked: string };\n\n/**\n * Renew one grant's engine claim: the SAME create, repeated with the SAME subscription id.\n *\n * This is the whole of the lease protocol on our side (fork ADR-0008). The engine has no separate\n * renew route because it needs none — a create naming a claim the shape already holds returns the same\n * handle, counts nothing, and moves the lease. So the re-mint, which already re-authorizes every grant\n * on the client's own refresh cadence, renews for free and renews exactly the grants that survived.\n *\n * The two failure outcomes are both \"this is no longer the stream the client follows\", and both end in\n * `revoked` rather than an error, because the client's answer to a revocation — truncate and\n * re-subscribe — is precisely the right one:\n *\n * - **A different handle.** The claim lapsed, or the shape was evicted, so this call re-subscribed\n * instead of renewing (ADR-0007) and the engine handed back a fresh shape on a fresh path. The\n * grant names the old one. The claim just taken is released immediately: nothing is following that\n * new stream, and the client's re-subscribe will take its own.\n * - **409.** The id names a different shape. Nothing was taken, so there is nothing to give back.\n *\n * Anything else the engine says is an OUTAGE and propagates — the route answers 503. A revocation\n * would tell the client it lost the scope, and a client told that clears the rows. An engine that\n * renames the claim propagates too, through {@link assertClaimRecorded}: that one is not an outage\n * either, it is the wrong engine.\n */\nasync function renewGrantClaim(\n engine: CircuitsEngineClient,\n request: CreateShapeRequest,\n grant: StreamGrant,\n ttlSeconds: number,\n): Promise<RenewalOutcome> {\n let handle;\n try {\n handle = await engine.createShape({ ...request, subscription: grant.claim });\n } catch (error) {\n if (error instanceof CircuitsEngineError && error.status === 409) {\n return { revoked: \"subscription id is held by another shape; re-subscribe\" };\n }\n throw error;\n }\n assertClaimRecorded(handle, grant.claim);\n // The handle comparison and the release of a fresh claim come BEFORE the lease guard, deliberately:\n // a misconfigured window is fatal to this request, and throwing it first would strand the claim\n // this very call just took.\n if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {\n await engine.releaseShape(handle.shapeId, grant.claim);\n return { revoked: \"shape stream changed; re-subscribe\" };\n }\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n return { renewed: true };\n}\n\n/**\n * What one requested shape expands to: the scopes to compile it at.\n *\n * `[undefined]` — a single scope-less compile — is the private tier, whose subject arrives in the\n * claims instead. A shared-tier shape expands to one entry per entitled scope, and none is a\n * refusal rather than an empty success: a subject with no scopes has nothing to read, and returning\n * zero grants silently would leave the client waiting on streams that were never created.\n *\n * An unknown shapeKey deliberately expands to `[undefined]` and is refused downstream by\n * `compileShapeRequest`, so the message for \"no such shape\" has exactly one author.\n *\n * Throws {@link EntitlementsUnavailableError} when the set exists but cannot be trusted yet — an\n * outage, not a refusal, and the route turns it into a 503.\n */\nfunction expandToScopes(\n options: Pick<SubscribeOptions, \"registry\" | \"entitlements\">,\n subject: string,\n shapeKey: string,\n): { scopes: readonly (readonly PredicateValue[] | undefined)[] } | { refusal: string } {\n const entry: SyncTableEntry | undefined = resolveEntryByShapeKey(options.registry, shapeKey);\n const shape = entry?.shape;\n if (shape == null) return { scopes: [undefined] };\n if (readShapeTier(shape) === \"private\") return { scopes: [undefined] };\n\n if (options.entitlements === undefined) {\n return { refusal: \"shared-tier shape, but this deployment configured no entitlement set\" };\n }\n // A refusal above, a THROW here, and the difference is permanence. \"No entitlement set configured\"\n // is a statement about this deployment that will read the same on every future request. \"Not ready\"\n // is a statement about this instant, and answering it with a denial would tell the client it lost\n // the scope — which makes it clear those rows. See {@link EntitlementsUnavailableError}.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n const held = options.entitlements.scopesFor(subject, shapeKey);\n if (held.length === 0) return { refusal: \"no entitled scopes\" };\n return { scopes: held };\n}\n\n/**\n * Subscribe to a batch of shapes: compile each against the registry, check entitlement, register it\n * with the engine, and mint ONE token covering all of them.\n *\n * A shared-tier shape FANS OUT: one stream per scope the subject holds, so K requested shapes yield\n * however many grants their entitlements come to. Expansion happens here rather than on the client\n * because this is the side holding the entitlement set — see {@link SubscriptionRequest}.\n *\n * A partial result rather than an all-or-nothing one. A subject holding K scopes at boot may\n * legitimately have lost one of them, and failing the whole batch on that would deny them the K-1\n * they still hold — so a denial is reported per subscription and the rest proceed.\n *\n * That partiality covers AUTHORIZATION only. An engine that cannot answer — degraded, unreachable —\n * is not a denial and must never be reported as one: a client told \"not entitled\" truncates that\n * scope and unsubscribes, so reporting an outage that way would turn a transient engine fault into\n * client-side data loss. Engine failures propagate, and the route answers 503.\n *\n * An entitlement set that is not `ready` joins it. It is the same shape of failure — a dependency\n * that cannot answer right now — and the client's response to a denial is the same clear, so it\n * propagates as {@link EntitlementsUnavailableError} and the route answers 503 too. What stays a\n * denial is the set being absent altogether: that is a deployment's permanent configuration.\n *\n * Entitlement is checked HERE as well as at the edge, and the duplication is deliberate: this is\n * what stops a shape being created and a capability minted for a scope the subject never held. The\n * edge's check bounds how long an already-minted one keeps working.\n */\nexport async function subscribeToShapes(\n options: SubscribeOptions,\n claims: JwtClaims | null,\n requests: readonly SubscriptionRequest[],\n now: number,\n): Promise<SubscribeResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const granted: GrantedSubscription[] = [];\n const denied: DeniedSubscription[] = [];\n const grants: StreamGrant[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const request of requests) {\n const deny = (reason: string, scope?: readonly PredicateValue[]) =>\n denied.push({ shapeKey: request.shapeKey, ...(scope !== undefined ? { scope } : {}), reason });\n\n // Every read is bound to a subject, both tiers. The private tier fuses the subject into the\n // predicate and the shared tier checks it against the entitlement set, but neither has an\n // anonymous form — a token with no subject would name a bearer no revocation could reach.\n if (subject === null) {\n deny(\"no subject\");\n continue;\n }\n\n const expanded = expandToScopes(options, subject, request.shapeKey);\n if (\"refusal\" in expanded) {\n deny(expanded.refusal);\n continue;\n }\n\n for (const scope of expanded.scopes) {\n const scoped = scope !== undefined ? { scope } : {};\n const compiled = compileGrant(options, claims, request.shapeKey, scope);\n if (compiled.outcome === \"deny\") {\n deny(compiled.reason, scope);\n continue;\n }\n\n // Enumeration said yes; ask the predicate too. The two are required to agree, and when they do\n // not it is this side that must catch it: the edge checks `permits` on EVERY read, so a scope\n // only `scopesFor` believes in would mint a capability for a stream the client can never\n // actually read. Better a denial it can see now than a stream that 403s forever.\n if (compiled.tier === \"shared\" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {\n deny(\"not entitled to this scope\", scope);\n continue;\n }\n\n // The private tier's grant records WHAT was authorized, not merely that something was. Its\n // predicate is a function of this subject's claims, and those change under the client's feet —\n // a role removed mid-session — so the re-mint has to be able to ask whether the shape this\n // grant points at is still the shape these claims compile to. The fingerprint is how it asks\n // without storing anything (ADR-0055 decision 6). The shared tier needs none: its predicate is\n // generated from the scope values, which the entitlement re-check already covers.\n const fp = compiled.tier === \"private\" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};\n\n // The claim is NAMED before it is taken, and the name is ours (fork ADR-0008). That is what\n // makes this create idempotent — a repeat with the same id renews rather than joining twice —\n // and what makes the release retry-safe: `DELETE ?subscription=…` drops this claim and only\n // this one. A uuid per grant, never per shape: two grants that deduplicate onto one shapeId are\n // two joins, and one id could only ever release one of them.\n const claim = crypto.randomUUID();\n\n // Deliberately unguarded: see the note above on why an engine fault is not a denial.\n const handle = await options.engine.createShape({ ...compiled.request, subscription: claim });\n assertClaimRecorded(handle, claim);\n // Checked per create rather than once at boot: the lease window is the engine's to report, and\n // this is the only place it is reported. A misconfigured pairing must surface as a 503 on the\n // very first subscribe, not as sessions quietly lapsing an idle window later.\n //\n // The claim is already taken by the time this can trip, so it is handed back before the error\n // leaves — nobody will ever follow this stream. Best effort, and the failure is SWALLOWED: the\n // configuration fault is what the operator has to see, and a release that also fails must not\n // mask it. An unreleased claim lapses on its own.\n try {\n assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);\n } catch (error) {\n await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});\n throw error;\n }\n\n granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });\n // The grant carries the shapeId this `createShape` returned AND the claim it was taken under,\n // and together they are what make the renew and release routes possible at all: both are\n // stateless, so the signed token is the only record of what this session holds.\n grants.push({\n path: handle.streamPath,\n shapeKey: request.shapeKey,\n shapeId: handle.shapeId,\n claim,\n ...scoped,\n ...fp,\n });\n }\n }\n\n if (subject === null || grants.length === 0) return { granted, denied };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, denied };\n}\n\n/**\n * The subscribe route: verified claims in, a token and stream paths out.\n *\n * Deliberately a POST that returns paths rather than a redirect to them. The client needs the whole\n * batch to open K long-polls and to know when to re-mint, and a redirect would give it one stream\n * and no expiry.\n */\nexport function createSubscribeHandler(\n options: SubscribeOptions & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleSubscribe(request: Request): Promise<Response> {\n let body: { subscriptions?: SubscriptionRequest[] };\n try {\n body = (await request.json()) as { subscriptions?: SubscriptionRequest[] };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (!Array.isArray(body.subscriptions)) {\n return Response.json({ error: \"subscriptions must be an array\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n\n // Unauthenticated is NOT a denial, for the same reason an engine outage is not: a client told\n // \"not entitled\" truncates the scope and unsubscribes, so answering an expired JWT that way\n // turns a re-login into data loss. 401 is what makes it a distinct, recoverable status the\n // client can retry through (ADR-0013).\n //\n // The check is on the SUBJECT, not on the claims object: a verified token with no `sub` names a\n // bearer no revocation could ever reach, so it is exactly as unusable as no token at all. A\n // deployment with no auth adapter never reaches here — `createSyncServer` refuses that pairing\n // at construction.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: SubscribeResult;\n try {\n result = await subscribeToShapes(options, claims, body.subscriptions, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer is an OUTAGE, and 503 is what keeps the client retrying.\n // Relaying it as a per-subscription denial would tell the client it lost entitlement, and a\n // client told that truncates the scope and unsubscribes — turning a transient fault into data\n // loss.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n // A lease window shorter than the token TTL is an operator's misconfiguration, and it joins the\n // 503s for the same reason: it is a statement about this deployment, never about this subject's\n // entitlements. Denying instead would make an unserviceable pairing look like lost access.\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n // 200 even when everything was denied: the per-subscription reasons ARE the response, and\n // collapsing them to a status code would tell a client that lost one scope out of K nothing\n // about which one.\n return Response.json(result);\n };\n}\n\nexport interface RefreshResult {\n token?: string;\n expiresAt?: number;\n /** Grants that survived re-authorization — see {@link refreshStreamToken} for what that is per tier. */\n granted: StreamGrant[];\n /**\n * Grants the subject may no longer read as granted: a shared scope they have lost, or a private\n * shape their current claims no longer compile to. The client truncates each and unsubscribes,\n * then re-subscribes for whatever it is entitled to now.\n */\n revoked: DeniedSubscription[];\n}\n\n/**\n * Re-mint a stream token from an existing one (ADR-0055 decision 6).\n *\n * The expiring token IS the request: its signature proves this control plane issued those grants, so\n * nothing has to be stored server-side to know what the subject held, and the edge stays stateless on\n * both halves. Expiry is deliberately not enforced here — a token is presented for re-mint precisely\n * because it is at or past its TTL — but the signature is, and **every grant is re-authorized**.\n * That re-check is what makes the TTL a revocation bound rather than a formality.\n *\n * BOTH TIERS are re-authorized, by the question each tier's authorization actually turns on.\n *\n * - Shared: the live entitlement set. Its predicate is generated from the scope values, so it cannot\n * drift with the subject; what can change is whether the subject still holds the scope.\n * - Private: **recompile the shape with the subject's CURRENT claims** and compare the fingerprint\n * the grant carries. A private predicate may read ANY verified claim, not only `sub`, so a subject\n * demoted mid-session — a role dropped, a tenant changed — is still the same authenticated subject\n * and would sail through a check that only re-verified the JWT. Re-verifying the JWT proves the\n * bearer is still who they were; it says nothing about whether the shape they hold is still the\n * shape their claims compile to, and only recompiling answers that.\n *\n * A fingerprint mismatch is a REVOCATION by design, including when the recompiled predicate would\n * still permit the subject something. The grant names one stream, that stream serves the old\n * predicate, and this route may not hand out a new one — the client's re-subscribe is where a new\n * shape is created, and this route is not that. So the grant is revoked, the client re-subscribes, the\n * control plane creates the shape its current claims compile to, and because the handle differs the\n * client re-snapshots through ADR-0056 decision 7's must-refetch.\n *\n * **This is also where every surviving grant's engine claim is RENEWED** (fork ADR-0008). A claim is a\n * lease: the engine releases one not renewed within `leaseSeconds`, because native reads terminate on\n * durable-streams and the renewal is the only liveness signal it has. Renewing here rather than on a\n * timer is what makes the cadence honest — this route already runs once per subject per TTL window and\n * already decides which grants are still authorized, so the renewal covers exactly the grants that\n * survived and costs no extra round trip. A revoked grant is deliberately NOT renewed: its lease\n * lapses and the engine reclaims the shape.\n *\n * The renewal is the same create, repeated with the grant's own `claim` id. Its outcomes are in\n * {@link renewGrantClaim}; a renewal that comes back a different handle, or 409s, revokes the grant\n * with a re-subscribe reason rather than failing the whole re-mint.\n *\n * `registry` is therefore REQUIRED rather than optional: a refresh route that cannot recompile cannot\n * re-authorize the private tier — and now cannot renew either, since the renewal IS the compiled\n * create. `engine` is required for the same reason.\n *\n * Throws {@link EntitlementsUnavailableError} rather than revoking when the set cannot be consulted —\n * the same outage-is-not-a-denial rule {@link subscribeToShapes} follows, and it matters more here:\n * `revoked` is the wire's clear-this-scope instruction, and this route runs every few minutes for\n * the life of every subscription. An engine that cannot answer a renewal joins it, as does a lease\n * window this deployment's TTL does not fit inside ({@link CircuitsLeaseConfigError}).\n */\nexport async function refreshStreamToken(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\">,\n claims: JwtClaims | null,\n expiringToken: string,\n now: number,\n): Promise<RefreshResult> {\n const subject = typeof claims?.sub === \"string\" ? claims.sub : null;\n const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });\n if (!verified.ok || subject === null) return { granted: [], revoked: [] };\n\n // The token names its subject; a token presented by anyone else is not a re-mint, it is a theft.\n if (verified.claims.sub !== subject) return { granted: [], revoked: [] };\n\n const granted: StreamGrant[] = [];\n const revoked: DeniedSubscription[] = [];\n const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n\n for (const grant of verified.claims.grants) {\n const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};\n if (grant.scope === undefined) {\n // Private tier: re-authorize by recompiling. See the note above on why the signed grant alone\n // is not the entitlement — the predicate is a function of claims that may have changed since\n // it was issued.\n const compiled = compileGrant(options, claims, grant.shapeKey);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, reason: compiled.reason });\n continue;\n }\n if (grant.fp === undefined) {\n // Nothing to compare against, so nothing that could establish this grant is still the right\n // one. Fail closed rather than trust it: the recovery is a re-subscribe, which costs the\n // client a re-snapshot and costs the subject nothing they are still entitled to.\n revoked.push({\n shapeKey: grant.shapeKey,\n reason: \"private grant carries no fingerprint and cannot be re-authorized\",\n });\n continue;\n }\n if ((await fingerprintShapeRequest(compiled.request)) !== grant.fp) {\n revoked.push({ shapeKey: grant.shapeKey, reason: \"shape predicate changed for this subject\" });\n continue;\n }\n // Re-authorized, so renew the claim it holds — the recompiled request is exactly the one that\n // took it, which the fingerprint just proved.\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n continue;\n }\n if (options.entitlements === undefined) {\n // Permanent, and therefore a real revocation: this deployment has no entitlement set, so a\n // shared grant can never be re-minted and the scope is not coming back.\n //\n // Worded as the EDGE words the same condition, and deliberately not as \"entitlements\n // unavailable\" — that string is now the 503 outage body, which means the exact opposite here:\n // an outage says nothing about this subject's scopes and must never clear a row.\n revoked.push({\n shapeKey: grant.shapeKey,\n ...scoped,\n reason: \"shared-tier grant, but this deployment configured no entitlement set\",\n });\n continue;\n }\n // Transient, and therefore NOT a revocation. `revoked` is an instruction to clear the scope, and\n // a re-mint is the most routine request on this route — an entitlement subscription that is a few\n // seconds behind would otherwise empty a subject's store every time it reconnected.\n if (!options.entitlements.ready) throw new EntitlementsUnavailableError();\n if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: \"not entitled to this scope\" });\n continue;\n }\n // Still entitled, so renew. The shared tier carries no fingerprint — its predicate is generated\n // from the scope values, which is why the entitlement check above is the whole question — so the\n // request is recompiled here, through the same {@link compileGrant} subscribe used.\n const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);\n if (compiled.outcome === \"deny\") {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });\n continue;\n }\n const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);\n if (\"revoked\" in renewal) {\n revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });\n continue;\n }\n granted.push(grant);\n }\n\n if (granted.length === 0) return { granted, revoked };\n\n const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });\n return { token, expiresAt: now + ttlSeconds, granted, revoked };\n}\n\n/**\n * The re-mint route. Takes the expiring token, answers with a fresh one and the list of grants that\n * did not survive re-authorization — the shared tier's against the live entitlement set, the private\n * tier's against a recompile with the subject's current claims — and **renews the engine claim of\n * every grant that did survive** (fork ADR-0008).\n *\n * `registry` for that recompile and `engine` for that renewal, both required for the reasons\n * {@link refreshStreamToken} gives.\n *\n * 200 even when everything was revoked, for the same reason subscribe answers 200 on a full denial:\n * the per-grant reasons ARE the response, and a client that lost one scope of K needs to know which.\n */\nexport function createRefreshHandler(\n options: Pick<SubscribeOptions, \"registry\" | \"engine\" | \"entitlements\" | \"key\" | \"ttlSeconds\" | \"params\"> & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRefresh(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // Same as subscribe: an unauthenticated re-mint is a credential problem, not a revocation. The\n // difference matters more here — a `revoked` answer makes the client truncate, and a token\n // expiring is the single most ordinary thing that happens on this route.\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: RefreshResult;\n try {\n result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // 503, never a `revoked` list: an entitlement set that cannot answer has said nothing about\n // this subject's scopes, and a client that read it as a revocation would clear rows it still\n // holds. The client retries with the token it already has, which the edge keeps honouring\n // until its TTL lapses.\n if (error instanceof EntitlementsUnavailableError) {\n return Response.json({ error: \"entitlements unavailable\" }, { status: 503 });\n }\n // An engine that could not answer a RENEWAL is the same case: the claim is still held (a lease\n // outlives a failed renewal by the rest of its window), the token the client holds still works,\n // and a `revoked` answer would clear rows over a transient fault.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n if (error instanceof CircuitsLeaseConfigError) {\n return Response.json({ error: \"sync engine lease window shorter than the token TTL\" }, { status: 503 });\n }\n throw error;\n }\n return Response.json(result);\n };\n}\n\n/**\n * Give back the engine claims a token's grants acquired — the close half of subscribe.\n *\n * **Why this route exists.** A native `POST /shapes` with a definition the engine already holds does\n * not create a second shape: it JOINS the existing one, under a claim of its own. Live claims are\n * load-bearing rather than bookkeeping — one live claim blocks both dormancy and eviction, precisely\n * because native durable-streams reads bypass the engine entirely, so a claim is the only thing that\n * tells it a reader it cannot see still exists. Without a release, a shape waits out its whole lease\n * window before it can go dormant, every time.\n *\n * **The token IS the request**, exactly as on the re-mint path: its signature proves this control\n * plane minted these grants, so nothing has to be stored server-side to know what was acquired.\n * Verified with `allowExpired`, and that is not a weakening — a session releases at CLOSE, which is\n * routinely past a 5-minute TTL, and expiry bounds how long a grant keeps *working*, not what it\n * proves was issued. A release grants its bearer nothing; the only thing it can do is give away\n * claims that this token's own subject holds.\n *\n * **ONE release per GRANT, deliberately not deduplicated by `shapeId`.** Two grants naming one shape\n * are two joins — the engine deduplicated identical definitions and counted both (ADR-0055 decision\n * 6) — so collapsing them here would return one of two claims and leak the other permanently. Each\n * grant releases its OWN claim (`DELETE /shapes/{id}?subscription=<claim>`), which is what makes one\n * release distinguishable from the other at all.\n *\n * **Idempotent and retry-safe** (fork ADR-0008). A claim is named, so releasing it twice is releasing\n * it once: the second `DELETE` is a no-op `200` and cannot touch another subscriber's claim. That is\n * a change in kind from the anonymous refcount decrement this route was first written against, and it\n * collapses the old asymmetry — a client, a proxy or an operator may repeat a release freely. A\n * release that never arrives at all is not a permanent leak either: the claim is a LEASE, renewed on\n * the token re-mint, so a session that crashed or was unloaded has its claims reclaimed by the engine\n * within `leaseSeconds`. What this route buys is promptness, not correctness.\n *\n * Refusals are refusals, not no-ops: a bad signature or a mismatched subject answers an error rather\n * than `{ released: 0 }`, because a token presented by anyone but its own subject is not a release,\n * it is an attempt to drop the victim's claims.\n */\nexport async function releaseStreamGrants(\n options: { engine: CircuitsEngineClient; key: CryptoKey },\n claims: JwtClaims | null,\n token: string,\n now: number,\n): Promise<{ released: number } | { refused: string }> {\n const subject = typeof claims?.sub === \"string\" && claims.sub !== \"\" ? claims.sub : null;\n if (subject === null) return { refused: \"unauthenticated\" };\n\n const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });\n if (!verified.ok) return { refused: verified.reason };\n if (verified.claims.sub !== subject) return { refused: \"token subject does not match the caller\" };\n\n for (const grant of verified.claims.grants) {\n await options.engine.releaseShape(grant.shapeId, grant.claim);\n }\n return { released: verified.claims.grants.length };\n}\n\n/**\n * The release route: the token a session was given, back at its close.\n *\n * **Safe to call more than once.** Every grant releases a NAMED claim, so a repeat is the same act\n * once (fork ADR-0008) — a duplicate close, a proxy retry or an operator replaying a request all\n * answer 200 and change nothing. The client still sends it at most once, but that is now a matter of\n * not making a pointless request rather than of correctness.\n *\n * 403 rather than 200 on a refusal — see {@link releaseStreamGrants} for why a refused release must\n * be visible. 401 when the caller has no subject, the same rule subscribe and re-mint follow: an\n * unauthenticated call is a credential problem, and it is the one thing here a client could fix.\n */\nexport function createReleaseHandler(\n options: {\n engine: CircuitsEngineClient;\n key: CryptoKey;\n } & {\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n },\n) {\n return async function handleRelease(request: Request): Promise<Response> {\n let body: { token?: string };\n try {\n body = (await request.json()) as { token?: string };\n } catch {\n return Response.json({ error: \"malformed body\" }, { status: 400 });\n }\n if (typeof body.token !== \"string\") {\n return Response.json({ error: \"token must be a string\" }, { status: 400 });\n }\n\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n if (typeof claims?.sub !== \"string\" || claims.sub === \"\") {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n let result: { released: number } | { refused: string };\n try {\n result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));\n } catch (error) {\n // An engine that could not answer has not dropped the claims. 503 says \"this deployment, not\n // you\", and a client is free to come back: releases are named and therefore idempotent (fork\n // ADR-0008), so a retry that races a release which actually landed is a no-op rather than a\n // theft. Whether it retries or not, the residue is bounded by the lease — an unreleased claim\n // lapses within `leaseSeconds` of its last renewal.\n if (error instanceof CircuitsEngineError) {\n return Response.json({ error: \"sync engine unavailable\" }, { status: 503 });\n }\n throw error;\n }\n\n if (\"refused\" in result) return Response.json({ error: result.refused }, { status: 403 });\n return Response.json(result);\n };\n}\n\n/** The control-plane paths the native read path mounts. */\nexport const subscribePath = \"/sync/v1/subscribe\";\nexport const refreshPath = \"/sync/v1/refresh\";\nexport const releasePath = \"/sync/v1/release\";\n\n/**\n * The convergence-barrier route (ADR-0056 decision 4).\n *\n * Proxied rather than exposed: the engine's control plane is unauthenticated by design and is not\n * client-reachable, so surfacing the barrier on our own authenticated endpoint costs nothing and\n * keeps the trust boundary intact.\n *\n * `maxAgeSeconds` may cache the answer briefly, but only a HEALTHY one. For the `pendingFlips` term\n * staleness is safe in exactly one direction — it moves the barrier backwards, so a stale reading can\n * only DELAY an alignment, never satisfy one falsely. `flipFailures` inverts that: a cached\n * pre-degradation zero would let a group align against an engine that has already\n * lost membership effects, which is precisely the alignment the term exists to refuse. So a degraded\n * reading is never cached and never served from cache, and the cache window is exactly the bound on\n * how long a client may align against a freshly-degraded engine — which is why the default is 0.\n */\nexport function createBarrierHandler(options: {\n engine: CircuitsEngineClient;\n resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;\n maxAgeSeconds?: number;\n}) {\n let cached: { at: number; body: BarrierBody } | null = null;\n const maxAge = options.maxAgeSeconds ?? 0;\n\n return async function handleBarrier(request: Request): Promise<Response> {\n const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;\n // The barrier says nothing about any subject's data — only whether the engine has finished\n // propagating — but it is still engine internals, so it needs a caller we recognise.\n if (options.resolveAuthClaims && claims === null) {\n return Response.json({ error: \"unauthenticated\" }, { status: 401 });\n }\n\n const now = Date.now() / 1000;\n if (cached && now - cached.at < maxAge) return Response.json(cached.body);\n\n const state = await options.engine.replicationState();\n const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };\n cached = body.flipFailures > 0 ? null : { at: now, body };\n return Response.json(body);\n };\n}\n\nexport const barrierPath = \"/sync/v1/barrier\";\n\n/** The barrier as the client reads it — the engine's LSN is operator detail and stays server-side. */\ninterface BarrierBody {\n pendingFlips: number;\n /** Abandoned flip batches. Non-zero is terminal for a group reading it, and is never cached. */\n flipFailures: number;\n}\n",
7
7
  "import { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport {\n conjoinPredicates,\n DENY_ALL_PREDICATE,\n isAndPredicate,\n isIsNullPredicate,\n isLeafPredicate,\n readShapeTier,\n type JwtClaims,\n type Predicate,\n type PredicateValue,\n type ShapeSpec,\n type SyncTableEntry,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport type { CreateShapeRequest } from \"./wire\";\n\n/** What a client asks the control plane for: a declared shape, plus the inputs its tier consumes. */\nexport interface ShapeRequest {\n /** The shape's unique identity, exactly as declared. Never a table name the client chose. */\n shapeKey: string;\n /** Verified claims. The private tier's only subject input; the shared tier never sees them. */\n claims: JwtClaims | null;\n /**\n * SHARED TIER — the scope values, positionally matching the shape's declared `scope` columns.\n * `null` is a legal value and compiles to `IS NULL`, so an absent element and a null one are\n * different things: arity is checked strictly rather than padded.\n */\n scope?: readonly PredicateValue[];\n /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */\n params?: Record<string, unknown>;\n}\n\n/**\n * The outcome of compiling a request. A denial is a first-class result rather than an exception\n * because it is an ordinary, expected outcome — an anonymous caller, a subject with no membership —\n * and because the caller's response to it (no handle, no shape, 403) is the same for every reason.\n */\nexport type CompiledShapeRequest =\n | { outcome: \"create\"; tier: \"shared\" | \"private\"; request: CreateShapeRequest }\n | { outcome: \"deny\"; reason: string };\n\n/**\n * Resolve the entry a request selects by its **`shapeKey`** — not by table name, since several\n * shapes (a read projection and its owner) legitimately read one physical table under distinct keys.\n * Schema qualification is significant. Returns undefined when nothing declares that key, and the\n * caller fails closed.\n */\nexport function resolveEntryByShapeKey(registry: SyncTableRegistry, shapeKey: string): SyncTableEntry | undefined {\n return Object.values(registry).find((entry) => entry?.shape?.shapeKey === shapeKey);\n}\n\n/**\n * The physical table the engine reads.\n *\n * Circuits introspects `information_schema` with `table_schema = 'public'` and keys its tables by\n * bare name, so a schema-qualified registry target has no engine-side spelling. Rather than send a\n * name that would 404 deep inside shape creation, refuse here with the reason — a real limitation of\n * the engine, tracked against the fork, not something the control plane can paper over.\n */\nfunction resolveShapeTarget(shape: ShapeSpec): { table: string } | { refusal: string } {\n const target = shape.physicalTable ?? shape.tableName;\n if (!target.includes(\".\")) return { table: target };\n const [schema] = target.split(\".\");\n if (schema === \"public\") return { table: target.slice(\"public.\".length) };\n return {\n refusal:\n `shape \"${shape.shapeKey}\" reads \"${target}\", but the engine introspects the public schema ` +\n `only and names tables bare — a non-public target has no shape it can be created under.`,\n };\n}\n\n/**\n * The columns the ENGINE emits onto the stream, or undefined for the whole row.\n *\n * Not the same set as the columns the CLIENT receives, and the difference is load-bearing. Read off\n * `shape.rowFilter.columns` when the registry declares one — which for a read projection is the\n * client keep-set PLUS its `serverOnlyColumns` — otherwise off `localTable`, so a shape with no\n * allow-list emits exactly what the local schema declares.\n *\n * `serverOnlyColumns` therefore ARE emitted by the engine, deliberately: an egress\n * `serverProjection.rowTransform` has to READ them, and the engine is the only thing that can fetch\n * them. They come off the wire at the stream edge, which strips every rewritten row back to the local\n * table's columns AFTER the transform has run (`createStreamGate`, ADR-0055 decision 5). So the\n * ordering hazard between rewriting and omission is ANSWERED — transform first, strip second, in one\n * place — rather than dissolved: this function must not \"helpfully\" narrow the allow-list to the\n * client keep-set, because that would starve the transform of its inputs and fail it open.\n */\nfunction emittedColumns(entry: SyncTableEntry): string[] | undefined {\n const explicit = entry.shape?.rowFilter?.columns;\n if (explicit != null && explicit.length > 0) return [...explicit];\n if (entry.clientProjection?.omitColumns == null) return undefined;\n return getTableConfig(entry.localTable).columns.map((column) => column.name);\n}\n\n/**\n * Compile a shape request into the engine's `POST /shapes` body, or a denial.\n *\n * The whole predicate is built here, in the control plane, from the registry — nothing predicate\n * shaped arrives on the wire. That is strictly stronger than the proxy's \"discard the client's\n * `where`\": there is no `where` on the wire to discard, so no parameter parsing to get right and no\n * grammar for a client to probe.\n */\nexport function compileShapeRequest(registry: SyncTableRegistry, request: ShapeRequest): CompiledShapeRequest {\n const entry = resolveEntryByShapeKey(registry, request.shapeKey);\n const shape = entry?.shape;\n if (entry == null || shape == null) {\n return { outcome: \"deny\", reason: `no shape declares shapeKey \"${request.shapeKey}\"` };\n }\n\n const target = resolveShapeTarget(shape);\n if (\"refusal\" in target) return { outcome: \"deny\", reason: target.refusal };\n\n const tier = readShapeTier(shape);\n const subject =\n tier === \"shared\" ? scopePredicate(shape, request.scope) : privatePredicate(shape, request.claims, request.params);\n if (\"refusal\" in subject) return { outcome: \"deny\", reason: subject.refusal };\n\n const where = conjoinPredicates(subject.predicate, shape.where);\n\n const narrowing = assertLocalPrimaryKeyIsPinned(entry, where);\n if (narrowing != null) return { outcome: \"deny\", reason: narrowing };\n\n const columns = emittedColumns(entry);\n\n return {\n outcome: \"create\",\n tier,\n request: {\n table: target.table,\n ...(where !== undefined ? { where } : {}),\n ...(columns !== undefined ? { columns } : {}),\n },\n };\n}\n\n/**\n * The shared tier's predicate: an `AND` of equalities over the declared scope columns, generated —\n * never authored. Every property the tier depends on comes from that generation. Two shapes of a\n * family cannot overlap, because a row carries one value per scope column. Two subscribers holding\n * the same scope values produce byte-identical requests, which is what lets Circuits collapse them\n * onto one stream and what makes the resulting stream cacheable at all.\n */\nfunction scopePredicate(\n shape: ShapeSpec,\n values: readonly PredicateValue[] | undefined,\n): { predicate: Predicate | undefined } | { refusal: string } {\n const columns = shape.scope ?? [];\n if (values == null) {\n return { refusal: `shape \"${shape.shapeKey}\" is shared-tier and requires ${columns.length} scope value(s)` };\n }\n if (values.length !== columns.length) {\n return {\n refusal:\n `shape \"${shape.shapeKey}\" takes ${columns.length} scope value(s) ` +\n `(${columns.join(\", \")}) but got ${values.length}`,\n };\n }\n\n const equalities = columns.map((col, index): Predicate => {\n const value = values[index]!;\n // NULL is a scope value like any other, and `col = NULL` is UNKNOWN for every row — so the one\n // that would silently match nothing is the one that has to become `IS NULL`.\n return value === null ? { col, isNull: true } : { col, op: \"eq\", value };\n });\n\n return { predicate: conjoinPredicates(...equalities) };\n}\n\n/**\n * Every column pinned to exactly one value by a predicate's **top-level conjunction**.\n *\n * Conservative on purpose: only `col = value` and `col IS NULL` conjuncts pin, and only where they\n * sit in the outermost `AND` chain. A branch under `OR` or `NOT` admits more than one value for its\n * column by construction, and an `IN (subquery)` admits as many as the subquery returns — none of\n * those pin, so none are collected.\n */\nfunction pinnedColumns(node: Predicate | undefined, into: Set<string> = new Set()): Set<string> {\n if (node == null) return into;\n if (isAndPredicate(node)) {\n for (const child of node.and) pinnedColumns(child, into);\n return into;\n }\n if (isIsNullPredicate(node)) {\n into.add(node.col);\n return into;\n }\n if (isLeafPredicate(node) && node.op === \"eq\") {\n into.add(node.col);\n }\n return into;\n}\n\n/**\n * Refuse a `clientProjection.localPrimaryKey` that narrows the server key without the predicate\n * pinning what it drops.\n *\n * The second of the two checks replacing ADR-0014's primary-key collision tripwire, and the one case\n * where a collision was never machinery at all. Narrowing is the point of `localPrimaryKey` — server\n * key `(owner_id, card_id)` becomes local key `(card_id)` because the caller only ever syncs their\n * own rows — and it is sound *exactly when* the shape's predicate admits one value for every dropped\n * column. Pinned, two server rows can never collapse onto one local key. Unpinned, they can, and the\n * client would silently keep whichever arrived last: under a plain INSERT that surfaced as a PK\n * collision, and under `upsert` it does not surface at all.\n *\n * Checked here rather than at `defineSyncTable` because the predicate is claims-dependent: what pins\n * `owner_id` is the subject fused into it, which does not exist until a real caller subscribes. The\n * refusal is therefore per-subscription, and lands at the same place and in the same form as every\n * other compile denial.\n */\nfunction assertLocalPrimaryKeyIsPinned(entry: SyncTableEntry, where: Predicate | undefined): string | null {\n const localKey = entry.clientProjection?.localPrimaryKey?.columns;\n if (localKey == null || localKey.length === 0) return null;\n\n const localKeySet = new Set<string>(localKey);\n const dropped = entry.primaryKey.columns.filter((column) => !localKeySet.has(column));\n if (dropped.length === 0) return null;\n\n const pinned = pinnedColumns(where);\n const unpinned = dropped.filter((column) => !pinned.has(column));\n if (unpinned.length === 0) return null;\n\n return (\n `shape \"${entry.shape!.shapeKey}\" declares clientProjection.localPrimaryKey ` +\n `(${localKey.join(\", \")}), dropping ${unpinned.join(\", \")} from the server primary key ` +\n `(${entry.primaryKey.columns.join(\", \")}) — but this caller's predicate does not pin ` +\n `${unpinned.length === 1 ? \"that column\" : \"those columns\"} to a single value, so two server rows ` +\n `could collapse onto one local key. Pin it with a top-level equality in the shape's rowFilter (or ` +\n `its scope), or widen localPrimaryKey to include it.`\n );\n}\n\n/** The private tier's predicate: the registry's own claims-fused filter, or a denial. */\nfunction privatePredicate(\n shape: ShapeSpec,\n claims: JwtClaims | null,\n params: Record<string, unknown> | undefined,\n): { predicate: Predicate | undefined } | { refusal: string } {\n const filter = shape.rowFilter?.customPredicate;\n if (filter == null) return { predicate: undefined };\n\n const resolved = filter(claims ?? {}, params);\n // Reference identity: a denied subject gets no shape at\n // all rather than an empty one, so nothing is created and nothing has to be torn down later.\n if (resolved === DENY_ALL_PREDICATE) {\n return { refusal: `shape \"${shape.shapeKey}\" denies this caller` };\n }\n return { predicate: resolved ?? undefined };\n}\n\n/**\n * Canonical JSON: object keys sorted, `undefined` members dropped, array order preserved.\n *\n * Emitted as a string directly rather than by rebuilding an object and handing it to\n * `JSON.stringify`, because a rebuilt object's key order is not entirely ours to choose — a JS engine\n * enumerates integer-like keys numerically ahead of insertion order, so a sorted rebuild is only\n * *usually* serialized in the order it was sorted into. Writing the bytes here removes the\n * \"usually\".\n *\n * Array order IS significant and is kept: `columns` is a projection whose order the engine sees, and\n * an `and`/`or` chain's operand order is part of the predicate as sent.\n */\nfunction canonicalJson(value: unknown): string {\n if (value === null || typeof value !== \"object\") return JSON.stringify(value ?? null);\n if (Array.isArray(value)) return `[${value.map((member) => canonicalJson(member ?? null)).join(\",\")}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, member]) => member !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : 1));\n return `{${entries.map(([key, member]) => `${JSON.stringify(key)}:${canonicalJson(member)}`).join(\",\")}}`;\n}\n\n/**\n * A content fingerprint of a compiled shape request — SHA-256 over its canonical JSON, lowercase hex.\n *\n * CANONICAL because the input is not a literal an author wrote: a predicate reaches here through\n * `rowFilter.customPredicate`, whose closure may assemble `{ col, op, value }` in whatever order its\n * branches happen to take, and `p.and(a, b)` on one path may nest where another flattens. Two\n * compiles that MEAN the same thing must fingerprint the same, or the equality below degrades into a\n * test of how the author's code was written on the day.\n *\n * This is an AUTHORIZATION equality check, not a cache key. Two requests fingerprinting the same are\n * the same shape to the engine — same table, same predicate, same projection — so a subject whose\n * recompiled shape still fingerprints as the one their grant names is still authorized for exactly\n * the stream that grant points at. A collision is therefore not a performance regression, it is an\n * authorization one, which is why this is a cryptographic digest and not a cheap hash.\n *\n * Used by the re-mint path (ADR-0055 decision 6) to re-authorize a private-tier grant against the\n * subject's current claims. Never sent to the engine, which knows nothing about it.\n */\nexport async function fingerprintShapeRequest(request: CreateShapeRequest): Promise<string> {\n const canonical = canonicalJson({\n table: request.table,\n where: request.where,\n columns: request.columns,\n changesOnly: request.changesOnly,\n });\n const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(canonical));\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n",
8
- "import { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport type { PredicateValue, RowTransform, RowTransformContext, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { resolveEntryByShapeKey } from \"./compile\";\nimport { findGrant, verifyStreamToken, type StreamGrant } from \"./stream-token\";\n\n/**\n * The live entitlement set the edge checks a shared-tier read against (ADR-0055 decision 7).\n *\n * An interface, not an implementation, because the source is a Circuits subscription over the\n * membership relations themselves — freshness is engine propagation, not a cache TTL, and there is\n * no database on the read path.\n */\nexport interface EntitlementSet {\n /**\n * Whether the entitlement set can be trusted right now. False while the subscription is catching\n * up, degraded, or stale.\n *\n * The edge denies when this is false. An unavailable entitlement set is never a permit — the\n * failure mode of the alternative is a disclosure, and the failure mode of this one is a subject\n * retrying a read.\n */\n readonly ready: boolean;\n /** Whether `subject` may read `shapeKey` at `scope`. */\n permits(subject: string, shapeKey: string, scope: readonly PredicateValue[]): boolean;\n /**\n * Every scope of `shapeKey` that `subject` holds, each an ordered tuple matching the shape's\n * declared scope columns.\n *\n * This is what lets a client subscribe by shape alone (ADR-0055 decision 6): it names\n * `offering_content`, and the control plane answers with one stream per offering the subject can\n * actually read. The alternative — the client naming scopes — makes it restate something only this\n * set knows, so its every answer is either redundant or wrong.\n *\n * Enumeration and `permits` must agree: a scope returned here that `permits` would refuse is a\n * grant the edge then rejects on every read.\n */\n scopesFor(subject: string, shapeKey: string): readonly (readonly PredicateValue[])[];\n}\n\n/**\n * The entitlement set cannot be consulted right now — it is catching up, degraded, or stale.\n *\n * An OUTAGE, and thrown rather than reported per subscription for exactly the reason an engine fault\n * is: a client told \"not entitled\" clears that scope and unsubscribes (ADR-0055 decision 6), so\n * relaying an unavailable set as a denial would turn a transient control-plane condition into\n * client-side data loss. The routes map it to 503, which is a status a client retries through.\n *\n * The EDGE does not throw this. A read arriving while the set is unavailable is denied (see\n * {@link EntitlementSet.ready}) and a denied read is not a revocation — it is a request the client\n * makes again.\n */\nexport class EntitlementsUnavailableError extends Error {\n constructor() {\n super(\n \"[pgxsinkit] the entitlement set is unavailable — it is catching up, degraded or stale; \" +\n \"shared-tier subscriptions cannot be decided right now\",\n );\n this.name = \"EntitlementsUnavailableError\";\n }\n}\n\nexport interface StreamGateOptions {\n /** Verifies the stream token. Minted by the control plane in the same process. */\n key: CryptoKey;\n /**\n * The registry the granted shapes are declared in — REQUIRED, unlike every other option here.\n *\n * The gate needs it to answer one question per read: does this shape declare a\n * `serverProjection.rowTransform`, and must its bytes therefore be rewritten before they reach the\n * client (ADR-0055 decision 5)? A gate that cannot see the registry cannot know, so it would proxy\n * a transform shape's raw rows — including the `serverOnlyColumns` fetched solely for the transform\n * — with nothing anywhere reporting a discrepancy. Making it required is what makes that mount\n * impossible to write, which is why it is not optional \"for deployments with no transform shape\":\n * the leak arrives on the day someone adds the first one, in a file nobody was editing.\n */\n registry: SyncTableRegistry;\n /**\n * The live entitlement set backing the shared tier. Optional for the same reason it is optional on\n * the control plane: a deployment whose registry declares no shared shape has nothing to ask it.\n * Absent, a shared-tier grant is DENIED rather than waved through — the two sides then agree that\n * an unconfigured entitlement set can never permit.\n */\n entitlements?: EntitlementSet;\n /**\n * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the\n * same value the engine is given as `ELECTRIC_CIRCUITS_DS_URL`, since both address the same paths.\n */\n durableStreamsUrl: string;\n /**\n * Deployment-supplied runtime params, handed to an egress `rowTransform` as its context's `params`\n * — the same values `SubscribeOptions.params` hands to `rowFilter.customPredicate`. A deployment\n * that configures them on one side and not the other gives its registry two different runtime\n * environments for one shape, so mount both from the same source.\n */\n params?: Record<string, unknown>;\n /** Injected for tests; defaults to the ambient `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * What DECIDING one read needs: the signing key, plus the entitlement set the shared tier is checked\n * against.\n *\n * Spelled as the gate's options with everything else relaxed to optional, rather than as\n * {@link StreamGateOptions} itself, because a caller that wants only the decision — a mount that\n * proxies for itself, a test pinning the authorization rules — has no gate to configure, and\n * requiring it to invent a `registry` and a `durableStreamsUrl` would demand values the answer\n * provably does not depend on.\n */\nexport type StreamAuthorizationOptions = Pick<StreamGateOptions, \"key\" | \"entitlements\"> &\n Partial<Omit<StreamGateOptions, \"key\" | \"entitlements\">>;\n\nexport type GateDecision =\n | {\n allow: true;\n grant: StreamGrant;\n /**\n * The token's subject. Carried on the decision because the egress transform stage needs it and\n * re-verifying the token to recover it would pay for a second HMAC on every rewritten read —\n * the verification that established it already happened here.\n */\n subject: string;\n }\n | { allow: false; reason: string };\n\n/**\n * Authorize one read of one stream path.\n *\n * Two checks, and they are not redundant. The token is a capability bounded by its TTL, which is the\n * only bound available when a hit-serving CDN sits in front and the request never reaches us. The\n * entitlement lookup is live, and bounds revocation by propagation latency instead whenever the\n * request does reach us. Which one binds is a property of the deployment, not of this code.\n *\n * A private-tier grant has no scope to check, so the token is the whole authorization and its TTL is\n * the whole revocation bound. That is the same bound a CDN-fronted shared read has, and it is worth\n * stating rather than leaving to be inferred.\n */\nexport async function authorizeStreamRead(\n options: StreamAuthorizationOptions,\n token: string | null,\n path: string,\n now: number,\n): Promise<GateDecision> {\n if (token == null || token === \"\") return { allow: false, reason: \"no stream token\" };\n\n const verified = await verifyStreamToken(options.key, token, now);\n if (!verified.ok) return { allow: false, reason: verified.reason };\n\n const grant = findGrant(verified.claims, path);\n if (grant == null) return { allow: false, reason: \"token grants no such stream\" };\n\n const subject = verified.claims.sub;\n if (grant.scope === undefined) return { allow: true, grant, subject };\n\n const entitlements = options.entitlements;\n if (entitlements === undefined) {\n return { allow: false, reason: \"shared-tier grant, but this deployment configured no entitlement set\" };\n }\n if (!entitlements.ready) return { allow: false, reason: \"entitlements unavailable\" };\n if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n return { allow: false, reason: \"not entitled to this scope\" };\n }\n return { allow: true, grant, subject };\n}\n\n/**\n * Read the stream token off a request.\n *\n * `Authorization`, never a query parameter, and this is a correctness condition rather than a\n * convention: the cache key is the URL, so a token in the URL gives every subscriber a distinct key\n * and destroys precisely the sharing the shared tier exists for. A cache must also be configured not\n * to vary on this header — which it can only do if the header is where the token is.\n */\nexport function readStreamToken(request: Request): string | null {\n const header = request.headers.get(\"authorization\");\n if (header == null) return null;\n const [scheme, value] = header.split(\" \");\n return scheme?.toLowerCase() === \"bearer\" && value ? value : null;\n}\n\n/**\n * The response headers a browser must be allowed to READ off a stream-edge response.\n *\n * CORS lets script see only a short safelist of response headers (`cache-control`, `content-language`,\n * `content-length`, `content-type`, `expires`, `last-modified`, `pragma`). Every header the\n * durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them\n * unless the mount names them on `Access-Control-Expose-Headers`.\n *\n * The failure that follows is silent and expensive rather than loud. `@durable-streams/client` drives\n * its entire read loop off these headers — verified by grepping the installed 0.2.6 dist\n * (`@durable-streams/client/dist/index.js`, mirrored in its shipped `src/`): `Stream-Next-Offset`,\n * `Stream-Cursor` and `Stream-Closed` are read per response, `Stream-Up-To-Date` is a presence check\n * (`headers.has`, which is why it is easy to miss), `stream-sse-data-encoding` decides SSE payload\n * decoding, and `etag` is read on the stream-metadata path. Stripped of them, the client never learns\n * an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which presents\n * as a hot loop of hundreds of requests per second per shape with no error raised anywhere.\n *\n * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are request headers in that client version. They\n * are named here anyway because this list is a statement about the ds protocol's response namespace\n * rather than about which subset one client version happens to read today — exposing a header a\n * response never carries is inert, while omitting one that it does carry wedges the reader. The\n * `Producer-*` headers are deliberately absent: they belong to the write path, which does not come\n * through this gate.\n *\n * EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL\n * (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's\n * headers (verbatim for an ordinary shape, minus the caching ones for a rewritten one), and an\n * exposure list is meaningless without the `Access-Control-Allow-Origin` decision that only the mount\n * owns.\n */\nexport const STREAM_READ_EXPOSED_HEADERS: readonly string[] = [\n \"stream-next-offset\",\n \"stream-up-to-date\",\n \"stream-cursor\",\n \"stream-closed\",\n \"stream-seq\",\n \"stream-ttl\",\n \"stream-expires-at\",\n \"stream-sse-data-encoding\",\n \"etag\",\n];\n\n/**\n * A durable-streams long-poll body as the transform stage handles it.\n *\n * Deliberately NOT `StreamEnvelope`: the gate is a proxy, and typing the body as the contract would\n * assert that the edge validates a wire form it only ever forwards. All it needs to know is that an\n * envelope may carry a `value` object — a delete envelope is key-only, so it has nothing to rewrite\n * and nothing to disclose.\n */\ninterface ProxiedEnvelope {\n value?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * The response headers a rewritten body may be answered with.\n *\n * `cache-control: private, no-store` is the governing invariant, not a precaution: a transform makes\n * the bytes a function of the SUBJECT, so nothing between this edge and the browser that requested\n * them may share or store them. `etag` goes for the same reason — an upstream validator describes the\n * bytes durable-streams holds, not the ones we just produced, and honouring it would let a\n * revalidation return another subject's rewrite. `content-length` and `content-encoding` describe a\n * body that no longer exists: the length changed under the rewrite, and `fetch` already decoded what\n * it handed us.\n *\n * Everything else is kept VERBATIM — every `stream-*` header and the content type. The client's whole\n * read loop drives off them (see {@link STREAM_READ_EXPOSED_HEADERS}); an edge that dropped\n * `stream-next-offset` while rewriting would present as a hot loop, not as a redaction bug.\n */\nfunction rewrittenEgressHeaders(upstream: Headers): Headers {\n const headers = new Headers(upstream);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n headers.set(\"cache-control\", \"private, no-store\");\n return headers;\n}\n\n/** Whether this read asks for SSE framing, by either of the two ways the ds protocol expresses it. */\nfunction asksForSse(request: Request): boolean {\n return (\n new URL(request.url).searchParams.get(\"live\") === \"sse\" ||\n (request.headers.get(\"accept\") ?? \"\").includes(\"text/event-stream\")\n );\n}\n\n/**\n * The edge: gate, then proxy bytes — rewriting them only for the shapes that declare a rewrite.\n *\n * There is no per-read FILTERING here at all, and no per-read rewriting for shapes that declare none.\n * Predicates were resolved at shape creation, so what remains for almost every read is a decision and\n * a copy — which is why this can sit in the TypeScript control-plane process without CPU being the\n * axis that decides where it belongs.\n *\n * A shape that declares `serverProjection.rowTransform` is the one exception: it is rewritten HERE,\n * per request, with the subject taken from the stream token, and answered `private, no-store`. This\n * is the rewriting origin ADR-0055 decision 5 names, confined to the shapes that incur it — a\n * transform shape gives up CDN shareability and SSE framing, and every other shape gives up nothing.\n * The transform's `serverOnlyColumns` are fetched by the engine so the transform can read them and\n * are stripped here, after it runs, to the columns the client's local table declares.\n *\n * The claims a transform sees at the edge are `{ sub }` and nothing else: a stream token carries the\n * subject, not the JWT it was minted from, and re-deriving richer claims per read would put an auth\n * provider call on the read path this whole topology exists to keep off it. A transform that needs\n * more than the subject is therefore NOT expressible at egress — put the subject-dependent part in\n * the shape's private `rowFilter.customPredicate`, which is compiled at subscribe time from the full\n * verified claims.\n */\nexport function createStreamGate(options: StreamGateOptions) {\n const doFetch = options.fetch ?? fetch;\n const base = options.durableStreamsUrl.replace(/\\/+$/, \"\");\n\n return async function handleStreamRead(request: Request, path: string, now: number): Promise<Response> {\n const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);\n if (!decision.allow) {\n return new Response(JSON.stringify({ error: decision.reason }), {\n status: 403,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Resolved by shapeKey, exactly as the control plane resolved it to create the shape, so the edge\n // and the control plane cannot disagree about which declaration governs this stream.\n const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);\n const transform: RowTransform | undefined = entry?.serverProjection?.rowTransform;\n\n // Refused BEFORE the upstream fetch: the rewrite needs a whole JSON body per response, and SSE\n // delivers a frame stream instead. Parsing that would mean a second body parser for a mode no\n // pgxsinkit client uses, so the mode is declined rather than half-supported.\n if (transform != null && asksForSse(request)) {\n return new Response(\n JSON.stringify({ error: \"this shape is rewritten at egress and is served as JSON long-poll only\" }),\n { status: 406, headers: { \"content-type\": \"application/json\" } },\n );\n }\n\n // Forward the ds protocol's own query string untouched — offsets and the live flag are the\n // protocol's, not ours, and rewriting them is how a proxy ends up owning a contract it does not\n // define. The token does NOT travel on: durable-streams has no read authorization in any\n // implementation, so it would only be an unread secret sitting in another service's logs.\n const upstreamUrl = new URL(`${base}/${path}`);\n upstreamUrl.search = new URL(request.url).search;\n\n const forwarded = new Headers(request.headers);\n forwarded.delete(\"authorization\");\n forwarded.delete(\"host\");\n\n const init: RequestInit = { method: request.method, headers: forwarded, signal: request.signal };\n\n // A downstream that walks away mid-long-poll (a client's clean `stop()`/unsubscribe) aborts\n // `request.signal`, and the forwarded fetch rejects with an AbortError. That is the cancellation\n // working as designed, not a failure — but left to propagate it surfaced as a 500 plus a raw\n // DOMException in every consumer's error log, once per stream, at every clean shutdown. Nothing\n // is ever delivered on an aborted request, so answer the mount's await with 499 (client closed\n // request) and stay quiet. A rejection with the signal NOT aborted is a real failure and still\n // propagates.\n const upstreamFetch = async (): Promise<Response> => {\n try {\n return await doFetch(upstreamUrl, init);\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n };\n\n // The pass-through path hands back the upstream Response OBJECT, untouched. Not \"an equivalent\n // response\" — the same one, so a shape that declares no transform pays nothing for the existence\n // of this stage and keeps whatever caching headers durable-streams answered with.\n if (transform == null || entry == null) return upstreamFetch();\n\n const upstream = await upstreamFetch();\n if (upstream.status === 499) return upstream;\n const headers = rewrittenEgressHeaders(upstream.headers);\n\n // 204 long-poll timeouts, 304s, upstream errors, and HEAD probes: nothing to rewrite, but they\n // are still answers about a subject-dependent stream, so they leave with the same no-store,\n // no-etag posture. HEAD belongs here because it answers `application/json` with NO body — parsing\n // it would throw on a request that is only asking for the headers.\n if (\n request.method === \"HEAD\" ||\n upstream.status !== 200 ||\n !(upstream.headers.get(\"content-type\") ?? \"\").includes(\"application/json\")\n ) {\n return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });\n }\n\n // The body read can abort the same way the fetch can (the poll delivered headers, the client\n // left before the body finished) — same cancellation, same quiet answer.\n let parsed: unknown;\n try {\n parsed = (await upstream.json()) as unknown;\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n const isBatch = Array.isArray(parsed);\n const envelopes = (isBatch ? parsed : [parsed]) as ProxiedEnvelope[];\n\n // The client keep-set: the columns the LOCAL table declares, computed once per request. Stripping\n // to it after the transform runs is what keeps `serverOnlyColumns` — fetched by the engine solely\n // so the transform could read them — off the client wire, and it also drops any key a transform\n // invented, so an egress rewrite can never widen the shape the client's schema was built for.\n const keep = new Set(getTableConfig(entry.localTable).columns.map((column) => column.name));\n const context: RowTransformContext = {\n claims: { sub: decision.subject },\n ...(options.params ? { params: options.params } : {}),\n };\n\n const rewritten = envelopes.map((envelope) => {\n const value = envelope?.value;\n if (value == null || typeof value !== \"object\") return envelope;\n const transformed = transform(value as Record<string, unknown>, context);\n const stripped: Record<string, unknown> = {};\n for (const [column, cell] of Object.entries(transformed)) {\n if (keep.has(column)) stripped[column] = cell;\n }\n return { ...envelope, value: stripped };\n });\n\n // Answered in the shape it arrived in. A ds long-poll body is an array, and the single-object case\n // is only defensive — re-emitting it as an array would corrupt a body the client can parse today.\n return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {\n status: upstream.status,\n statusText: upstream.statusText,\n headers,\n });\n };\n}\n",
8
+ "import { getTableConfig } from \"drizzle-orm/pg-core\";\n\nimport type { PredicateValue, RowTransform, RowTransformContext, SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { resolveEntryByShapeKey } from \"./compile\";\nimport { findGrant, verifyStreamToken, type StreamGrant } from \"./stream-token\";\n\n/**\n * The live entitlement set the edge checks a shared-tier read against (ADR-0055 decision 7).\n *\n * An interface, not an implementation, because the source is a Circuits subscription over the\n * membership relations themselves — freshness is engine propagation, not a cache TTL, and there is\n * no database on the read path.\n */\nexport interface EntitlementSet {\n /**\n * Whether the entitlement set can be trusted right now. False while the subscription is catching\n * up, degraded, or stale.\n *\n * The edge denies when this is false. An unavailable entitlement set is never a permit — the\n * failure mode of the alternative is a disclosure, and the failure mode of this one is a subject\n * retrying a read.\n */\n readonly ready: boolean;\n /** Whether `subject` may read `shapeKey` at `scope`. */\n permits(subject: string, shapeKey: string, scope: readonly PredicateValue[]): boolean;\n /**\n * Every scope of `shapeKey` that `subject` holds, each an ordered tuple matching the shape's\n * declared scope columns.\n *\n * This is what lets a client subscribe by shape alone (ADR-0055 decision 6): it names\n * `offering_content`, and the control plane answers with one stream per offering the subject can\n * actually read. The alternative — the client naming scopes — makes it restate something only this\n * set knows, so its every answer is either redundant or wrong.\n *\n * Enumeration and `permits` must agree: a scope returned here that `permits` would refuse is a\n * grant the edge then rejects on every read.\n */\n scopesFor(subject: string, shapeKey: string): readonly (readonly PredicateValue[])[];\n}\n\n/**\n * The entitlement set cannot be consulted right now — it is catching up, degraded, or stale.\n *\n * An OUTAGE, and thrown rather than reported per subscription for exactly the reason an engine fault\n * is: a client told \"not entitled\" clears that scope and unsubscribes (ADR-0055 decision 6), so\n * relaying an unavailable set as a denial would turn a transient control-plane condition into\n * client-side data loss. The routes map it to 503, which is a status a client retries through.\n *\n * The EDGE does not throw this. A read arriving while the set is unavailable is denied (see\n * {@link EntitlementSet.ready}) and a denied read is not a revocation — it is a request the client\n * makes again.\n */\nexport class EntitlementsUnavailableError extends Error {\n constructor() {\n super(\n \"[pgxsinkit] the entitlement set is unavailable — it is catching up, degraded or stale; \" +\n \"shared-tier subscriptions cannot be decided right now\",\n );\n this.name = \"EntitlementsUnavailableError\";\n }\n}\n\nexport interface StreamGateOptions {\n /** Verifies the stream token. Minted by the control plane in the same process. */\n key: CryptoKey;\n /**\n * The registry the granted shapes are declared in — REQUIRED, unlike every other option here.\n *\n * The gate needs it to answer one question per read: does this shape declare a\n * `serverProjection.rowTransform`, and must its bytes therefore be rewritten before they reach the\n * client (ADR-0055 decision 5)? A gate that cannot see the registry cannot know, so it would proxy\n * a transform shape's raw rows — including the `serverOnlyColumns` fetched solely for the transform\n * — with nothing anywhere reporting a discrepancy. Making it required is what makes that mount\n * impossible to write, which is why it is not optional \"for deployments with no transform shape\":\n * the leak arrives on the day someone adds the first one, in a file nobody was editing.\n */\n registry: SyncTableRegistry;\n /**\n * The live entitlement set backing the shared tier. Optional for the same reason it is optional on\n * the control plane: a deployment whose registry declares no shared shape has nothing to ask it.\n * Absent, a shared-tier grant is DENIED rather than waved through — the two sides then agree that\n * an unconfigured entitlement set can never permit.\n */\n entitlements?: EntitlementSet;\n /**\n * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the\n * same value the engine is given as `CIRCUITS_DS_URL`, since both address the same paths.\n */\n durableStreamsUrl: string;\n /**\n * Deployment-supplied runtime params, handed to an egress `rowTransform` as its context's `params`\n * — the same values `SubscribeOptions.params` hands to `rowFilter.customPredicate`. A deployment\n * that configures them on one side and not the other gives its registry two different runtime\n * environments for one shape, so mount both from the same source.\n */\n params?: Record<string, unknown>;\n /** Injected for tests; defaults to the ambient `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * What DECIDING one read needs: the signing key, plus the entitlement set the shared tier is checked\n * against.\n *\n * Spelled as the gate's options with everything else relaxed to optional, rather than as\n * {@link StreamGateOptions} itself, because a caller that wants only the decision — a mount that\n * proxies for itself, a test pinning the authorization rules — has no gate to configure, and\n * requiring it to invent a `registry` and a `durableStreamsUrl` would demand values the answer\n * provably does not depend on.\n */\nexport type StreamAuthorizationOptions = Pick<StreamGateOptions, \"key\" | \"entitlements\"> &\n Partial<Omit<StreamGateOptions, \"key\" | \"entitlements\">>;\n\nexport type GateDecision =\n | {\n allow: true;\n grant: StreamGrant;\n /**\n * The token's subject. Carried on the decision because the egress transform stage needs it and\n * re-verifying the token to recover it would pay for a second HMAC on every rewritten read —\n * the verification that established it already happened here.\n */\n subject: string;\n }\n | { allow: false; reason: string };\n\n/**\n * Authorize one read of one stream path.\n *\n * Two checks, and they are not redundant. The token is a capability bounded by its TTL, which is the\n * only bound available when a hit-serving CDN sits in front and the request never reaches us. The\n * entitlement lookup is live, and bounds revocation by propagation latency instead whenever the\n * request does reach us. Which one binds is a property of the deployment, not of this code.\n *\n * A private-tier grant has no scope to check, so the token is the whole authorization and its TTL is\n * the whole revocation bound. That is the same bound a CDN-fronted shared read has, and it is worth\n * stating rather than leaving to be inferred.\n */\nexport async function authorizeStreamRead(\n options: StreamAuthorizationOptions,\n token: string | null,\n path: string,\n now: number,\n): Promise<GateDecision> {\n if (token == null || token === \"\") return { allow: false, reason: \"no stream token\" };\n\n const verified = await verifyStreamToken(options.key, token, now);\n if (!verified.ok) return { allow: false, reason: verified.reason };\n\n const grant = findGrant(verified.claims, path);\n if (grant == null) return { allow: false, reason: \"token grants no such stream\" };\n\n const subject = verified.claims.sub;\n if (grant.scope === undefined) return { allow: true, grant, subject };\n\n const entitlements = options.entitlements;\n if (entitlements === undefined) {\n return { allow: false, reason: \"shared-tier grant, but this deployment configured no entitlement set\" };\n }\n if (!entitlements.ready) return { allow: false, reason: \"entitlements unavailable\" };\n if (!entitlements.permits(subject, grant.shapeKey, grant.scope)) {\n return { allow: false, reason: \"not entitled to this scope\" };\n }\n return { allow: true, grant, subject };\n}\n\n/**\n * Read the stream token off a request.\n *\n * `Authorization`, never a query parameter, and this is a correctness condition rather than a\n * convention: the cache key is the URL, so a token in the URL gives every subscriber a distinct key\n * and destroys precisely the sharing the shared tier exists for. A cache must also be configured not\n * to vary on this header — which it can only do if the header is where the token is.\n */\nexport function readStreamToken(request: Request): string | null {\n const header = request.headers.get(\"authorization\");\n if (header == null) return null;\n const [scheme, value] = header.split(\" \");\n return scheme?.toLowerCase() === \"bearer\" && value ? value : null;\n}\n\n/**\n * The response headers a browser must be allowed to READ off a stream-edge response.\n *\n * CORS lets script see only a short safelist of response headers (`cache-control`, `content-language`,\n * `content-length`, `content-type`, `expires`, `last-modified`, `pragma`). Every header the\n * durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them\n * unless the mount names them on `Access-Control-Expose-Headers`.\n *\n * The failure that follows is silent and expensive rather than loud. `@durable-streams/client` drives\n * its entire read loop off these headers — verified by grepping the installed 0.2.6 dist\n * (`@durable-streams/client/dist/index.js`, mirrored in its shipped `src/`): `Stream-Next-Offset`,\n * `Stream-Cursor` and `Stream-Closed` are read per response, `Stream-Up-To-Date` is a presence check\n * (`headers.has`, which is why it is easy to miss), `stream-sse-data-encoding` decides SSE payload\n * decoding, and `etag` is read on the stream-metadata path. Stripped of them, the client never learns\n * an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which presents\n * as a hot loop of hundreds of requests per second per shape with no error raised anywhere.\n *\n * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are request headers in that client version. They\n * are named here anyway because this list is a statement about the ds protocol's response namespace\n * rather than about which subset one client version happens to read today — exposing a header a\n * response never carries is inert, while omitting one that it does carry wedges the reader. The\n * `Producer-*` headers are deliberately absent: they belong to the write path, which does not come\n * through this gate.\n *\n * EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL\n * (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's\n * headers (verbatim for an ordinary shape, minus the caching ones for a rewritten one), and an\n * exposure list is meaningless without the `Access-Control-Allow-Origin` decision that only the mount\n * owns.\n */\nexport const STREAM_READ_EXPOSED_HEADERS: readonly string[] = [\n \"stream-next-offset\",\n \"stream-up-to-date\",\n \"stream-cursor\",\n \"stream-closed\",\n \"stream-seq\",\n \"stream-ttl\",\n \"stream-expires-at\",\n \"stream-sse-data-encoding\",\n \"etag\",\n];\n\n/**\n * A durable-streams long-poll body as the transform stage handles it.\n *\n * Deliberately NOT `StreamEnvelope`: the gate is a proxy, and typing the body as the contract would\n * assert that the edge validates a wire form it only ever forwards. All it needs to know is that an\n * envelope may carry a `value` object — a delete envelope is key-only, so it has nothing to rewrite\n * and nothing to disclose.\n */\ninterface ProxiedEnvelope {\n value?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * The response headers a rewritten body may be answered with.\n *\n * `cache-control: private, no-store` is the governing invariant, not a precaution: a transform makes\n * the bytes a function of the SUBJECT, so nothing between this edge and the browser that requested\n * them may share or store them. `etag` goes for the same reason — an upstream validator describes the\n * bytes durable-streams holds, not the ones we just produced, and honouring it would let a\n * revalidation return another subject's rewrite. `content-length` and `content-encoding` describe a\n * body that no longer exists: the length changed under the rewrite, and `fetch` already decoded what\n * it handed us.\n *\n * Everything else is kept VERBATIM — every `stream-*` header and the content type. The client's whole\n * read loop drives off them (see {@link STREAM_READ_EXPOSED_HEADERS}); an edge that dropped\n * `stream-next-offset` while rewriting would present as a hot loop, not as a redaction bug.\n */\nfunction rewrittenEgressHeaders(upstream: Headers): Headers {\n const headers = new Headers(upstream);\n headers.delete(\"content-length\");\n headers.delete(\"content-encoding\");\n headers.delete(\"etag\");\n headers.set(\"cache-control\", \"private, no-store\");\n return headers;\n}\n\n/** Whether this read asks for SSE framing, by either of the two ways the ds protocol expresses it. */\nfunction asksForSse(request: Request): boolean {\n return (\n new URL(request.url).searchParams.get(\"live\") === \"sse\" ||\n (request.headers.get(\"accept\") ?? \"\").includes(\"text/event-stream\")\n );\n}\n\n/**\n * The edge: gate, then proxy bytes — rewriting them only for the shapes that declare a rewrite.\n *\n * There is no per-read FILTERING here at all, and no per-read rewriting for shapes that declare none.\n * Predicates were resolved at shape creation, so what remains for almost every read is a decision and\n * a copy — which is why this can sit in the TypeScript control-plane process without CPU being the\n * axis that decides where it belongs.\n *\n * A shape that declares `serverProjection.rowTransform` is the one exception: it is rewritten HERE,\n * per request, with the subject taken from the stream token, and answered `private, no-store`. This\n * is the rewriting origin ADR-0055 decision 5 names, confined to the shapes that incur it — a\n * transform shape gives up CDN shareability and SSE framing, and every other shape gives up nothing.\n * The transform's `serverOnlyColumns` are fetched by the engine so the transform can read them and\n * are stripped here, after it runs, to the columns the client's local table declares.\n *\n * The claims a transform sees at the edge are `{ sub }` and nothing else: a stream token carries the\n * subject, not the JWT it was minted from, and re-deriving richer claims per read would put an auth\n * provider call on the read path this whole topology exists to keep off it. A transform that needs\n * more than the subject is therefore NOT expressible at egress — put the subject-dependent part in\n * the shape's private `rowFilter.customPredicate`, which is compiled at subscribe time from the full\n * verified claims.\n */\nexport function createStreamGate(options: StreamGateOptions) {\n const doFetch = options.fetch ?? fetch;\n const base = options.durableStreamsUrl.replace(/\\/+$/, \"\");\n\n return async function handleStreamRead(request: Request, path: string, now: number): Promise<Response> {\n const decision = await authorizeStreamRead(options, readStreamToken(request), path, now);\n if (!decision.allow) {\n return new Response(JSON.stringify({ error: decision.reason }), {\n status: 403,\n headers: { \"content-type\": \"application/json\" },\n });\n }\n\n // Resolved by shapeKey, exactly as the control plane resolved it to create the shape, so the edge\n // and the control plane cannot disagree about which declaration governs this stream.\n const entry = resolveEntryByShapeKey(options.registry, decision.grant.shapeKey);\n const transform: RowTransform | undefined = entry?.serverProjection?.rowTransform;\n\n // Refused BEFORE the upstream fetch: the rewrite needs a whole JSON body per response, and SSE\n // delivers a frame stream instead. Parsing that would mean a second body parser for a mode no\n // pgxsinkit client uses, so the mode is declined rather than half-supported.\n if (transform != null && asksForSse(request)) {\n return new Response(\n JSON.stringify({ error: \"this shape is rewritten at egress and is served as JSON long-poll only\" }),\n { status: 406, headers: { \"content-type\": \"application/json\" } },\n );\n }\n\n // Forward the ds protocol's own query string untouched — offsets and the live flag are the\n // protocol's, not ours, and rewriting them is how a proxy ends up owning a contract it does not\n // define. The token does NOT travel on: durable-streams has no read authorization in any\n // implementation, so it would only be an unread secret sitting in another service's logs.\n const upstreamUrl = new URL(`${base}/${path}`);\n upstreamUrl.search = new URL(request.url).search;\n\n const forwarded = new Headers(request.headers);\n forwarded.delete(\"authorization\");\n forwarded.delete(\"host\");\n\n const init: RequestInit = { method: request.method, headers: forwarded, signal: request.signal };\n\n // A downstream that walks away mid-long-poll (a client's clean `stop()`/unsubscribe) aborts\n // `request.signal`, and the forwarded fetch rejects with an AbortError. That is the cancellation\n // working as designed, not a failure — but left to propagate it surfaced as a 500 plus a raw\n // DOMException in every consumer's error log, once per stream, at every clean shutdown. Nothing\n // is ever delivered on an aborted request, so answer the mount's await with 499 (client closed\n // request) and stay quiet. A rejection with the signal NOT aborted is a real failure and still\n // propagates.\n const upstreamFetch = async (): Promise<Response> => {\n try {\n return await doFetch(upstreamUrl, init);\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n };\n\n // The pass-through path hands back the upstream Response OBJECT, untouched. Not \"an equivalent\n // response\" — the same one, so a shape that declares no transform pays nothing for the existence\n // of this stage and keeps whatever caching headers durable-streams answered with.\n if (transform == null || entry == null) return upstreamFetch();\n\n const upstream = await upstreamFetch();\n if (upstream.status === 499) return upstream;\n const headers = rewrittenEgressHeaders(upstream.headers);\n\n // 204 long-poll timeouts, 304s, upstream errors, and HEAD probes: nothing to rewrite, but they\n // are still answers about a subject-dependent stream, so they leave with the same no-store,\n // no-etag posture. HEAD belongs here because it answers `application/json` with NO body — parsing\n // it would throw on a request that is only asking for the headers.\n if (\n request.method === \"HEAD\" ||\n upstream.status !== 200 ||\n !(upstream.headers.get(\"content-type\") ?? \"\").includes(\"application/json\")\n ) {\n return new Response(upstream.body, { status: upstream.status, statusText: upstream.statusText, headers });\n }\n\n // The body read can abort the same way the fetch can (the poll delivered headers, the client\n // left before the body finished) — same cancellation, same quiet answer.\n let parsed: unknown;\n try {\n parsed = (await upstream.json()) as unknown;\n } catch (error) {\n if (request.signal.aborted) return new Response(null, { status: 499 });\n throw error;\n }\n const isBatch = Array.isArray(parsed);\n const envelopes = (isBatch ? parsed : [parsed]) as ProxiedEnvelope[];\n\n // The client keep-set: the columns the LOCAL table declares, computed once per request. Stripping\n // to it after the transform runs is what keeps `serverOnlyColumns` — fetched by the engine solely\n // so the transform could read them — off the client wire, and it also drops any key a transform\n // invented, so an egress rewrite can never widen the shape the client's schema was built for.\n const keep = new Set(getTableConfig(entry.localTable).columns.map((column) => column.name));\n const context: RowTransformContext = {\n claims: { sub: decision.subject },\n ...(options.params ? { params: options.params } : {}),\n };\n\n const rewritten = envelopes.map((envelope) => {\n const value = envelope?.value;\n if (value == null || typeof value !== \"object\") return envelope;\n const transformed = transform(value as Record<string, unknown>, context);\n const stripped: Record<string, unknown> = {};\n for (const [column, cell] of Object.entries(transformed)) {\n if (keep.has(column)) stripped[column] = cell;\n }\n return { ...envelope, value: stripped };\n });\n\n // Answered in the shape it arrived in. A ds long-poll body is an array, and the single-object case\n // is only defensive — re-emitting it as an array would corrupt a body the client can parse today.\n return new Response(JSON.stringify(isBatch ? rewritten : rewritten[0]), {\n status: upstream.status,\n statusText: upstream.statusText,\n headers,\n });\n };\n}\n",
9
9
  "import type { PredicateValue } from \"@pgxsinkit/contracts\";\n\n/**\n * One stream a token admits its bearer to.\n *\n * The grant is **self-describing**: it carries the durable-streams path together with the shape and\n * scope that path serves. That is what keeps the edge stateless. Shape creation happened on whichever\n * replica the client reached, and the edge is replica-scaled, so a path→scope map held in memory\n * would have to be shared between replicas — a second piece of distributed state on the read path,\n * to answer a question the token can simply carry.\n */\nexport interface StreamGrant {\n /** The durable-streams path, e.g. `shape/s1`. */\n path: string;\n /** The shape this path serves — the entitlement rule's binding key. */\n shapeKey: string;\n /**\n * The engine claim this grant acquired — one `POST /shapes` join — so the session that holds it can\n * release exactly what it acquired.\n *\n * Carried rather than looked up, for the same reason the path and scope are: the release route is\n * stateless, and the signed token is the only proof of what the control plane handed out. It is not\n * the same thing as {@link StreamGrant.path}: the engine's own id is what `DELETE /shapes/{id}`\n * takes, and two grants can legitimately name ONE shapeId when the engine deduplicated two\n * identical definitions (ADR-0055 decision 6) — which is precisely why release counts grants, not\n * distinct ids.\n */\n shapeId: string;\n /**\n * The **subscription id** this grant's claim was taken under — the name the control plane gave it\n * on `POST /shapes` (fork ADR-0008).\n *\n * Carried for the same reason {@link StreamGrant.shapeId} is: renewal and release are stateless.\n * The re-mint renews this exact claim (the same create, repeated with this id) and the release\n * route drops this exact claim (`DELETE /shapes/{id}?subscription=…`) — both of them from the\n * signed token alone, with nothing remembered server-side. It is also what makes a release\n * idempotent: a claim named is a claim that can only be given back once, however many times the\n * request arrives.\n *\n * Distinct per grant even when two grants share a `shapeId`: two joins onto one deduplicated shape\n * are two claims, and one id could only ever release one of them.\n */\n claim: string;\n /**\n * Scope values, positionally matching the shape's declared scope columns. Shared tier only; a\n * private-tier grant has none, and its authorization is the token itself.\n */\n scope?: readonly PredicateValue[];\n /**\n * PRIVATE TIER ONLY: the fingerprint of the compiled shape request this grant authorized.\n *\n * A re-mint recompiles the shape with the subject's CURRENT claims and admits the grant only if the\n * result fingerprints the same; a grant without one cannot be re-authorized and is revoked. That is\n * what keeps the re-mint stateless — the token carries the thing that was authorized, so nothing\n * server-side has to remember it.\n *\n * Shared-tier grants carry none, and deliberately: their predicate is generated from the scope\n * values alone, so it cannot drift with the subject's claims and the live entitlement re-check is\n * the whole question.\n */\n fp?: string;\n}\n\n/** The verified body of a stream token. */\nexport interface StreamTokenClaims {\n /** The subject the token was minted for. */\n sub: string;\n grants: StreamGrant[];\n /** Issued-at and expiry, seconds since the epoch. */\n iat: number;\n exp: number;\n}\n\nexport interface MintStreamTokenOptions {\n sub: string;\n grants: readonly StreamGrant[];\n /**\n * Lifetime in seconds. The ADR-0055 default is 5 minutes, which is also the revocation bound when\n * a hit-serving third-party CDN sits in front: shorten it where that bound matters more than the\n * re-mint traffic, lengthen it where it does not.\n */\n ttlSeconds?: number;\n /** Seconds since the epoch. Injected so minting is testable and so a batch shares one issue time. */\n now: number;\n}\n\nexport const DEFAULT_STREAM_TOKEN_TTL_SECONDS = 300;\n\nexport type StreamTokenVerification = { ok: true; claims: StreamTokenClaims } | { ok: false; reason: string };\n\n/**\n * The signing key. HMAC-SHA256 over a compact JWS: the same process mints and verifies, so there is\n * one trust domain and no reason to pay for asymmetric keys — and no reason to take a JWT dependency\n * into a published library for what Web Crypto already does.\n *\n * The token still IS a JWT, so it stays readable by ordinary tooling when someone has to debug one.\n */\nexport async function importStreamTokenKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\"raw\", new TextEncoder().encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n \"verify\",\n ]);\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return btoa(String.fromCharCode(...bytes))\n .replaceAll(\"+\", \"-\")\n .replaceAll(\"/\", \"_\")\n .replaceAll(\"=\", \"\");\n}\n\nfunction base64UrlDecode(value: string): Uint8Array<ArrayBuffer> {\n const padded = value\n .replaceAll(\"-\", \"+\")\n .replaceAll(\"_\", \"/\")\n .padEnd(Math.ceil(value.length / 4) * 4, \"=\");\n const binary = atob(padded);\n const bytes = new Uint8Array(new ArrayBuffer(binary.length));\n for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);\n return bytes;\n}\n\nconst HEADER = base64UrlEncode(new TextEncoder().encode(JSON.stringify({ alg: \"HS256\", typ: \"JWT\" })));\n\n/**\n * Mint one token for a whole batch of grants.\n *\n * Batched by design, not as an optimisation: a subject in K scopes holds K subscriptions, and\n * re-minting per subscription would put K requests on every TTL boundary for every subject. One\n * token covering all K collapses that to one request per subject per window.\n */\nexport async function mintStreamToken(key: CryptoKey, options: MintStreamTokenOptions): Promise<string> {\n const ttl = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;\n const claims: StreamTokenClaims = {\n sub: options.sub,\n grants: options.grants.map((grant) => ({\n path: grant.path,\n shapeKey: grant.shapeKey,\n shapeId: grant.shapeId,\n claim: grant.claim,\n ...(grant.scope !== undefined ? { scope: [...grant.scope] } : {}),\n ...(grant.fp !== undefined ? { fp: grant.fp } : {}),\n })),\n iat: options.now,\n exp: options.now + ttl,\n };\n\n const body = base64UrlEncode(new TextEncoder().encode(JSON.stringify(claims)));\n const signingInput = `${HEADER}.${body}`;\n const signature = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(signingInput));\n return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;\n}\n\n/**\n * Verify a token and read its grants back.\n *\n * `now` is the request-start time, and is passed rather than read here so that a long-poll held open\n * across the expiry is judged by when it started — the alternative silently kills connections\n * mid-flight at the TTL boundary, which presents as a stall rather than as the re-auth it is.\n *\n * Signature verification goes through `crypto.subtle.verify`, so the comparison is the platform's\n * constant-time one rather than a string equality that leaks by how early it diverges.\n */\nexport interface VerifyStreamTokenOptions {\n /**\n * Accept a token past its expiry, for the **re-mint path only**.\n *\n * The signature is still verified, so the grants are still ones this control plane issued — that is\n * the whole claim being relied on. Expiry bounds how long a grant keeps *working*, and the re-mint\n * re-authorizes every grant before re-signing — the shared tier against the live entitlement set,\n * the private tier by recompiling its shape against the subject's current claims — so an expired\n * token buys its bearer nothing on its own. Never set this on a read.\n */\n allowExpired?: boolean;\n}\n\nexport async function verifyStreamToken(\n key: CryptoKey,\n token: string,\n now: number,\n options?: VerifyStreamTokenOptions,\n): Promise<StreamTokenVerification> {\n const parts = token.split(\".\");\n if (parts.length !== 3) return { ok: false, reason: \"malformed token\" };\n const [header, body, signature] = parts as [string, string, string];\n if (header !== HEADER) return { ok: false, reason: \"unexpected token header\" };\n\n let valid: boolean;\n try {\n valid = await crypto.subtle.verify(\n \"HMAC\",\n key,\n base64UrlDecode(signature),\n new TextEncoder().encode(`${header}.${body}`),\n );\n } catch {\n return { ok: false, reason: \"malformed signature\" };\n }\n if (!valid) return { ok: false, reason: \"bad signature\" };\n\n let claims: StreamTokenClaims;\n try {\n claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(body))) as StreamTokenClaims;\n } catch {\n return { ok: false, reason: \"malformed payload\" };\n }\n if (typeof claims.sub !== \"string\" || !Array.isArray(claims.grants) || typeof claims.exp !== \"number\") {\n return { ok: false, reason: \"malformed payload\" };\n }\n if (claims.exp <= now && options?.allowExpired !== true) return { ok: false, reason: \"expired\" };\n\n return { ok: true, claims };\n}\n\n/**\n * The grant covering a requested stream path, if the token carries one.\n *\n * Exact path match, deliberately: durable-streams paths are a monotonic counter (`shape/s1`,\n * `shape/s2`, …), so they are enumerable rather than capability-bearing, and any prefix or pattern\n * match over them would hand the bearer streams the control plane never granted.\n */\nexport function findGrant(claims: StreamTokenClaims, path: string): StreamGrant | undefined {\n return claims.grants.find((grant) => grant.path === path);\n}\n",
10
10
  "import type { CircuitsShapeHandle, CreateShapeRequest } from \"./wire\";\n\nexport interface CircuitsEngineOptions {\n /** Base URL of the Circuits engine's control API, e.g. `http://circuits-engine:4000`. */\n baseUrl: string;\n /** Injected for tests; defaults to the ambient `fetch`. */\n fetch?: typeof fetch;\n}\n\n/**\n * An engine call that did not return 2xx, carrying the status so a caller can map it to its own.\n *\n * The one status with a MEANING rather than a severity is **409**: a create whose `subscription` id\n * is already held by a different shape (fork ADR-0008 — one name, one shape). It is the caller's\n * conflict, not an outage, and no retry changes it; match it as `error.status === 409` and re-subscribe\n * under a fresh id. Everything else is either a request this client built wrong (4xx) or an engine\n * that could not answer (5xx), and both propagate as a 503 to the client.\n */\nexport class CircuitsEngineError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string, message: string) {\n super(message);\n this.name = \"CircuitsEngineError\";\n this.status = status;\n this.body = body;\n }\n}\n\n/**\n * The control plane's client for the Circuits engine.\n *\n * Only the shape LIFECYCLE goes through here. Reads never do: they terminate on durable-streams,\n * which is the whole point of the native topology — the engine is asked once, at subscribe time,\n * for a stream to follow, and is then out of the read path entirely.\n */\nexport function createCircuitsEngineClient(options: CircuitsEngineOptions) {\n const doFetch = options.fetch ?? fetch;\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n\n async function call(path: string, init: RequestInit): Promise<unknown> {\n const headers = new Headers(init.headers);\n headers.set(\"content-type\", \"application/json\");\n const response = await doFetch(`${base}${path}`, { ...init, headers });\n const body = await response.text();\n if (!response.ok) {\n throw new CircuitsEngineError(\n response.status,\n body,\n `[pgxsinkit] circuits engine ${init.method ?? \"GET\"} ${path} → ${response.status}: ${body}`,\n );\n }\n return body === \"\" ? undefined : JSON.parse(body);\n }\n\n return {\n /**\n * Register a shape and get the stream to follow — **and renew that registration**.\n *\n * There is deliberately no `renewShape`: a renewal IS this call, repeated with the same\n * `request.subscription` on the same definition (fork ADR-0008). The engine answers the same\n * handle, counts nothing extra, and moves the lease forward. That is also why a create whose\n * response was lost can simply be sent again, and why the control plane's token re-mint can renew\n * every live claim without a second route.\n *\n * Two outcomes a caller must distinguish:\n * - **409** ({@link CircuitsEngineError.status}) — the id names a DIFFERENT shape already. One\n * name, one shape; nothing was taken, and a retry will not change it.\n * - a **different handle** — the claim had lapsed or the shape was evicted, so this call\n * re-subscribed rather than renewed. The stream the old grant named is not this one (ADR-0007).\n *\n * The engine shares by definition: two identical bodies collapse onto one maintained stream and\n * return the same handle. Nothing here has to check for that or cache against it — which is\n * exactly why the shared tier's predicate must be GENERATED. Two subscribers in one scope produce\n * identical bodies only because neither's identity reached the predicate; they are still two\n * distinct subscriptions, because each names its own claim.\n *\n * The answer is VALIDATED, not cast, for the same reason {@link replicationState} validates the\n * barrier: an engine that acknowledges a create without saying which subscription it recorded or\n * how long that subscription lives cannot be renewed or released by id at all, and defaulting\n * either field would invent a lease this control plane was never promised.\n */\n async createShape(request: CreateShapeRequest): Promise<CircuitsShapeHandle> {\n const body = (await call(\"/shapes\", {\n method: \"POST\",\n body: JSON.stringify(request),\n })) as Partial<CircuitsShapeHandle> | null;\n if (body === null || typeof body !== \"object\") throw unusableCreate(\"the body\", body);\n if (typeof body.shapeId !== \"string\") throw unusableCreate(\"shapeId\", body.shapeId);\n if (typeof body.streamPath !== \"string\") throw unusableCreate(\"streamPath\", body.streamPath);\n if (typeof body.subscription !== \"string\" || body.subscription === \"\") {\n throw unusableCreate(\"subscription\", body.subscription);\n }\n if (typeof body.leaseSeconds !== \"number\") throw unusableCreate(\"leaseSeconds\", body.leaseSeconds);\n return body as CircuitsShapeHandle;\n },\n\n /**\n * Release ONE named subscription's claim on a shape (`DELETE /shapes/{id}?subscription=…`).\n *\n * **Idempotent**, and that is the whole point of naming the claim: releasing one that is already\n * gone is a no-op `200` rather than a decrement that steals another subscriber's. A caller whose\n * response was lost may simply send it again.\n *\n * There is no anonymous form here. The engine still accepts a bare `DELETE /shapes/{id}` as a\n * legacy refcount decrement, but it carries no claim identity and is not retry-safe, so this\n * client never issues one.\n *\n * The shape itself survives its other subscribers and then follows the engine's retention\n * lifecycle (idle → dormant → evicted); this is a release, not a delete.\n */\n async releaseShape(shapeId: string, subscription: string): Promise<void> {\n const query = `?subscription=${encodeURIComponent(subscription)}`;\n await call(`/shapes/${encodeURIComponent(shapeId)}${query}`, { method: \"DELETE\" });\n },\n\n /**\n * The engine's convergence barrier (ADR-0056): where replication is, how many\n * computed-but-undelivered subquery flips remain, and how many flip batches the engine gave up\n * on.\n *\n * The engine answers a `sync` field beside these and it is deliberately NOT read: it is the\n * `__el_sync` sentinel watermark — an i64 the engine's conformance harness bumps and waits on as\n * a global quiescence fence — which no pgxsinkit database ever writes, so it is 0 everywhere and\n * says nothing about convergence.\n *\n * `pendingFlips > 0` means a revocation has been computed and not yet written to any stream,\n * which no wire-format watermark can see. That is the term the Electric wire could not express\n * at all, and the reason the barrier is read out of band rather than inferred from a position.\n *\n * `flipFailures > 0` means a batch was **abandoned** after exhausting its propagation retries:\n * those membership effects are gone rather than late. The engine keeps the abandoned batch's\n * `pendingFlips` count held — so the waiting terms never falsely read converged — and latches\n * itself degraded: `/v1/health` answers 503, so do its membership-bearing routes, and a reaper\n * deletes every subquery shape stream. Recovery is an operator restart.\n *\n * The answer is VALIDATED, not cast. An engine that does not report both counters cannot answer\n * the question this barrier asks, and defaulting a missing term to zero would manufacture a\n * converged reading out of an engine that never claimed one.\n */\n async replicationState(): Promise<CircuitsReplicationState> {\n const body = (await call(\"/replication/lsn\", { method: \"GET\" })) as Partial<CircuitsReplicationState>;\n if (body === null || typeof body !== \"object\") throw unusableBarrier(\"the body\", body);\n if (body.lsn !== null && typeof body.lsn !== \"string\") throw unusableBarrier(\"lsn\", body.lsn);\n if (typeof body.pendingFlips !== \"number\") throw unusableBarrier(\"pendingFlips\", body.pendingFlips);\n if (typeof body.flipFailures !== \"number\") throw unusableBarrier(\"flipFailures\", body.flipFailures);\n return { lsn: body.lsn, pendingFlips: body.pendingFlips, flipFailures: body.flipFailures };\n },\n };\n}\n\n/**\n * An engine whose barrier this client cannot read is not a degraded engine — it is the wrong engine,\n * and saying so is the point. Silently tolerating the omission would leave a gate claiming to check a\n * term nothing reports.\n */\nfunction unusableBarrier(field: string, value: unknown): Error {\n return new Error(\n `[pgxsinkit] the engine's GET /replication/lsn answered with an unusable \\`${field}\\` (${JSON.stringify(value)}). ` +\n `This client requires an engine reporting the whole convergence barrier — \\`lsn\\`, \\`pendingFlips\\` and ` +\n `\\`flipFailures\\` (ADR-0056 decision 3); the engine at this URL is not the one this client targets.`,\n );\n}\n\n/**\n * An engine whose create answer this client cannot read is not a degraded engine — it is the wrong\n * engine, exactly as {@link unusableBarrier} says of the barrier. A create that does not name the\n * subscription it was recorded under, or the window that subscription must be renewed within, leaves\n * a claim nothing can renew and nothing can release by id; defaulting either would manufacture a\n * lease the engine never granted.\n */\nfunction unusableCreate(field: string, value: unknown): Error {\n return new Error(\n `[pgxsinkit] the engine's POST /shapes answered with an unusable \\`${field}\\` (${JSON.stringify(value)}). ` +\n `This client requires an engine that records every shape claim under a named, leased subscription — ` +\n `\\`shapeId\\`, \\`streamPath\\`, \\`subscription\\` and \\`leaseSeconds\\` (fork ADR-0008); the engine at this ` +\n `URL is not the one this client targets.`,\n );\n}\n\nexport type CircuitsEngineClient = ReturnType<typeof createCircuitsEngineClient>;\n\n/** What `GET /replication/lsn` answers that this client reads — these fields exactly, no more. */\nexport interface CircuitsReplicationState {\n /** The ingest head — where the replication tailer has read to. */\n lsn: string | null;\n pendingFlips: number;\n /**\n * Flip batches the engine abandoned after exhausting their retries. Non-zero means membership\n * effects were **lost**, not delayed: the batch's pending count stays held, the engine is latched\n * degraded, and only a restart clears it.\n */\n flipFailures: number;\n}\n",
11
11
  "import { sql } from \"drizzle-orm\";\n\nimport { eventQueueMessageSchema, type EventQueueMessage } from \"@pgxsinkit/contracts\";\n\nimport {\n assertEventQueueReceipts,\n eventStreamQueueName,\n MalformedEventQueueMessageError,\n type DeadLetteredEventMessage,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueExecutor,\n type EventQueueReadOptions,\n type EventQueueReceipt,\n} from \"./queue\";\n\n/**\n * The shipped {@link EventQueue} backend: **pgmq** (ADR-0053 decision 5). Postgres-native, so the Event lane\n * adds no new infrastructure to the supabase-ecosystem stacks consumers already run, and an enqueue joins the\n * endpoint's own transaction rather than crossing a second system.\n *\n * One queue per Event stream (`pgxsinkit_events_<stream>`), so a poison event or a slow consumer in one stream\n * can never head-of-line-block another. Queues are provisioned at DEPLOY time (`pgxsinkit-generate --events`),\n * never created at runtime: the endpoint may enqueue long before any runner first starts, and a\n * create-if-missing probe would put a query back in front of the zero-startup-query posture.\n *\n * **pgmq assumptions**, all read off pgmq's own extension SQL and pinned by the integration lane:\n * - The extension is NOT relocatable and its control file declares `schema = 'pgmq'`, so every call is\n * `pgmq.`-qualified and the schema is never configurable here.\n * - Its control file declares no `requires`, so the DDL needs no `CASCADE` (pg_partman is needed only for\n * PARTITIONED queues, which the toolkit never creates).\n * - Per-queue tables are `pgmq.q_<queue>` and `pgmq.a_<queue>` (`pgmq.format_table_name`); the archive is the\n * dead-letter storage.\n *\n * SQL tier discipline: pgmq's surface IS a set of SQL functions and two dynamically-named tables, so Drizzle's\n * tier-1 builders cannot express any of it. Everything below is tier 2 — a tagged `sql` template with the\n * queue name and every value as BOUND PARAMETERS and each table name as a typed `sql.identifier`; no\n * identifier or value is ever baked into the template text.\n */\n\n/**\n * The reserved key the dead-letter reason is stamped under, INSIDE the archived message body.\n *\n * Least surface, deliberately: pgmq's archive is the dead-letter storage (no library-owned DLQ table), the\n * archive row has no free column to carry a reason, and its `headers` column only exists on newer pgmq\n * versions. So the reason rides one reserved key on the ARCHIVED body — the live queue row is never mutated,\n * a normally-consumed message is byte-identical to what was enqueued, and the key is stripped again by\n * {@link EventQueue.listDeadLetters} / {@link EventQueue.requeueDeadLetter} so a requeued message is exactly\n * the message that was enqueued.\n */\nexport const PGMQ_DEAD_LETTER_KEY = \"__pgxsinkitDeadLetter\";\n\nexport interface CreatePgmqEventQueueOptions {\n /** The default executor — the server's drizzle handle. Per-call executors (a transaction) take precedence. */\n db: EventQueueExecutor;\n}\n\ninterface DeliveredRow {\n receipt: string;\n deliveryCount: number;\n enqueuedAtUs: string;\n message: string;\n}\n\ninterface DeadLetterRow {\n id: string;\n deliveryCount: number;\n deadLetteredAtUs: string;\n message: string;\n reason: string | null;\n}\n\ninterface CountRow {\n affected: number;\n}\n\ninterface ReceiptRow {\n receipt: string | null;\n}\n\nfunction toRows<TRow>(result: unknown): TRow[] {\n return Array.from(result as Iterable<unknown>, (row) => row as TRow);\n}\n\n/** Parse a queue body back into the contract shape, naming the offending receipt if it is not one. */\nfunction parseQueueMessage(stream: string, receipt: EventQueueReceipt, body: string): EventQueueMessage {\n let raw: unknown;\n try {\n raw = JSON.parse(body);\n } catch (error) {\n throw new MalformedEventQueueMessageError(stream, receipt, error instanceof Error ? error.message : \"invalid JSON\");\n }\n const parsed = eventQueueMessageSchema.safeParse(raw);\n if (!parsed.success) {\n throw new MalformedEventQueueMessageError(stream, receipt, parsed.error.message);\n }\n return parsed.data;\n}\n\nexport function createPgmqEventQueue(options: CreatePgmqEventQueueOptions): EventQueue {\n const run = (executor: EventQueueExecutor | undefined, query: Parameters<EventQueueExecutor[\"execute\"]>[0]) =>\n (executor ?? options.db).execute(query);\n\n return {\n enqueueBatch: async (messages, executor) => {\n if (messages.length === 0) {\n return;\n }\n\n // Group by Event stream, preserving the order the endpoint assembled: one `send_batch` per stream, all\n // inside the CALLER's transaction, so a mixed flush batch is enqueued atomically or not at all.\n const byStream = new Map<string, EventQueueMessage[]>();\n for (const message of messages) {\n const bucket = byStream.get(message.stream);\n if (bucket) {\n bucket.push(message);\n } else {\n byStream.set(message.stream, [message]);\n }\n }\n\n for (const [stream, streamMessages] of byStream) {\n const queueName = eventStreamQueueName(stream);\n // The bodies ride as ONE bound json parameter expanded to `jsonb[]` in SQL — never a driver-specific\n // array binding, and never string-built SQL.\n await run(\n executor,\n sql`SELECT pgmq.send_batch(${queueName}, ARRAY(SELECT jsonb_array_elements(${JSON.stringify(streamMessages)}::text::jsonb)))`,\n );\n }\n },\n\n readBatch: async (stream: string, readOptions: EventQueueReadOptions): Promise<DeliveredEventMessage[]> => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT \"msg_id\"::text AS \"receipt\", \"read_ct\" AS \"deliveryCount\", (EXTRACT(EPOCH FROM \"enqueued_at\") * 1000000)::bigint::text AS \"enqueuedAtUs\", \"message\"::text AS \"message\" FROM pgmq.read(${queueName}, ${readOptions.visibilityTimeoutSeconds}, ${readOptions.maxMessages})`,\n );\n\n return toRows<DeliveredRow>(result).map((row) => ({\n receipt: row.receipt,\n stream,\n message: parseQueueMessage(stream, row.receipt, row.message),\n deliveryCount: Number(row.deliveryCount),\n enqueuedAtUs: row.enqueuedAtUs,\n }));\n },\n\n extendVisibility: async (stream, receipts, visibilityTimeoutSeconds, executor) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n // pgmq gained an ARRAY-taking `set_vt` only in 1.8.0, while the single-message form has existed\n // throughout — and the toolkit pins no pgmq version. So the portable shape is the single-message\n // function applied over the receipts with a LATERAL: still ONE statement and one round trip, but it\n // works on every pgmq a consumer's supabase-ecosystem stack might carry. The `::int` cast picks the\n // seconds-offset overload over the `timestamptz` one.\n const result = await run(\n executor,\n sql`SELECT count(*)::int AS \"affected\" FROM unnest(string_to_array(${receipts.join(\",\")}, ',')::bigint[]) AS \"renewed\"(\"msg_id\"), LATERAL pgmq.set_vt(${queueName}, \"renewed\".\"msg_id\", ${visibilityTimeoutSeconds}::int) AS \"extended\"`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n ack: async (stream, receipts) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.delete(${queueName}, string_to_array(${receipts.join(\",\")}, ',')::bigint[])`,\n );\n return Number(toRows<CountRow>(result)[0]?.affected ?? 0);\n },\n\n deadLetter: async (stream, receipts, reason) => {\n if (receipts.length === 0) {\n return 0;\n }\n assertEventQueueReceipts(receipts);\n const queueName = eventStreamQueueName(stream);\n const ids = receipts.join(\",\");\n\n // pgmq's own archive move first — it is the version-correct transfer (it carries every column the\n // installed pgmq version has, including ones this code does not know about).\n const archived = await run(\n undefined,\n sql`SELECT count(*)::int AS \"affected\" FROM pgmq.archive(${queueName}, string_to_array(${ids}, ',')::bigint[])`,\n );\n\n // Then stamp the reason onto the ARCHIVED body. Deliberately second: if it fails the message is still\n // dead-lettered (the fail-safe direction), and the archived row is terminal so nothing races this.\n await run(\n undefined,\n sql`UPDATE pgmq.${sql.identifier(`a_${queueName}`)} SET \"message\" = COALESCE(\"message\", '{}'::jsonb) || jsonb_build_object(${PGMQ_DEAD_LETTER_KEY}::text, jsonb_build_object('reason', ${reason}::text, 'atUs', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000000)::bigint::text)) WHERE \"msg_id\" = ANY(string_to_array(${ids}, ',')::bigint[])`,\n );\n\n return Number(toRows<CountRow>(archived)[0]?.affected ?? 0);\n },\n\n listDeadLetters: async (stream, limit) => {\n const queueName = eventStreamQueueName(stream);\n const result = await run(\n undefined,\n sql`SELECT \"msg_id\"::text AS \"id\", \"read_ct\" AS \"deliveryCount\", (EXTRACT(EPOCH FROM \"archived_at\") * 1000000)::bigint::text AS \"deadLetteredAtUs\", (\"message\" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS \"message\", \"message\" -> ${PGMQ_DEAD_LETTER_KEY}::text ->> 'reason' AS \"reason\" FROM pgmq.${sql.identifier(`a_${queueName}`)} ORDER BY \"msg_id\" DESC LIMIT ${limit}`,\n );\n\n return toRows<DeadLetterRow>(result).map((row): DeadLetteredEventMessage => {\n const message = parseQueueMessage(stream, row.id, row.message);\n return {\n id: row.id,\n stream,\n message,\n ...(row.reason != null ? { reason: row.reason } : {}),\n deliveryCount: Number(row.deliveryCount),\n deadLetteredAtUs: row.deadLetteredAtUs,\n };\n });\n },\n\n requeueDeadLetter: async (stream, id) => {\n assertEventQueueReceipts([id]);\n const queueName = eventStreamQueueName(stream);\n // ONE statement: the archive row is removed and its (reason-stripped) body re-sent in the same command,\n // so a requeue can never leave the message both dead-lettered and queued.\n const result = await run(\n undefined,\n sql`WITH restored AS (DELETE FROM pgmq.${sql.identifier(`a_${queueName}`)} WHERE \"msg_id\" = ${id}::bigint RETURNING \"message\") SELECT pgmq.send(${queueName}, \"message\" - ${PGMQ_DEAD_LETTER_KEY}::text)::text AS \"receipt\" FROM restored`,\n );\n return toRows<ReceiptRow>(result)[0]?.receipt ?? null;\n },\n };\n}\n",
@@ -24,7 +24,7 @@
24
24
  "import {\n getSyncRegistryStreams,\n type EventQueueMessage,\n type StampedEvent,\n type SyncTableRegistry,\n} from \"@pgxsinkit/contracts\";\n\nimport {\n MalformedEventQueueMessageError,\n type DeliveredEventMessage,\n type EventQueue,\n type EventQueueReceipt,\n} from \"./queue\";\n\n/**\n * The **Event lane**'s consumer runner (ADR-0053 decisions 6 and 7): the library defines it, the app hosts it.\n *\n * `defineEventConsumer` returns a `start()`/`stop()` handle the app runs in its OWN long-lived Bun process —\n * the toolkit's first long-lived server artifact, deliberately separate from `createSyncServer`'s\n * zero-startup-query serverless posture. There is no supervisor, no CLI entrypoint, no daemon and no signal\n * handling here: the app owns its process lifecycle and calls `stop()` from wherever it already handles\n * shutdown. Construction stays query-free — the FIRST statement this runner sends is the first poll inside\n * `start()`.\n *\n * Because the app owns the process, it also owns the health endpoint — so the runner reports the one thing\n * that endpoint cannot see from outside: {@link DefineEventConsumerOptions.onPoll} fires after EVERY read,\n * productive or empty, in both pacing modes. Beat a liveness probe from that, never from `callback`, which\n * by design says nothing at all while the queue is idle.\n *\n * One runner hosts many Event streams: each gets its own independent loop (a poison event or slow callback in\n * one stream must never head-of-line-block another), so small deployments run one process and large ones split\n * `streams` across processes.\n *\n * **Pacing is adaptive interval polling, and it is INTERNAL** (ADR-0053 decision 7 — out of consumer-app design\n * space by ratified requirement; only the floor/ceiling/factor are exposed as tuning, never as contract):\n *\n * - a NON-EMPTY read is followed by an immediate re-read, so a backlog drains back-to-back;\n * - consecutive EMPTY reads grow the wait from a floor ({@link DEFAULT_EVENT_POLL_FLOOR_MS}) toward an idle\n * ceiling ({@link DEFAULT_EVENT_POLL_CEILING_MS}) by {@link DEFAULT_EVENT_POLL_FACTOR};\n * - one non-empty read resets the wait to the floor.\n *\n * LISTEN/NOTIFY and `pgmq.read_with_poll` long-polling are REJECTED as wake mechanisms (ADR-0053, maintainer\n * decision): Bun's native `SQL` — the sanctioned Postgres driver — has no LISTEN/NOTIFY, and both mechanisms\n * hold a connection per stream through the transaction poolers the consumers' stacks run behind. Because\n * pacing is internal, the mechanism can change later without any contract change.\n *\n * **Leases are RENEWED while a read is being worked through; a thrown sub-batch's lease is deliberately left\n * to lapse** (ADR-0053 decision 7: visibility renewal is internal). One read makes up to `batchSize` messages\n * invisible at once, so the timeout cannot be \"the processing budget\": ten ordinary ten-second callbacks\n * would outlive a 60-second window for the later messages, and in a documented multi-runner deployment\n * another process would pick them up while the first is still working toward them. So for as long as a read\n * is in flight the runner extends EVERY not-yet-settled receipt of that read — the one running plus the ones\n * still queued behind it — every `visibilityTimeoutSeconds / 2`. Renewal is best-effort: a failure is\n * warn-logged and the loop carries on, because redelivery is the safety net it would fall back on anyway.\n *\n * `visibilityTimeoutSeconds` therefore means two retry-shaped things, never a budget:\n *\n * - **the redelivery delay of a FAILED sub-batch.** A callback that throws is not acked AND is dropped from\n * renewal immediately, so its lease lapses and the queue redelivers it with an incremented `deliveryCount`.\n * That lapse IS the retry pacing — the runner never sleeps \"on behalf of\" a failed message, and if a\n * backend ever wants exponential redelivery backoff it belongs INSIDE that backend, behind the\n * {@link EventQueue} seam, so the runner stays backend-agnostic;\n * - **the crash-recovery bound.** A runner that dies takes its renewals with it, so everything it held comes\n * back one timeout later.\n *\n * **A graceful stop does not cancel renewal — it narrows it.** `stop()` starts no further read and no further\n * callback, but the callbacks already in flight are AWAITED and then acked, so their receipts must stay\n * invisible until they settle: cancelling renewal at `stop()` would hand a second runner the very message\n * this one is deliberately finishing, on every ordinary SIGTERM/rollout. What IS released at `stop()` is the\n * rest of that read — the messages no callback has started — which drop out of the renewal set so their\n * leases lapse and the queue redelivers them promptly. `stop()` therefore resolves only once every in-flight\n * callback has settled AND its renewal task has shut down.\n *\n * **The SECOND pacing mode: `drainOnce()`, for hosts that cannot hold a process** (ADR-0053 amendment,\n * 2026-08-02). Everything above describes the primary mode. A serverless-only deployment — managed\n * Supabase, whose edge functions are the only compute — has nowhere to put a `start()`; its queue would\n * simply never drain. So the SAME handle also answers `drainOnce({ budgetMs })`: one bounded pass that\n * reads/delivers/acks through the identical internals until every stream reads empty or the wall-clock\n * budget runs out. Nothing about the delivery contract moves — at-least-once, batch-internal order only,\n * dead-lettering to the backend's archive are all the same code — because pacing was internal from the\n * start (decision 7), which is exactly what makes this a HOSTING addition rather than a contract change.\n * The long-lived runner remains the primary mode; `drainOnce` is what a scheduled invocation calls.\n */\n\n/** Max messages (each ONE single-stream sub-batch) a single read delivers, when the app sets nothing. */\nexport const DEFAULT_EVENT_CONSUMER_BATCH_SIZE = 10;\n/**\n * How long a delivered sub-batch stays invisible, when the app sets nothing — and how long the runner extends\n * it by on each renewal (it renews at half this). Healthy long processing is covered by renewal, so this is\n * the REDELIVERY DELAY of a sub-batch whose callback threw and the crash-recovery bound, not a budget: it\n * wants to sit above a single callback's worst case (too short redelivers a callback that is merely slower\n * than one renewal interval), never above the whole batch's.\n */\nexport const DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS = 60;\n/** Deliveries a sub-batch gets before a further callback failure dead-letters it, when the app sets nothing. */\nexport const DEFAULT_EVENT_MAX_ATTEMPTS = 5;\n/** The adaptive poll's floor — the wait after the FIRST empty read (ADR-0053 decision 7: ~250 ms). */\nexport const DEFAULT_EVENT_POLL_FLOOR_MS = 250;\n/** The adaptive poll's idle ceiling — the longest an idle stream ever waits between reads. */\nexport const DEFAULT_EVENT_POLL_CEILING_MS = 5_000;\n/** How fast consecutive empty reads grow the wait from the floor toward the ceiling. */\nexport const DEFAULT_EVENT_POLL_FACTOR = 2;\n/**\n * The wall-clock budget one {@link EventConsumer.drainOnce} pass gets, when the caller sets nothing.\n *\n * **Set it under your platform's invocation wall-clock cap**, with head-room for one callback: the budget is\n * only ever checked BETWEEN sub-batches, so a pass can overrun it by however long the callback that was\n * already running takes. 25 s suits the common serverless caps (Supabase Edge, Vercel, Cloud Run jobs); a\n * platform with a tighter cap wants a tighter budget, and a generous one (a cron container) can raise it.\n */\nexport const DEFAULT_EVENT_DRAIN_BUDGET_MS = 25_000;\n\n/**\n * Adaptive-poll tuning. Defaults are the ADR's; they are TUNING, not contract — the pacing mechanism itself is\n * internal and may change.\n */\nexport interface EventConsumerPollOptions {\n /** The wait after the first empty read. Defaults to {@link DEFAULT_EVENT_POLL_FLOOR_MS}. */\n floorMs?: number;\n /** The longest wait an idle stream reaches. Defaults to {@link DEFAULT_EVENT_POLL_CEILING_MS}. */\n ceilingMs?: number;\n /** The growth factor per consecutive empty read. Defaults to {@link DEFAULT_EVENT_POLL_FACTOR}. */\n factor?: number;\n}\n\n/** One callback invocation: exactly ONE delivered queue message, i.e. one single-stream sub-batch. */\nexport interface EventConsumerBatch {\n /** The Event stream these events were appended under. */\n stream: string;\n /**\n * The stamped envelopes, EXACTLY as the ingestion endpoint enqueued them (ADR-0053 decision 5) — in append\n * order within this sub-batch. Across sub-batches there is no ordering promise (decision 6).\n */\n events: readonly StampedEvent[];\n}\n\n/**\n * The consumer callback. Returning (resolving) ACKS the sub-batch; THROWING retries it — the message stays\n * invisible until its visibility timeout lapses and the queue redelivers it.\n *\n * It MUST be idempotent (ADR-0053 decision 6, at-least-once): the blessed pattern is deduping on `eventId`\n * against the app's own durable store, which composes to effectively-exactly-once.\n */\nexport type EventConsumerCallback = (batch: EventConsumerBatch) => void | Promise<void>;\n\n/** What {@link DefineEventConsumerOptions.onDeadLetter} is told about a sub-batch the runner gave up on. */\nexport interface EventDeadLetterReport {\n stream: string;\n /** Why it was dead-lettered — the same reason recorded in the backend's dead-letter storage. */\n reason: string;\n /** Deliveries this message had received. `0` when the body was unreadable (nothing was ever delivered from it). */\n attempts: number;\n /** The receipt it was dead-lettered under — always present, including for an unparseable body. */\n receipt: EventQueueReceipt;\n /** The message, when it was readable. Absent for a malformed body (that is exactly what could not be parsed). */\n message?: EventQueueMessage;\n /** The error behind it: the callback's throw, or the {@link MalformedEventQueueMessageError}. */\n cause?: unknown;\n}\n\n/**\n * What {@link DefineEventConsumerOptions.onPoll} is told after each read — the host's liveness heartbeat.\n *\n * One report per read the runner performs, productive or not, in BOTH pacing modes. `delivered` counts the\n * sub-batches that read returned (the queue's unit: one message, one callback invocation), and `empty` is\n * exactly `delivered === 0` — including on a faulted read, which is why `fault` is a separate flag rather\n * than something to infer from the counts.\n */\nexport interface EventPollReport {\n /** The Event stream that was read. Each stream has its own loop, so each beats on its own cadence. */\n readonly stream: string;\n /** Sub-batches this read returned. `0` on an empty or faulted read. */\n readonly delivered: number;\n /** `delivered === 0` — nothing came back from this read. */\n readonly empty: boolean;\n /**\n * The read itself FAILED: a queue/database fault, or a message body that could not be parsed (which fails\n * the whole read). The runner backs off and carries on either way — a fault never ends a loop — so a host\n * watching the heartbeat still sees it turning, and this is what tells it the queue is unhealthy.\n */\n readonly fault: boolean;\n /** When the read settled, from the runner's own clock (`Date.now` unless one is injected). */\n readonly at: number;\n}\n\n/**\n * The deterministic seam the runner waits on. `signal` is aborted by `stop()`, so a stopping runner never\n * lingers for a full idle ceiling. Injected only by tests; production uses an abortable `setTimeout`.\n */\nexport type EventConsumerSleep = (ms: number, signal: AbortSignal) => Promise<void>;\n\n/** What {@link EventConsumer.drainOnce} is tuned with. */\nexport interface EventDrainOptions {\n /**\n * The pass's wall-clock budget. Defaults to {@link DEFAULT_EVENT_DRAIN_BUDGET_MS}. Checked between\n * sub-batches only, never inside a callback — so size it under the invocation's cap with head-room for\n * one callback's worst case.\n */\n budgetMs?: number;\n}\n\n/** What one {@link EventConsumer.drainOnce} pass reports back. Counts are SUB-BATCHES (one queue message,\n * one callback invocation), the unit the queue and the dead-letter archive both work in. */\nexport interface EventDrainSummary {\n /**\n * Sub-batches whose callback completed during this pass. An ack that then failed still counts — the work\n * was delivered, and at-least-once means it may be delivered again later (the callback is idempotent).\n */\n delivered: number;\n /** Sub-batches this pass moved to the backend's dead-letter storage. */\n deadLettered: number;\n /**\n * `true` when every configured Event stream read empty before the budget ran out — the queue is drained\n * as far as this pass can see.\n *\n * `false` means the pass ended with work possibly still queued: the budget cut it short, or a stream's\n * read faulted. It is the caller's signal that another tick has something to do — a scheduler that\n * chains passes should invoke again promptly rather than waiting out its full period.\n */\n empty: boolean;\n}\n\nexport interface DefineEventConsumerOptions<TRegistry extends SyncTableRegistry> {\n /** The sync registry whose `streams` this runner consumes. */\n registry: TRegistry;\n /**\n * The queue to consume from — REQUIRED, and the reason the runner is backend-agnostic by construction. The\n * ordinary wiring is `createPgmqEventQueue({ db })` with the app's own drizzle handle; constructing it here\n * from a `db` option would bake the shipped backend into the runner for one line of ergonomics.\n */\n queue: EventQueue;\n callback: EventConsumerCallback;\n /**\n * Narrow to a subset of the registered Event streams — the knob that splits streams across processes.\n * Defaults to ALL registered streams. An unknown name is a definition-time throw (fail-closed): a runner\n * that silently consumed nothing is the failure mode this forbids.\n */\n streams?: readonly string[];\n /** Max messages per read. Defaults to {@link DEFAULT_EVENT_CONSUMER_BATCH_SIZE}. */\n batchSize?: number;\n /**\n * The delivered-message invisibility window, renewed at half of it while the runner is still working\n * through a read. Defaults to {@link DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS}. Size it above ONE\n * callback's worst case (renewal covers the rest of the batch), not above the whole batch's.\n */\n visibilityTimeoutSeconds?: number;\n /**\n * Max CONCURRENT callback invocations per Event stream. Defaults to `1` (strictly sequential). Values above 1\n * are safe for the idempotent callback the lane already requires: ADR-0053 decision 6 disclaims any ordering\n * across sub-batches precisely so concurrency is available. Reads stay serial — only the callbacks of one\n * delivered read run in parallel.\n */\n concurrency?: number;\n /**\n * Deliveries a sub-batch gets before a further callback failure dead-letters it. Defaults to\n * {@link DEFAULT_EVENT_MAX_ATTEMPTS}. A malformed body never gets attempts — it dead-letters on sight.\n */\n maxAttempts?: number;\n /** Adaptive-poll tuning. See {@link EventConsumerPollOptions}. */\n poll?: EventConsumerPollOptions;\n /**\n * Notified for every dead-lettered sub-batch. The runner ALSO warn-logs each one unconditionally: loudness is\n * the ADR's requirement and a hook that swallows (or throws) must not be able to make a dead letter silent.\n */\n onDeadLetter?: (report: EventDeadLetterReport) => void;\n /**\n * Notified after EVERY read the runner performs — productive or empty, in both pacing modes — which makes it\n * the host's **liveness heartbeat**. The {@link DefineEventConsumerOptions.callback} fires only on delivered\n * batches, so on an idle queue it goes quiet and a liveness/readiness probe answering from it would report a\n * healthy runner as dead; beat from this instead and treat `fault` as the queue-health signal.\n *\n * It fires on the READ, before the batch is delivered, so a slow callback cannot delay the heartbeat. A hook\n * that THROWS can never take a loop down: the throw is caught, warn-logged ONCE per runner (a hook that\n * throws every poll must not drown the log), and the loop carries on.\n */\n onPoll?: (report: EventPollReport) => void;\n /** @internal The injectable wait — the deterministic seam the pacing tests drive. Defaults to `setTimeout`. */\n sleep?: EventConsumerSleep;\n /** @internal The injectable clock `drainOnce` measures its budget against. Defaults to `Date.now`. */\n now?: () => number;\n /**\n * @internal The injectable RENEWAL wait, deliberately a second seam rather than `sleep`: the two cadences\n * are independent (one paces reads, one paces lease renewal) and sharing one would make every pacing\n * assertion depend on renewal timing. Defaults to `setTimeout`.\n */\n renewalSleep?: EventConsumerSleep;\n}\n\nexport interface EventConsumer {\n /**\n * Begin every stream's loop. Idempotent; a no-op after {@link EventConsumer.stop}. Throws while a\n * {@link EventConsumer.drainOnce} pass is in flight — one handle drives one pacing mode at a time.\n */\n start: () => void;\n /**\n * Graceful stop: no new reads, no new callbacks, in-flight callbacks are awaited (and their leases KEPT\n * renewed until they ack or dead-letter), and the promise resolves when every loop — and every renewal\n * task it still owned — is quiet. Safe to call twice (the second call awaits the first). Messages of an\n * in-progress read whose callback had not started are released at once: they stop being renewed and are\n * left unacked, so at-least-once redelivers them as soon as their lease lapses.\n *\n * A `drainOnce` pass in flight is treated the same way: it starts no further read, finishes the callback\n * it is on, and `stop()` resolves once it has.\n */\n stop: () => Promise<void>;\n /**\n * One bounded drain pass — the pacing mode for a host that cannot hold a process (ADR-0053 amendment,\n * 2026-08-02).\n *\n * It walks every configured Event stream, read → deliver → ack, and keeps going until EITHER every stream\n * has returned an empty read OR the wall-clock budget is spent. Same internals as the loop mode\n * throughout: the same read/deliver/ack path, the same lease renewal while a callback runs, the same\n * per-sub-batch retry-by-lapsing-lease, the same dead-lettering after `maxAttempts` with the same\n * `onDeadLetter` hook and unconditional warn log. It never sleeps: a stream that reads empty is finished\n * for this pass, and there is no adaptive interval to wait out.\n *\n * **The budget is checked BETWEEN sub-batches, never inside one.** A callback already running is awaited\n * and acked exactly as the runner would (its lease stays renewed throughout), and no new read starts once\n * the budget is gone — so a pass can overrun its budget by one callback, and `budgetMs` must leave\n * head-room for that under the platform's invocation cap. A sub-batch whose callback THROWS near the\n * budget edge is not special-cased: it is left unacked and dropped from renewal, its lease lapses, and the\n * queue redelivers it on a later pass with an incremented delivery count. That is at-least-once working as\n * designed, not a lost event — and it is why the callback must be idempotent.\n *\n * **Hosting it.** Wire a SCHEDULED invocation (a platform cron, e.g. every 10 s) that calls `drainOnce`\n * and, optionally, an ingest-side nudge (`createSyncServer({ onEventsEnqueued })` firing a\n * fetch-and-forget at the same endpoint) so an interactive append is drained in milliseconds instead of\n * waiting for the next tick. The **schedule is the delivery guarantee; the nudge is only latency** — a\n * lost nudge costs nothing but time. Overlapping invocations are SAFE: two processes reading the same\n * queue are arbitrated by the visibility timeout, exactly as two long-lived runners would be. (Two passes\n * on ONE handle are not — that is a bug, and throws; see below.)\n *\n * **One handle, one pacing mode.** Throws if `start()` is live, if another `drainOnce` is already in\n * flight on this handle, or if the handle has been stopped — the lifecycle is one-way, so the next drain\n * builds a fresh `defineEventConsumer` (construction is query-free, so that costs nothing).\n */\n drainOnce: (options?: EventDrainOptions) => Promise<EventDrainSummary>;\n}\n\n/**\n * The adaptive wait for `idleCount` CONSECUTIVE unproductive reads (an empty read or a queue fault), clamped to\n * the ceiling. `idleCount` is 1 for the first one; a productive read resets it to 0 and re-reads immediately.\n */\nexport function computeEventPollWaitMs(idleCount: number, options: EventConsumerPollOptions = {}): number {\n const floorMs = options.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS;\n const ceilingMs = options.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS;\n const factor = options.factor ?? DEFAULT_EVENT_POLL_FACTOR;\n const exponent = Math.max(idleCount - 1, 0);\n return Math.min(Math.round(floorMs * factor ** exponent), ceilingMs);\n}\n\n/** The production wait: a `setTimeout` that is CLEARED on abort, so `stop()` never leaves a timer holding the process open. */\nconst abortableSleep: EventConsumerSleep = (ms, signal) =>\n new Promise<void>((resolve) => {\n if (signal.aborted) {\n resolve();\n return;\n }\n let handle: ReturnType<typeof setTimeout> | undefined;\n const finish = (): void => {\n if (handle !== undefined) {\n clearTimeout(handle);\n }\n signal.removeEventListener(\"abort\", finish);\n resolve();\n };\n handle = setTimeout(finish, ms);\n signal.addEventListener(\"abort\", finish, { once: true });\n });\n\nfunction assertPositive(label: string, value: number, minimum: number): number {\n if (!Number.isFinite(value) || value < minimum) {\n throw new Error(\n `pgxsinkit: defineEventConsumer's \\`${label}\\` must be a finite number >= ${minimum} (got ${value}).`,\n );\n }\n return value;\n}\n\nexport function defineEventConsumer<TRegistry extends SyncTableRegistry>(\n options: DefineEventConsumerOptions<TRegistry>,\n): EventConsumer {\n // ─── Definition-time resolution (fail-closed, and query-free) ────────────────────────────────────────\n const registered = getSyncRegistryStreams(options.registry) ?? {};\n const registeredNames = Object.keys(registered);\n if (registeredNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is nothing for a consumer runner to \" +\n \"consume. Register one with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n\n let streams: string[];\n if (options.streams) {\n const unknown = options.streams.filter((stream) => !Object.hasOwn(registered, stream));\n if (unknown.length > 0) {\n // Every offender is named: a typo'd stream on a runner would otherwise present as \"the events never\n // arrive\", which is the most expensive shape of silence in the lane.\n throw new Error(\n `pgxsinkit: defineEventConsumer was asked for Event stream(s) [${unknown.join(\", \")}] this registry ` +\n `does not register — it registers [${registeredNames.join(\", \")}].`,\n );\n }\n streams = [...new Set(options.streams)];\n if (streams.length === 0) {\n throw new Error(\n \"pgxsinkit: defineEventConsumer was given an empty `streams` list. Omit it to consume every registered \" +\n \"Event stream, or name at least one.\",\n );\n }\n } else {\n streams = registeredNames;\n }\n\n const batchSize = assertPositive(\"batchSize\", options.batchSize ?? DEFAULT_EVENT_CONSUMER_BATCH_SIZE, 1);\n const visibilityTimeoutSeconds = assertPositive(\n \"visibilityTimeoutSeconds\",\n options.visibilityTimeoutSeconds ?? DEFAULT_EVENT_VISIBILITY_TIMEOUT_SECONDS,\n 1,\n );\n const concurrency = assertPositive(\"concurrency\", options.concurrency ?? 1, 1);\n const maxAttempts = assertPositive(\"maxAttempts\", options.maxAttempts ?? DEFAULT_EVENT_MAX_ATTEMPTS, 1);\n const poll = options.poll ?? {};\n const floorMs = assertPositive(\"poll.floorMs\", poll.floorMs ?? DEFAULT_EVENT_POLL_FLOOR_MS, 0);\n const ceilingMs = assertPositive(\"poll.ceilingMs\", poll.ceilingMs ?? DEFAULT_EVENT_POLL_CEILING_MS, floorMs);\n const factor = assertPositive(\"poll.factor\", poll.factor ?? DEFAULT_EVENT_POLL_FACTOR, 1);\n const pollOptions: EventConsumerPollOptions = { floorMs, ceilingMs, factor };\n\n const queue = options.queue;\n const sleep = options.sleep ?? abortableSleep;\n const renewalSleep = options.renewalSleep ?? abortableSleep;\n const now = options.now ?? Date.now;\n /** Renew at HALF the window: one missed renewal still leaves a full half-window of head-room. */\n const renewalIntervalMs = Math.max(1, Math.floor((visibilityTimeoutSeconds * 1000) / 2));\n\n // ─── Lifecycle state ─────────────────────────────────────────────────────────────────────────────────\n const stopController = new AbortController();\n let started = false;\n let stopping = false;\n let loops: Promise<void>[] = [];\n let stopPromise: Promise<void> | null = null;\n /** The in-flight bounded drain, if any — the second pacing mode's whole lifecycle state. */\n let activeDrain: Promise<EventDrainSummary> | null = null;\n /**\n * The counters of the drain pass in flight, or `null` in loop mode. The settle points below feed it\n * rather than returning counts, so `drainOnce` reports on the SAME delivery path the runner uses instead\n * of a parallel one. Exactly one pass can be in flight (the mode is mutually exclusive), so one slot is\n * all this needs.\n */\n let drainStats: { delivered: number; deadLettered: number } | null = null;\n\n // ─── The per-read heartbeat ──────────────────────────────────────────────────────────────────────────\n /** Latched once the `onPoll` hook has thrown: the warn is per RUNNER, not per poll (see the option's doc). */\n let pollHookFailed = false;\n /**\n * Beat once for one completed read. Called from BOTH pacing modes and from the fault paths, so a host\n * watching this sees every turn of every loop; `empty` is derived here so the two modes cannot disagree\n * about what an empty read is.\n */\n const reportPoll = (stream: string, delivered: number, fault: boolean): void => {\n if (!options.onPoll) {\n return;\n }\n try {\n options.onPoll({ stream, delivered, empty: delivered === 0, fault, at: now() });\n } catch (error) {\n // A liveness hook that throws must never be able to stop the loop it is observing — that would turn a\n // reporting bug into an outage. Loud once, then silent: it typically throws on EVERY poll.\n if (!pollHookFailed) {\n pollHookFailed = true;\n console.warn(\n \"pgxsinkit: the `onPoll` hook threw; the event consumer carries on regardless (this is warned once \" +\n \"per runner, not once per poll)\",\n error,\n );\n }\n }\n };\n\n // ─── Dead-lettering (ADR-0053 decision 7: the loudness lives HERE) ───────────────────────────────────\n const reportDeadLetter = (report: EventDeadLetterReport): void => {\n // Unconditional, and deliberately not the client report surface's \"warn only when nobody subscribed\"\n // rule: a dead letter is rare and terminal, so it is worth a line in the operator's log even when the\n // app also handles it.\n console.warn(\n `pgxsinkit: dead-lettered an event sub-batch on Event stream \"${report.stream}\" (receipt ${report.receipt}, ` +\n `${report.attempts} delivery attempt(s)) — ${report.reason}. It is in the queue's dead-letter storage; ` +\n \"requeue it deliberately with `requeueDeadLetter` once the cause is fixed.\",\n report.cause,\n );\n if (!options.onDeadLetter) {\n return;\n }\n try {\n options.onDeadLetter(report);\n } catch (error) {\n console.error(\"pgxsinkit: the `onDeadLetter` hook threw; the message is dead-lettered regardless\", error);\n }\n };\n\n /** Move one message to dead-letter storage and report it. Resolves `false` when the QUEUE refused the move. */\n const deadLetter = async (\n stream: string,\n receipt: EventQueueReceipt,\n attempts: number,\n reason: string,\n cause: unknown,\n message?: EventQueueMessage,\n ): Promise<boolean> => {\n try {\n await queue.deadLetter(stream, [receipt], reason);\n } catch (error) {\n // The message is still queued and still invisible; it redelivers and dead-letters on a later pass.\n console.warn(\n `pgxsinkit: could not dead-letter message ${receipt} on Event stream \"${stream}\"; it stays queued and ` +\n \"will be retried\",\n error,\n );\n return false;\n }\n if (drainStats) {\n drainStats.deadLettered += 1;\n }\n reportDeadLetter({ stream, reason, attempts, receipt, ...(message ? { message } : {}), cause });\n return true;\n };\n\n // ─── Lease renewal (ADR-0053 decision 7: internal, and not optional) ─────────────────────────────────\n /**\n * Keep every UNSETTLED receipt of one read invisible for as long as that read is being worked through.\n * Returns the stopper, which the caller awaits so no renewal outlives its read (a stray timer would hold\n * the app's process open, and a stray extension would delay a redelivery the runner no longer wants).\n *\n * Its lifetime is the READ's, deliberately NOT the runner's: this task is wired to its OWN controller and\n * never to `stopController`. A graceful stop still awaits the callbacks already in flight, so aborting\n * renewal there would let their leases lapse mid-callback and let another runner take the work this one is\n * finishing. `stop()` instead shrinks `unsettled` (see `processDelivered`), and the loop below exits on its\n * own the moment that set drains.\n */\n const startRenewal = (stream: string, unsettled: Set<EventQueueReceipt>): (() => Promise<void>) => {\n const controller = new AbortController();\n\n const task = (async () => {\n while (!controller.signal.aborted && unsettled.size > 0) {\n await renewalSleep(renewalIntervalMs, controller.signal);\n if (controller.signal.aborted || unsettled.size === 0) {\n return;\n }\n try {\n await queue.extendVisibility(stream, [...unsettled], visibilityTimeoutSeconds);\n } catch (error) {\n // Best-effort by design: the worst case of a failed renewal is the behaviour there would be with\n // no renewal at all — the lease lapses and the sub-batch is redelivered to an idempotent callback.\n console.warn(\n `pgxsinkit: could not renew the visibility lease on Event stream \"${stream}\" (receipts ` +\n `${[...unsettled].join(\", \")}); the sub-batch may be redelivered while it is still being processed`,\n error,\n );\n }\n }\n })();\n\n return async () => {\n controller.abort();\n await task;\n };\n };\n\n // ─── One delivered message ───────────────────────────────────────────────────────────────────────────\n const processMessage = async (\n stream: string,\n delivered: DeliveredEventMessage,\n /** Drop this message from the read's renewal set — it is settled, one way or the other. */\n settle: () => void,\n ): Promise<void> => {\n try {\n await options.callback({ stream, events: delivered.message.events });\n } catch (error) {\n // Settled the moment it throws, and settled FIRST: a failed sub-batch's lease is deliberately allowed\n // to lapse, because that lapse IS the retry pacing. Renewing it would postpone its own redelivery.\n settle();\n const detail = error instanceof Error ? error.message : String(error);\n if (delivered.deliveryCount >= maxAttempts) {\n await deadLetter(\n stream,\n delivered.receipt,\n delivered.deliveryCount,\n `the consumer callback failed on delivery ${delivered.deliveryCount} of ${maxAttempts}: ${detail}`,\n error,\n delivered.message,\n );\n return;\n }\n // NOT acked, and no longer renewed: the lapsing lease IS the retry pacing (see the module note).\n console.warn(\n `pgxsinkit: the event consumer callback failed for Event stream \"${stream}\" (receipt ${delivered.receipt}, ` +\n `delivery ${delivered.deliveryCount} of ${maxAttempts}); the sub-batch will be redelivered after its ` +\n `${visibilityTimeoutSeconds}s visibility timeout`,\n error,\n );\n return;\n }\n\n if (drainStats) {\n // Counted on the callback's success, before the ack: the work was delivered either way, and an ack\n // that fails only means at-least-once will deliver it again to an idempotent callback.\n drainStats.delivered += 1;\n }\n\n try {\n await queue.ack(stream, [delivered.receipt]);\n } catch (error) {\n // At-least-once's honest failure mode: the work succeeded but the ack did not, so the sub-batch will be\n // redelivered. The idempotent callback the lane requires is exactly what makes that harmless.\n console.warn(\n `pgxsinkit: could not ack message ${delivered.receipt} on Event stream \"${stream}\"; it will be ` +\n \"redelivered (the callback must be idempotent)\",\n error,\n );\n }\n // Settled either way: an acked message is gone, and one whose ack failed is meant to be redelivered.\n settle();\n };\n\n /**\n * Process one read's messages, at most `concurrency` callbacks at a time. Never throws.\n *\n * The renewal task spans the WHOLE read, not one callback: the messages queued behind the one in flight are\n * just as invisible, and they are precisely the ones a long first callback would otherwise let lapse.\n *\n * `halted` is the \"enter no further callback\" predicate — a graceful stop in loop mode, and additionally\n * the spent wall-clock budget under {@link EventConsumer.drainOnce}. It is consulted BETWEEN sub-batches\n * only, so whatever is already running is always awaited and settled first; the messages of this read no\n * callback ever entered are then released from renewal so their leases lapse and they redeliver at once,\n * rather than staying invisible behind work this pass will not do.\n */\n const processDelivered = async (\n stream: string,\n messages: readonly DeliveredEventMessage[],\n halted: () => boolean,\n ): Promise<void> => {\n const unsettled = new Set(messages.map((delivered) => delivered.receipt));\n const settleOf = (delivered: DeliveredEventMessage) => () => unsettled.delete(delivered.receipt);\n /** Receipts a callback has actually been entered for — the ones a graceful stop must keep renewing. */\n const startedReceipts = new Set<EventQueueReceipt>();\n /**\n * A graceful stop enters no further callback, so every message of this read the workers never reached is\n * released HERE: dropping it from the renewal set lets its lease lapse and the queue redeliver it at once,\n * instead of holding it invisible for as long as the in-flight callbacks still take. The started ones stay\n * in the set and keep being renewed until `processMessage` settles them.\n */\n const releaseUnstarted = (): void => {\n for (const delivered of messages) {\n if (!startedReceipts.has(delivered.receipt)) {\n unsettled.delete(delivered.receipt);\n }\n }\n };\n if (stopController.signal.aborted) {\n releaseUnstarted();\n } else {\n stopController.signal.addEventListener(\"abort\", releaseUnstarted, { once: true });\n }\n const stopRenewal = startRenewal(stream, unsettled);\n\n // The `halted` check and this call are one synchronous step, so a stop (or an expiring budget) can never\n // land between \"we decided to run it\" and \"it counts as started\".\n const runOne = async (delivered: DeliveredEventMessage): Promise<void> => {\n startedReceipts.add(delivered.receipt);\n await processMessage(stream, delivered, settleOf(delivered));\n };\n\n try {\n if (concurrency <= 1) {\n for (const delivered of messages) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n await runOne(delivered);\n }\n return;\n }\n\n let cursor = 0;\n const worker = async (): Promise<void> => {\n for (;;) {\n if (halted()) {\n releaseUnstarted();\n return;\n }\n const delivered = messages[cursor++];\n if (!delivered) {\n return;\n }\n await runOne(delivered);\n }\n };\n await Promise.all(Array.from({ length: Math.min(concurrency, messages.length) }, worker));\n } finally {\n // Every callback of this read has settled by now (the workers await theirs), so the renewal task has\n // nothing left to protect — and `stop()`, which awaits this loop, therefore awaits the shutdown too.\n stopController.signal.removeEventListener(\"abort\", releaseUnstarted);\n await stopRenewal();\n }\n };\n\n // ─── One stream's loop ───────────────────────────────────────────────────────────────────────────────\n const runStream = async (stream: string): Promise<void> => {\n let idleCount = 0;\n\n while (!stopping) {\n let productive = false;\n try {\n const messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n // Beat on the READ, before delivery, so a slow callback cannot delay the heartbeat. `processDelivered`\n // never throws, so this iteration can produce exactly one report: this one, or the fault one below.\n reportPoll(stream, messages.length, false);\n if (messages.length > 0) {\n productive = true;\n await processDelivered(stream, messages, () => stopping);\n }\n } catch (error) {\n // The read did not complete. An unparseable body fails the WHOLE read exactly as a queue fault does,\n // so both beat the same way: nothing delivered, `fault: true`, and the loop carries on.\n reportPoll(stream, 0, true);\n if (error instanceof MalformedEventQueueMessageError) {\n // The endpoint is the only writer of these queues and it writes contract-shaped bodies, so this is a\n // hand-inserted or corrupted message. It fails the WHOLE read, so it must go on sight or it wedges\n // the stream: dead-letter exactly the named receipt, then re-read for the rest of the batch.\n productive = await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n } else {\n // A queue/database fault. A runner NEVER exits on a transient one — it backs off exactly like an\n // idle stream and keeps trying.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\"; backing off and retrying`,\n error,\n );\n }\n }\n\n if (productive) {\n // A backlog drains back-to-back: read again immediately, at the floor again once it runs dry.\n idleCount = 0;\n continue;\n }\n\n idleCount += 1;\n if (stopping) {\n break;\n }\n await sleep(computeEventPollWaitMs(idleCount, pollOptions), stopController.signal);\n }\n };\n\n // ─── One bounded drain pass (the serverless pacing mode) ─────────────────────────────────────────────\n /**\n * Read → deliver → ack across every stream until they all read empty or the budget is spent. Deliberately\n * built out of `processDelivered` and `deadLetter` — the loop mode's own path — so retry, renewal and\n * dead-lettering cannot drift between the two modes.\n */\n const runDrain = async (budgetMs: number): Promise<EventDrainSummary> => {\n const stats = { delivered: 0, deadLettered: 0 };\n drainStats = stats;\n const deadline = now() + budgetMs;\n /** Streams not yet known to be empty. A stream leaves the set on an empty read, or on a read fault. */\n const pending = new Set(streams);\n /** Anything that ended the pass with work possibly still queued — the `empty: false` reasons. */\n let unfinished = false;\n // Budget AND stop: a `stop()` during a pass must wind it down just as it winds down a loop.\n const halted = (): boolean => stopping || now() >= deadline;\n\n try {\n while (pending.size > 0) {\n if (halted()) {\n unfinished = true;\n break;\n }\n for (const stream of [...pending]) {\n if (halted()) {\n unfinished = true;\n break;\n }\n\n let messages: readonly DeliveredEventMessage[];\n try {\n messages = await queue.readBatch(stream, { visibilityTimeoutSeconds, maxMessages: batchSize });\n // The heartbeat covers this pacing mode too — a scheduled drain is exactly the deployment whose\n // host most wants to know a pass actually reached the queue.\n reportPoll(stream, messages.length, false);\n } catch (error) {\n reportPoll(stream, 0, true);\n if (error instanceof MalformedEventQueueMessageError) {\n // Same policy as the loop: it fails the WHOLE read, so it goes on sight and the stream stays\n // pending for the re-read that fetches the rest of the batch.\n await deadLetter(\n stream,\n error.receipt,\n 0,\n `the queue message body is not a valid event queue message: ${error.message}`,\n error,\n );\n continue;\n }\n // A queue/database fault. The loop mode backs off and retries; a bounded pass has nothing to\n // back off INTO (it must not busy-spin against a broken queue for the whole budget), so the\n // stream is left for the next invocation and the pass reports itself unfinished.\n console.warn(\n `pgxsinkit: the event consumer could not read Event stream \"${stream}\" during a bounded drain; ` +\n \"leaving it for the next pass\",\n error,\n );\n pending.delete(stream);\n unfinished = true;\n continue;\n }\n\n if (messages.length === 0) {\n pending.delete(stream);\n continue;\n }\n await processDelivered(stream, messages, halted);\n }\n }\n } finally {\n drainStats = null;\n }\n\n return { delivered: stats.delivered, deadLettered: stats.deadLettered, empty: !unfinished };\n };\n\n return {\n start: () => {\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: this event consumer is running a bounded `drainOnce()` pass, so `start()` cannot also \" +\n \"run its polling loops — one handle drives one pacing mode at a time. Await the pass first.\",\n );\n }\n if (started || stopping) {\n // Idempotent, and a no-op after `stop()` — the handle's lifecycle is one-way, matching the client's\n // flush driver. A restart is a new `defineEventConsumer`.\n return;\n }\n started = true;\n loops = streams.map((stream) =>\n // The catch is attached HERE, at creation: a loop is only awaited by `stop()`, so an unexpected\n // rejection must never be able to surface as an unhandled promise in the app's process.\n runStream(stream).catch((error: unknown) => {\n console.error(`pgxsinkit: the event consumer loop for Event stream \"${stream}\" ended unexpectedly`, error);\n }),\n );\n },\n\n stop: () => {\n stopping = true;\n stopController.abort();\n stopPromise ??= (async () => {\n await Promise.all(loops);\n loops = [];\n // A bounded pass is stopped like a loop: `halted()` already saw `stopping`, so it enters no further\n // callback — this just makes `stop()` resolve only once the one it was on has settled.\n await activeDrain?.catch(() => undefined);\n })();\n return stopPromise;\n },\n\n // Deliberately `async`, so every refusal below is a REJECTION rather than a synchronous throw from a\n // promise-returning function — a caller that only wired `.catch()` must not lose one.\n drainOnce: async (drainOptions = {}) => {\n if (started) {\n throw new Error(\n \"pgxsinkit: `drainOnce()` cannot run while this consumer's polling loops are live — one handle \" +\n \"drives one pacing mode at a time. Use the long-lived runner OR bounded drains, not both on one \" +\n \"handle. (Two separate PROCESSES draining the same queues concurrently is safe: the visibility \" +\n \"timeout arbitrates them.)\",\n );\n }\n if (stopping) {\n throw new Error(\n \"pgxsinkit: this event consumer handle is stopped — its lifecycle is one-way. Build a fresh \" +\n \"`defineEventConsumer` for the next drain pass; construction is query-free, so that costs nothing.\",\n );\n }\n if (activeDrain) {\n throw new Error(\n \"pgxsinkit: a `drainOnce()` pass is already in flight on this handle. Two SEPARATE PROCESSES \" +\n \"draining concurrently is safe (the queue's visibility timeouts arbitrate); two passes on one \" +\n \"handle would share its internal state, so it is refused. Await the first pass.\",\n );\n }\n\n const budgetMs = drainOptions.budgetMs ?? DEFAULT_EVENT_DRAIN_BUDGET_MS;\n if (!Number.isFinite(budgetMs) || budgetMs < 0) {\n throw new Error(`pgxsinkit: drainOnce's \\`budgetMs\\` must be a finite number >= 0 (got ${budgetMs}).`);\n }\n const pass = runDrain(budgetMs).finally(() => {\n activeDrain = null;\n });\n activeDrain = pass;\n return pass;\n },\n };\n}\n",
25
25
  "import { getSyncRegistryStreams, hashString, quoteSqlLiteral, type SyncTableRegistry } from \"@pgxsinkit/contracts\";\n\nimport { eventStreamQueueName } from \"./queue\";\n\n/**\n * The Event lane's **deploy-time** DDL (ADR-0053 decision 5): the pgmq extension plus one queue per registered\n * Event stream, derived from the registry.\n *\n * Provisioning is deploy-time and never runtime create-if-missing — the ingestion endpoint may enqueue long\n * before any consumer runner first starts, and a create-if-missing probe would put a query back in front of\n * the server's zero-startup-query posture.\n *\n * **pgmq assumptions** (read off pgmq's own extension SQL, and pinned by the integration lane):\n * - `CREATE EXTENSION IF NOT EXISTS pgmq` needs **no `CASCADE`**: pgmq's control file declares no `requires`.\n * (pg_partman is needed only for PARTITIONED queues, which this DDL never creates.) `CASCADE` would be\n * harmless but would also silently install whatever a future control file starts requiring.\n * - **No schema qualification is configurable**: the control file is `relocatable = false` with\n * `schema = 'pgmq'`, so the extension always lives in `pgmq` and every call is `pgmq.`-qualified.\n * - `pgmq.create()` is **idempotent**: it delegates to `create_non_partitioned`, whose tables and indexes are\n * `IF NOT EXISTS` and whose `pgmq.meta` insert is `ON CONFLICT DO NOTHING`. So the emitted statements need\n * no guard block and re-applying the migration is a no-op.\n *\n * The artifact is a MIGRATION body (raw SQL text) — `CREATE EXTENSION` and a SQL function call are outside\n * anything Drizzle's builders can express, which is the sanctioned raw-SQL case. Every interpolated queue\n * name is a registry-validated `[a-z][a-z0-9_]*` name, emitted through `quoteSqlLiteral`.\n */\n\n/** Stamped into the emitted DDL so `--check` can detect drift between the registry and a committed migration. */\nexport const EVENT_LANE_FINGERPRINT_PREFIX = \"pgxsinkit:events:fp1:\";\n\n/** The registered Event-stream names, SORTED — so the artifact and its fingerprint are registry-order-independent. */\nexport function eventLaneStreamNames(registry: SyncTableRegistry): string[] {\n return Object.keys(getSyncRegistryStreams(registry) ?? {}).sort();\n}\n\nfunction buildEventLaneDdlBody(streamNames: readonly string[]): string {\n const header =\n \"-- The pgxsinkit event lane's queues (ADR-0053 decision 5): one pgmq queue per registered Event stream.\\n\" +\n \"-- Provisioning is DEPLOY-TIME: the ingestion endpoint may enqueue long before any consumer runner starts.\\n\" +\n \"-- No CASCADE: pgmq's control file declares no `requires`. pgmq is non-relocatable (schema = 'pgmq').\\n\" +\n \"-- pgmq.create() is idempotent (IF NOT EXISTS tables/indexes + ON CONFLICT DO NOTHING meta), so\\n\" +\n \"-- re-applying this migration is a no-op and adding a stream only appends a line.\";\n\n const statements = streamNames.map(\n (stream) => `SELECT pgmq.create(${quoteSqlLiteral(eventStreamQueueName(stream))});`,\n );\n\n return `${header}\\nCREATE EXTENSION IF NOT EXISTS pgmq;\\n${statements.join(\"\\n\")}`;\n}\n\nfunction assertHasStreams(registry: SyncTableRegistry): string[] {\n const streamNames = eventLaneStreamNames(registry);\n if (streamNames.length === 0) {\n throw new Error(\n \"pgxsinkit: this registry registers no Event streams, so there is no event-lane DDL to emit. Register one \" +\n \"with `defineSyncRegistry({ tables, streams: { <name>: defineEventStream({ … }) } })`.\",\n );\n }\n return streamNames;\n}\n\n/**\n * The fingerprint the event-lane artifact carries for this registry. Derived from the emitted DDL body, so it\n * moves when a stream is added or removed (and when this generator's output changes) — and does NOT move for a\n * payload-schema change, which provisions nothing.\n */\nexport function eventLaneDdlFingerprint(registry: SyncTableRegistry): string {\n return EVENT_LANE_FINGERPRINT_PREFIX + hashString(buildEventLaneDdlBody(assertHasStreams(registry)));\n}\n\n/**\n * The full migration body: the DDL plus its fingerprint as a SQL comment. The comment is what\n * `pgxsinkit-generate --events --check` scans committed migrations for — the same pre-deploy drift detection\n * the apply-function artifact gets, minus the in-database stamp (there is no function here to comment on).\n */\nexport function renderEventLaneMigration(registry: SyncTableRegistry): string {\n const body = buildEventLaneDdlBody(assertHasStreams(registry));\n return `-- ${EVENT_LANE_FINGERPRINT_PREFIX + hashString(body)}\\n${body}`;\n}\n"
26
26
  ],
27
- "mappings": ";;AAUA,oDAA0B;;;ACV1B;AAAA,mBACE;AAAA;;;ACDF;AAEA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgDO,SAAS,sBAAsB,CAAC,UAA6B,UAA8C;AAAA,EAChH,OAAO,OAAO,OAAO,QAAQ,EAAE,KAAK,CAAC,UAAU,OAAO,OAAO,aAAa,QAAQ;AAAA;AAWpF,SAAS,kBAAkB,CAAC,OAA2D;AAAA,EACrF,MAAM,SAAS,MAAM,iBAAiB,MAAM;AAAA,EAC5C,IAAI,CAAC,OAAO,SAAS,GAAG;AAAA,IAAG,OAAO,EAAE,OAAO,OAAO;AAAA,EAClD,OAAO,UAAU,OAAO,MAAM,GAAG;AAAA,EACjC,IAAI,WAAW;AAAA,IAAU,OAAO,EAAE,OAAO,OAAO,MAAM,UAAU,MAAM,EAAE;AAAA,EACxE,OAAO;AAAA,IACL,SACE,UAAU,MAAM,oBAAoB,2DACpC;AAAA,EACJ;AAAA;AAmBF,SAAS,cAAc,CAAC,OAA6C;AAAA,EACnE,MAAM,WAAW,MAAM,OAAO,WAAW;AAAA,EACzC,IAAI,YAAY,QAAQ,SAAS,SAAS;AAAA,IAAG,OAAO,CAAC,GAAG,QAAQ;AAAA,EAChE,IAAI,MAAM,kBAAkB,eAAe;AAAA,IAAM;AAAA,EACjD,OAAO,eAAe,MAAM,UAAU,EAAE,QAAQ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AAI,EAAE,KAAK,WAAW,CAAC,KAAK,MAAM,KAAK,CAAC,CACnE;AAAA;AAGF,SAAS,sBAAsB,CAAC,QAAqC,iBAAiB,OAAsB;AAAA,EAC1G,IAAI,WAAW,OAAO;AAAA,IACpB,OAAO;AAAA,EACT;AAAA,EAEA,IAAI,WAAW,aAAa,CAAC,gBAAgB;AAAA,IAC3C,OAAO;AAAA,EACT;AAAA,EAEA,IAAI,OAAO,WAAW,YAAY,UAAU,QAAQ;AAAA,IAClD,OAAO,OAAO;AAAA,EAChB;AAAA,EAEA,OAAO;AAAA;AAGT,SAAS,eAAe,GAA6B;AAAA,EACnD,MAAM,WAAY,WAAsC;AAAA,EACxD,OAAO;AAAA;AAGT,SAAS,kBAAiB,CAAC,OAAgD;AAAA,EACzE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,YAAY,SAAS,MAAM,QAAQ,MAAM,MAAM;AAAA;AAGvG,SAAS,0BAA0B,CAAC,SAAsD;AAAA,EACxF,OAAO;AAAA,IACL,SAAS,SAAS,WAAW;AAAA,EAC/B;AAAA;",
28
+ "debugId": "A99B60012F83C2B064756E2164756E21",
29
29
  "names": []
30
30
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pgxsinkit/server",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "keywords": [
5
5
  "tanstack-intent"
6
6
  ],
@@ -32,7 +32,7 @@
32
32
  "build": "bun --cwd ../.. run build:public-packages"
33
33
  },
34
34
  "dependencies": {
35
- "@pgxsinkit/contracts": "0.5.1"
35
+ "@pgxsinkit/contracts": "0.5.2"
36
36
  },
37
37
  "peerDependencies": {
38
38
  "drizzle-orm": "1.0.0-rc.4"
@@ -15,7 +15,7 @@ description: >-
15
15
  metadata:
16
16
  type: task
17
17
  library: "@pgxsinkit/server"
18
- library_version: "0.5.1"
18
+ library_version: "0.5.2"
19
19
  source: https://pgxsinkit.github.io/start/deploying-the-server/
20
20
  ---
21
21
 
@@ -85,7 +85,7 @@ export interface StreamGateOptions {
85
85
  entitlements?: EntitlementSet;
86
86
  /**
87
87
  * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the
88
- * same value the engine is given as `ELECTRIC_CIRCUITS_DS_URL`, since both address the same paths.
88
+ * same value the engine is given as `CIRCUITS_DS_URL`, since both address the same paths.
89
89
  */
90
90
  durableStreamsUrl: string;
91
91
  /**
@@ -81,7 +81,7 @@ export interface SubscribeOptions {
81
81
  *
82
82
  * The control plane renews every live claim on exactly one cadence: the token re-mint, which the
83
83
  * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The
84
- * engine releases a claim not renewed within `leaseSeconds` (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`).
84
+ * engine releases a claim not renewed within `leaseSeconds` (`CIRCUITS_SHAPE_IDLE_SECS`).
85
85
  * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a
86
86
  * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The
87
87
  * factor of two is the margin for exactly one missed refresh.
@@ -91,7 +91,7 @@ export interface SubscribeOptions {
91
91
  * you" — and never a denial: a client told it lost entitlement truncates its rows.
92
92
  */
93
93
  export class CircuitsLeaseConfigError extends Error {
94
- /** The engine's `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
94
+ /** The engine's `CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
95
95
  readonly leaseSeconds: number;
96
96
  /** The stream-token TTL this control plane is configured with. */
97
97
  readonly ttlSeconds: number;
@@ -99,11 +99,11 @@ export class CircuitsLeaseConfigError extends Error {
99
99
  constructor(leaseSeconds: number, ttlSeconds: number) {
100
100
  super(
101
101
  `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +
102
- `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +
102
+ `CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +
103
103
  `(${ttlSeconds}s, the \`ttlSeconds\` option). Claims are renewed on the token re-mint, so a single ` +
104
104
  `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +
105
- `it. Raise ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` +
106
- `at most ${Math.floor(leaseSeconds / 2)}, or set ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +
105
+ `it. Raise CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` +
106
+ `at most ${Math.floor(leaseSeconds / 2)}, or set CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +
107
107
  `leases entirely.`,
108
108
  );
109
109
  this.name = "CircuitsLeaseConfigError";
@@ -58,7 +58,7 @@ export interface CircuitsShapeHandle {
58
58
  subscription: string;
59
59
  /**
60
60
  * How long this subscription may go unrenewed before the engine releases it
61
- * (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, default 1800). `0` means leases never lapse, because that
61
+ * (`CIRCUITS_SHAPE_IDLE_SECS`, default 1800). `0` means leases never lapse, because that
62
62
  * setting also disables dormancy.
63
63
  *
64
64
  * Reported rather than guessed: the renewal cadence is the deployment's to set, and a control plane