@powerhousedao/reactor-browser 6.2.3-dev.1 → 6.2.3-dev.100

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 (107) hide show
  1. package/dist/attachment-service-DXfpfp98.d.ts +1757 -0
  2. package/dist/attachment-service-DXfpfp98.d.ts.map +1 -0
  3. package/dist/auth-DzIYxeEJ.d.ts +32 -0
  4. package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
  5. package/dist/client-1n_ZUXeu.js +135 -0
  6. package/dist/client-1n_ZUXeu.js.map +1 -0
  7. package/dist/{client-BIHN_UyR.d.ts → client-BFk0MY6A.d.ts} +4 -3
  8. package/dist/client-BFk0MY6A.d.ts.map +1 -0
  9. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  10. package/dist/client-BFnMV-EO.js.map +1 -0
  11. package/dist/dispatch-Cylwl2Dk.js +1173 -0
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/document-by-id-DdvqanGR.js +16 -0
  14. package/dist/document-by-id-DdvqanGR.js.map +1 -0
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/document-operations-D5QXcJbV.js +4609 -0
  18. package/dist/document-operations-D5QXcJbV.js.map +1 -0
  19. package/dist/global-DAAmZGCO.d.ts +612 -0
  20. package/dist/global-DAAmZGCO.d.ts.map +1 -0
  21. package/dist/{index-CkJNhsQo.d.ts → index-Bj1poVfa.d.ts} +32 -100
  22. package/dist/index-Bj1poVfa.d.ts.map +1 -0
  23. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  24. package/dist/index-rtDmzViP.d.ts.map +1 -0
  25. package/dist/index.d.ts +938 -405
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +883 -307
  28. package/dist/index.js.map +1 -1
  29. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  30. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  31. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  32. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  33. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  34. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  35. package/dist/{relational-D4sxGPz7.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-BIEv6bSI.js → renown-B3MUaiq7.js} +78 -33
  38. package/dist/renown-B3MUaiq7.js.map +1 -0
  39. package/dist/renown-CBoTdGrg.js +394 -0
  40. package/dist/renown-CBoTdGrg.js.map +1 -0
  41. package/dist/{types-Dcv1ZLoW.d.ts → schema-Bn6L3QR1.d.ts} +324 -64
  42. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  43. package/dist/{client-D66jVnot.js → schema-D0G1oAo9.js} +358 -150
  44. package/dist/schema-D0G1oAo9.js.map +1 -0
  45. package/dist/src/ai/index.d.ts +313 -79
  46. package/dist/src/ai/index.d.ts.map +1 -1
  47. package/dist/src/ai/index.js +1030 -173
  48. package/dist/src/ai/index.js.map +1 -1
  49. package/dist/src/analytics/index.d.ts +36 -44
  50. package/dist/src/analytics/index.d.ts.map +1 -1
  51. package/dist/src/analytics/index.js +4 -4
  52. package/dist/src/analytics/index.js.map +1 -1
  53. package/dist/src/document-model.d.ts +3 -4
  54. package/dist/src/document-model.d.ts.map +1 -1
  55. package/dist/src/document-model.js.map +1 -1
  56. package/dist/src/graphql/client.d.ts +4 -3
  57. package/dist/src/graphql/client.js +1 -1
  58. package/dist/src/graphql-client/entry.d.ts +7 -4
  59. package/dist/src/graphql-client/entry.js +4 -4
  60. package/dist/src/relational/index.d.ts +15 -9
  61. package/dist/src/relational/index.d.ts.map +1 -1
  62. package/dist/src/relational/index.js +1 -1
  63. package/dist/src/renown/index.d.ts +3 -2
  64. package/dist/src/renown/index.js +3 -3
  65. package/dist/src/rpc/index.d.ts +217 -140
  66. package/dist/src/rpc/index.d.ts.map +1 -1
  67. package/dist/src/rpc/index.js +602 -623
  68. package/dist/src/rpc/index.js.map +1 -1
  69. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  70. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  71. package/dist/switchboard-directory-CWf5SRo7.js +435 -0
  72. package/dist/switchboard-directory-CWf5SRo7.js.map +1 -0
  73. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  74. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  75. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  76. package/dist/types-520nWrB3.d.ts.map +1 -0
  77. package/dist/types-CyPDurGV.d.ts +63 -0
  78. package/dist/types-CyPDurGV.d.ts.map +1 -0
  79. package/package.json +24 -23
  80. package/dist/attachment-service-CdwHrbDH.d.ts +0 -1063
  81. package/dist/attachment-service-CdwHrbDH.d.ts.map +0 -1
  82. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  83. package/dist/client-D66jVnot.js.map +0 -1
  84. package/dist/client-DjK30EQ-.js.map +0 -1
  85. package/dist/document-by-id-BSZqTN66.js +0 -517
  86. package/dist/document-by-id-BSZqTN66.js.map +0 -1
  87. package/dist/document-model-modules-DfQBNGc-.js +0 -419
  88. package/dist/document-model-modules-DfQBNGc-.js.map +0 -1
  89. package/dist/document-operations-Bgo6A6W2.js +0 -2545
  90. package/dist/document-operations-Bgo6A6W2.js.map +0 -1
  91. package/dist/global-BggszP4X.d.ts +0 -401
  92. package/dist/global-BggszP4X.d.ts.map +0 -1
  93. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  94. package/dist/index-CkJNhsQo.d.ts.map +0 -1
  95. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  96. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  97. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  98. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  99. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  100. package/dist/relational-D4sxGPz7.js.map +0 -1
  101. package/dist/renown-BHxwP7xU.js +0 -97
  102. package/dist/renown-BHxwP7xU.js.map +0 -1
  103. package/dist/renown-BIEv6bSI.js.map +0 -1
  104. package/dist/switchboard-D4-_jwk-.js +0 -271
  105. package/dist/switchboard-D4-_jwk-.js.map +0 -1
  106. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  107. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -1,42 +1,7 @@
1
- import { t as RegistryClient } from "../../client-DjK30EQ-.js";
2
- import { normalizeDocumentModelVersion } from "@powerhousedao/shared/document-model";
3
- import { DriveCollectionId, ReactorEventTypes, SyncEventTypes } from "@powerhousedao/reactor";
4
- //#region src/rpc/listeners.ts
5
- var KeyedListeners = class {
6
- map = /* @__PURE__ */ new Map();
7
- add(key, fn) {
8
- let set = this.map.get(key);
9
- if (!set) {
10
- set = /* @__PURE__ */ new Set();
11
- this.map.set(key, set);
12
- }
13
- set.add(fn);
14
- return () => {
15
- const current = this.map.get(key);
16
- if (!current) return;
17
- current.delete(fn);
18
- if (current.size === 0) this.map.delete(key);
19
- };
20
- }
21
- emit(key, ...a) {
22
- const set = this.map.get(key);
23
- if (!set) return;
24
- for (const fn of [...set]) fn(...a);
25
- }
26
- emitAll(...a) {
27
- for (const set of [...this.map.values()]) for (const fn of [...set]) fn(...a);
28
- }
29
- };
30
- var Listeners = class {
31
- keyed = new KeyedListeners();
32
- add(fn) {
33
- return this.keyed.add(null, fn);
34
- }
35
- emit(...a) {
36
- this.keyed.emit(null, ...a);
37
- }
38
- };
39
- //#endregion
1
+ import { l as SYNC_REMOTES_CHANGED_EVENT, t as RegistryClient, u as SYNC_STATUS_CHANGED_EVENT } from "../../client-BFnMV-EO.js";
2
+ import { DriveCollectionId, INSPECTOR_OPS, ReactorEventTypes, SYNC_INSPECTION_OPS, SyncEventTypes, collectionIdFromKey, createPeerAgreement, dispatchTableOp, messagePortTransport, methodOf, opKeyOf, registerLocalPeer, removeLocalPeer } from "@powerhousedao/reactor";
3
+ import { KeyedListeners, KeyedListeners as KeyedListeners$1, Listeners, Listeners as Listeners$1, MessageRouter, RPC_PROTOCOL_VERSION, RPC_PROTOCOL_VERSION as RPC_PROTOCOL_VERSION$1, ReactorHostServer, ReactorHostServer as ReactorHostServer$1, RpcCorrelator, SubscriptionStore, SubscriptionStore as SubscriptionStore$1, createCorrelatedSubscriptions, createCorrelatedSubscriptions as createCorrelatedSubscriptions$1, createPortTransport, createPortTransport as createPortTransport$1, createReactorClientProxy, createReactorClientProxy as createReactorClientProxy$1, fromErrorInfo, fromErrorInfo as fromErrorInfo$1, hostResponder, hostResponder as hostResponder$1, toErrorInfo } from "@powerhousedao/reactor/rpc";
4
+ import { init, parse } from "es-module-lexer";
40
5
  //#region src/rpc/op-channel.ts
41
6
  const RPC_DEFAULT_TIMEOUT_MS = 3e4;
42
7
  function toVoid(promise) {
@@ -55,11 +20,53 @@ function opChannel(router, kind, timeoutMs = RPC_DEFAULT_TIMEOUT_MS) {
55
20
  };
56
21
  }
57
22
  //#endregion
