@powerhousedao/reactor-browser 6.2.3-dev.43 → 6.2.3-dev.45

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.
@@ -1,43 +1,7 @@
1
1
  import { t as RegistryClient } from "../../client-Cq5avLW5.js";
2
2
  import { DriveCollectionId, ReactorEventTypes, SyncEventTypes, createPeerAgreement } from "@powerhousedao/reactor";
3
- import { normalizeDocumentModelVersion } from "@powerhousedao/shared/document-model";
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
4
  import { rewritePackageSource } from "@powerhousedao/shared/connect";
5
- //#region src/rpc/listeners.ts
6
- var KeyedListeners = class {
7
- map = /* @__PURE__ */ new Map();
8
- add(key, fn) {
9
- let set = this.map.get(key);
10
- if (!set) {
11
- set = /* @__PURE__ */ new Set();
12
- this.map.set(key, set);
13
- }
14
- set.add(fn);
15
- return () => {
16
- const current = this.map.get(key);
17
- if (!current) return;
18
- current.delete(fn);
19
- if (current.size === 0) this.map.delete(key);
20
- };
21
- }
22
- emit(key, ...a) {
23
- const set = this.map.get(key);
24
- if (!set) return;
25
- for (const fn of [...set]) fn(...a);
26
- }
27
- emitAll(...a) {
28
- for (const set of [...this.map.values()]) for (const fn of [...set]) fn(...a);
29
- }
30
- };
31
- var Listeners = class {
32
- keyed = new KeyedListeners();
33
- add(fn) {
34
- return this.keyed.add(null, fn);
35
- }
36
- emit(...a) {
37
- this.keyed.emit(null, ...a);
38
- }
39
- };
40
- //#endregion
41
5
  //#region src/rpc/op-channel.ts
42
6
  const RPC_DEFAULT_TIMEOUT_MS = 3e4;
