@pgxsinkit/client 0.1.32 → 0.1.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +11 -0
  2. package/dist/boot-report.d.ts +134 -0
  3. package/dist/boot-report.d.ts.map +1 -0
  4. package/dist/convergence.d.ts +76 -0
  5. package/dist/convergence.d.ts.map +1 -0
  6. package/dist/debug.d.ts +34 -0
  7. package/dist/debug.d.ts.map +1 -0
  8. package/dist/export-data.d.ts +100 -0
  9. package/dist/export-data.d.ts.map +1 -0
  10. package/dist/export-dump.d.ts +92 -0
  11. package/dist/export-dump.d.ts.map +1 -0
  12. package/dist/export-store.d.ts +214 -0
  13. package/dist/export-store.d.ts.map +1 -0
  14. package/dist/index.d.ts +615 -8
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8083 -2286
  17. package/dist/index.js.map +81 -44
  18. package/dist/lazy-guard.d.ts +59 -0
  19. package/dist/lazy-guard.d.ts.map +1 -0
  20. package/dist/lifecycle-slot.d.ts +31 -0
  21. package/dist/lifecycle-slot.d.ts.map +1 -0
  22. package/dist/live-rows-sql.d.ts +21 -0
  23. package/dist/live-rows-sql.d.ts.map +1 -0
  24. package/dist/local-store.d.ts +56 -0
  25. package/dist/local-store.d.ts.map +1 -0
  26. package/dist/local-tables.d.ts +707 -0
  27. package/dist/local-tables.d.ts.map +1 -0
  28. package/dist/mutation-state.d.ts +69 -0
  29. package/dist/mutation-state.d.ts.map +1 -0
  30. package/dist/mutation.d.ts +129 -4
  31. package/dist/mutation.d.ts.map +1 -1
  32. package/dist/schema.d.ts +82 -0
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/shape-sync.d.ts +190 -0
  35. package/dist/shape-sync.d.ts.map +1 -0
  36. package/dist/store-path.d.ts +132 -0
  37. package/dist/store-path.d.ts.map +1 -0
  38. package/dist/sync/apply.d.ts +51 -0
  39. package/dist/sync/apply.d.ts.map +1 -0
  40. package/dist/sync/copy.d.ts +43 -0
  41. package/dist/sync/copy.d.ts.map +1 -0
  42. package/dist/sync/drizzle-executor.d.ts +5 -0
  43. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  44. package/dist/sync/index.d.ts +32 -0
  45. package/dist/sync/index.d.ts.map +1 -0
  46. package/dist/sync/metadata-tables.d.ts +131 -0
  47. package/dist/sync/metadata-tables.d.ts.map +1 -0
  48. package/dist/sync/nudge.d.ts +49 -0
  49. package/dist/sync/nudge.d.ts.map +1 -0
  50. package/dist/sync/shape-inbox.d.ts +215 -0
  51. package/dist/sync/shape-inbox.d.ts.map +1 -0
  52. package/dist/sync/subscription-state.d.ts +39 -0
  53. package/dist/sync/subscription-state.d.ts.map +1 -0
  54. package/dist/sync/tags.d.ts +130 -0
  55. package/dist/sync/tags.d.ts.map +1 -0
  56. package/dist/sync/types.d.ts +126 -0
  57. package/dist/sync/types.d.ts.map +1 -0
  58. package/dist/sync-auth.d.ts +53 -0
  59. package/dist/sync-auth.d.ts.map +1 -0
  60. package/dist/testing.d.ts +27 -0
  61. package/dist/testing.d.ts.map +1 -0
  62. package/dist/testing.js +17 -0
  63. package/dist/testing.js.map +11 -0
  64. package/dist/worker/attach-sync-client.d.ts +96 -0
  65. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  66. package/dist/worker/define-sync-worker.d.ts +76 -0
  67. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  68. package/dist/worker/live-diff.d.ts +44 -0
  69. package/dist/worker/live-diff.d.ts.map +1 -0
  70. package/dist/worker/protocol.d.ts +341 -0
  71. package/dist/worker/protocol.d.ts.map +1 -0
  72. package/dist/worker/token-cache.d.ts +26 -0
  73. package/dist/worker/token-cache.d.ts.map +1 -0
  74. package/oxlint-plugin.js +143 -0
  75. package/package.json +20 -7
  76. package/skills/core/SKILL.md +210 -0
  77. package/skills/operating/SKILL.md +303 -0
  78. package/src/boot-report.ts +287 -0
  79. package/src/convergence.ts +197 -0
  80. package/src/debug.ts +151 -0
  81. package/src/export-data.ts +300 -0
  82. package/src/export-dump.ts +239 -0
  83. package/src/export-store.ts +309 -0
  84. package/src/index.ts +1652 -51
  85. package/src/lazy-guard.ts +135 -0
  86. package/src/lifecycle-slot.ts +66 -0
  87. package/src/live-rows-sql.ts +45 -0
  88. package/src/local-store.ts +193 -0
  89. package/src/local-tables.ts +546 -0
  90. package/src/mutation-state.ts +99 -0
  91. package/src/mutation.ts +1910 -562
  92. package/src/schema.ts +472 -28
  93. package/src/shape-sync.ts +498 -0
  94. package/src/store-path.ts +249 -0
  95. package/src/sync/apply.ts +530 -0
  96. package/src/sync/copy.ts +206 -0
  97. package/src/sync/drizzle-executor.ts +48 -0
  98. package/src/sync/index.ts +1087 -0
  99. package/src/sync/metadata-tables.ts +67 -0
  100. package/src/sync/nudge.ts +110 -0
  101. package/src/sync/shape-inbox.ts +566 -0
  102. package/src/sync/subscription-state.ts +135 -0
  103. package/src/sync/tags.ts +365 -0
  104. package/src/sync/types.ts +141 -0
  105. package/src/sync-auth.ts +117 -0
  106. package/src/testing.ts +53 -0
  107. package/src/worker/attach-sync-client.ts +653 -0
  108. package/src/worker/define-sync-worker.ts +762 -0
  109. package/src/worker/live-diff.ts +140 -0
  110. package/src/worker/protocol.ts +425 -0
  111. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,762 @@