23
+ //#region src/rpc/adopt-sync-peer.ts
24
+ /** Moves `port` to the host, which adopts the peer as a local remote over it. */
25
+ function sendAdoptSyncPeer(router, params, port) {
26
+ return toVoid(router.request((id) => ({
27
+ k: "adopt-sync-peer",
28
+ id,
29
+ peerId: params.peerId,
30
+ channelName: params.channelName,
31
+ collectionIdKey: params.collectionIdKey,
32
+ remoteName: params.remoteName,
33
+ filter: params.filter,
34
+ port
35
+ }), { transfer: [port] }));
36
+ }
37
+ /** Removes the peer's remote and closes its port in the host's registry. */
38
+ function sendRemoveSyncPeer(router, params) {
39
+ return toVoid(router.request((id) => ({
40
+ k: "remove-sync-peer",
41
+ id,
42
+ peerId: params.peerId,
43
+ channelName: params.channelName,
44
+ remoteName: params.remoteName
45
+ })));
46
+ }
47
+ //#endregion
48
+ //#region src/rpc/local-sync-peer-handlers.ts
49
+ /** The host's adopt/remove handlers over the reactor's local peer registry. */
50
+ function localSyncPeerHandlers(syncManager, registry) {
51
+ return {
52
+ onAdoptSyncPeer: async (params, port) => {
53
+ await registerLocalPeer(syncManager, registry, {
54
+ peerId: params.peerId,
55
+ channelName: params.channelName,
56
+ collectionId: collectionIdFromKey(params.collectionIdKey),
57
+ remoteName: params.remoteName,
58
+ filter: params.filter
59
+ }, messagePortTransport(port));
60
+ },
61
+ onRemoveSyncPeer: (params) => removeLocalPeer(syncManager, registry, params)
62
+ };
63
+ }
64
+ //#endregion
58
65
  //#region src/rpc/admin-client.ts
59
66
  /** Worker lifecycle channel (info/restart/clearStorage/migrate) over the shared router. */
