@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,140 @@
1
+ // The live-query DIFF machinery (ADR-0032 S2 §4). Two pure pieces sit either side of the bridge:
2
+ // - {@link computeLiveDiff} (worker-side): turn a fresh ordered result-set into a {added, changed, removed}
3
+ // diff against the previously-sent one, keyed by the query's PK — so only deltas cross the wire.
4
+ // - {@link LiveRowsMaterializer} (tab-side): fold each diff back into an ordered array while preserving
5
+ // row-object identity for unchanged rows (React memo bails on `===`).
6
+ // Both are transport-free and worker-free, so they unit-test directly.
7
+
8
+ import type { LiveDiffPayload } from "./protocol";
9
+
10
+ // A NUL separator — never a legitimate character inside a PK text value, so composite keys can't collide.
11
+ const KEY_SEP = String.fromCharCode(0);
12
+
13
+ /**
14
+ * The stable key for a result row (§4). With `pkColumns`, join their values (composite-safe) — this is the
15
+ * diff-keying identity, so a row whose PK is unchanged is the SAME logical row even if other columns moved.
16
+ * Without `pkColumns` (a keyless query) fall back to the whole-row JSON value: still diff-shaped (never a
17
+ * full resend), but an update surfaces as remove+add rather than a `changed` — the documented keyless
18
+ * fallback. Duplicate identical keyless rows collapse under this scheme (accepted for the fallback).
19
+ */
20
+ export function rowKey(row: Record<string, unknown>, pkColumns: readonly string[] | undefined): string {
21
+ if (pkColumns && pkColumns.length > 0) {
22
+ return pkColumns.map((col) => String(row[col])).join(KEY_SEP);
23
+ }
24
+ return JSON.stringify(row);
25
+ }
26
+
27
+ /** A shallow value-equality over a row's own enumerable keys — decides `changed` vs unchanged in a diff. */
28
+ function rowsEqual(a: Record<string, unknown>, b: Record<string, unknown>): boolean {
29
+ const aKeys = Object.keys(a);
30
+ const bKeys = Object.keys(b);
31
+ if (aKeys.length !== bKeys.length) return false;
32
+ for (const key of aKeys) {
33
+ if (!Object.is(a[key], b[key])) return false;
34
+ }
35
+ return true;
36
+ }
37
+
38
+ /** The worker's per-subscription memory: the last delivered rows keyed by {@link rowKey}, in delivered order. */
39
+ export interface LiveDiffState {
40
+ pkColumns?: readonly string[];
41
+ /** key → the exact row body last sent, so the next diff can detect `changed` and skip unchanged rows. */
42
+ previous: Map<string, Record<string, unknown>>;
43
+ }
44
+
45
+ /** Seed the diff state from the initial snapshot (which the worker sends verbatim, not as a diff). */
46
+ export function seedLiveDiffState(
47
+ rows: readonly Record<string, unknown>[],
48
+ pkColumns: readonly string[] | undefined,
49
+ ): LiveDiffState {
50
+ const previous = new Map<string, Record<string, unknown>>();
51
+ for (const row of rows) previous.set(rowKey(row, pkColumns), row);
52
+ return { ...(pkColumns ? { pkColumns } : {}), previous };
53
+ }
54
+
55
+ /**
56
+ * Diff a fresh ordered result set against the state's previous set, MUTATING the state to the new set and
57
+ * returning the wire diff (§4). `order` is every key in the new ORDER BY order (keys only — cheap); `added`/
58
+ * `changed` carry the delta row BODIES; `removed` carries dropped keys. Never emits the full result set: a
59
+ * single-row change yields one `changed` and the (key-only) `order`.
60
+ */
61
+ export function computeLiveDiff(
62
+ state: LiveDiffState,
63
+ nextRows: readonly Record<string, unknown>[],
64
+ ): Omit<LiveDiffPayload, "queryId"> {
65
+ const order: string[] = [];
66
+ const added: { key: string; row: Record<string, unknown> }[] = [];
67
+ const changed: { key: string; row: Record<string, unknown> }[] = [];
68
+ const nextKeys = new Set<string>();
69
+ const nextMap = new Map<string, Record<string, unknown>>();
70
+
71
+ for (const row of nextRows) {
72
+ const key = rowKey(row, state.pkColumns);
73
+ // A duplicate key within one result set (composite PK not actually unique, or a keyless collision):
74
+ // keep the first, so `order`/diff stay a faithful set. Rare; the read projections are PK-unique.
75
+ if (nextKeys.has(key)) continue;
76
+ nextKeys.add(key);
77
+ nextMap.set(key, row);
78
+ order.push(key);
79
+
80
+ const prior = state.previous.get(key);
81
+ if (prior === undefined) {
82
+ added.push({ key, row });
83
+ } else if (!rowsEqual(prior, row)) {
84
+ changed.push({ key, row });
85
+ }
86
+ }
87
+
88
+ const removed: string[] = [];
89
+ for (const key of state.previous.keys()) {
90
+ if (!nextKeys.has(key)) removed.push(key);
91
+ }
92
+
93
+ state.previous = nextMap;
94
+ return { order, added, changed, removed };
95
+ }
96
+
97
+ /**
98
+ * The tab-side fold of live diffs into an ordered row array with STABLE object identity (§4). The initial
99
+ * snapshot seeds the cache; each diff rebuilds the array from `diff.order`, reusing the cached object for
100
+ * any key not in `added`/`changed` (so an unchanged row keeps `===` and a memoized React row skips its
101
+ * re-render), and installing a fresh object for added/changed keys. Order is exactly `diff.order` — the
102
+ * query's ORDER BY as delivered by the worker.
103
+ */
104
+ export class LiveRowsMaterializer<TRow extends Record<string, unknown> = Record<string, unknown>> {
105
+ private byKey = new Map<string, TRow>();
106
+ private rows: TRow[] = [];
107
+ private readonly pkColumns: readonly string[] | undefined;
108
+
109
+ constructor(pkColumns: readonly string[] | undefined) {
110
+ this.pkColumns = pkColumns;
111
+ }
112
+
113
+ /** Seed from the initial snapshot; returns the initial ordered rows (each a distinct cached object). */
114
+ seed(initialRows: readonly TRow[]): TRow[] {
115
+ this.byKey = new Map();
116
+ this.rows = [];
117
+ for (const row of initialRows) {
118
+ const key = rowKey(row, this.pkColumns);
119
+ this.byKey.set(key, row);
120
+ this.rows.push(row);
121
+ }
122
+ return this.rows;
123
+ }
124
+
125
+ /** Apply a diff; returns the new ordered array (a fresh array, but unchanged rows keep their object identity). */
126
+ apply(diff: Omit<LiveDiffPayload, "queryId">): TRow[] {
127
+ for (const key of diff.removed) this.byKey.delete(key);
128
+ for (const { key, row } of diff.added) this.byKey.set(key, row as TRow);
129
+ for (const { key, row } of diff.changed) this.byKey.set(key, row as TRow);
130
+ // Rebuild strictly from the delivered order, reusing whatever object each key now maps to. Added/changed
131
+ // keys already point at fresh objects (set above); every other key keeps its prior object (=== holds).
132
+ this.rows = diff.order.map((key) => this.byKey.get(key)!).filter((row): row is TRow => row !== undefined);
133
+ return this.rows;
134
+ }
135
+
136
+ /** The current ordered rows (identity-stable across `apply` calls for unchanged rows). */
137
+ current(): TRow[] {
138
+ return this.rows;
139
+ }
140
+ }
@@ -0,0 +1,425 @@
1
+ // The bridge protocol (ADR-0032 S2). Everything that crosses between a tab and the shared sync engine
2
+ // travels as a typed {@link BridgeEnvelope} over a minimal {@link BridgePort} (a MessagePort-shaped
3
+ // transport). The router only ever inspects the envelope's `type`/`id`; its `payload` is OPAQUE to the
4
+ // router and always passes through a {@link BridgeCodec}, so a later columnar/transferable codec can be
5
+ // swapped in WITHOUT any protocol change (see BridgeCodec's doc).
6
+ //
7
+ // Deliberately transport-agnostic: `defineSyncWorker` and `attachSyncClient` both talk to a `BridgePort`,
8
+ // never a real `Worker`/`SharedWorker` directly — which is exactly why the whole bridge is unit-testable
9
+ // over bun's `MessageChannel` with no worker at all.
10
+
11
+ import type { SyncRuntimeStatus } from "@pgxsinkit/contracts";
12
+
13
+ import type { BootReport } from "../boot-report";
14
+ import type { ExportReport } from "../export-store";
15
+
16
+ export const BRIDGE_CHANNEL = "pgxsinkit-bridge" as const;
17
+ export const BRIDGE_PROTOCOL_VERSION = 1 as const;
18
+
19
+ /**
20
+ * A structured-clone transferable (an `ArrayBuffer`, a `MessagePort`, …). The library carries no DOM lib
21
+ * dependency (like the convergence triggers), so this is the toolkit's own name for the type a future
22
+ * columnar codec would hand to `postMessage`'s transfer list. v1's identity codec never produces one.
23
+ */
24
+ export type BridgeTransferable = unknown;
25
+
26
+ /**
27
+ * The minimal MessagePort-shaped transport the bridge needs — the intersection of a real `MessagePort`,
28
+ * a `SharedWorker` port, and a dedicated `Worker`/`self`. Injected everywhere so the protocol layer is
29
+ * exercised with a plain `MessageChannel` (no Worker) in tests. `start()` is optional (MessagePort needs
30
+ * it, `Worker`/`self` do not); `close()` is optional (a dedicated `self` cannot be closed by the tab).
31
+ */
32
+ export interface BridgePort {
33
+ postMessage: (message: unknown, transfer?: BridgeTransferable[]) => void;
34
+ addEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
35
+ removeEventListener: (type: "message", listener: (event: { data: unknown }) => void) => void;
36
+ start?: () => void;
37
+ close?: () => void;
38
+ }
39
+
40
+ /**
41
+ * The wire envelope. `payload` is the codec-encoded body — opaque to the router, which only routes on
42
+ * `type` and correlates on `id`. Keeping the body opaque is what lets a future codec return a columnar
43
+ * buffer (a transferable) in `payload` without any change to routing.
44
+ */
45
+ export interface BridgeEnvelope {
46
+ ch: typeof BRIDGE_CHANNEL;
47
+ v: typeof BRIDGE_PROTOCOL_VERSION;
48
+ type: BridgeMessageType;
49
+ /** Correlation id for request/response pairs (rpc, subscribe, token pull). Absent for fire-and-forget fanout. */
50
+ id?: string;
51
+ /** Codec-encoded body — opaque to the router; decode with the same {@link BridgeCodec}. */
52
+ payload: unknown;
53
+ }
54
+
55
+ export type BridgeMessageType =
56
+ // tab → worker
57
+ | "provision"
58
+ | "attach"
59
+ | "detach"
60
+ | "token-push"
61
+ | "token-response"
62
+ | "rpc"
63
+ | "subscribe"
64
+ | "unsubscribe"
65
+ | "wake"
66
+ | "set-online"
67
+ // worker → tab
68
+ | "provision-ack"
69
+ | "attach-ack"
70
+ | "token-request"
71
+ | "rpc-result"
72
+ | "live-initial"
73
+ | "live-diff"
74
+ | "event";
75
+
76
+ // ─── Payload shapes ───────────────────────────────────────────────────────────
77
+
78
+ /** A single auth token snapshot the tab owns and pushes to the worker (ADR-0032 decision 3). */
79
+ export interface AuthTokenSnapshot {
80
+ accessToken: string;
81
+ /** Absolute expiry in epoch milliseconds (`Date.now()`-comparable), so the worker can apply an expiry margin. */
82
+ expiresAt: number;
83
+ }
84
+
85
+ /**
86
+ * tab → worker: pre-spawn the store WITHOUT booting the engine (ADR-0032 decision 5). Sent at the
87
+ * login screen against the freshly-named spare worker: the worker only runs PGlite `create`/initdb
88
+ * (off every thread that matters) and holds the raw store idle — no schema, no shape streams, no token
89
+ * — until the real {@link AttachPayload} arrives (with config + token) and adopts the provisioned store.
90
+ * Role-agnostic on purpose: the spare is minted before the user (and role) is known, so provisioning
91
+ * carries no registry — the schema is applied at attach with the role-resolved registry.
92
+ */
93
+ export interface ProvisionPayload {
94
+ /** The bound store id (informational; naming is done tab-side via the SharedWorker name). */
95
+ storeId?: string;
96
+ /**
97
+ * The plain store PATH (ADR-0036) to `create` ahead of attach — a name, not a storage URL; the worker
98
+ * derives the backend (IndexedDB in a browser worker). When omitted, `storeId`/the worker default is used.
99
+ */
100
+ storePath?: string;
101
+ /**
102
+ * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend
103
+ * override across the bridge, because a symbol-keyed marker does NOT survive `postMessage` structured
104
+ * clone — so the worker's memory-store selection travels as this explicit field. Set only by the test
105
+ * lane (via the attaching helper); a browser worker never sends it.
106
+ */
107
+ testStoreBackend?: "memory";
108
+ }
109
+
110
+ /** worker → tab: the provision completed (or failed). Lets the login screen confirm the spare is warm. */
111
+ export interface ProvisionAckPayload {
112
+ ok: boolean;
113
+ storeId?: string;
114
+ /** Present when `!ok` — the initdb/create failed; the worker falls back to a fresh create at attach. */
115
+ error?: { message: string };
116
+ }
117
+
118
+ /**
119
+ * tab → worker: a store-backup tarball to restore from, carried on the boot {@link AttachPayload}
120
+ * (ADR-0035 decision 6). The mirror image of {@link ExportArtefactWire}: a `File`/`Blob` cannot cross the
121
+ * bridge as a transferable, so it is decomposed into its zero-copy `ArrayBuffer` (listed on `postMessage`'s
122
+ * transfer list) plus the metadata to rebuild it, and the worker reassembles a `Blob` from
123
+ * `buffer`/`mimeType` to hand `createSyncClient` as `restoreFrom`.
124
+ */
125
+ export interface RestoreArtefactWire {
126
+ /** The backup tarball bytes — transferred, not copied. */
127
+ buffer: ArrayBuffer;
128
+ /** The backup file name (informational; PGlite's `loadDataDir` reads the bytes, not the name). */
129
+ fileName: string;
130
+ /** The backup MIME type (`application/x-gzip` / `application/x-tar`), used to rebuild the `Blob`. */
131
+ mimeType: string;
132
+ }
133
+
134
+ /** tab → worker: the attach handshake. The first attach boots the engine; later attaches join it. */
135
+ export interface AttachPayload {
136
+ /** The bound store id (SharedWorker naming resolves it tab-side before attach — ADR-0032 decision 5). */
137
+ storeId?: string;
138
+ /**
139
+ * Explicit plain store PATH (ADR-0036) if the worker should create its own store — a name, not a storage
140
+ * URL; the worker derives the backend. When omitted, `storeId`/the worker default is used.
141
+ */
142
+ storePath?: string;
143
+ /**
144
+ * @internal INTERNAL WIRE FIELD (not consumer config, ADR-0036). Carries the testing memory-backend
145
+ * override across the bridge — a symbol-keyed marker does not survive structured clone, so the worker's
146
+ * memory-store selection travels as this explicit field. Set only by the test lane; never by a browser tab.
147
+ */
148
+ testStoreBackend?: "memory";
149
+ /**
150
+ * Restore the store from a backup on THIS attach (ADR-0035 decision 6) — the worker-mode carrier of
151
+ * `createSyncClient`'s `restoreFrom`. Restore rides the FIRST attach (the boot attach): a `File`/`Blob`
152
+ * cannot cross `postMessage` as a transferable, so the tab decomposes it into a transferred `ArrayBuffer`
153
+ * plus its name/mime — the {@link ExportArtefactWire} pattern in reverse — and the worker recomposes it
154
+ * into a `Blob` and hands it to `createSyncClient`. Absent on every ordinary attach. An attach that carries
155
+ * this AFTER the engine has already booted is REFUSED (you cannot restore into a running store).
156
+ */
157
+ restore?: RestoreArtefactWire;
158
+ /** The tab's current auth token at attach time, or null when unauthenticated. */
159
+ token: AuthTokenSnapshot | null;
160
+ /**
161
+ * Serializable per-attach config overrides (kept minimal; the urls are baked into the worker). `role`
162
+ * selects which baked registry the worker boots (ADR-0032 S3): the spare is minted role-agnostic, so
163
+ * the role is only known at claim/attach — a single worker file bakes BOTH registries and picks here.
164
+ * `freshStore` is the fresh-store prefetch-overlap hint (ADR-0032 S4): the tab's claim path knows a
165
+ * claimed spare is schemaless (fresh) while a mapped/returning store never is, and forwards that here so
166
+ * the worker's `createSyncClient` can overlap the shape catch-up with the local boot phases.
167
+ */
168
+ config?: { syncEnabled?: boolean; role?: string; freshStore?: boolean };
169
+ }
170
+
171
+ /**
172
+ * tab → worker: gate the worker's outbound convergence (the board's Offline toggle, ADR-0032 S3). In
173
+ * in-process mode the toggle gates the local `autoSync` trigger; the worker owns convergence instead, so
174
+ * the tab forwards the flag and the worker suppresses/resumes its flush passes. Going back online fires
175
+ * one immediate pass so queued writes flush without waiting for the next interval tick.
176
+ */
177
+ export interface SetOnlinePayload {
178
+ online: boolean;
179
+ }
180
+
181
+ /** worker → tab: attach acknowledged. `alreadyBooted` is false for the attach that booted the engine. */
182
+ export interface AttachAckPayload {
183
+ alreadyBooted: boolean;
184
+ /**
185
+ * True when the engine's initial sync had ALREADY fired by the time this attach was acked (a late
186
+ * attach, ADR-0032 FIX 3). `ready` is monotonic in-process — once it resolves it stays resolved even if
187
+ * the phase later degrades — so a tab attaching after that moment must resolve `ready` immediately from
188
+ * the ack, rather than wait for a phase-"ready" status that may never come again.
189
+ */
190
+ engineReady?: boolean;
191
+ /**
192
+ * Present when the engine boot REJECTED for this attach: the tab rejects `attachSyncClient` with this
193
+ * message instead of hanging forever on the ack (ADR-0032 FIX 1). A later attach retries the boot.
194
+ */
195
+ error?: { message: string; detail?: unknown };
196
+ }
197
+
198
+ /** worker → tab: a broadcast pull-request — any attached tab may answer, first response wins (ADR-0032 decision 3). */
199
+ export interface TokenRequestPayload {
200
+ requestId: string;
201
+ }
202
+
203
+ /** tab → worker: the answer to a {@link TokenRequestPayload}. `token: null` = the tab has none. */
204
+ export interface TokenResponsePayload {
205
+ requestId: string;
206
+ token: AuthTokenSnapshot | null;
207
+ }
208
+
209
+ /**
210
+ * The RPC ops the attach facade proxies to the worker's booted client — the write API (mirrors
211
+ * `client.mutate`/flush), mutation-state reads, and the one-shot raw inspection reads (`rawQuery`/`rawExec`).
212
+ */
213
+ export type RpcOp =
214
+ | "create"
215
+ | "update"
216
+ | "delete"
217
+ | "batch"
218
+ | "transaction"
219
+ | "flush"
220
+ | "reconcile"
221
+ | "retryFailed"
222
+ | "recoverSending"
223
+ | "discardConflict"
224
+ | "discardQuarantined"
225
+ | "desync"
226
+ | "discardEphemeral"
227
+ | "readMutationDetails"
228
+ | "diagnostics"
229
+ | "rawQuery"
230
+ | "rawExec"
231
+ // Boot observability (ADR-0034): pull the worker engine's most recent completed boot report. Returns the
232
+ // stored report (or null) regardless of when this tab attached, so a late tab reads a boot predating it.
233
+ | "bootReport"
234
+ // Store backup (ADR-0035): the worker runs the live `exportStore` on its owned client; the dump crosses
235
+ // back as a transferred `ArrayBuffer` ({@link ExportArtefactWire}), rebuilt into a `File` tab-side.
236
+ | "exportStore"
237
+ // Diagnostic dump (ADR-0035): the worker runs `exportDiagnostics` on its owned client (live datadir dump
238
+ // → memory throwaway clone → `pg_dump`); the SQL crosses back as the same transferred `ArrayBuffer` wire.
239
+ | "exportDiagnostics"
240
+ // Data export (ADR-0035): the worker runs `exportData` on its owned client (drain the journal → throwaway
241
+ // clone → `pg_dump -t` per synced table); the portable SQL crosses back as the same transferred wire.
242
+ | "exportData";
243
+
244
+ /** tab → worker: a write/read-of-mutation-state RPC. `id` correlates the matching {@link RpcResultPayload}. */
245
+ export interface RpcPayload {
246
+ op: RpcOp;
247
+ args: unknown[];
248
+ }
249
+
250
+ /**
251
+ * worker → tab: the wire form of ANY local-store export (ADR-0035) — the store backup's tarball OR the
252
+ * diagnostic dump's SQL — carried as the `value` of an {@link RpcResultPayload}. The artefact crosses as a
253
+ * transferred `ArrayBuffer` (zero-copy — the sender lists `buffer` in `postMessage`'s transfer list) plus
254
+ * the metadata to rebuild it; the tab reconstructs a `File` from `buffer`/`fileName`/`mimeType`. A `File`
255
+ * cannot itself be transferred, so it is decomposed here and reassembled tab-side, exactly the pattern the
256
+ * codec's transferable seam anticipates for a zero-copy live-diff payload. `report` is the discriminated
257
+ * {@link ExportReport} union, so the tab knows which export it round-tripped.
258
+ */
259
+ export interface ExportArtefactWire {
260
+ /** The artefact bytes (tarball or SQL) — transferred, not copied. */
261
+ buffer: ArrayBuffer;
262
+ /** The generated (or caller-supplied) artefact file name. */
263
+ fileName: string;
264
+ /** The artefact MIME type (`application/x-gzip` / `application/x-tar` for a backup, `application/sql` for a dump). */
265
+ mimeType: string;
266
+ /** The export report (ADR-0035), structured-cloned as a plain object — the `kind`-discriminated union. */
267
+ report: ExportReport;
268
+ }
269
+
270
+ /** worker → tab: an RPC outcome, mirroring today's in-process resolve/reject semantics. */
271
+ export interface RpcResultPayload {
272
+ ok: boolean;
273
+ /** The resolved value (present when `ok`). */
274
+ value?: unknown;
275
+ /** The rejection message + optional structured detail (present when `!ok`). */
276
+ error?: { message: string; detail?: unknown };
277
+ }
278
+
279
+ /** tab → worker: register a live query. `id` correlates the initial snapshot; `queryId` keys subsequent diffs. */
280
+ export interface SubscribePayload {
281
+ queryId: string;
282
+ sql: string;
283
+ params: unknown[];
284
+ /**
285
+ * The unique output aliases the worker wraps the query's columns under so it is safe to MATERIALISE
286
+ * (one per output column, in the compiled SQL's column order). ADDITIVE and backward-compatible: an
287
+ * older tab omits it and the worker leaves the SQL untouched (name-keyed rows, as before); a newer tab
288
+ * supplies it for a JOIN with same-named columns, which `live.query`/`live.incrementalQuery` otherwise
289
+ * refuse to materialise (`column "title" specified more than once`). When present, result columns are
290
+ * the aliases, so {@link pkColumns} must name a PK by its alias.
291
+ */
292
+ fields?: string[];
293
+ /**
294
+ * The result's primary-key columns, driving diff keying (§4). One column → the incremental path
295
+ * (`live.incrementalQuery`); many → worker-side diff by composite PK; empty/absent → value-identity
296
+ * fallback for a keyless query. When {@link fields} is supplied these name the ALIASED result columns.
297
+ */
298
+ pkColumns?: string[];
299
+ /** Lazy relations to activate before the query runs (ADR-0021), forwarded to the worker's `prepareQuery`. */
300
+ use?: string[];
301
+ }
302
+
303
+ /** worker → tab: the initial ordered snapshot for a subscription. `id` correlates the `subscribe` request. */
304
+ export interface LiveInitialPayload {
305
+ queryId: string;
306
+ rows: Record<string, unknown>[];
307
+ }
308
+
309
+ /**
310
+ * worker → tab: a DIFF update for a subscription (§4). Never a full result-set resend after the initial
311
+ * snapshot. `order` is the full ordered list of row keys (cheap — keys only, no row bodies); `added`/
312
+ * `changed` carry only the delta row bodies; `removed` carries only the dropped keys. The tab materializer
313
+ * rebuilds the ordered array from `order`, reusing cached row objects for keys not in `added`/`changed` so
314
+ * an unchanged row keeps its object identity (React memo bails on `===`).
315
+ */
316
+ export interface LiveDiffPayload {
317
+ queryId: string;
318
+ /** Every result key in ORDER BY order (the query's delivered order). */
319
+ order: string[];
320
+ added: { key: string; row: Record<string, unknown> }[];
321
+ changed: { key: string; row: Record<string, unknown> }[];
322
+ removed: string[];
323
+ }
324
+
325
+ /** worker → tab: the single broadcast event stream (ADR-0032 decision 7), re-exposed as today's callbacks. */
326
+ export type BridgeEvent =
327
+ | { kind: "status"; status: SyncRuntimeStatus }
328
+ | { kind: "groupReady"; groupKey: string }
329
+ | { kind: "conflict"; details: unknown }
330
+ | { kind: "quarantine"; details: unknown }
331
+ | { kind: "reject"; details: unknown }
332
+ | { kind: "schema-change"; event: unknown }
333
+ | { kind: "sync-error"; message: string }
334
+ | { kind: "timing"; label: string; ms: number; data?: Record<string, unknown> }
335
+ // Boot observability (ADR-0034): the one-shot boot report, broadcast to currently-attached ports when the
336
+ // engine's boot finalizes (the push counterpart of the `bootReport` pull). Later tabs read it via the pull.
337
+ | { kind: "boot-report"; report: BootReport }
338
+ // The debug rail (ADR-0032 decision 7): stamped with the WORKER's monotonic clock and origin-tagged so a
339
+ // tab can re-print it as `[pgxsinkit·w <stamp>ms] <line>` — a SharedWorker's own console is invisible.
340
+ | { kind: "debug"; stamp: number; line: string; data?: Record<string, unknown> };
341
+
342
+ /** tab → worker: an app-driven wake (online/visibilitychange), treated as a convergence pass request. */
343
+ export interface WakePayload {
344
+ reason: "online" | "visibility" | "manual";
345
+ }
346
+
347
+ // ─── Codec seam ─────────────────────────────────────────────────────────────
348
+
349
+ /**
350
+ * The codec every bridge payload crosses through (owner-mandated seam, ADR-0032 S2 §1). v1 ships exactly
351
+ * ONE codec — {@link identityCodec}, which relies on the transport's own structured clone. The seam exists
352
+ * so a columnar/transferable codec (e.g. one that packs live-diff rows into a shared `ArrayBuffer` and
353
+ * returns it as a transferable) can be swapped in later WITHOUT any protocol change: the router already
354
+ * treats `BridgeEnvelope.payload` as opaque, and `encode` may return `{ payload, transfer }` so the sender
355
+ * hands transferables to `postMessage`. Keep encode/decode inverse and side-effect free.
356
+ */
357
+ export interface BridgeCodec {
358
+ /** Encode a raw payload into the envelope body. May declare transferables for a future zero-copy codec. */
359
+ encode: (payload: unknown) => { payload: unknown; transfer?: BridgeTransferable[] };
360
+ /** Decode an envelope body back into the raw payload. Inverse of {@link encode}. */
361
+ decode: (payload: unknown) => unknown;
362
+ }
363
+
364
+ /**
365
+ * The v1 identity codec: the body IS the payload, and the transport's structured clone does the real
366
+ * copying. No transferables. The only codec shipped in S2 — swapping in a columnar codec later touches
367
+ * only this object, never the message types or the router.
368
+ */
369
+ export const identityCodec: BridgeCodec = {
370
+ encode: (payload) => ({ payload }),
371
+ decode: (payload) => payload,
372
+ };
373
+
374
+ // ─── Envelope helpers ─────────────────────────────────────────────────────────
375
+
376
+ /** Build a wire envelope, running the payload through the codec. Returns the envelope + any transferables. */
377
+ export function encodeEnvelope(
378
+ codec: BridgeCodec,
379
+ type: BridgeMessageType,
380
+ payload: unknown,
381
+ id?: string,
382
+ ): { envelope: BridgeEnvelope; transfer?: BridgeTransferable[] } {
383
+ const encoded = codec.encode(payload);
384
+ const envelope: BridgeEnvelope = {
385
+ ch: BRIDGE_CHANNEL,
386
+ v: BRIDGE_PROTOCOL_VERSION,
387
+ type,
388
+ payload: encoded.payload,
389
+ ...(id !== undefined ? { id } : {}),
390
+ };
391
+ return { envelope, ...(encoded.transfer ? { transfer: encoded.transfer } : {}) };
392
+ }
393
+
394
+ /** Type-guard a received message as a bridge envelope of the current protocol version (ignore foreign traffic). */
395
+ export function isBridgeEnvelope(data: unknown): data is BridgeEnvelope {
396
+ return (
397
+ typeof data === "object" &&
398
+ data !== null &&
399
+ (data as { ch?: unknown }).ch === BRIDGE_CHANNEL &&
400
+ (data as { v?: unknown }).v === BRIDGE_PROTOCOL_VERSION
401
+ );
402
+ }
403
+
404
+ /**
405
+ * Send a typed message over a port: encode → post (with any transferables). The one write choke point.
406
+ * `transfer` lets a caller declare payload-specific transferables (e.g. a store-backup's `ArrayBuffer`,
407
+ * ADR-0035) WITHOUT teaching the shared codec about that op — they are merged after any the codec itself
408
+ * produces, so both the codec's future zero-copy path and per-message transfers coexist.
409
+ */
410
+ export function postBridgeMessage(
411
+ port: BridgePort,
412
+ codec: BridgeCodec,
413
+ type: BridgeMessageType,
414
+ payload: unknown,
415
+ id?: string,
416
+ transfer?: BridgeTransferable[],
417
+ ): void {
418
+ const { envelope, transfer: codecTransfer } = encodeEnvelope(codec, type, payload, id);
419
+ const allTransfer = [...(codecTransfer ?? []), ...(transfer ?? [])];
420
+ if (allTransfer.length > 0) {
421
+ port.postMessage(envelope, allTransfer);
422
+ } else {
423
+ port.postMessage(envelope);
424
+ }
425
+ }
@@ -0,0 +1,84 @@
1
+ // The worker's single auth token cache + pull mechanism (ADR-0032 decision 3). The worker holds exactly
2
+ // ONE token and NEVER refreshes it — the tab layer is the sole auth owner (exactly one refresher exists, so
3
+ // GoTrue refresh-token reuse detection can never trip). A read/write that finds the cache within the expiry
4
+ // margin triggers ONE pull broadcast; concurrent needs dedupe onto that single in-flight pull; the first
5
+ // tab answer wins. Factored out of `defineSyncWorker` so this mechanism is unit-tested in isolation.
6
+
7
+ import type { AuthTokenSnapshot } from "./protocol";
8
+
9
+ export interface WorkerTokenCache {
10
+ /**
11
+ * Resolve the access token for a shape/flush request. Returns the cached token when it is comfortably
12
+ * ahead of expiry; otherwise broadcasts ONE pull (deduped across concurrent callers) and resolves when a
13
+ * tab answers. Falls back to the (stale) cached token if a pull yields nothing.
14
+ */
15
+ getToken: () => Promise<string | undefined>;
16
+ /** The tab pushed a fresh token (auth state change or the initial attach) — cache it and satisfy any pull. */
17
+ push: (token: AuthTokenSnapshot | null) => void;
18
+ /**
19
+ * Seed the cache from a LATER attach's token, but only if it is strictly fresher than what is cached
20
+ * (ADR-0032 FIX 5). Attach seeding must never CLOBBER a fresher cached token with an older/null one —
21
+ * only the explicit `push` path (the tab as auth owner saying "this is current") may overwrite
22
+ * unconditionally, including null on logout.
23
+ */
24
+ pushIfFresher: (token: AuthTokenSnapshot | null) => void;
25
+ /** A tab answered a pull-request. First matching answer wins; later duplicates are ignored. */
26
+ respond: (requestId: string, token: AuthTokenSnapshot | null) => void;
27
+ }
28
+
29
+ export function createWorkerTokenCache(options: {
30
+ marginMs: number;
31
+ broadcastRequest: (requestId: string) => void;
32
+ now?: () => number;
33
+ }): WorkerTokenCache {
34
+ const now = options.now ?? (() => Date.now());
35
+ let cached: AuthTokenSnapshot | null = null;
36
+ let inFlight: Promise<AuthTokenSnapshot | null> | null = null;
37
+ let resolveInFlight: ((token: AuthTokenSnapshot | null) => void) | null = null;
38
+ let currentRequestId: string | null = null;
39
+ let requestCounter = 0;
40
+
41
+ const settle = (token: AuthTokenSnapshot | null) => {
42
+ if (token) cached = token;
43
+ const resolve = resolveInFlight;
44
+ inFlight = null;
45
+ resolveInFlight = null;
46
+ currentRequestId = null;
47
+ resolve?.(token);
48
+ };
49
+
50
+ return {
51
+ getToken: async () => {
52
+ if (cached && cached.expiresAt - now() > options.marginMs) {
53
+ return cached.accessToken;
54
+ }
55
+ if (!inFlight) {
56
+ currentRequestId = `pull-${++requestCounter}`;
57
+ inFlight = new Promise<AuthTokenSnapshot | null>((resolve) => {
58
+ resolveInFlight = resolve;
59
+ });
60
+ // Exactly one broadcast per pull; concurrent getToken calls below await the same `inFlight`.
61
+ options.broadcastRequest(currentRequestId);
62
+ }
63
+ const answered = await inFlight;
64
+ return answered?.accessToken ?? cached?.accessToken;
65
+ },
66
+ push: (token) => {
67
+ cached = token;
68
+ // A push satisfies an outstanding pull too (the tab volunteered before answering the request).
69
+ if (inFlight) settle(token);
70
+ },
71
+ pushIfFresher: (token) => {
72
+ if (!token) return;
73
+ if (cached && cached.expiresAt >= token.expiresAt) return;
74
+ // Strictly fresher than the cache (or the cache is empty) → adopt it via `push`, which also settles
75
+ // any in-flight pull.
76
+ cached = token;
77
+ if (inFlight) settle(token);
78
+ },
79
+ respond: (requestId, token) => {
80
+ // First response for the CURRENT pull wins; a stale/duplicate requestId (or no pull) is ignored.
81
+ if (inFlight && requestId === currentRequestId) settle(token);
82
+ },
83
+ };
84
+ }