1
+ // The worker entry factory (ADR-0032 S2, decisions 3/4/6/7). `defineSyncWorker` boots ONE sync engine and
2
+ // fans it out to N attached tabs over the bridge. The first attach boots the engine by calling the
3
+ // unchanged `createSyncClient` (the strongest form of "reuse createSyncClient internals" — the in-process
4
+ // boot pipeline runs verbatim, so the unit suite stays its equivalence proof); later attaches join it.
5
+ //
6
+ // It serves BOTH a native `SharedWorker` (`onconnect`, many ports) and a dedicated `Worker` (one implicit
7
+ // port) behind {@link SyncWorkerHost.connect} — the same entry a test drives with a plain `MessageChannel`
8
+ // port, so no real Worker is needed to exercise the whole protocol.
9
+
10
+ import type { SyncRuntimeStatus, SyncTableName, SyncTableRegistry, WriteMode } from "@pgxsinkit/contracts";
11
+
12
+ import { type ConvergenceTrigger, createIntervalConvergenceTrigger } from "../convergence";
13
+ import { setSyncDebugSink, syncDebug } from "../debug";
14
+ import {
15
+ type ClientPGlite,
16
+ createClientPGlite,
17
+ type CreateSyncClientOptions,
18
+ createSyncClient,
19
+ type DataExportOptions,
20
+ type DiagnosticExportOptions,
21
+ type MutationBatchItem,
22
+ type RawQueryOptions,
23
+ type StoreExportOptions,
24
+ type SyncClient,
25
+ } from "../index";
26
+ import { wrapLiveQueryForMaterialization } from "../live-rows-sql";
27
+ import type { LocalStoreVersionEvent } from "../local-store";
28
+ import { readTestStoreMarker, TEST_STORE_BACKEND, type TestStoreMarker } from "../store-path";
29
+ import { computeLiveDiff, seedLiveDiffState } from "./live-diff";
30
+ import {
31
+ type AttachPayload,
32
+ type BridgeCodec,
33
+ type BridgeEnvelope,
34
+ type BridgeEvent,
35
+ type BridgePort,
36
+ type ExportArtefactWire,
37
+ identityCodec,
38
+ isBridgeEnvelope,
39
+ postBridgeMessage,
40
+ type ProvisionPayload,
41
+ type RpcOp,
42
+ type RpcPayload,
43
+ type SetOnlinePayload,
44
+ type SubscribePayload,
45
+ type TokenResponsePayload,
46
+ } from "./protocol";
47
+ import { createWorkerTokenCache } from "./token-cache";
48
+
49
+ export interface DefineSyncWorkerOptions<TRegistry extends SyncTableRegistry> {
50
+ /**
51
+ * The sync registry — imported as CODE by the worker file, never cloned into it (ADR-0032 decision 4).
52
+ * When {@link resolveRegistry} is also given this is the DEFAULT (used when the attach carries no role
53
+ * or an unknown one).
54
+ */
55
+ registry: TRegistry;
56
+ /**
57
+ * Resolve the registry to boot from the attach's `config.role` (ADR-0032 S3). A single worker file can
58
+ * bake BOTH role variants (e.g. the board's admin/member registries — same TS shape, different write
59
+ * capability) and pick per-attach, which the spare flow needs: the spare is provisioned role-agnostic
60
+ * (before the user is known) and the role is only settled at claim/attach. Returns `undefined` to fall
61
+ * back to {@link registry}.
62
+ */
63
+ resolveRegistry?: (role: string | undefined) => TRegistry | undefined;
64
+ /**
65
+ * How the worker creates its raw PGlite store (provision + fresh-attach paths). Defaults to
66
+ * {@link createClientPGlite}, which loads PGlite's own boot assets — in a browser worker those hit the
67
+ * same-origin HTTP cache the tab's login-screen warm already primed (ADR-0032 S3). Injected in tests.
68
+ * Takes a plain store PATH (ADR-0036); the internal `backendOverride` is the test lane's memory selection.
69
+ */
70
+ createPglite?: (storePath: string, backendOverride?: "memory") => Promise<ClientPGlite>;
71
+ electricUrl: string;
72
+ writeUrl: string;
73
+ /** Static headers on every read + write request (e.g. a gateway `apikey`). See `createSyncClient`. */
74
+ requestHeaders?: Record<string, string>;
75
+ /** Write-only headers merged over {@link requestHeaders} (e.g. region/DB-affinity). See `createSyncClient`. */
76
+ writeRequestHeaders?: Record<string, string>;
77
+ /** Default plain store PATH (ADR-0036) if the first attach carries none — a name, not a storage URL. */
78
+ storePath?: string;
79
+ maxMutationAttempts?: number;
80
+ syncEnabled?: boolean;
81
+ /**
82
+ * How close to expiry (ms) a cached token may be before a read/write that needs it triggers a pull
83
+ * broadcast (ADR-0032 decision 3). Default 30s — comfortably ahead of a long-poll cycle.
84
+ */
85
+ tokenExpiryMarginMs?: number;
86
+ /**
87
+ * The worker's own convergence cadence (ms) — the interval trigger FALLBACK only. Local writes
88
+ * flush immediately via the event-driven `requestPass` seam and tab `wake` signals, so this
89
+ * interval exists purely for retry/recovery sweeps; each idle pass still costs real worker CPU
90
+ * (`flush` + `reconcile` queries). Default 15000.
91
+ */
92
+ convergenceIntervalMs?: number;
93
+ /** Injected transport binder. Defaults to auto-detecting the SharedWorker/dedicated-worker global scope. */
94
+ installGlobal?: boolean;
95
+ /** Injected codec (ADR-0032 S2 §1). Defaults to the v1 identity codec. */
96
+ codec?: BridgeCodec;
97
+ /**
98
+ * A raw PGlite the worker uses instead of creating its own (forwarded to `createSyncClient`'s
99
+ * {@link CreateSyncClientOptions.precreatedPglite}) — the client still applies schema/reconcile. In a
100
+ * browser worker the store is minted internally (`storePath`); this is the seam for a prepopulated store in
101
+ * tests, and the future spare-worker claim (ADR-0032 decision 5).
102
+ */
103
+ precreatedPglite?: CreateSyncClientOptions<TRegistry>["precreatedPglite"];
104
+ /** A fully-provisioned PGlite (forwarded to {@link CreateSyncClientOptions.pgliteInstance}; caller owns schema). */
105
+ pgliteInstance?: CreateSyncClientOptions<TRegistry>["pgliteInstance"];
106
+ }
107
+
108
+ /** The worker-side host: attach ports, await the boot, and (for tests) tear down. */
109
+ export interface SyncWorkerHost<TRegistry extends SyncTableRegistry> {
110
+ /** Bind a transport port (a SharedWorker connection, the dedicated-worker `self`, or a test channel port). */
111
+ connect: (port: BridgePort) => void;
112
+ /** Resolves with the booted in-process engine once the first attach's `createSyncClient` completes. */
113
+ whenBooted: () => Promise<SyncClient<TRegistry>>;
114
+ /** Detach every port and stop the underlying client — for tests and dedicated-worker teardown. */
115
+ close: () => Promise<void>;
116
+ }
117
+
118
+ interface LiveSub {
119
+ unsubscribe: () => void;
120
+ port: BridgePort;
121
+ }
122
+
123
+ /**
124
+ * Build a worker host over the given engine config. In a real worker file the consumer calls this at module
125
+ * top level and it auto-binds the global scope; a test constructs it and drives {@link SyncWorkerHost.connect}.
126
+ */
127
+ export function defineSyncWorker<const TRegistry extends SyncTableRegistry>(
128
+ options: DefineSyncWorkerOptions<TRegistry>,
129
+ ): SyncWorkerHost<TRegistry> {
130
+ const codec = options.codec ?? identityCodec;
131
+ const tokenExpiryMarginMs = options.tokenExpiryMarginMs ?? 30_000;
132
+ const convergenceIntervalMs = options.convergenceIntervalMs ?? 15_000;
133
+ const createPglite =
134
+ options.createPglite ??
135
+ ((storePath: string, backendOverride?: "memory") =>
136
+ createClientPGlite(storePath, backendOverride ? { backendOverride } : undefined));
137
+ // A testing acknowledgment (ADR-0036) spread into THIS worker's options — needed when a test injects a
138
+ // non-persistent BYO store (`precreatedPglite` / `pgliteInstance` / a memory-returning `createPglite`),
139
+ // which `createSyncClient` would otherwise refuse. Forwarded to the boot below. A browser worker never
140
+ // sets it; a memory selection carried on the attach wire wins over it.
141
+ const workerTestMarker = readTestStoreMarker(options);
142
+
143
+ const ports = new Set<BridgePort>();
144
+ const liveSubs = new Map<string, LiveSub>();
145
+
146
+ // ─── Pre-spawned (schemaless) store — the spare flow (ADR-0032 decision 5) ────────────────────────
147
+ // A `provision` mints the raw PGlite (initdb only) and holds it idle here; the first real `attach`
148
+ // adopts it as `precreatedPglite` (the client still runs schema/journal recovery/reconcile). Provision
149
+ // is role-agnostic — the registry is chosen at attach — so the same warmed store serves either role.
150
+ // `stamp` carries the spare's create timing (ADR-0034): a boot adopting this store reports the initdb cost
151
+ // as `BootReport.provision` (with `phases.pgliteCreateMs = null`) instead of timing a create it never ran.
152
+ let provisioned: {
153
+ storePath: string;
154
+ pglite: Promise<ClientPGlite>;
155
+ stamp: Promise<{ initdbMs: number; provisionReadyAt: number }>;
156
+ } | null = null;
157
+
158
+ // ─── Outbound-convergence gate — the tab's Offline toggle over the bridge (ADR-0032 S3) ───────────
159
+ // The worker owns convergence; the tab forwards its Offline flag as `set-online`. When suppressed the
160
+ // interval trigger's `shouldConverge` returns false (writes stage in the journal, unsent) and a `wake`
161
+ // is ignored; resuming fires one immediate pass so the queue flushes at once.
162
+ let convergenceSuppressed = false;
163
+ let fireConvergence: (() => void) | null = null;
164
+ const baseTrigger = createIntervalConvergenceTrigger(convergenceIntervalMs);
165
+ const gatedTrigger: ConvergenceTrigger = {
166
+ subscribe: (onSignal) => {
167
+ fireConvergence = onSignal;
168
+ const unsubscribe = baseTrigger.subscribe(onSignal);
169
+ return () => {
170
+ fireConvergence = null;
171
+ unsubscribe();
172
+ };
173
+ },
174
+ shouldConverge: () => !convergenceSuppressed && baseTrigger.shouldConverge(),
175
+ };
176
+
177
+ // ─── The single auth token cache + pull mechanism (ADR-0032 decision 3) ──────────────────────────
178
+ const tokenCache = createWorkerTokenCache({
179
+ marginMs: tokenExpiryMarginMs,
180
+ broadcastRequest: (requestId) => {
181
+ syncDebug("worker token pull broadcast", { requestId, tabs: ports.size });
182
+ broadcast("token-request", { requestId });
183
+ },
184
+ });
185
+ const getWorkerAuthToken = () => tokenCache.getToken();
186
+
187
+ // ─── The broadcast event channel (ADR-0032 decision 7) ───────────────────────────────────────────
188
+ const seenReadyGroups = new Set<string>();
189
+ const broadcast = (type: BridgeEnvelope["type"], payload: unknown) => {
190
+ for (const port of ports) postBridgeMessage(port, codec, type, payload);
191
+ };
192
+ const broadcastEvent = (event: BridgeEvent) => broadcast("event", event);
193
+
194
+ // ─── Debug-rail buffer + replay (ADR-0034) ───────────────────────────────────────────────────────
195
+ // The engine boots on the first ATTACH, but the front half of boot (provision, and the boot rail's
196
+ // schema/journal/reconcile lines) can be emitted before any debug-enabled tab is listening — so they
197
+ // vanished. Install the sink at construction (not at boot) into a bounded ring buffer, so the whole boot
198
+ // is captured from worker start; the buffer is REPLAYED (marked `[replay]`) to the first attach, while the
199
+ // back half streams live over the bridge. Bounded so a long-lived worker never grows the buffer unbounded.
200
+ const RAIL_BUFFER_MAX = 500;
201
+ const railBuffer: Array<{ stamp: number; line: string; data?: Record<string, unknown> }> = [];
202
+ let railReplayed = false;
203
+ setSyncDebugSink((line, stamp, data) => {
204
+ if (railBuffer.length >= RAIL_BUFFER_MAX) railBuffer.shift();
205
+ railBuffer.push({ stamp, line, ...(data ? { data } : {}) });
206
+ broadcastEvent({ kind: "debug", stamp, line, ...(data ? { data } : {}) });
207
+ });
208
+ const nowStamp = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
209
+ // Replay the pre-attach rail buffer to the first attaching port. Taken as a snapshot BEFORE this attach's
210
+ // boot runs, so the boot's own lines (which stream live to this now-connected port) are never doubled.
211
+ const replayRailBufferTo = (port: BridgePort) => {
212
+ if (railReplayed) return;
213
+ railReplayed = true;
214
+ const buffered = [...railBuffer];
215
+ postBridgeMessage(port, codec, "event", {
216
+ kind: "debug",
217
+ stamp: nowStamp(),
218
+ line: `[replay] replaying ${buffered.length} buffered rail line(s)`,
219
+ } satisfies BridgeEvent);
220
+ for (const entry of buffered) {
221
+ postBridgeMessage(port, codec, "event", {
222
+ kind: "debug",
223
+ stamp: entry.stamp,
224
+ line: `[replay] ${entry.line}`,
225
+ ...(entry.data ? { data: entry.data } : {}),
226
+ } satisfies BridgeEvent);
227
+ }
228
+ };
229
+
230
+ const emitStatus = (status: SyncRuntimeStatus) => {
231
+ broadcastEvent({ kind: "status", status });
232
+ // Derive a per-group `groupReady` event for each group that newly reached ready, so a tab gets both the
233
+ // status snapshot (`status.groups`) and a discrete edge to await (ADR-0032 decision 6/7).
234
+ for (const [groupKey, ready] of Object.entries(status.groups ?? {})) {
235
+ if (ready && !seenReadyGroups.has(groupKey)) {
236
+ seenReadyGroups.add(groupKey);
237
+ broadcastEvent({ kind: "groupReady", groupKey });
238
+ }
239
+ }
240
+ };
241
+
242
+ // ─── Engine boot — reuse createSyncClient verbatim (ADR-0032 decision 1/4) ────────────────────────
243
+ let client: SyncClient<TRegistry> | null = null;
244
+ let bootPromise: Promise<SyncClient<TRegistry>> | null = null;
245
+ // The role the engine actually booted with (from the FIRST attach's config). Later attaches compare
246
+ // their requested role against this and get a warning on mismatch (ADR-0032 FIX 5) — never a reject.
247
+ let bootedRole: string | undefined;
248
+ // The engine's `ready` is monotonic: once its initial sync lands it stays resolved even if the phase
249
+ // later degrades. A tab attaching AFTER that moment must still get a resolved `ready`, so track whether
250
+ // it has fired and tell the ack (ADR-0032 FIX 3).
251
+ let engineReadyFired = false;
252
+ let resolveBooted!: (client: SyncClient<TRegistry>) => void;
253
+ const bootedPromise = new Promise<SyncClient<TRegistry>>((resolve) => {
254
+ resolveBooted = resolve;
255
+ });
256
+
257
+ const boot = (attach: AttachPayload): Promise<SyncClient<TRegistry>> => {
258
+ if (bootPromise) return bootPromise;
259
+ // The tab is the auth owner: seed the cache with the token it presented at attach (decision 3).
260
+ tokenCache.push(attach.token);
261
+ bootedRole = attach.config?.role;
262
+ // The debug-rail sink is installed at construction (ADR-0034) so it buffers from worker start and
263
+ // forwards live to tabs, stamped with the WORKER's monotonic clock (decision 7) — see above.
264
+ // Resolve the registry from the attach's role (ADR-0032 S3): a single worker file bakes both variants
265
+ // and the claim/attach settles which one boots — the spare was provisioned before the role was known.
266
+ const registry = options.resolveRegistry?.(attach.config?.role) ?? options.registry;
267
+ // storePath-first, matching the `provision` handler's resolution (below): the board sends BOTH a bare
268
+ // `storeId` (SharedWorker naming, tab-side) AND the real `storePath` (`pgxsinkit-board-<id>`), and the
269
+ // PGlite store lives at `storePath` — so the provisioned store's path must be what we adopt on.
270
+ // `storeId` is only a last-ditch fallback for a caller that passes it as the store path.
271
+ const storePath = attach.storePath ?? attach.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
272
+ // The testing memory-backend override rides as an explicit wire field (a symbol does not survive
273
+ // structured clone, ADR-0036); re-stamp it as the internal marker on the createSyncClient options below.
274
+ // A memory selection on the attach wins over the worker's own acknowledgment (memory implies acknowledged).
275
+ const backendOverride = attach.testStoreBackend;
276
+ const testMarker: TestStoreMarker | undefined = backendOverride === "memory" ? "memory" : workerTestMarker;
277
+ // Restore (ADR-0035 decision 6): the tab decomposed the backup into a transferred `ArrayBuffer` + mime
278
+ // (`RestoreArtefactWire`); recompose a `Blob` to hand `createSyncClient` as `restoreFrom`. Restore OWNS the
279
+ // store's creation (a `loadDataDir` seed), so it is mutually exclusive with adopting a pre-provisioned or
280
+ // caller-supplied instance — when restoring, we suppress the adopt paths below rather than let
281
+ // createSyncClient throw the exclusion error.
282
+ const restoreFrom = attach.restore
283
+ ? new Blob([attach.restore.buffer], { type: attach.restore.mimeType })
284
+ : undefined;
285
+ // Adopt a matching pre-provisioned store (its initdb already ran off-thread) as `precreatedPglite`;
286
+ // createSyncClient falls back to a fresh `storePath` create if that promise rejects — a pure accelerator.
287
+ // Never adopt when restoring (restore boots a brand-new store from the backup, not the provisioned one).
288
+ const adoptingProvisioned = restoreFrom == null && provisioned != null && provisioned.storePath === storePath;
289
+ const precreatedPglite = adoptingProvisioned
290
+ ? provisioned!.pglite
291
+ : restoreFrom
292
+ ? undefined
293
+ : options.precreatedPglite;
294
+ // The adopted spare's create timing feeds `BootReport.provision` (ADR-0034); absent otherwise.
295
+ const provisionStamp = adoptingProvisioned ? provisioned!.stamp : undefined;
296
+ if (adoptingProvisioned) {
297
+ syncDebug("worker adopting provisioned store", { storePath });
298
+ }
299
+ if (restoreFrom) {
300
+ syncDebug("worker restoring store from backup", { storePath, byteLength: attach.restore!.buffer.byteLength });
301
+ }
302
+ bootPromise = createSyncClient<TRegistry>({
303
+ registry,
304
+ electricUrl: options.electricUrl,
305
+ writeUrl: options.writeUrl,
306
+ storePath,
307
+ // Re-stamp the internal testing marker (ADR-0036) so `createSyncClient`'s option handling selects the
308
+ // memory backend on its fallback create and/or bypasses the BYO refusal for an injected test store —
309
+ // the wire field / worker acknowledgment are the cross-clone carriers for it.
310
+ ...(testMarker ? { [TEST_STORE_BACKEND]: testMarker } : {}),
311
+ // Restore rides the boot attach (ADR-0035 decision 6): createSyncClient seeds the fresh store via
312
+ // `loadDataDir`, boots offline, and quarantines the recovered journal.
313
+ ...(restoreFrom ? { restoreFrom } : {}),
314
+ // Boot observability (ADR-0034): label the report `worker`, and forward the provision stamp so an
315
+ // adopted spare's initdb cost is reported rather than a create this boot never ran.
316
+ bootMode: "worker",
317
+ ...(provisionStamp ? { provisionStamp } : {}),
318
+ ...(precreatedPglite ? { precreatedPglite } : {}),
319
+ ...(options.pgliteInstance && restoreFrom == null ? { pgliteInstance: options.pgliteInstance } : {}),
320
+ // Fresh-store prefetch overlap (ADR-0032 S4): the tab's claim path proved this store a schemaless
321
+ // spare and forwarded the hint in the attach config, so the shape catch-up overlaps schema exec +
322
+ // journal recovery + reconcile. Never inferred from "adopting a provisioned store": the board
323
+ // provisions a worker even for a MAPPED (returning) user, whose idb is NOT fresh — only the claim
324
+ // path's explicit hint distinguishes them.
325
+ ...(attach.config?.freshStore === true ? { freshStore: true } : {}),
326
+ getAuthToken: getWorkerAuthToken,
327
+ // The worker owns convergence via the interval trigger, GATED by the tab's Offline toggle
328
+ // (`set-online`); tabs additionally forward online/visibility as `wake` pass requests (below).
329
+ autoSync: gatedTrigger,
330
+ syncEnabled: attach.config?.syncEnabled ?? options.syncEnabled ?? true,
331
+ ...(options.requestHeaders ? { requestHeaders: options.requestHeaders } : {}),
332
+ ...(options.writeRequestHeaders ? { writeRequestHeaders: options.writeRequestHeaders } : {}),
333
+ ...(options.maxMutationAttempts != null ? { maxMutationAttempts: options.maxMutationAttempts } : {}),
334
+ onStatusChange: (status) => emitStatus(status),
335
+ onConflict: (details) => broadcastEvent({ kind: "conflict", details }),
336
+ onQuarantine: (details) => broadcastEvent({ kind: "quarantine", details }),
337
+ onReject: (details) => broadcastEvent({ kind: "reject", details }),
338
+ onSchemaChange: (event: LocalStoreVersionEvent) => broadcastEvent({ kind: "schema-change", event }),
339
+ onSyncError: (error) => broadcastEvent({ kind: "sync-error", message: error.message }),
340
+ // Boot observability (ADR-0034): broadcast the finalized report to currently-attached ports (one-shot
341
+ // push). Later tabs read the same report via the `bootReport` pull RPC — there is no replay event.
342
+ onBootReport: (report) => broadcastEvent({ kind: "boot-report", report }),
343
+ });
344
+ return bootPromise;
345
+ };
346
+
347
+ const whenBooted = () => bootedPromise;
348
+
349
+ // ─── Write / mutation-state RPC dispatch ─────────────────────────────────────────────────────────
350
+ const dispatchRpc = async (active: SyncClient<TRegistry>, op: RpcOp, args: unknown[]): Promise<unknown> => {
351
+ type TableKey = SyncTableName<TRegistry>;
352
+ switch (op) {
353
+ case "create":
354
+ return active.mutate.create(args[0] as TableKey, args[1] as never);
355
+ case "update":
356
+ return active.mutate.update(args[0] as TableKey, args[1] as Record<string, string>, args[2] as never);
357
+ case "delete":
358
+ return active.mutate.delete(args[0] as TableKey, args[1] as Record<string, string>);
359
+ case "batch":
360
+ return active.mutate.batch(args[0] as ReadonlyArray<MutationBatchItem<TRegistry>>);
361
+ case "transaction": {
362
+ // The tab collected the unit's mutations (the run callback can't cross the wire); the worker replays
363
+ // the serialized items into a real `client.transaction` so pessimistic acks / optimistic flush match
364
+ // the in-process semantics exactly.
365
+ const { mode, items } = args[0] as { mode: WriteMode; items: MutationBatchItem<TRegistry>[] };
366
+ return active.transaction({ mode }, (tx) => {
367
+ for (const item of items) {
368
+ const handle = tx.tables[item.table];
369
+ if (item.kind === "create") {
370
+ handle.create(item.input as never);
371
+ } else if (item.kind === "update") {
372
+ // ADR-0022 addendum: a `blind` update replays through `updateBlind` (journal-only, no overlay).
373
+ if (item.blind) handle.updateBlind(item.entityKey, item.patch as never);
374
+ else handle.update(item.entityKey, item.patch as never);
375
+ } else {
376
+ handle.delete(item.entityKey);
377
+ }
378
+ }
379
+ });
380
+ }
381
+ case "flush":
382
+ return active.flush(args[0] as TableKey | undefined);
383
+ case "reconcile":
384
+ return active.reconcile(args[0] as TableKey | undefined);
385
+ case "retryFailed":
386
+ return active.retryFailed(args[0] as TableKey | undefined);
387
+ case "recoverSending":
388
+ return active.recoverSending(args[0] as TableKey | undefined);
389
+ case "discardConflict":
390
+ return active.discardConflict(args[0] as TableKey, args[1] as Record<string, string>);
391
+ case "discardQuarantined":
392
+ return active.discardQuarantined(args[0] as TableKey, args[1] as Record<string, string>);
393
+ case "desync":
394
+ return active.desync(args[0] as TableKey);
395
+ case "discardEphemeral":
396
+ return active.discardEphemeral(args[0] as TableKey);
397
+ case "readMutationDetails":
398
+ return active.readMutationDetails(args[0] as TableKey | undefined);
399
+ case "diagnostics":
400
+ return active.diagnostics(args[0] as TableKey | undefined);
401
+ case "rawQuery":
402
+ // Inspection read (ADR-0032 S2): run straight against the worker's own store — `active.pglite`
403
+ // exists worker-side (it's the in-process client). `Results` rows/fields structured-clone across
404
+ // the wire (Dates survive postMessage), so the tab receives the same shape it would in-process.
405
+ // The options arg is the clonable RawQueryOptions subset (rowMode) — the REPL's array mode.
406
+ return active.rawQuery(args[0] as string, args[1] as unknown[] | undefined, args[2] as RawQueryOptions);
407
+ case "rawExec":
408
+ return active.rawExec(args[0] as string, args[1] as RawQueryOptions);
409
+ case "bootReport":
410
+ // Boot observability (ADR-0034): the worker engine's stored report (or null). Pull, so a late tab
411
+ // reads a boot predating it; the report structured-clones across the bridge as a plain object.
412
+ return active.bootReport();
413
+ case "exportStore": {
414
+ // Store backup (ADR-0035): run the live export on the worker's OWN client (its lifecycle slot
415
+ // serialises it against every tab's export). A `File` cannot cross the bridge as a transferable, so
416
+ // decompose it into an `ExportArtefactWire` — the `ArrayBuffer` is listed on `postMessage`'s transfer
417
+ // list in the `rpc` handler and rebuilt into a `File` tab-side.
418
+ const { file, report } = await active.exportStore(args[0] as StoreExportOptions | undefined);
419
+ const buffer = await file.arrayBuffer();
420
+ return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;
421
+ }
422
+ case "exportDiagnostics": {
423
+ // Diagnostic dump (ADR-0035): identical bridge shape to the store backup — the worker runs the live
424
+ // datadir dump → memory throwaway clone → `pg_dump` on its OWN client (same lifecycle slot), and the
425
+ // SQL crosses back as the same transferred-`ArrayBuffer` `ExportArtefactWire`.
426
+ const { file, report } = await active.exportDiagnostics(args[0] as DiagnosticExportOptions | undefined);
427
+ const buffer = await file.arrayBuffer();
428
+ return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;
429
+ }
430
+ case "exportData": {
431
+ // Data export (ADR-0035): identical bridge shape — the worker runs the drain-guarded `pg_dump -t`
432
+ // per-synced-table export on its OWN client (same lifecycle slot), and the portable SQL crosses back
433
+ // as the same transferred-`ArrayBuffer` `ExportArtefactWire`. A DataExportDrainError rejects the RPC
434
+ // like any other failure (serialised back to the tab).
435
+ const { file, report } = await active.exportData(args[0] as DataExportOptions | undefined);
436
+ const buffer = await file.arrayBuffer();
437
+ return { buffer, fileName: file.name, mimeType: file.type, report } satisfies ExportArtefactWire;
438
+ }
439
+ default: {
440
+ const exhaustive: never = op;
441
+ throw new Error(`unknown rpc op ${String(exhaustive)}`);
442
+ }
443
+ }
444
+ };
445
+
446
+ // ─── Live-query bridge (ADR-0032 S2 §4) ──────────────────────────────────────────────────────────
447
+ const handleSubscribe = async (port: BridgePort, id: string | undefined, payload: SubscribePayload) => {
448
+ const active = client ?? (await bootPromise);
449
+ if (!active) throw new Error("subscribe before attach");
450
+ const { queryId, sql, params, pkColumns, use, fields } = payload;
451
+ // Activate any lazy relations the query reads BEFORE registering the live query (ADR-0021) — the worker
452
+ // owns the real client, so its `prepareQuery` does the real work; the tab's `prepareQuery` is a no-op.
453
+ // Scan the ORIGINAL sql (the wrap only adds an outer `SELECT * FROM (...)`; table refs are inside).
454
+ await active.prepareQuery({ sql, ...(use ? { use: use as SyncTableName<TRegistry>[] } : {}) });
455
+
456
+ const live = active.pglite.live;
457
+ // Render the query safe to materialise: a JOIN with same-named columns fails BOTH live APIs' temp-view
458
+ // creation (`column "title" specified more than once`) unless every output column has a unique alias.
459
+ // No `fields` → SQL unchanged (backward-compatible name-keyed rows; the aliased path keys by alias).
460
+ const materialSql = wrapLiveQueryForMaterialization(sql, fields);
461
+ // Single-column PK → PGlite's incremental machinery (`live.incrementalQuery`): it maintains the ordered
462
+ // result via an internal `__after__` linked list and only recomputes changed rows. Composite/keyless →
463
+ // `live.query` (full ordered result each fire) and we diff worker-side. Either way the CROSS-WIRE shape
464
+ // is a diff computed by `computeLiveDiff` — neither live API emits an ordered, identity-friendly delta.
465
+ const registered =
466
+ pkColumns && pkColumns.length === 1
467
+ ? await live.incrementalQuery<Record<string, unknown>>(materialSql, params as unknown[], pkColumns[0]!)
468
+ : await live.query<Record<string, unknown>>(materialSql, params as unknown[]);
469
+
470
+ const state = seedLiveDiffState(registered.initialResults.rows, pkColumns);
471
+ // Initial snapshot verbatim (not a diff), correlated to the subscribe request so the tab resolves.
472
+ postBridgeMessage(port, codec, "live-initial", { queryId, rows: registered.initialResults.rows }, id);
473
+
474
+ const listener = (results: { rows: Record<string, unknown>[] }) => {
475
+ // `subscribe` fires only on a real change (never the initial), so every fire yields a genuine delta.
476
+ const diff = computeLiveDiff(state, results.rows);
477
+ postBridgeMessage(port, codec, "live-diff", { queryId, ...diff });
478
+ };
479
+ registered.subscribe(listener);
480
+ liveSubs.set(queryId, {
481
+ port,
482
+ unsubscribe: () => void registered.unsubscribe(listener),
483
+ });
484
+ };
485
+
486
+ // ─── Per-port message routing ────────────────────────────────────────────────────────────────────
487
+ const onPortMessage = (port: BridgePort, data: unknown) => {
488
+ if (!isBridgeEnvelope(data)) return;
489
+ const envelope = data;
490
+ const payload = codec.decode(envelope.payload);
491
+ switch (envelope.type) {
492
+ case "provision": {
493
+ // Pre-spawn the raw store (initdb only), idle and schemaless, for the first attach to adopt
494
+ // (ADR-0032 decision 5). A no-op once the engine has booted or a store is already provisioned.
495
+ const provision = payload as ProvisionPayload;
496
+ const storePath = provision.storePath ?? provision.storeId ?? options.storePath ?? "pgxsinkit-overlay-v1";
497
+ // The testing memory-backend override rides as an explicit wire field (ADR-0036) — a symbol does not
498
+ // survive structured clone, so the store's backend selection travels here and is passed to createPglite.
499
+ const backendOverride = provision.testStoreBackend;
500
+ if (bootPromise != null || provisioned != null) {
501
+ postBridgeMessage(port, codec, "provision-ack", {
502
+ ok: true,
503
+ ...(provision.storeId ? { storeId: provision.storeId } : {}),
504
+ });
505
+ break;
506
+ }
507
+ // Stamp the spare's create timing (ADR-0034): initdb cost + the monotonic instant it became ready,
508
+ // so an adopting boot can compute how long it sat idle before adoption.
509
+ const provisionStartedAt = nowStamp();
510
+ const pglite = createPglite(storePath, backendOverride);
511
+ const stamp = pglite.then(() => {
512
+ const readyAt = nowStamp();
513
+ return { initdbMs: readyAt - provisionStartedAt, provisionReadyAt: readyAt };
514
+ });
515
+ provisioned = { storePath, pglite, stamp };
516
+ // Guard an unobserved rejection when no attach ever adopts it (the page navigated away).
517
+ void pglite.catch(() => undefined);
518
+ void stamp.catch(() => undefined);
519
+ syncDebug("worker store provisioned", { storePath });
520
+ void pglite.then(
521
+ () =>
522
+ postBridgeMessage(port, codec, "provision-ack", {
523
+ ok: true,
524
+ ...(provision.storeId ? { storeId: provision.storeId } : {}),
525
+ }),
526
+ (error: unknown) =>
527
+ postBridgeMessage(port, codec, "provision-ack", {
528
+ ok: false,
529
+ error: serializeError(error),
530
+ ...(provision.storeId ? { storeId: provision.storeId } : {}),
531
+ }),
532
+ );
533
+ break;
534
+ }
535
+ case "set-online": {
536
+ // The tab's Offline toggle over the bridge (ADR-0032 S3). Suppress/resume the worker's outbound
537
+ // convergence; resuming fires one immediate pass so queued writes flush at once.
538
+ const { online } = payload as SetOnlinePayload;
539
+ convergenceSuppressed = !online;
540
+ syncDebug("worker convergence gate", { online });
541
+ if (online) fireConvergence?.();
542
+ break;
543
+ }
544
+ case "attach": {
545
+ const attach = payload as AttachPayload;
546
+ // Boot observability (ADR-0034): replay the pre-attach rail buffer (provision + any early lines) to
547
+ // the FIRST attaching tab, so the front half of boot is no longer invisible. Snapshotted before this
548
+ // attach's boot runs, so the boot's own lines (streamed live) are not doubled.
549
+ replayRailBufferTo(port);
550
+ const alreadyBooted = bootPromise !== null;
551
+ // Restore rides the FIRST (boot) attach only (ADR-0035 decision 6): a restore attach that arrives once
552
+ // the engine has already booted CANNOT be honoured — `loadDataDir` is a create-time seed and the store
553
+ // is already live. Reject THIS attach with a typed error rather than silently ignoring the backup, so
554
+ // the caller learns their restore did not happen (the engine keeps running its existing store).
555
+ if (alreadyBooted && attach.restore != null) {
556
+ postBridgeMessage(port, codec, "attach-ack", {
557
+ alreadyBooted,
558
+ error: {
559
+ message:
560
+ "[pgxsinkit] cannot restore into a running store: the worker engine has already booted, and a store backup can only seed a brand-new store on the FIRST attach (ADR-0035 decision 6). Restore into a fresh worker instead.",
561
+ },
562
+ });
563
+ break;
564
+ }
565
+ if (alreadyBooted) {
566
+ // A later attach seeds auth WITHOUT clobbering a fresher cached token (ADR-0032 FIX 5) — the
567
+ // first-boot `push` already ran, and only an explicit `token-push` (auth owner) may overwrite.
568
+ tokenCache.pushIfFresher(attach.token);
569
+ // Role is a property of the (user, store) the engine already booted for: the worker is
570
+ // one-engine-per-(user,store) by ADR-0032 decision 2 and is NOT keyed by role. A mismatch is an
571
+ // app-layer bug to surface, not a supported topology — warn, keep the booted registry.
572
+ const requested = attach.config?.role;
573
+ if (requested !== bootedRole) {
574
+ syncDebug("worker attach role mismatch — engine keeps its booted registry", {
575
+ booted: bootedRole,
576
+ requested,
577
+ });
578
+ }
579
+ }
580
+ void boot(attach).then(
581
+ (booted) => {
582
+ client = booted;
583
+ resolveBooted(booted);
584
+ // Track the engine's monotonic `ready` edge exactly once, so a LATER attach acked after the
585
+ // initial sync landed can resolve its `ready` straight from the ack (ADR-0032 FIX 3).
586
+ if (!engineReadyFired) {
587
+ void booted.ready.then(() => {
588
+ engineReadyFired = true;
589
+ });
590
+ }
591
+ // Ack AFTER the engine exists so the tab's subsequent traffic (rpc/subscribe) has a client to
592
+ // hit; include current status + per-group readiness for a late-joining tab (decisions 4/6).
593
+ postBridgeMessage(port, codec, "attach-ack", {
594
+ alreadyBooted,
595
+ ...(engineReadyFired ? { engineReady: true } : {}),
596
+ });
597
+ postBridgeMessage(port, codec, "event", { kind: "status", status: booted.status });
598
+ },
599
+ (error: unknown) => {
600
+ // The engine boot rejected: tell THIS attaching tab so it rejects `attachSyncClient` instead of
601
+ // hanging on the ack (ADR-0032 FIX 1), and clear `bootPromise` so a later attach retries the
602
+ // boot. Do NOT clear `provisioned`: a resolved provisioned PGlite holds the only open handle on
603
+ // that store, so a retry must adopt it (createSyncClient falls back internally if it rejected).
604
+ bootPromise = null;
605
+ postBridgeMessage(port, codec, "attach-ack", {
606
+ alreadyBooted,
607
+ error: serializeError(error),
608
+ });
609
+ },
610
+ );
611
+ break;
612
+ }
613
+ case "token-push": {
614
+ // The tab pushed a fresh token (auth state change) — update the cache and satisfy any in-flight pull.
615
+ tokenCache.push(payload as AttachPayload["token"]);
616
+ break;
617
+ }
618
+ case "token-response": {
619
+ const response = payload as TokenResponsePayload;
620
+ // First response for the current pull wins; a stale/duplicate requestId is ignored.
621
+ tokenCache.respond(response.requestId, response.token);
622
+ break;
623
+ }
624
+ case "rpc": {
625
+ const { op, args } = payload as RpcPayload;
626
+ const id = envelope.id;
627
+ void (async () => {
628
+ try {
629
+ const active = client ?? (await bootPromise);
630
+ if (!active) throw new Error("rpc before attach");
631
+ const value = await dispatchRpc(active, op, args);
632
+ // An export artefact (backup tarball or diagnostic SQL) crosses zero-copy: transfer its
633
+ // `ArrayBuffer` (rebuilt into a `File` tab-side, ADR-0035). Every other op's value
634
+ // structured-clones in place with no transfer list.
635
+ const transfer =
636
+ op === "exportStore" || op === "exportDiagnostics" || op === "exportData"
637
+ ? [(value as ExportArtefactWire).buffer]
638
+ : undefined;
639
+ postBridgeMessage(port, codec, "rpc-result", { ok: true, value }, id, transfer);
640
+ } catch (error) {
641
+ postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
642
+ }
643
+ })();
644
+ break;
645
+ }
646
+ case "subscribe": {
647
+ const id = envelope.id;
648
+ void handleSubscribe(port, id, payload as SubscribePayload).catch((error) => {
649
+ postBridgeMessage(port, codec, "rpc-result", { ok: false, error: serializeError(error) }, id);
650
+ });
651
+ break;
652
+ }
653
+ case "unsubscribe": {
654
+ const { queryId } = payload as { queryId: string };
655
+ const sub = liveSubs.get(queryId);
656
+ if (sub) {
657
+ sub.unsubscribe();
658
+ liveSubs.delete(queryId);
659
+ }
660
+ break;
661
+ }
662
+ case "wake": {
663
+ // A tab forwarded online/visibilitychange (or a manual nudge): treat it as a convergence pass request
664
+ // so a write flushes promptly without waiting for the worker's interval tick (decision 5 seam).
665
+ // Suppressed while the Offline toggle is off — a wake must not flush a simulated-offline board.
666
+ if (!convergenceSuppressed) void bootPromise?.then((active) => void active.flush());
667
+ break;
668
+ }
669
+ default:
670
+ break;
671
+ }
672
+ };
673
+
674
+ const detachPort = (port: BridgePort) => {
675
+ ports.delete(port);
676
+ for (const [queryId, sub] of liveSubs) {
677
+ if (sub.port === port) {
678
+ sub.unsubscribe();
679
+ liveSubs.delete(queryId);
680
+ }
681
+ }
682
+ };
683
+
684
+ const connect = (port: BridgePort) => {
685
+ ports.add(port);
686
+ const listener = (event: { data: unknown }) => {
687
+ if (isBridgeEnvelope(event.data) && event.data.type === "detach") {
688
+ detachPort(port);
689
+ port.removeEventListener("message", listener);
690
+ return;
691
+ }
692
+ onPortMessage(port, event.data);
693
+ };
694
+ port.addEventListener("message", listener);
695
+ port.start?.();
696
+ };
697
+
698
+ // ─── Global-scope auto-binding (real worker only; tests inject ports via connect) ─────────────────
699
+ if (options.installGlobal !== false) bindGlobalScope(connect);
700
+
701
+ return {
702
+ connect,
703
+ whenBooted,
704
+ close: async () => {
705
+ for (const sub of liveSubs.values()) sub.unsubscribe();
706
+ liveSubs.clear();
707
+ ports.clear();
708
+ setSyncDebugSink(undefined);
709
+ const active = client ?? (bootPromise ? await bootPromise.catch(() => null) : null);
710
+ await active?.stop();
711
+ },
712
+ };
713
+ }
714
+
715
+ /** Serialize a thrown value into the bridge's `{message, detail}` error shape (detail only when structured). */
716
+ function serializeError(error: unknown): { message: string; detail?: unknown } {
717
+ if (error instanceof Error) {
718
+ const detail = (error as Error & { detail?: unknown }).detail;
719
+ return { message: error.message, ...(detail !== undefined ? { detail } : {}) };
720
+ }
721
+ return { message: String(error) };
722
+ }
723
+
724
+ interface SharedWorkerConnectEvent {
725
+ ports: BridgePort[];
726
+ }
727
+ interface WorkerGlobalScopeLike {
728
+ onconnect?: (event: SharedWorkerConnectEvent) => void;
729
+ postMessage?: (message: unknown) => void;
730
+ addEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
731
+ removeEventListener?: (type: "message", listener: (event: { data: unknown }) => void) => void;
732
+ }
733
+
734
+ /**
735
+ * Bind the running global scope to `connect`. A `SharedWorkerGlobalScope` exposes `onconnect` (one event per
736
+ * tab, each carrying a port); a dedicated `DedicatedWorkerGlobalScope` has no `onconnect` but IS itself the
737
+ * single implicit port (`self.postMessage`/`addEventListener`). Neither exists in a plain test/Node context,
738
+ * where the host is driven via {@link SyncWorkerHost.connect} directly — so this is a no-op there.
739
+ */
740
+ function bindGlobalScope(connect: (port: BridgePort) => void): void {
741
+ const scope = globalThis as unknown as WorkerGlobalScopeLike;
742
+ const hasSharedWorkerScope =
743
+ typeof (globalThis as { SharedWorkerGlobalScope?: unknown }).SharedWorkerGlobalScope !== "undefined";
744
+ const hasDedicatedWorkerScope =
745
+ typeof (globalThis as { DedicatedWorkerGlobalScope?: unknown }).DedicatedWorkerGlobalScope !== "undefined";
746
+
747
+ if (hasSharedWorkerScope) {
748
+ scope.onconnect = (event: SharedWorkerConnectEvent) => {
749
+ const port = event.ports[0];
750
+ if (port) connect(port);
751
+ };
752
+ return;
753
+ }
754
+ if (hasDedicatedWorkerScope && scope.postMessage && scope.addEventListener && scope.removeEventListener) {
755
+ // The dedicated worker's own global scope IS the single port.
756
+ connect({
757
+ postMessage: (message: unknown) => scope.postMessage!(message),
758
+ addEventListener: (type, listener) => scope.addEventListener!(type, listener),
759
+ removeEventListener: (type, listener) => scope.removeEventListener!(type, listener),
760
+ });
761
+ }
762
+ }