60
67
  function createWorkerAdminClient(router) {
61
68
  let migrationState = { status: "idle" };
62
- const migrationListeners = new Listeners();
69
+ const migrationListeners = new Listeners$1();
63
70
  router.on("migration", (msg) => {
64
71
  migrationState = msg.state;
65
72
  migrationListeners.emit();
@@ -79,307 +86,40 @@ function createWorkerAdminClient(router) {
79
86
  };
80
87
  }
81
88
  //#endregion
82
- //#region src/rpc/error-info.ts
83
- const MAX_STACK_LENGTH = 8 * 1024;
84
- const MAX_CAUSE_DEPTH = 8;
85
- function toErrorInfo(err, depth = 0) {
86
- if (depth > MAX_CAUSE_DEPTH) return {
87
- name: "Error",
88
- message: "cause chain truncated"
89
- };
90
- if (err instanceof Error) {
91
- const info = {
92
- name: err.name || "Error",
93
- message: err.message
94
- };
95
- if (typeof err.stack === "string") info.stack = err.stack.length > MAX_STACK_LENGTH ? err.stack.slice(0, MAX_STACK_LENGTH) : err.stack;
96
- if (err.cause !== void 0) info.cause = toErrorInfo(err.cause, depth + 1);
97
- return info;
98
- }
99
- if (typeof err === "string") return {
100
- name: "Error",
101
- message: err
102
- };
103
- if (err && typeof err === "object") {
104
- const record = err;
105
- return {
106
- name: typeof record.name === "string" ? record.name : "Error",
107
- message: typeof record.message === "string" ? record.message : safeStringify(err)
108
- };
109
- }
110
- return {
111
- name: "Error",
112
- message: safeStringify(err)
113
- };
114
- }
115
- function safeStringify(value) {
116
- if (value === null || value === void 0) return String(value);
117
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
118
- try {
119
- return JSON.stringify(value);
120
- } catch {
121
- return "[unserializable]";
122
- }
123
- }
124
- function fromErrorInfo(info) {
125
- const err = new Error(info.message);
126
- Object.defineProperty(err, "name", {
127
- value: info.name,
128
- configurable: true,
129
- writable: true
130
- });
131
- if (info.stack !== void 0) err.stack = info.stack;
132
- if (info.cause !== void 0) Object.defineProperty(err, "cause", {
133
- value: fromErrorInfo(info.cause),
134
- configurable: true,
135
- writable: true
136
- });
137
- return err;
138
- }
139
- //#endregion
140
- //#region src/rpc/paging.ts
141
- function isPageableResult(value) {
142
- return value !== null && typeof value === "object" && typeof value.next === "function";
143
- }
144
- function hasNextToken(value) {
145
- return value !== null && typeof value === "object" && typeof value.nextToken === "string";
146
- }
147
- function dehydratePage(value, registerCursor) {
148
- if (!isPageableResult(value)) return value;
149
- const { next, ...rest } = value;
150
- return {
151
- ...rest,
152
- nextToken: registerCursor(next)
153
- };
154
- }
155
- function rehydratePage(value, fetchPage) {
156
- if (!hasNextToken(value)) return value;
157
- const { nextToken, ...rest } = value;
158
- return {
159
- ...rest,
160
- next: () => fetchPage(nextToken)
161
- };
162
- }
163
- //#endregion
164
- //#region src/rpc/subscription.ts
165
- var SubscriptionStore = class {
166
- map = /* @__PURE__ */ new Map();
167
- set(id, unsubscribe) {
168
- this.map.set(id, unsubscribe);
169
- }
170
- get(id) {
171
- return this.map.get(id);
172
- }
173
- delete(id) {
174
- this.map.delete(id);
175
- }
176
- end(id) {
177
- const unsubscribe = this.map.get(id);
178
- if (unsubscribe) {
179
- this.map.delete(id);
180
- unsubscribe();
181
- }
182
- }
183
- drain() {
184
- for (const unsubscribe of this.map.values()) unsubscribe();
185
- this.map.clear();
186
- }
187
- };
188
- function createCorrelatedSubscriptions(router, config) {
189
- let counter = 0;
190
- const subs = /* @__PURE__ */ new Map();
191
- router.on(config.eventKind, (message) => {
192
- const sub = subs.get(message.id);
193
- if (sub) config.onEvent(sub, message);
194
- });
195
- router.on(config.errKind, (message) => {
196
- const id = message.id;
197
- const sub = subs.get(id);
198
- if (sub) {
199
- subs.delete(id);
200
- router.post(config.close(id));
201
- config.onError(sub, message);
202
- }
203
- });
204
- return { subscribe(sub, open) {
205
- const id = `${config.idPrefix}${++counter}`;
206
- subs.set(id, sub);
207
- router.post(open(id));
208
- return () => {
209
- subs.delete(id);
210
- router.post(config.close(id));
211
- };
212
- } };
213
- }
214
- //#endregion
215
- //#region src/rpc/client-proxy.ts
216
- function isAbortSignal(value) {
217
- return typeof value === "object" && value !== null && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
218
- }
219
- function createReactorClientProxy(router, options = {}) {
220
- const registry = options.registry;
221
- function fetchPage(token) {
222
- return router.request((id) => ({
223
- k: "page",
224
- id,
225
- token
226
- }), { transform: rehydrate });
227
- }
228
- function rehydrate(value) {
229
- return rehydratePage(value, fetchPage);
230
- }
231
- const changeSubs = createCorrelatedSubscriptions(router, {
232
- idPrefix: "sub",
233
- eventKind: "event",
234
- errKind: "sub-err",
235
- onEvent: (callback, msg) => callback(msg.change),
236
- onError: (_callback, msg) => console.error("Reactor subscription failed:", fromErrorInfo(msg.error)),
237
- close: (id) => ({
238
- k: "unsub",
239
- id
240
- })
241
- });
242
- router.on("reload", (msg) => {
243
- options.onReload?.(msg.reason, msg.workerGen);
244
- });
245
- const call = (method, args) => {
246
- let abortAt;
247
- for (let i = 0; i < args.length; i++) if (isAbortSignal(args[i])) abortAt = i;
248
- let wire = args;
249
- if (abortAt !== void 0) {
250
- wire = args.slice();
251
- wire[abortAt] = void 0;
252
- }
253
- return router.request((id) => ({
254
- k: "req",
255
- id,
256
- method,
257
- args: wire,
258
- abortAt
259
- }), {
260
- transform: rehydrate,
261
- setup: (id) => {
262
- if (abortAt === void 0) return;
263
- const signal = args[abortAt];
264
- const sendAbort = () => router.post({
265
- k: "abort",
266
- targetId: id
267
- });
268
- if (signal.aborted) {
269
- sendAbort();
270
- return;
271
- }
272
- signal.addEventListener("abort", sendAbort, { once: true });
273
- return () => signal.removeEventListener("abort", sendAbort);
274
- }
275
- });
276
- };
277
- const subscribe = (search, callback, view) => changeSubs.subscribe(callback, (id) => ({
278
- k: "sub",
279
- id,
280
- search,
281
- view
282
- }));
283
- const forwarders = /* @__PURE__ */ new Map();
284
- const forwarder = (method) => {
285
- let fn = forwarders.get(method);
286
- if (!fn) {
287
- fn = (...args) => call(method, args);
288
- forwarders.set(method, fn);
289
- }
290
- return fn;
291
- };
292
- const drives = new Proxy({}, { get: (_target, prop) => typeof prop === "string" ? forwarder(`drives.${prop}`) : void 0 });
293
- return new Proxy({}, { get(_target, prop) {
294
- if (typeof prop !== "string" || prop === "then") return;
295
- if (prop === "drives") return drives;
296
- if (prop === "subscribe") return subscribe;
297
- if (registry) {
298
- if (prop === "getDocumentModelModule") return (documentType) => Promise.resolve().then(() => registry.getModule(documentType));
299
- if (prop === "getDocumentModelModuleForDocument") return (document) => Promise.resolve().then(() => registry.getModule(document.header.documentType, normalizeDocumentModelVersion(document.state.document?.version)));
300
- if (prop === "getDocumentModelModules") return (_namespace, paging) => Promise.resolve({
301
- results: registry.getAllModules(),
302
- options: paging ?? {
303
- cursor: "",
304
- limit: Number.MAX_SAFE_INTEGER
305
- }
306
- });
307
- }
308
- return forwarder(prop);
309
- } });
310
- }
311
- //#endregion
312
89
  //#region src/rpc/inspector-proxy.ts
90
+ /** Every row of `INSPECTOR_OPS`; the host decides which tiers it serves. */
313
91
  function createInspectorProxy(router) {
314
92
  const ops = opChannel(router, "inspector-op");
315
- return {
316
- getQueueState: () => ops.call("queue.getState"),
317
- pauseQueue: () => ops.callVoid("queue.pause"),
318
- resumeQueue: () => ops.callVoid("queue.resume"),
319
- getProcessors: () => ops.call("processors.getAll"),
320
- retryProcessor: (processorId) => ops.callVoid("processors.retry", [processorId]),
321
- validateDocument: (documentId, branch) => ops.call("integrity.validate", [documentId, branch]),
322
- rebuildKeyframes: (documentId, branch) => ops.call("integrity.rebuildKeyframes", [documentId, branch]),
323
- rebuildSnapshots: (documentId, branch) => ops.call("integrity.rebuildSnapshots", [documentId, branch]),
324
- queryReactorDb: (sql, params) => ops.call("db.query", [sql, params ?? []])
325
- };
93
+ const proxy = {};
94
+ for (const [key, spec] of Object.entries(INSPECTOR_OPS)) proxy[key] = (...args) => ops.call(spec.rpc, args);
95
+ const queryDb = (sql, params) => ops.call(INSPECTOR_OPS.queryDb.rpc, [sql, params ?? []]);
96
+ proxy.queryDb = queryDb;
97
+ proxy.queryReactorDb = queryDb;
98
+ return proxy;
326
99
  }
327
100
  //#endregion
328
- //#region src/rpc/protocol.ts
329
- const RPC_PROTOCOL_VERSION = 2;
330
- /** Error reply kind for a client message kind, so it reaches the right registry. */
331
- function responseErrorKind(k) {
332
- if (k === "sub") return "sub-err";
333
- if (k === "sub-live") return "live-err";
334
- return "err";
101
+ //#region src/rpc/inspector-ops.ts
102
+ /** Host side of `inspector-op`; refuses tiers `access` does not grant. */
103
+ function dispatchInspectorOp(targets, access, method, args) {
104
+ return dispatchTableOp(INSPECTOR_OPS, (key) => key === "queryDb" ? methodOf(targets.dbQuery, key) : methodOf(targets.inspector, key), access, method, args);
335
105
  }
336
- //#endregion
337
- //#region src/rpc/host-reply.ts
338
- const defaultOk = () => ({ ok: true });
339
- function hostResponder(transport) {
340
- const ok = (id, value = { ok: true }) => {
341
- transport.post({
342
- k: "res",
343
- id,
344
- value
345
- });
346
- };
347
- const err = (id, error) => {
348
- transport.post({
349
- k: "err",
350
- id,
351
- error: toErrorInfo(error)
352
- });
353
- };
354
- return {
355
- ok,
356
- err,
357
- errForKind(message, error) {
358
- if (!("id" in message)) return;
359
- transport.post({
360
- k: responseErrorKind(message.k),
361
- id: message.id,
362
- error: toErrorInfo(error)
363
- });
364
- },
365
- async run(id, body, mapOk = defaultOk) {
366
- try {
367
- ok(id, mapOk(await body()));
368
- } catch (error) {
369
- err(id, error);
370
- }
371
- }
372
- };
106
+ /** Whether `method` is one of the `sync-op` rows `dispatchSyncInspectionOp` serves. */
107
+ function isSyncInspectionOp(method) {
108
+ return opKeyOf(SYNC_INSPECTION_OPS, method) !== void 0;
109
+ }
110
+ /** Host side of the inspection and repair rows of `sync-op`. */
111
+ function dispatchSyncInspectionOp(targets, access, method, args) {
112
+ return dispatchTableOp(SYNC_INSPECTION_OPS, (key) => SYNC_INSPECTION_OPS[key].tier === "read" ? methodOf(targets.inspector, key) : methodOf(targets.admin, key), access, method, args);
373
113
  }
374
114
  //#endregion
375
115
  //#region src/rpc/live-query-proxy.ts
376
116
  function createLiveQueryProxy(router) {
377
- const subs = createCorrelatedSubscriptions(router, {
117
+ const subs = createCorrelatedSubscriptions$1(router, {
378
118
  idPrefix: "live",
379
119
  eventKind: "event-live",
380
120
  errKind: "live-err",
381
121
  onEvent: (sub, msg) => sub.onResults(msg.results),
382
- onError: (sub, msg) => sub.onError?.(fromErrorInfo(msg.error)),
122
+ onError: (sub, msg) => sub.onError?.(fromErrorInfo$1(msg.error)),
383
123
  close: (id) => ({
384
124
  k: "unsub-live",
385
125
  id
@@ -425,7 +165,6 @@ function createRelationalPgliteProxy(router) {
425
165
  }
426
166
  //#endregion
427
167
  //#region src/rpc/sync-manager-proxy.ts
428
- const SYNC_STATUS_CHANGED_EVENT = 90001;
429
168
  const SEED_MAX_ATTEMPTS = 3;
430
169
  const SEED_RETRY_DELAY_MS = 500;
431
170
  const DEFAULT_SNAPSHOT = {
@@ -470,7 +209,8 @@ function rehydrateMeta(wire) {
470
209
  collectionId: DriveCollectionId.forDrive(wire.collectionId.driveId, wire.collectionId.branch),
471
210
  channelConfig: wire.channelConfig,
472
211
  filter: wire.filter,
473
- options: wire.options
212
+ options: wire.options,
213
+ peer: wire.peer
474
214
  };
475
215
  }
476
216
  function channelUrl(meta) {
@@ -480,10 +220,11 @@ function channelUrl(meta) {
480
220
  var SyncManagerProxy = class {
481
221
  ops;
482
222
  connectionStates = /* @__PURE__ */ new Map();
483
- connectionListeners = new KeyedListeners();
223
+ connectionListeners = new KeyedListeners$1();
484
224
  syncStatuses = /* @__PURE__ */ new Map();
485
- syncStatusListeners = new Listeners();
225
+ syncStatusListeners = new Listeners$1();
486
226
  remotes = [];
227
+ basis;
487
228
  seedPromise = null;
488
229
  constructor(router, busProxy) {
489
230
  this.ops = opChannel(router, "sync-op");
@@ -497,18 +238,22 @@ var SyncManagerProxy = class {
497
238
  this.syncStatuses.set(e.documentId, e.status);
498
239
  this.syncStatusListeners.emit(e.documentId, e.status);
499
240
  });
241
+ busProxy.subscribe(SYNC_REMOTES_CHANGED_EVENT, (_type, event) => {
242
+ this.applyRemotes(event.remotes);
243
+ });
500
244
  this.ensureSeeded();
501
245
  }
502
- async startup() {
503
- let lastError;
504
- for (let attempt = 0; attempt < SEED_MAX_ATTEMPTS; attempt++) try {
246
+ /** Attempts that fail while `isWaiting()` (the worker waits on a store lock) are not counted. */
247
+ async startup({ isWaiting = () => false } = {}) {
248
+ let failures = 0;
249
+ for (;;) try {
505
250
  await this.ensureSeeded();
506
251
  return;
507
252
  } catch (error) {
508
- lastError = error;
509
- if (attempt < SEED_MAX_ATTEMPTS - 1) await new Promise((resolve) => setTimeout(resolve, SEED_RETRY_DELAY_MS));
253
+ if (!isWaiting()) failures++;
254
+ if (failures >= SEED_MAX_ATTEMPTS) throw error;
255
+ await new Promise((resolve) => setTimeout(resolve, SEED_RETRY_DELAY_MS));
510
256
  }
511
- throw lastError;
512
257
  }
513
258
  shutdown() {
514
259
  return {
@@ -537,6 +282,24 @@ var SyncManagerProxy = class {
537
282
  await this.refreshRemotes();
538
283
  return this.getByName(name);
539
284
  }
285
+ async setPeerManifest(id, manifest) {
286
+ await this.callSyncOp("setPeerManifest", [id, manifest]);
287
+ await this.refreshRemotes();
288
+ }
289
+ /** Fetched once; the worker's flags do not change at runtime. */
290
+ localManifest() {
291
+ return this.agreementBasis().local;
292
+ }
293
+ async listHolds(filter) {
294
+ return await this.callSyncOp("listHolds", [filter]);
295
+ }
296
+ agreement() {
297
+ return createPeerAgreement(this.agreementBasis(), this.remotes.map((remote) => remote.meta));
298
+ }
299
+ agreementBasis() {
300
+ if (!this.basis) throw new Error("Peer agreement has not been fetched from the worker yet");
301
+ return this.basis;
302
+ }
540
303
  async bindRemote(id, boundAddress) {
541
304
  await this.callSyncOp("bindRemote", [id, boundAddress]);
542
305
  await this.refreshRemotes();
@@ -562,6 +325,31 @@ var SyncManagerProxy = class {
562
325
  onSyncStatusChange(callback) {
563
326
  return this.syncStatusListeners.add(callback);
564
327
  }
328
+ async inspectRemote(remoteName) {
329
+ return await this.tableOp("inspectRemote", [remoteName]);
330
+ }
331
+ async inspectRemotes() {
332
+ return await this.tableOp("inspectRemotes", []);
333
+ }
334
+ async listDeadLetters(remoteName, cursor, limit) {
335
+ return await this.tableOp("listDeadLetters", [
336
+ remoteName,
337
+ cursor,
338
+ limit
339
+ ]);
340
+ }
341
+ async resetChannel(remoteName) {
342
+ await this.tableOp("resetChannel", [remoteName]);
343
+ }
344
+ async requeueDeadLetter(remoteName, id) {
345
+ await this.tableOp("requeueDeadLetter", [remoteName, id]);
346
+ }
347
+ async clearDeadLetter(remoteName, id) {
348
+ await this.tableOp("clearDeadLetter", [remoteName, id]);
349
+ }
350
+ tableOp(key, args) {
351
+ return this.ops.call(SYNC_INSPECTION_OPS[key].rpc, args);
352
+ }
565
353
  callSyncOp(method, args) {
566
354
  return this.ops.call(method, args);
567
355
  }
@@ -589,11 +377,17 @@ var SyncManagerProxy = class {
589
377
  console.error(`triggerPull failed for remote "${remoteName}":`, error);
590
378
  });
591
379
  },
380
+ notePoll: () => {},
381
+ lastHolderPollUtcMs: () => void 0,
382
+ setLocalManifest: () => {},
383
+ onPeerManifest: () => () => {},
592
384
  config: { url }
593
385
  };
594
386
  }
595
387
  async refreshRemotes() {
596
- const wire = await this.callSyncOp("list", []);
388
+ this.applyRemotes(await this.callSyncOp("list", []));
389
+ }
390
+ applyRemotes(wire) {
597
391
  const names = /* @__PURE__ */ new Set();
598
392
  this.remotes = wire.map((w) => {
599
393
  const meta = rehydrateMeta(w.meta);
@@ -608,6 +402,9 @@ var SyncManagerProxy = class {
608
402
  this.notifyConnection();
609
403
  }
610
404
  ensureSeeded() {
405
+ if (!this.basis) this.callSyncOp("peerAgreementBasis", []).then((basis) => {
406
+ this.basis = basis;
407
+ }).catch(() => {});
611
408
  if (!this.seedPromise) {
612
409
  const pending = this.refreshRemotes();
613
410
  this.seedPromise = pending;
@@ -631,13 +428,17 @@ const FORWARDED_EVENT_TYPES = [
631
428
  SyncEventTypes.CONNECTION_STATE_CHANGED,
632
429
  ReactorEventTypes.MODEL_LOADED
633
430
  ];
634
- const FORWARDED_BUS_EVENT_TYPES = [...FORWARDED_EVENT_TYPES, SYNC_STATUS_CHANGED_EVENT];
431
+ const FORWARDED_BUS_EVENT_TYPES = [
432
+ ...FORWARDED_EVENT_TYPES,
433
+ SYNC_STATUS_CHANGED_EVENT,
434
+ SYNC_REMOTES_CHANGED_EVENT
435
+ ];
635
436
  //#endregion
636
437
  //#region src/rpc/event-bus-proxy.ts
637
438
  /** Tab-side IEventBus over bus-event; emit() is unsupported (the worker emits). */
638
439
  var ReactorEventBusProxy = class {
639
440
  forwardedTypes = new Set(FORWARDED_BUS_EVENT_TYPES);
640
- subscribers = new KeyedListeners();
441
+ subscribers = new KeyedListeners$1();
641
442
  constructor(router) {
642
443
  router.on("bus-event", (msg) => {
643
444
  this.subscribers.emit(msg.eventType, msg.eventType, msg.event);
@@ -658,7 +459,7 @@ function createReactorEventBusProxy(router) {
658
459
  //#endregion
659
460
  //#region src/rpc/connect-reactor.ts
660
461
  function connectReactorClient(router, hello, onReload, registry) {
661
- const client = createReactorClientProxy(router, {
462
+ const client = createReactorClientProxy$1(router, {
662
463
  onReload,
663
464
  registry
664
465
  });
@@ -678,146 +479,13 @@ function postReactorIdentity(router, user) {
678
479
  });
679
480
  }
680
481
  //#endregion
681
- //#region src/rpc/host-server.ts
682
- const MAX_PENDING_PAGES = 1e3;
683
- var ReactorHostServer = class {
684
- client;
685
- transport;
686
- reply;
687
- aborters = /* @__PURE__ */ new Map();
688
- subscriptions = new SubscriptionStore();
689
- pages = /* @__PURE__ */ new Map();
690
- pageCounter = 0;
691
- detach = () => {};
692
- constructor(client, transport) {
693
- this.client = client;
694
- this.transport = transport;
695
- this.reply = hostResponder(transport);
696
- }
697
- start() {
698
- this.detach = this.transport.onMessage((message) => {
699
- this.handleMessage(message);
700
- });
701
- }
702
- stop() {
703
- this.detach();
704
- this.subscriptions.drain();
705
- this.aborters.clear();
706
- this.pages.clear();
707
- }
708
- async handleMessage(message) {
709
- try {
710
- switch (message.k) {
711
- case "req":
712
- await this.handleRequest(message);
713
- return;
714
- case "page":
715
- await this.handlePage(message);
716
- return;
717
- case "abort":
718
- this.aborters.get(message.targetId)?.abort();
719
- return;
720
- case "sub":
721
- this.handleSubscribe(message);
722
- return;
723
- case "unsub":
724
- this.subscriptions.end(message.id);
725
- return;
726
- }
727
- } catch (error) {
728
- this.reply.errForKind(message, error);
729
- }
730
- }
731
- async handleRequest(message) {
732
- let args = message.args;
733
- let controller;
734
- if (message.abortAt !== void 0) {
735
- controller = new AbortController();
736
- this.aborters.set(message.id, controller);
737
- args = message.args.slice();
738
- args[message.abortAt] = controller.signal;
739
- }
740
- try {
741
- const value = await this.resolveMethod(message.method)(...args);
742
- this.reply.ok(message.id, this.prepareResult(value));
743
- } catch (error) {
744
- this.reply.err(message.id, error);
745
- } finally {
746
- if (controller) this.aborters.delete(message.id);
747
- }
748
- }
749
- async handlePage(message) {
750
- const next = this.pages.get(message.token);
751
- this.pages.delete(message.token);
752
- if (!next) {
753
- this.reply.err(message.id, /* @__PURE__ */ new Error("Paged cursor already consumed or expired"));
754
- return;
755
- }
756
- try {
757
- const value = await next();
758
- this.reply.ok(message.id, this.prepareResult(value));
759
- } catch (error) {
760
- this.reply.err(message.id, error);
761
- }
762
- }
763
- handleSubscribe(message) {
764
- const unsubscribe = this.client.subscribe(message.search, (change) => this.transport.post({
765
- k: "event",
766
- id: message.id,
767
- change
768
- }), message.view);
769
- this.subscriptions.set(message.id, unsubscribe);
770
- }
771
- prepareResult(value) {
772
- return dehydratePage(value, (next) => {
773
- const token = `p${++this.pageCounter}`;
774
- this.pages.set(token, next);
775
- if (this.pages.size > MAX_PENDING_PAGES) {
776
- const oldest = this.pages.keys().next().value;
777
- if (oldest !== void 0) this.pages.delete(oldest);
778
- }
779
- return token;
780
- });
781
- }
782
- resolveMethod(path) {
783
- if (path.startsWith("drives.")) {
784
- const name = path.slice(7);
785
- const fn = this.client.drives[name];
786
- if (typeof fn !== "function") throw new Error(`Unknown drive method: ${name}`);
787
- return fn.bind(this.client.drives);
788
- }
789
- const fn = this.client[path];
790
- if (typeof fn !== "function") throw new Error(`Unknown reactor method: ${path}`);
791
- return fn.bind(this.client);
792
- }
793
- };
794
- //#endregion
795
- //#region src/rpc/transport.ts
796
- function createPortTransport(port) {
797
- port.start();
798
- port.addEventListener("messageerror", (event) => {
799
- console.error("[rpc transport] failed to deserialize message", event);
800
- });
801
- return {
802
- post(message) {
803
- port.postMessage(message);
804
- },
805
- onMessage(listener) {
806
- const handler = (event) => {
807
- listener(event.data);
808
- };
809
- port.addEventListener("message", handler);
810
- return () => port.removeEventListener("message", handler);
811
- },
812
- close() {
813
- port.close();
814
- }
815
- };
816
- }
817
- //#endregion
818
482
  //#region src/rpc/reactor-host.ts
819
483
  function isDataMessage(msg) {
820
- return msg.k === "req" || msg.k === "sub" || msg.k === "page" || msg.k === "sync-op" || msg.k === "db-op" || msg.k === "inspector-op" || msg.k === "sub-live";
484
+ return msg.k === "req" || msg.k === "sub" || msg.k === "page" || msg.k === "sync-op" || msg.k === "db-op" || msg.k === "inspector-op" || msg.k === "adopt-sync-peer" || msg.k === "remove-sync-peer" || msg.k === "sub-live";
485
+ }
486
+ /** A rejected adopt still owns the port it moved here, so close it. */
487
+ function closeTransferredPort(msg) {
488
+ if (msg.k === "adopt-sync-peer") msg.port.close();
821
489
  }
822
490
  function versionsCompatible(a, b) {
823
491
  return a.appBuildId === b.appBuildId && a.rpcProtocolVersion === b.rpcProtocolVersion && (a.featureFlags ?? "") === (b.featureFlags ?? "");
@@ -827,25 +495,38 @@ function workerGenForVersion(version) {
827
495
  const suffix = flags === "" ? "" : `-${hashFlags(flags)}`;
828
496
  return `v${version.rpcProtocolVersion}-${version.appBuildId}${suffix}`;
829
497
  }
498
+ const VERSION_MISMATCH = "reactor version mismatch";
499
+ const FLAGS_CHANGED = "reactor enforcement flags changed";
500
+ /** Whether a reload reason comes from a build fingerprint mismatch. */
501
+ function isFingerprintMismatchReload(reason) {
502
+ return reason === VERSION_MISMATCH || reason.startsWith(FLAGS_CHANGED);
503
+ }
830
504
  /** Names what differs, so a reload is diagnosable from the tab's console. */
831
505
  function mismatchReason(baseline, incoming) {
832
- if ((baseline.featureFlags ?? "") !== (incoming.featureFlags ?? "")) return `reactor enforcement flags changed (worker: ${baseline.featureFlags || "none"}, tab: ${incoming.featureFlags || "none"})`;
833
- return "reactor version mismatch";
506
+ if ((baseline.featureFlags ?? "") !== (incoming.featureFlags ?? "")) return `${FLAGS_CHANGED} (worker: ${baseline.featureFlags || "none"}, tab: ${incoming.featureFlags || "none"})`;
507
+ return VERSION_MISMATCH;
834
508
  }
835
509
  function hashFlags(flags) {
836
510
  let hash = 0;
837
511
  for (let i = 0; i < flags.length; i++) hash = hash * 31 + flags.charCodeAt(i) | 0;
838
512
  return (hash >>> 0).toString(36);
839
513
  }
514
+ const RETIRED_WORKER_RELOAD_REASON = "worker retired";
515
+ function retiredError() {
516
+ return /* @__PURE__ */ new Error("This worker was retired; reloading into the current one");
517
+ }
840
518
  var ReactorHost = class {
841
519
  options;
842
520
  disposers = /* @__PURE__ */ new Set();
843
521
  clients = /* @__PURE__ */ new Set();
844
522
  clientPromise = null;
523
+ buildFailure = null;
845
524
  baseline = null;
846
525
  ownerId;
847
526
  bootedAtMs;
848
527
  migrationState = null;
528
+ retirement = null;
529
+ reloadSent = false;
849
530
  constructor(options) {
850
531
  this.options = options;
851
532
  this.ownerId = options.ownerId ?? crypto.randomUUID();
@@ -856,11 +537,12 @@ var ReactorHost = class {
856
537
  let server = null;
857
538
  let ready = false;
858
539
  const buffer = [];
859
- const liveSubs = new SubscriptionStore();
860
- const reply = hostResponder(transport);
540
+ const liveSubs = new SubscriptionStore$1();
541
+ const reply = hostResponder$1(transport);
861
542
  const ensureServer = async (construct) => {
862
543
  if (server) return;
863
- server = new ReactorHostServer(await this.resolveClient(construct), transport);
544
+ const client = await this.resolveClient(construct);
545
+ server = new ReactorHostServer$1(client, transport);
864
546
  };
865
547
  const drainBuffer = async () => {
866
548
  while (buffer.length > 0) {
@@ -881,9 +563,15 @@ var ReactorHost = class {
881
563
  return;
882
564
  }
883
565
  if (this.migrationState?.status === "migrating" && isDataMessage(msg)) {
566
+ closeTransferredPort(msg);
884
567
  reply.errForKind(msg, /* @__PURE__ */ new Error("migration in progress"));
885
568
  return;
886
569
  }
570
+ if (this.retirement && isDataMessage(msg)) {
571
+ closeTransferredPort(msg);
572
+ reply.errForKind(msg, retiredError());
573
+ return;
574
+ }
887
575
  if (msg.k === "hello") {
888
576
  this.handleHello(msg, transport, reply, ensureServer, drainBuffer);
889
577
  return;
@@ -901,7 +589,7 @@ var ReactorHost = class {
901
589
  return;
902
590
  }
903
591
  if (msg.k === "sync-op") {
904
- this.handleOp(msg, this.options.onSyncOp, "sync", reply);
592
+ this.handleSyncOp(msg, reply);
905
593
  return;
906
594
  }
907
595
  if (msg.k === "db-op") {
@@ -912,6 +600,14 @@ var ReactorHost = class {
912
600
  this.handleOp(msg, this.options.onInspectorOp, "inspector", reply);
913
601
  return;
914
602
  }
603
+ if (msg.k === "adopt-sync-peer") {
604
+ this.handleAdoptSyncPeer(msg, reply);
605
+ return;
606
+ }
607
+ if (msg.k === "remove-sync-peer") {
608
+ this.handleRemoveSyncPeer(msg, reply);
609
+ return;
610
+ }
915
611
  if (msg.k === "sub-live") {
916
612
  this.handleLiveSubscribe(msg, transport, reply, liveSubs);
917
613
  return;
@@ -921,7 +617,7 @@ var ReactorHost = class {
921
617
  return;
922
618
  }
923
619
  if (msg.k === "admin") {
924
- this.handleAdmin(msg, reply);
620
+ this.handleAdmin(msg, reply, transport);
925
621
  return;
926
622
  }
927
623
  if (ready && server) server.handleMessage(msg);
@@ -932,6 +628,10 @@ var ReactorHost = class {
932
628
  k: "migration",
933
629
  state: this.migrationState
934
630
  });
631
+ if (this.retirement && this.reloadSent) transport.post({
632
+ k: "reload",
633
+ ...this.retirement
634
+ });
935
635
  if (this.options.client) ensureServer().then(drainBuffer).catch((error) => {
936
636
  console.error("ReactorHost buffer drain failed", error);
937
637
  });
@@ -946,7 +646,7 @@ var ReactorHost = class {
946
646
  return dispose;
947
647
  }
948
648
  connectPort(port) {
949
- return this.connect(createPortTransport(port));
649
+ return this.connect(createPortTransport$1(port));
950
650
  }
951
651
  broadcastBusEvent(eventType, event) {
952
652
  for (const transport of this.clients) transport.post({
@@ -962,6 +662,37 @@ var ReactorHost = class {
962
662
  workerGen
963
663
  });
964
664
  }
665
+ retireAndReload(reason, workerGen) {
666
+ if (this.retirement) return;
667
+ this.retirement = {
668
+ reason,
669
+ workerGen
670
+ };
671
+ const drain = this.options.drainBeforeReload;
672
+ if (!drain || !isFingerprintMismatchReload(reason)) {
673
+ this.sendReload(reason, workerGen);
674
+ return;
675
+ }
676
+ this.drainThenReload(drain, reason, workerGen);
677
+ }
678
+ async drainThenReload(drain, reason, workerGen) {
679
+ try {
680
+ await drain();
681
+ } catch (error) {
682
+ console.error("ReactorHost drain before reload failed", error);
683
+ }
684
+ this.sendReload(reason, workerGen);
685
+ }
686
+ sendReload(reason, workerGen) {
687
+ this.reloadSent = true;
688
+ this.broadcastReload(reason, workerGen);
689
+ this.stopRetired(reason);
690
+ }
691
+ stopRetired(reason) {
692
+ this.options.onRetire?.(reason).catch((error) => {
693
+ console.error("ReactorHost retirement cleanup failed", error);
694
+ });
695
+ }
965
696
  setMigrationState(state) {
966
697
  this.migrationState = state;
967
698
  for (const transport of this.clients) transport.post({
@@ -969,10 +700,22 @@ var ReactorHost = class {
969
700
  state
970
701
  });
971
702
  }
703
+ get retired() {
704
+ return this.retirement !== null;
705
+ }
972
706
  get connectionCount() {
973
707
  return this.disposers.size;
974
708
  }
975
- handleAdmin(message, reply) {
709
+ handleAdmin(message, reply, transport) {
710
+ if (this.retirement && message.method !== "info") {
711
+ if (this.reloadSent) transport.post({
712
+ k: "reload",
713
+ reason: RETIRED_WORKER_RELOAD_REASON,
714
+ workerGen: this.retirement.workerGen
715
+ });
716
+ reply.err(message.id, retiredError());
717
+ return;
718
+ }
976
719
  if (message.method === "restart") {
977
720
  this.options.onAdminRestart?.();
978
721
  reply.ok(message.id);
@@ -992,7 +735,7 @@ var ReactorHost = class {
992
735
  bootedAtMs: this.bootedAtMs,
993
736
  connectedClients: this.connectionCount,
994
737
  appBuildId: this.baseline?.appBuildId ?? this.options.appBuildId ?? "unknown",
995
- rpcProtocolVersion: this.baseline?.rpcProtocolVersion ?? 2,
738
+ rpcProtocolVersion: this.baseline?.rpcProtocolVersion ?? RPC_PROTOCOL_VERSION$1,
996
739
  featureFlags: this.baseline?.featureFlags ?? ""
997
740
  };
998
741
  reply.ok(message.id, info);
@@ -1003,19 +746,31 @@ var ReactorHost = class {
1003
746
  });
1004
747
  }
1005
748
  resolveClient(construct) {
749
+ if (this.retirement) return Promise.reject(retiredError());
1006
750
  if (!this.clientPromise) {
1007
751
  const build = this.options.build;
1008
752
  if (!build) return Promise.reject(/* @__PURE__ */ new Error("ReactorHost has no client or builder"));
1009
753
  const pending = build(construct);
1010
754
  this.clientPromise = pending;
1011
- pending.catch(() => {
1012
- if (this.clientPromise === pending) this.clientPromise = null;
755
+ this.buildFailure = null;
756
+ pending.then(() => {
757
+ if (this.retirement && this.reloadSent) this.stopRetired(this.retirement.reason);
758
+ }, () => void 0);
759
+ pending.catch((error) => {
760
+ if (this.clientPromise === pending) {
761
+ this.clientPromise = null;
762
+ this.buildFailure = { error };
763
+ }
1013
764
  });
1014
765
  }
1015
766
  return this.clientPromise;
1016
767
  }
1017
768
  async awaitClientReady() {
1018
- if (this.clientPromise) await this.clientPromise;
769
+ if (this.clientPromise) {
770
+ await this.clientPromise;
771
+ return;
772
+ }
773
+ if (this.buildFailure) throw this.buildFailure.error;
1019
774
  }
1020
775
  requireHandler(handler, message, reply, label) {
1021
776
  if (handler) return true;
@@ -1025,11 +780,7 @@ var ReactorHost = class {
1025
780
  async handleHello(message, transport, reply, ensureServer, drainBuffer) {
1026
781
  if (this.baseline) {
1027
782
  if (!versionsCompatible(this.baseline, message.version)) {
1028
- transport.post({
1029
- k: "reload",
1030
- reason: mismatchReason(this.baseline, message.version),
1031
- workerGen: workerGenForVersion(message.version)
1032
- });
783
+ this.retireAndReload(mismatchReason(this.baseline, message.version), `${workerGenForVersion(message.version)}-${this.ownerId.slice(0, 8)}`);
1033
784
  reply.ok(message.id, { ok: false });
1034
785
  return;
1035
786
  }
@@ -1042,7 +793,7 @@ var ReactorHost = class {
1042
793
  }
1043
794
  async handleRegister(message, reply) {
1044
795
  await reply.run(message.id, async () => {
1045
- await this.options.registerPackages?.(message.specs);
796
+ await this.options.registerPackages?.(message.specs, message.sources);
1046
797
  });
1047
798
  }
1048
799
  async handleUnregister(message, reply) {
@@ -1057,6 +808,65 @@ var ReactorHost = class {
1057
808
  return handler(message.method, message.args);
1058
809
  }, (value) => value);
1059
810
  }
811
+ /** An `add` or `remove` changes the remotes every tab lists. */
812
+ async handleSyncOp(message, reply) {
813
+ const handler = this.options.onSyncOp;
814
+ if (!this.requireHandler(handler, message, reply, "sync")) return;
815
+ const changesRemotes = message.method === "add" || message.method === "remove";
816
+ await reply.run(message.id, async () => {
817
+ await this.awaitClientReady();
818
+ const value = await handler(message.method, message.args);
819
+ if (changesRemotes) await this.broadcastRemotes();
820
+ return value;
821
+ }, (value) => value);
822
+ }
823
+ /** Closes the moved port on every failure; the sender can no longer close it. */
824
+ async handleAdoptSyncPeer(message, reply) {
825
+ const handler = this.options.onAdoptSyncPeer;
826
+ if (!handler) {
827
+ closeTransferredPort(message);
828
+ reply.errForKind(message, /* @__PURE__ */ new Error("ReactorHost has no adopt-sync-peer handler"));
829
+ return;
830
+ }
831
+ await reply.run(message.id, async () => {
832
+ try {
833
+ await this.awaitClientReady();
834
+ await handler({
835
+ peerId: message.peerId,
836
+ channelName: message.channelName,
837
+ collectionIdKey: message.collectionIdKey,
838
+ remoteName: message.remoteName,
839
+ filter: message.filter
840
+ }, message.port);
841
+ } catch (error) {
842
+ closeTransferredPort(message);
843
+ throw error;
844
+ }
845
+ await this.broadcastRemotes();
846
+ });
847
+ }
848
+ async handleRemoveSyncPeer(message, reply) {
849
+ const handler = this.options.onRemoveSyncPeer;
850
+ if (!this.requireHandler(handler, message, reply, "remove-sync-peer")) return;
851
+ await reply.run(message.id, async () => {
852
+ await this.awaitClientReady();
853
+ await handler({
854
+ peerId: message.peerId,
855
+ channelName: message.channelName,
856
+ remoteName: message.remoteName
857
+ });
858
+ await this.broadcastRemotes();
859
+ });
860
+ }
861
+ async broadcastRemotes() {
862
+ const list = this.options.onSyncOp;
863
+ if (!list) return;
864
+ try {
865
+ this.broadcastBusEvent(SYNC_REMOTES_CHANGED_EVENT, { remotes: await list("list", []) });
866
+ } catch (error) {
867
+ console.error("ReactorHost could not list remotes for its tabs", error);
868
+ }
869
+ }
1060
870
  async handleLiveSubscribe(message, transport, reply, liveSubs) {
1061
871
  const handler = this.options.onLiveQuery;
1062
872
  if (!this.requireHandler(handler, message, reply, "live-query")) return;
@@ -1083,10 +893,179 @@ var ReactorHost = class {
1083
893
  }
1084
894
  };
1085
895
  //#endregion
896
+ //#region src/rpc/module-graph.ts
897
+ /** A bare specifier's URL in the shared table: an exact entry, else the longest trailing-slash prefix, as an import map does. */
898
+ function resolveSharedSpecifier(specifier, imports) {
899
+ if (Object.hasOwn(imports, specifier)) return imports[specifier];
900
+ let best;
901
+ for (const key of Object.keys(imports)) if (key.endsWith("/") && specifier.startsWith(key) && (best === void 0 || key.length > best.length)) best = key;
902
+ return best === void 0 ? void 0 : imports[best] + specifier.slice(best.length);
903
+ }
904
+ function isRelative(specifier) {
905
+ return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/");
906
+ }
907
+ function isUrl(specifier) {
908
+ return /^[a-z][a-z0-9+.-]*:/i.test(specifier);
909
+ }
910
+ async function fetchModuleSource(url) {
911
+ const response = await fetch(url);
912
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${url}`);
913
+ return response.text();
914
+ }
915
+ function blobModuleUrl(source) {
916
+ return URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
917
+ }
918
+ var ModuleGraph = class {
919
+ sharedImports;
920
+ fetchSource;
921
+ createModuleUrl;
922
+ warn;
923
+ parsed = /* @__PURE__ */ new Map();
924
+ built = /* @__PURE__ */ new Map();
925
+ constructor(options = {}) {
926
+ this.sharedImports = options.sharedImports ?? {};
927
+ this.fetchSource = options.fetchSource ?? fetchModuleSource;
928
+ this.createModuleUrl = options.createModuleUrl ?? blobModuleUrl;
929
+ this.warn = options.warn ?? ((message) => console.warn(message));
930
+ }
931
+ /** The URL to import in place of `entryUrl`; `entryUrl` itself when nothing needed a rewrite. */
932
+ async resolve(entryUrl) {
933
+ const modules = await this.collect(entryUrl);
934
+ this.assertMapped(entryUrl, modules);
935
+ const rewrite = this.needsRewrite(modules);
936
+ this.assertAcyclic(entryUrl, modules, rewrite);
937
+ return this.build(entryUrl, modules, rewrite);
938
+ }
939
+ async collect(entryUrl) {
940
+ const modules = /* @__PURE__ */ new Map();
941
+ const seen = /* @__PURE__ */ new Set();
942
+ const visit = async (url) => {
943
+ if (seen.has(url)) return;
944
+ seen.add(url);
945
+ const module = await this.parse(url);
946
+ modules.set(url, module);
947
+ await Promise.all(module.deps.map(visit));
948
+ };
949
+ await visit(entryUrl);
950
+ return modules;
951
+ }
952
+ parse(url) {
953
+ let pending = this.parsed.get(url);
954
+ if (!pending) {
955
+ pending = this.readModule(url);
956
+ pending.catch(() => this.parsed.delete(url));
957
+ this.parsed.set(url, pending);
958
+ }
959
+ return pending;
960
+ }
961
+ async readModule(url) {
962
+ const source = await this.fetchSource(url);
963
+ await init;
964
+ const [imports] = parse(source, url);
965
+ const deps = [];
966
+ const bare = [];
967
+ for (const specifier of imports) {
968
+ if (specifier.d === -2) continue;
969
+ const name = specifier.n;
970
+ if (name === void 0) {
971
+ this.warn(`[module-graph] ${url} has a dynamic import with a computed specifier; it is left as is`);
972
+ continue;
973
+ }
974
+ if (isRelative(name)) deps.push(new URL(name, url).href);
975
+ else if (!isUrl(name)) bare.push(name);
976
+ }
977
+ return {
978
+ url,
979
+ source,
980
+ imports,
981
+ deps: [...new Set(deps)],
982
+ bare
983
+ };
984
+ }
985
+ assertAcyclic(entryUrl, modules, rewrite) {
986
+ const state = /* @__PURE__ */ new Map();
987
+ const stack = [];
988
+ const visit = (url) => {
989
+ const seen = state.get(url);
990
+ if (seen === "done") return;
991
+ if (seen === "visiting") {
992
+ const cycle = [...stack.slice(stack.indexOf(url)), url];
993
+ throw new Error(`Can't load ${entryUrl} in the worker: its modules import each other (${cycle.join(" -> ")})`);
994
+ }
995
+ state.set(url, "visiting");
996
+ stack.push(url);
997
+ for (const dep of modules.get(url).deps) if (rewrite.has(dep)) visit(dep);
998
+ stack.pop();
999
+ state.set(url, "done");
1000
+ };
1001
+ for (const url of [entryUrl, ...rewrite]) if (rewrite.has(url)) visit(url);
1002
+ }
1003
+ assertMapped(entryUrl, modules) {
1004
+ for (const module of modules.values()) for (const name of module.bare) if (resolveSharedSpecifier(name, this.sharedImports) === void 0) throw new Error(`Can't load ${entryUrl} in the worker: ${module.url} imports "${name}", which the host doesn't share with the worker`);
1005
+ }
1006
+ needsRewrite(modules) {
1007
+ const importers = /* @__PURE__ */ new Map();
1008
+ for (const module of modules.values()) for (const dep of module.deps) importers.set(dep, [...importers.get(dep) ?? [], module.url]);
1009
+ const rewrite = /* @__PURE__ */ new Set();
1010
+ const queue = [...modules.values()].filter((module) => module.bare.length > 0).map((module) => module.url);
1011
+ while (queue.length > 0) {
1012
+ const url = queue.pop();
1013
+ if (rewrite.has(url)) continue;
1014
+ rewrite.add(url);
1015
+ queue.push(...importers.get(url) ?? []);
1016
+ }
1017
+ return rewrite;
1018
+ }
1019
+ build(url, modules, rewrite) {
1020
+ if (!rewrite.has(url)) return Promise.resolve(url);
1021
+ let pending = this.built.get(url);
1022
+ if (!pending) {
1023
+ pending = this.rewrite(modules.get(url), modules, rewrite);
1024
+ pending.catch(() => this.built.delete(url));
1025
+ this.built.set(url, pending);
1026
+ }
1027
+ return pending;
1028
+ }
1029
+ async rewrite(module, modules, rewrite) {
1030
+ const depUrls = /* @__PURE__ */ new Map();
1031
+ await Promise.all(module.deps.map(async (dep) => {
1032
+ depUrls.set(dep, await this.build(dep, modules, rewrite));
1033
+ }));
1034
+ let out = "";
1035
+ let last = 0;
1036
+ for (const specifier of module.imports) {
1037
+ const name = specifier.n;
1038
+ if (specifier.d === -2 || name === void 0 || isUrl(name)) continue;
1039
+ const target = isRelative(name) ? depUrls.get(new URL(name, module.url).href) : resolveSharedSpecifier(name, this.sharedImports);
1040
+ const replacement = specifier.d > -1 ? JSON.stringify(target) : target;
1041
+ out += module.source.slice(last, specifier.s) + replacement;
1042
+ last = specifier.e;
1043
+ }
1044
+ return this.createModuleUrl(out + module.source.slice(last));
1045
+ }
1046
+ };
1047
+ //#endregion
1086
1048
  //#region src/rpc/worker-package-loader.ts
1087
- function packageName(spec) {
1088
- const at = spec.lastIndexOf("@");
1089
- return at > 0 ? spec.slice(0, at) : spec;
1049
+ /** One line for a failed load: the package, its URL and why. */
1050
+ function describeLoadFailure(failure) {
1051
+ const reason = failure.error instanceof Error ? failure.error.message : String(failure.error);
1052
+ return `${failure.name} (${failure.url}): ${reason}`;
1053
+ }
1054
+ function summarize(results) {
1055
+ const types = /* @__PURE__ */ new Set();
1056
+ const failures = [];
1057
+ for (const result of results) if (result.status === "replaced") for (const type of result.types) types.add(type);
1058
+ else if (result.status === "failed") failures.push(result.failure);
1059
+ return {
1060
+ types: [...types],
1061
+ failures
1062
+ };
1063
+ }
1064
+ const SOURCE_KEY_PREFIX = "src:";
1065
+ function packageName(key) {
1066
+ if (key.startsWith(SOURCE_KEY_PREFIX)) return key.slice(4);
1067
+ const at = key.lastIndexOf("@");
1068
+ return at > 0 ? key.slice(0, at) : key;
1090
1069
  }
1091
1070
  function moduleKey(module) {
1092
1071
  return `${module.documentModel.global.id}@${module.version ?? 1}`;
@@ -1096,16 +1075,47 @@ function isDocumentModelModule(value) {
1096
1075
  const candidate = value;
1097
1076
  return typeof candidate.reducer === "function" && typeof candidate.documentModel?.global?.id === "string";
1098
1077
  }
1078
+ function isUpgradeManifest(value) {
1079
+ if (typeof value !== "object" || value === null) return false;
1080
+ const candidate = value;
1081
+ return typeof candidate.documentType === "string" && typeof candidate.upgrades === "object" && candidate.upgrades !== null;
1082
+ }
1083
+ function manifestsOf(namespace) {
1084
+ const out = [];
1085
+ for (const value of Object.values(namespace)) {
1086
+ if (isUpgradeManifest(value)) {
1087
+ out.push(value);
1088
+ continue;
1089
+ }
1090
+ if (Array.isArray(value)) {
1091
+ for (const inner of value) if (isUpgradeManifest(inner)) out.push(inner);
1092
+ }
1093
+ }
1094
+ return out;
1095
+ }
1099
1096
  var WorkerPackageLoader = class {
1100
1097
  cdnUrl;
1101
1098
  importPackage;
1102
1099
  resolvePackages;
1100
+ moduleGraph;
1103
1101
  modulesByKey = /* @__PURE__ */ new Map();
1104
- loadedSpecs = /* @__PURE__ */ new Set();
1102
+ manifestsByType = /* @__PURE__ */ new Map();
1103
+ keysBySource = /* @__PURE__ */ new Map();
1104
+ manifestTypesBySource = /* @__PURE__ */ new Map();
1105
+ loadedUrls = /* @__PURE__ */ new Map();
1105
1106
  failures = [];
1107
+ pendingLoads = /* @__PURE__ */ new Map();
1108
+ generationBySource = /* @__PURE__ */ new Map();
1109
+ generation = 0;
1106
1110
  constructor(options) {
1107
1111
  this.cdnUrl = options.cdnUrl.replace(/\/$/, "");
1108
1112
  this.importPackage = options.importPackage;
1113
+ this.moduleGraph = new ModuleGraph({
1114
+ sharedImports: options.sharedImports,
1115
+ fetchSource: options.fetchSource,
1116
+ createModuleUrl: options.createModuleUrl,
1117
+ warn: options.warn
1118
+ });
1109
1119
  const registryClient = new RegistryClient(options.cdnUrl);
1110
1120
  this.resolvePackages = options.resolvePackages ?? ((documentType) => registryClient.getPackagesByDocumentType(documentType));
1111
1121
  }
@@ -1113,6 +1123,25 @@ var WorkerPackageLoader = class {
1113
1123
  await Promise.all([...new Set(specs)].map((spec) => this.loadPackage(spec)));
1114
1124
  return this.models;
1115
1125
  }
1126
+ /** Loads registry packages added or updated after boot; returns the types whose modules changed, and the failures. */
1127
+ async updatePackages(specs) {
1128
+ return summarize(await Promise.all([...new Set(specs)].map((spec) => this.loadPackage(spec))));
1129
+ }
1130
+ /** Loads URL-addressed packages (local project packages). Idempotent. */
1131
+ async loadSources(sources) {
1132
+ await Promise.all(sources.map((source) => this.loadFromUrl(sourceKey(source), source.url)));
1133
+ }
1134
+ /**
1135
+ * Replaces previously loaded sources with freshly imported ones (a vetra
1136
+ * watch rebuild re-sends the same source under a cache-busted URL). Returns
1137
+ * every document type touched - removed, re-added, or new - so the caller
1138
+ * can replace the registry's version families. A source whose import fails
1139
+ * keeps its previous modules and is reported in `failures`; one superseded
1140
+ * by a newer reload of the same source contributes nothing.
1141
+ */
1142
+ async reloadSources(sources) {
1143
+ return summarize(await Promise.all(sources.map((source) => this.replaceSource(sourceKey(source), source.url))));
1144
+ }
1116
1145
  async load(documentType) {
1117
1146
  const existing = this.latestForType(documentType);
1118
1147
  if (existing) return existing;
@@ -1126,6 +1155,9 @@ var WorkerPackageLoader = class {
1126
1155
  get models() {
1127
1156
  return [...new Set(this.modulesByKey.values())];
1128
1157
  }
1158
+ get upgradeManifests() {
1159
+ return [...this.manifestsByType.values()];
1160
+ }
1129
1161
  get loadFailures() {
1130
1162
  return [...this.failures];
1131
1163
  }
@@ -1144,138 +1176,85 @@ var WorkerPackageLoader = class {
1144
1176
  const cause = failures.length === 1 ? failures[0].error : new AggregateError(failures.map((failure) => failure.error));
1145
1177
  return new Error(`Failed to import package(s) [${packageNames.join(", ")}] for document model: ${documentType}`, { cause });
1146
1178
  }
1147
- async loadPackage(spec) {
1148
- if (this.loadedSpecs.has(spec)) return;
1179
+ loadPackage(spec) {
1149
1180
  const name = packageName(spec);
1150
- const url = `${this.cdnUrl}/${name}/browser/document-models/index.js`;
1181
+ const url = `${this.cdnUrl}/${spec}/browser/document-models/index.js`;
1182
+ const loaded = this.loadedUrls.get(name);
1183
+ if (loaded !== void 0 && (spec === name || loaded === url)) return Promise.resolve({ status: "unchanged" });
1184
+ return this.loadFromUrl(name, url, loaded !== void 0);
1185
+ }
1186
+ loadFromUrl(key, url, replace = false) {
1187
+ if (!replace && this.loadedUrls.has(key)) return Promise.resolve({ status: "unchanged" });
1188
+ const pendingKey = `${key} ${url}`;
1189
+ let pending = this.pendingLoads.get(pendingKey);
1190
+ if (!pending) {
1191
+ pending = this.replaceSource(key, url).finally(() => this.pendingLoads.delete(pendingKey));
1192
+ this.pendingLoads.set(pendingKey, pending);
1193
+ }
1194
+ return pending;
1195
+ }
1196
+ async replaceSource(key, url) {
1197
+ const generation = ++this.generation;
1198
+ this.generationBySource.set(key, generation);
1199
+ let namespace;
1151
1200
  try {
1152
- const namespace = await this.importPackage(url);
1153
- for (const value of Object.values(namespace)) if (isDocumentModelModule(value)) this.modulesByKey.set(moduleKey(value), value);
1154
- this.loadedSpecs.add(spec);
1201
+ namespace = await this.importNamespace(key, url);
1155
1202
  } catch (error) {
1156
- this.failures.push({
1157
- name,
1203
+ if (this.generationBySource.get(key) !== generation) return { status: "stale" };
1204
+ const failure = {
1205
+ name: packageName(key),
1158
1206
  url,
1159
1207
  error
1160
- });
1208
+ };
1209
+ this.failures.push(failure);
1210
+ return {
1211
+ status: "failed",
1212
+ failure
1213
+ };
1161
1214
  }
1162
- }
1163
- };
1164
- //#endregion
1165
- //#region src/rpc/rpc-correlator.ts
1166
- /**
1167
- * Request/response correlation shared by every RPC proxy: one pending map,
1168
- * res/err settlement, and per-request timeout/transform/cleanup.
1169
- */
1170
- var RpcCorrelator = class {
1171
- counter = 0;
1172
- pending = /* @__PURE__ */ new Map();
1173
- constructor(poster, prefix = "r") {
1174
- this.poster = poster;
1175
- this.prefix = prefix;
1176
- }
1177
- nextId() {
1178
- return `${this.prefix}${++this.counter}`;
1179
- }
1180
- /** Settle the pending request a res/err refers to; a missing id is a no-op. */
1181
- handleMessage(message) {
1182
- if (message.k !== "res" && message.k !== "err") return;
1183
- const entry = this.pending.get(message.id);
1184
- if (!entry) return;
1185
- this.pending.delete(message.id);
1186
- if (entry.timer) clearTimeout(entry.timer);
1187
- entry.cleanup?.();
1188
- if (message.k === "res") entry.resolve(entry.transform ? entry.transform(message.value) : message.value);
1189
- else entry.reject(fromErrorInfo(message.error));
1190
- }
1191
- /** Send a request, resolving on its res/err. `build` stamps the generated id. */
1192
- request(build, options = {}) {
1193
- const id = this.nextId();
1194
- const message = build(id);
1195
- const method = message.method;
1196
- const label = typeof method === "string" ? `${message.k} "${method}"` : message.k;
1197
- const promise = new Promise((resolve, reject) => {
1198
- let timer;
1199
- if (options.timeoutMs !== void 0) {
1200
- const timeoutMs = options.timeoutMs;
1201
- timer = setTimeout(() => {
1202
- const entry = this.pending.get(id);
1203
- if (entry) {
1204
- this.pending.delete(id);
1205
- entry.cleanup?.();
1206
- reject(/* @__PURE__ */ new Error(`Reactor worker did not respond to ${label} within ${timeoutMs}ms; the worker may have failed to load`));
1207
- }
1208
- }, timeoutMs);
1209
- }
1210
- this.pending.set(id, {
1211
- resolve,
1212
- reject,
1213
- timer,
1214
- transform: options.transform
1215
- });
1216
- });
1217
- this.poster.post(message);
1218
- const cleanup = options.setup?.(id);
1219
- if (cleanup) {
1220
- const entry = this.pending.get(id);
1221
- if (entry) entry.cleanup = cleanup;
1222
- else cleanup();
1215
+ if (this.generationBySource.get(key) !== generation) return { status: "stale" };
1216
+ const types = /* @__PURE__ */ new Set();
1217
+ for (const removedKey of this.keysBySource.get(key) ?? []) {
1218
+ const removed = this.modulesByKey.get(removedKey);
1219
+ if (removed) types.add(removed.documentModel.global.id);
1220
+ this.modulesByKey.delete(removedKey);
1223
1221
  }
1224
- return promise;
1225
- }
1226
- };
1227
- //#endregion
1228
- //#region src/rpc/message-router.ts
1229
- /**
1230
- * Owns the single transport.onMessage and dispatches each message to the one
1231
- * consumer that owns its kind. Composes the shared RpcCorrelator (res/err) and
1232
- * exposes request/nextId; attach/detach swap the transport for reconnect.
1233
- */
1234
- var MessageRouter = class {
1235
- handlers = /* @__PURE__ */ new Map();
1236
- correlator;
1237
- transport = null;
1238
- detachTransport = () => {};
1239
- constructor(prefix = "r") {
1240
- this.correlator = new RpcCorrelator(this, prefix);
1241
- const settle = (message) => this.correlator.handleMessage(message);
1242
- this.handlers.set("res", settle);
1243
- this.handlers.set("err", settle);
1244
- }
1245
- attach(transport) {
1246
- this.detachTransport();
1247
- this.transport = transport;
1248
- this.detachTransport = transport.onMessage((message) => {
1249
- const msg = message;
1250
- this.handlers.get(msg.k)?.(msg);
1251
- });
1252
- }
1253
- detach() {
1254
- this.detachTransport();
1255
- this.detachTransport = () => {};
1256
- this.transport = null;
1257
- }
1258
- post(message) {
1259
- if (!this.transport) throw new Error("MessageRouter.post called before attach");
1260
- this.transport.post(message);
1261
- }
1262
- /** Register the sole owner of a message kind; throws on a duplicate. */
1263
- on(kind, handler) {
1264
- if (this.handlers.has(kind)) throw new Error(`MessageRouter already has a handler for "${kind}"`);
1265
- const route = handler;
1266
- this.handlers.set(kind, route);
1267
- return () => {
1268
- if (this.handlers.get(kind) === route) this.handlers.delete(kind);
1222
+ for (const type of this.manifestTypesBySource.get(key) ?? []) this.manifestsByType.delete(type);
1223
+ for (const added of this.registerNamespace(key, namespace)) types.add(added);
1224
+ this.loadedUrls.set(key, url);
1225
+ return {
1226
+ status: "replaced",
1227
+ types
1269
1228
  };
1270
1229
  }
1271
- request(build, options) {
1272
- return this.correlator.request(build, options);
1273
- }
1274
- nextId() {
1275
- return this.correlator.nextId();
1230
+ async importNamespace(key, url) {
1231
+ if (key.startsWith(SOURCE_KEY_PREFIX)) return this.importPackage(url);
1232
+ return this.importPackage(await this.moduleGraph.resolve(url));
1233
+ }
1234
+ /** Registers a namespace as the key's whole contribution; returns its module types. */
1235
+ registerNamespace(key, namespace) {
1236
+ const keys = /* @__PURE__ */ new Set();
1237
+ const manifestTypes = /* @__PURE__ */ new Set();
1238
+ const types = /* @__PURE__ */ new Set();
1239
+ for (const value of Object.values(namespace)) if (isDocumentModelModule(value)) {
1240
+ const k = moduleKey(value);
1241
+ this.modulesByKey.set(k, value);
1242
+ keys.add(k);
1243
+ types.add(value.documentModel.global.id);
1244
+ }
1245
+ for (const manifest of manifestsOf(namespace)) {
1246
+ this.manifestsByType.set(manifest.documentType, manifest);
1247
+ manifestTypes.add(manifest.documentType);
1248
+ }
1249
+ this.keysBySource.set(key, keys);
1250
+ this.manifestTypesBySource.set(key, manifestTypes);
1251
+ return types;
1276
1252
  }
1277
1253
  };
1254
+ function sourceKey(source) {
1255
+ return `${SOURCE_KEY_PREFIX}${source.name}`;
1256
+ }
1278
1257
  //#endregion
1279
- export { FORWARDED_BUS_EVENT_TYPES, FORWARDED_EVENT_TYPES, KeyedListeners, Listeners, MessageRouter, RPC_DEFAULT_TIMEOUT_MS, RPC_PROTOCOL_VERSION, ReactorEventBusProxy, ReactorHost, ReactorHostServer, RpcCorrelator, SYNC_STATUS_CHANGED_EVENT, SubscriptionStore, SyncManagerProxy, WorkerPackageLoader, connectReactorClient, createCorrelatedSubscriptions, createInspectorProxy, createLiveQueryProxy, createPortTransport, createReactorClientProxy, createReactorEventBusProxy, createRelationalPgliteProxy, createSyncManagerProxy, createWorkerAdminClient, fromErrorInfo, hostResponder, opChannel, postReactorIdentity, toErrorInfo, toVoid };
1258
+ export { FORWARDED_BUS_EVENT_TYPES, FORWARDED_EVENT_TYPES, KeyedListeners, Listeners, MessageRouter, ModuleGraph, RETIRED_WORKER_RELOAD_REASON, RPC_DEFAULT_TIMEOUT_MS, RPC_PROTOCOL_VERSION, ReactorEventBusProxy, ReactorHost, ReactorHostServer, RpcCorrelator, SYNC_REMOTES_CHANGED_EVENT, SYNC_STATUS_CHANGED_EVENT, SubscriptionStore, SyncManagerProxy, WorkerPackageLoader, connectReactorClient, createCorrelatedSubscriptions, createInspectorProxy, createLiveQueryProxy, createPortTransport, createReactorClientProxy, createReactorEventBusProxy, createRelationalPgliteProxy, createSyncManagerProxy, createWorkerAdminClient, describeLoadFailure, dispatchInspectorOp, dispatchSyncInspectionOp, fromErrorInfo, hostResponder, isFingerprintMismatchReload, isSyncInspectionOp, localSyncPeerHandlers, opChannel, postReactorIdentity, resolveSharedSpecifier, sendAdoptSyncPeer, sendRemoveSyncPeer, toErrorInfo, toVoid };
1280
1259
 
1281
1260
  //# sourceMappingURL=index.js.map