43
7
  function toVoid(promise) {
@@ -60,7 +24,7 @@ function opChannel(router, kind, timeoutMs = RPC_DEFAULT_TIMEOUT_MS) {
60
24
  /** Worker lifecycle channel (info/restart/clearStorage/migrate) over the shared router. */
61
25
  function createWorkerAdminClient(router) {
62
26
  let migrationState = { status: "idle" };
63
- const migrationListeners = new Listeners();
27
+ const migrationListeners = new Listeners$1();
64
28
  router.on("migration", (msg) => {
65
29
  migrationState = msg.state;
66
30
  migrationListeners.emit();
@@ -80,236 +44,6 @@ function createWorkerAdminClient(router) {
80
44
  };
81
45
  }
82
46
  //#endregion
83
- //#region src/rpc/error-info.ts
84
- const MAX_STACK_LENGTH = 8192;
85
- const MAX_CAUSE_DEPTH = 8;
86
- function toErrorInfo(err, depth = 0) {
87
- if (depth > MAX_CAUSE_DEPTH) return {
88
- name: "Error",
89
- message: "cause chain truncated"
90
- };
91
- if (err instanceof Error) {
92
- const info = {
93
- name: err.name || "Error",
94
- message: err.message
95
- };
96
- if (typeof err.stack === "string") info.stack = err.stack.length > MAX_STACK_LENGTH ? err.stack.slice(0, MAX_STACK_LENGTH) : err.stack;
97
- if (err.cause !== void 0) info.cause = toErrorInfo(err.cause, depth + 1);
98
- return info;
99
- }
100
- if (typeof err === "string") return {
101
- name: "Error",
102
- message: err
103
- };
104
- if (err && typeof err === "object") {
105
- const record = err;
106
- return {
107
- name: typeof record.name === "string" ? record.name : "Error",
108
- message: typeof record.message === "string" ? record.message : safeStringify(err)
109
- };
110
- }
111
- return {
112
- name: "Error",
113
- message: safeStringify(err)
114
- };
115
- }
116
- function safeStringify(value) {
117
- if (value === null || value === void 0) return String(value);
118
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
119
- try {
120
- return JSON.stringify(value);
121
- } catch {
122
- return "[unserializable]";
123
- }
124
- }
125
- function fromErrorInfo(info) {
126
- const err = new Error(info.message);
127
- Object.defineProperty(err, "name", {
128
- value: info.name,
129
- configurable: true,
130
- writable: true
131
- });
132
- if (info.stack !== void 0) err.stack = info.stack;
133
- if (info.cause !== void 0) Object.defineProperty(err, "cause", {
134
- value: fromErrorInfo(info.cause),
135
- configurable: true,
136
- writable: true
137
- });
138
- return err;
139
- }
140
- //#endregion
141
- //#region src/rpc/paging.ts
142
- function isPageableResult(value) {
143
- return value !== null && typeof value === "object" && typeof value.next === "function";
144
- }
145
- function hasNextToken(value) {
146
- return value !== null && typeof value === "object" && typeof value.nextToken === "string";
147
- }
148
- function dehydratePage(value, registerCursor) {
149
- if (!isPageableResult(value)) return value;
150
- const { next, ...rest } = value;
151
- return {
152
- ...rest,
153
- nextToken: registerCursor(next)
154
- };
155
- }
156
- function rehydratePage(value, fetchPage) {
157
- if (!hasNextToken(value)) return value;
158
- const { nextToken, ...rest } = value;
159
- return {
160
- ...rest,
161
- next: () => fetchPage(nextToken)
162
- };
163
- }
164
- //#endregion
165
- //#region src/rpc/subscription.ts
166
- var SubscriptionStore = class {
167
- map = /* @__PURE__ */ new Map();
168
- set(id, unsubscribe) {
169
- this.map.set(id, unsubscribe);
170
- }
171
- get(id) {
172
- return this.map.get(id);
173
- }
174
- delete(id) {
175
- this.map.delete(id);
176
- }
177
- end(id) {
178
- const unsubscribe = this.map.get(id);
179
- if (unsubscribe) {
180
- this.map.delete(id);
181
- unsubscribe();
182
- }
183
- }
184
- drain() {
185
- for (const unsubscribe of this.map.values()) unsubscribe();
186
- this.map.clear();
187
- }
188
- };
189
- function createCorrelatedSubscriptions(router, config) {
190
- let counter = 0;
191
- const subs = /* @__PURE__ */ new Map();
192
- router.on(config.eventKind, (message) => {
193
- const sub = subs.get(message.id);
194
- if (sub) config.onEvent(sub, message);
195
- });
196
- router.on(config.errKind, (message) => {
197
- const id = message.id;
198
- const sub = subs.get(id);
199
- if (sub) {
200
- subs.delete(id);
201
- router.post(config.close(id));
202
- config.onError(sub, message);
203
- }
204
- });
205
- return { subscribe(sub, open) {
206
- const id = `${config.idPrefix}${++counter}`;
207
- subs.set(id, sub);
208
- router.post(open(id));
209
- return () => {
210
- subs.delete(id);
211
- router.post(config.close(id));
212
- };
213
- } };
214
- }
215
- //#endregion
216
- //#region src/rpc/client-proxy.ts
217
- function isAbortSignal(value) {
218
- return typeof value === "object" && value !== null && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
219
- }
220
- function createReactorClientProxy(router, options = {}) {
221
- const registry = options.registry;
222
- function fetchPage(token) {
223
- return router.request((id) => ({
224
- k: "page",
225
- id,
226
- token
227
- }), { transform: rehydrate });
228
- }
229
- function rehydrate(value) {
230
- return rehydratePage(value, fetchPage);
231
- }
232
- const changeSubs = createCorrelatedSubscriptions(router, {
233
- idPrefix: "sub",
234
- eventKind: "event",
235
- errKind: "sub-err",
236
- onEvent: (callback, msg) => callback(msg.change),
237
- onError: (_callback, msg) => console.error("Reactor subscription failed:", fromErrorInfo(msg.error)),
238
- close: (id) => ({
239
- k: "unsub",
240
- id
241
- })
242
- });
243
- router.on("reload", (msg) => {
244
- options.onReload?.(msg.reason, msg.workerGen);
245
- });
246
- const call = (method, args) => {
247
- let abortAt;
248
- for (let i = 0; i < args.length; i++) if (isAbortSignal(args[i])) abortAt = i;
249
- let wire = args;
250
- if (abortAt !== void 0) {
251
- wire = args.slice();
252
- wire[abortAt] = void 0;
253
- }
254
- return router.request((id) => ({
255
- k: "req",
256
- id,
257
- method,
258
- args: wire,
259
- abortAt
260
- }), {
261
- transform: rehydrate,
262
- setup: (id) => {
263
- if (abortAt === void 0) return;
264
- const signal = args[abortAt];
265
- const sendAbort = () => router.post({
266
- k: "abort",
267
- targetId: id
268
- });
269
- if (signal.aborted) {
270
- sendAbort();
271
- return;
272
- }
273
- signal.addEventListener("abort", sendAbort, { once: true });
274
- return () => signal.removeEventListener("abort", sendAbort);
275
- }
276
- });
277
- };
278
- const subscribe = (search, callback, view) => changeSubs.subscribe(callback, (id) => ({
279
- k: "sub",
280
- id,
281
- search,
282
- view
283
- }));
284
- const forwarders = /* @__PURE__ */ new Map();
285
- const forwarder = (method) => {
286
- let fn = forwarders.get(method);
287
- if (!fn) {
288
- fn = (...args) => call(method, args);
289
- forwarders.set(method, fn);
290
- }
291
- return fn;
292
- };
293
- const drives = new Proxy({}, { get: (_target, prop) => typeof prop === "string" ? forwarder(`drives.${prop}`) : void 0 });
294
- return new Proxy({}, { get(_target, prop) {
295
- if (typeof prop !== "string" || prop === "then") return;
296
- if (prop === "drives") return drives;
297
- if (prop === "subscribe") return subscribe;
298
- if (registry) {
299
- if (prop === "getDocumentModelModule") return (documentType) => Promise.resolve().then(() => registry.getModule(documentType));
300
- if (prop === "getDocumentModelModuleForDocument") return (document) => Promise.resolve().then(() => registry.getModule(document.header.documentType, normalizeDocumentModelVersion(document.state.document?.version)));
301
- if (prop === "getDocumentModelModules") return (_namespace, paging) => Promise.resolve({
302
- results: registry.getAllModules(),
303
- options: paging ?? {
304
- cursor: "",
305
- limit: Number.MAX_SAFE_INTEGER
306
- }
307
- });
308
- }
309
- return forwarder(prop);
310
- } });
311
- }
312
- //#endregion
313
47
  //#region src/rpc/inspector-proxy.ts
314
48
  function createInspectorProxy(router) {
315
49
  const ops = opChannel(router, "inspector-op");
@@ -328,61 +62,14 @@ function createInspectorProxy(router) {
328
62
  };
329
63
  }
330
64
  //#endregion
331
- //#region src/rpc/protocol.ts
332
- const RPC_PROTOCOL_VERSION = 2;
333
- /** Error reply kind for a client message kind, so it reaches the right registry. */
334
- function responseErrorKind(k) {
335
- if (k === "sub") return "sub-err";
336
- if (k === "sub-live") return "live-err";
337
- return "err";
338
- }
339
- //#endregion
340
- //#region src/rpc/host-reply.ts
341
- const defaultOk = () => ({ ok: true });
342
- function hostResponder(transport) {
343
- const ok = (id, value = { ok: true }) => {
344
- transport.post({
345
- k: "res",
346
- id,
347
- value
348
- });
349
- };
350
- const err = (id, error) => {
351
- transport.post({
352
- k: "err",
353
- id,
354
- error: toErrorInfo(error)
355
- });
356
- };
357
- return {
358
- ok,
359
- err,
360
- errForKind(message, error) {
361
- if (!("id" in message)) return;
362
- transport.post({
363
- k: responseErrorKind(message.k),
364
- id: message.id,
365
- error: toErrorInfo(error)
366
- });
367
- },
368
- async run(id, body, mapOk = defaultOk) {
369
- try {
370
- ok(id, mapOk(await body()));
371
- } catch (error) {
372
- err(id, error);
373
- }
374
- }
375
- };
376
- }
377
- //#endregion
378
65
  //#region src/rpc/live-query-proxy.ts
379
66
  function createLiveQueryProxy(router) {
380
- const subs = createCorrelatedSubscriptions(router, {
67
+ const subs = createCorrelatedSubscriptions$1(router, {
381
68
  idPrefix: "live",
382
69
  eventKind: "event-live",
383
70
  errKind: "live-err",
384
71
  onEvent: (sub, msg) => sub.onResults(msg.results),
385
- onError: (sub, msg) => sub.onError?.(fromErrorInfo(msg.error)),
72
+ onError: (sub, msg) => sub.onError?.(fromErrorInfo$1(msg.error)),
386
73
  close: (id) => ({
387
74
  k: "unsub-live",
388
75
  id
@@ -484,9 +171,9 @@ function channelUrl(meta) {
484
171
  var SyncManagerProxy = class {
485
172
  ops;
486
173
  connectionStates = /* @__PURE__ */ new Map();
487
- connectionListeners = new KeyedListeners();
174
+ connectionListeners = new KeyedListeners$1();
488
175
  syncStatuses = /* @__PURE__ */ new Map();
489
- syncStatusListeners = new Listeners();
176
+ syncStatusListeners = new Listeners$1();
490
177
  remotes = [];
491
178
  basis;
492
179
  seedPromise = null;
@@ -667,7 +354,7 @@ const FORWARDED_BUS_EVENT_TYPES = [...FORWARDED_EVENT_TYPES, SYNC_STATUS_CHANGED
667
354
  /** Tab-side IEventBus over bus-event; emit() is unsupported (the worker emits). */
668
355
  var ReactorEventBusProxy = class {
669
356
  forwardedTypes = new Set(FORWARDED_BUS_EVENT_TYPES);
670
- subscribers = new KeyedListeners();
357
+ subscribers = new KeyedListeners$1();
671
358
  constructor(router) {
672
359
  router.on("bus-event", (msg) => {
673
360
  this.subscribers.emit(msg.eventType, msg.eventType, msg.event);
@@ -688,7 +375,7 @@ function createReactorEventBusProxy(router) {
688
375
  //#endregion
689
376
  //#region src/rpc/connect-reactor.ts
690
377
  function connectReactorClient(router, hello, onReload, registry) {
691
- const client = createReactorClientProxy(router, {
378
+ const client = createReactorClientProxy$1(router, {
692
379
  onReload,
693
380
  registry
694
381
  });
@@ -708,143 +395,6 @@ function postReactorIdentity(router, user) {
708
395
  });
709
396
  }
710
397
  //#endregion
711
- //#region src/rpc/host-server.ts
712
- const MAX_PENDING_PAGES = 1e3;
713
- var ReactorHostServer = class {
714
- client;
715
- transport;
716
- reply;
717
- aborters = /* @__PURE__ */ new Map();
718
- subscriptions = new SubscriptionStore();
719
- pages = /* @__PURE__ */ new Map();
720
- pageCounter = 0;
721
- detach = () => {};
722
- constructor(client, transport) {
723
- this.client = client;
724
- this.transport = transport;
725
- this.reply = hostResponder(transport);
726
- }
727
- start() {
728
- this.detach = this.transport.onMessage((message) => {
729
- this.handleMessage(message);
730
- });
731
- }
732
- stop() {
733
- this.detach();
734
- this.subscriptions.drain();
735
- this.aborters.clear();
736
- this.pages.clear();
737
- }
738
- async handleMessage(message) {
739
- try {
740
- switch (message.k) {
741
- case "req":
742
- await this.handleRequest(message);
743
- return;
744
- case "page":
745
- await this.handlePage(message);
746
- return;
747
- case "abort":
748
- this.aborters.get(message.targetId)?.abort();
749
- return;
750
- case "sub":
751
- this.handleSubscribe(message);
752
- return;
753
- case "unsub":
754
- this.subscriptions.end(message.id);
755
- return;
756
- }
757
- } catch (error) {
758
- this.reply.errForKind(message, error);
759
- }
760
- }
761
- async handleRequest(message) {
762
- let args = message.args;
763
- let controller;
764
- if (message.abortAt !== void 0) {
765
- controller = new AbortController();
766
- this.aborters.set(message.id, controller);
767
- args = message.args.slice();
768
- args[message.abortAt] = controller.signal;
769
- }
770
- try {
771
- const value = await this.resolveMethod(message.method)(...args);
772
- this.reply.ok(message.id, this.prepareResult(value));
773
- } catch (error) {
774
- this.reply.err(message.id, error);
775
- } finally {
776
- if (controller) this.aborters.delete(message.id);
777
- }
778
- }
779
- async handlePage(message) {
780
- const next = this.pages.get(message.token);
781
- this.pages.delete(message.token);
782
- if (!next) {
783
- this.reply.err(message.id, /* @__PURE__ */ new Error("Paged cursor already consumed or expired"));
784
- return;
785
- }
786
- try {
787
- const value = await next();
788
- this.reply.ok(message.id, this.prepareResult(value));
789
- } catch (error) {
790
- this.reply.err(message.id, error);
791
- }
792
- }
793
- handleSubscribe(message) {
794
- const unsubscribe = this.client.subscribe(message.search, (change) => this.transport.post({
795
- k: "event",
796
- id: message.id,
797
- change
798
- }), message.view);
799
- this.subscriptions.set(message.id, unsubscribe);
800
- }
801
- prepareResult(value) {
802
- return dehydratePage(value, (next) => {
803
- const token = `p${++this.pageCounter}`;
804
- this.pages.set(token, next);
805
- if (this.pages.size > MAX_PENDING_PAGES) {
806
- const oldest = this.pages.keys().next().value;
807
- if (oldest !== void 0) this.pages.delete(oldest);
808
- }
809
- return token;
810
- });
811
- }
812
- resolveMethod(path) {
813
- if (path.startsWith("drives.")) {
814
- const name = path.slice(7);
815
- const fn = this.client.drives[name];
816
- if (typeof fn !== "function") throw new Error(`Unknown drive method: ${name}`);
817
- return fn.bind(this.client.drives);
818
- }
819
- const fn = this.client[path];
820
- if (typeof fn !== "function") throw new Error(`Unknown reactor method: ${path}`);
821
- return fn.bind(this.client);
822
- }
823
- };
824
- //#endregion
825
- //#region src/rpc/transport.ts
826
- function createPortTransport(port) {
827
- port.start();
828
- port.addEventListener("messageerror", (event) => {
829
- console.error("[rpc transport] failed to deserialize message", event);
830
- });
831
- return {
832
- post(message) {
833
- port.postMessage(message);
834
- },
835
- onMessage(listener) {
836
- const handler = (event) => {
837
- listener(event.data);
838
- };
839
- port.addEventListener("message", handler);
840
- return () => port.removeEventListener("message", handler);
841
- },
842
- close() {
843
- port.close();
844
- }
845
- };
846
- }
847
- //#endregion
848
398
  //#region src/rpc/reactor-host.ts
849
399
  function isDataMessage(msg) {
850
400
  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";
@@ -887,11 +437,12 @@ var ReactorHost = class {
887
437
  let server = null;
888
438
  let ready = false;
889
439
  const buffer = [];
890
- const liveSubs = new SubscriptionStore();
891
- const reply = hostResponder(transport);
440
+ const liveSubs = new SubscriptionStore$1();
441
+ const reply = hostResponder$1(transport);
892
442
  const ensureServer = async (construct) => {
893
443
  if (server) return;
894
- server = new ReactorHostServer(await this.resolveClient(construct), transport);
444
+ const client = await this.resolveClient(construct);
445
+ server = new ReactorHostServer$1(client, transport);
895
446
  };
896
447
  const drainBuffer = async () => {
897
448
  while (buffer.length > 0) {
@@ -977,7 +528,7 @@ var ReactorHost = class {
977
528
  return dispose;
978
529
  }
979
530
  connectPort(port) {
980
- return this.connect(createPortTransport(port));
531
+ return this.connect(createPortTransport$1(port));
981
532
  }
982
533
  broadcastBusEvent(eventType, event) {
983
534
  for (const transport of this.clients) transport.post({
@@ -1023,7 +574,7 @@ var ReactorHost = class {
1023
574
  bootedAtMs: this.bootedAtMs,
1024
575
  connectedClients: this.connectionCount,
1025
576
  appBuildId: this.baseline?.appBuildId ?? this.options.appBuildId ?? "unknown",
1026
- rpcProtocolVersion: this.baseline?.rpcProtocolVersion ?? 2,
577
+ rpcProtocolVersion: this.baseline?.rpcProtocolVersion ?? RPC_PROTOCOL_VERSION$1,
1027
578
  featureFlags: this.baseline?.featureFlags ?? ""
1028
579
  };
1029
580
  reply.ok(message.id, info);
@@ -1211,122 +762,6 @@ var WorkerPackageLoader = class {
1211
762
  }
1212
763
  };
1213
764
  //#endregion
1214
- //#region src/rpc/rpc-correlator.ts
1215
- /**
1216
- * Request/response correlation shared by every RPC proxy: one pending map,
1217
- * res/err settlement, and per-request timeout/transform/cleanup.
1218
- */
1219
- var RpcCorrelator = class {
1220
- poster;
1221
- prefix;
1222
- counter = 0;
1223
- pending = /* @__PURE__ */ new Map();
1224
- constructor(poster, prefix = "r") {
1225
- this.poster = poster;
1226
- this.prefix = prefix;
1227
- }
1228
- nextId() {
1229
- return `${this.prefix}${++this.counter}`;
1230
- }
1231
- /** Settle the pending request a res/err refers to; a missing id is a no-op. */
1232
- handleMessage(message) {
1233
- if (message.k !== "res" && message.k !== "err") return;
1234
- const entry = this.pending.get(message.id);
1235
- if (!entry) return;
1236
- this.pending.delete(message.id);
1237
- if (entry.timer) clearTimeout(entry.timer);
1238
- entry.cleanup?.();
1239
- if (message.k === "res") entry.resolve(entry.transform ? entry.transform(message.value) : message.value);
1240
- else entry.reject(fromErrorInfo(message.error));
1241
- }
1242
- /** Send a request, resolving on its res/err. `build` stamps the generated id. */
1243
- request(build, options = {}) {
1244
- const id = this.nextId();
1245
- const message = build(id);
1246
- const method = message.method;
1247
- const label = typeof method === "string" ? `${message.k} "${method}"` : message.k;
1248
- const promise = new Promise((resolve, reject) => {
1249
- let timer;
1250
- if (options.timeoutMs !== void 0) {
1251
- const timeoutMs = options.timeoutMs;
1252
- timer = setTimeout(() => {
1253
- const entry = this.pending.get(id);
1254
- if (entry) {
1255
- this.pending.delete(id);
1256
- entry.cleanup?.();
1257
- reject(/* @__PURE__ */ new Error(`Reactor worker did not respond to ${label} within ${timeoutMs}ms; the worker may have failed to load`));
1258
- }
1259
- }, timeoutMs);
1260
- }
1261
- this.pending.set(id, {
1262
- resolve,
1263
- reject,
1264
- timer,
1265
- transform: options.transform
1266
- });
1267
- });
1268
- this.poster.post(message);
1269
- const cleanup = options.setup?.(id);
1270
- if (cleanup) {
1271
- const entry = this.pending.get(id);
1272
- if (entry) entry.cleanup = cleanup;
1273
- else cleanup();
1274
- }
1275
- return promise;
1276
- }
1277
- };
1278
- //#endregion
1279
- //#region src/rpc/message-router.ts
1280
- /**
1281
- * Owns the single transport.onMessage and dispatches each message to the one
1282
- * consumer that owns its kind. Composes the shared RpcCorrelator (res/err) and
1283
- * exposes request/nextId; attach/detach swap the transport for reconnect.
1284
- */
1285
- var MessageRouter = class {
1286
- handlers = /* @__PURE__ */ new Map();
1287
- correlator;
1288
- transport = null;
1289
- detachTransport = () => {};
1290
- constructor(prefix = "r") {
1291
- this.correlator = new RpcCorrelator(this, prefix);
1292
- const settle = (message) => this.correlator.handleMessage(message);
1293
- this.handlers.set("res", settle);
1294
- this.handlers.set("err", settle);
1295
- }
1296
- attach(transport) {
1297
- this.detachTransport();
1298
- this.transport = transport;
1299
- this.detachTransport = transport.onMessage((message) => {
1300
- const msg = message;
1301
- this.handlers.get(msg.k)?.(msg);
1302
- });
1303
- }
1304
- detach() {
1305
- this.detachTransport();
1306
- this.detachTransport = () => {};
1307
- this.transport = null;
1308
- }
1309
- post(message) {
1310
- if (!this.transport) throw new Error("MessageRouter.post called before attach");
1311
- this.transport.post(message);
1312
- }
1313
- /** Register the sole owner of a message kind; throws on a duplicate. */
1314
- on(kind, handler) {
1315
- if (this.handlers.has(kind)) throw new Error(`MessageRouter already has a handler for "${kind}"`);
1316
- const route = handler;
1317
- this.handlers.set(kind, route);
1318
- return () => {
1319
- if (this.handlers.get(kind) === route) this.handlers.delete(kind);
1320
- };
1321
- }
1322
- request(build, options) {
1323
- return this.correlator.request(build, options);
1324
- }
1325
- nextId() {
1326
- return this.correlator.nextId();
1327
- }
1328
- };
1329
- //#endregion
1330
765
  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 };
1331
766
 
1332
767
  //# sourceMappingURL=index.js.map