@xyo-network/bridge-pub-sub 2.99.2 → 2.99.4

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 (149) hide show
  1. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.cts +11 -0
  2. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.cts.map +1 -0
  3. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.mts +11 -0
  4. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.mts.map +1 -0
  5. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.ts +11 -0
  6. package/dist/neutral/AbstractModuleHost/AbstractModuleHost.d.ts.map +1 -0
  7. package/dist/neutral/AbstractModuleHost/index.d.cts +2 -0
  8. package/dist/neutral/AbstractModuleHost/index.d.cts.map +1 -0
  9. package/dist/neutral/AbstractModuleHost/index.d.mts +2 -0
  10. package/dist/neutral/AbstractModuleHost/index.d.mts.map +1 -0
  11. package/dist/neutral/AbstractModuleHost/index.d.ts +2 -0
  12. package/dist/neutral/AbstractModuleHost/index.d.ts.map +1 -0
  13. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.cts +144 -0
  14. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.cts.map +1 -0
  15. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.mts +144 -0
  16. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.mts.map +1 -0
  17. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.ts +144 -0
  18. package/dist/neutral/AsyncQueryBus/AsyncQueryBusBase.d.ts.map +1 -0
  19. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.cts +33 -0
  20. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.cts.map +1 -0
  21. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.mts +33 -0
  22. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.mts.map +1 -0
  23. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.ts +33 -0
  24. package/dist/neutral/AsyncQueryBus/AsyncQueryBusClient.d.ts.map +1 -0
  25. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.cts +72 -0
  26. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.cts.map +1 -0
  27. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.mts +72 -0
  28. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.mts.map +1 -0
  29. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.ts +72 -0
  30. package/dist/neutral/AsyncQueryBus/AsyncQueryBusHost.d.ts.map +1 -0
  31. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.cts +12 -0
  32. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.cts.map +1 -0
  33. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.mts +12 -0
  34. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.mts.map +1 -0
  35. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.ts +12 -0
  36. package/dist/neutral/AsyncQueryBus/ModuleHost/ModuleHost.d.ts.map +1 -0
  37. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.cts +2 -0
  38. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.cts.map +1 -0
  39. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.mts +2 -0
  40. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.mts.map +1 -0
  41. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.ts +2 -0
  42. package/dist/neutral/AsyncQueryBus/ModuleHost/index.d.ts.map +1 -0
  43. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts +19 -0
  44. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.cts.map +1 -0
  45. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts +19 -0
  46. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.mts.map +1 -0
  47. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts +19 -0
  48. package/dist/neutral/AsyncQueryBus/ModuleProxy/ModuleProxy.d.ts.map +1 -0
  49. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.cts +2 -0
  50. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.cts.map +1 -0
  51. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.mts +2 -0
  52. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.mts.map +1 -0
  53. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.ts +2 -0
  54. package/dist/neutral/AsyncQueryBus/ModuleProxy/index.d.ts.map +1 -0
  55. package/dist/neutral/AsyncQueryBus/index.d.cts +6 -0
  56. package/dist/neutral/AsyncQueryBus/index.d.cts.map +1 -0
  57. package/dist/neutral/AsyncQueryBus/index.d.mts +6 -0
  58. package/dist/neutral/AsyncQueryBus/index.d.mts.map +1 -0
  59. package/dist/neutral/AsyncQueryBus/index.d.ts +6 -0
  60. package/dist/neutral/AsyncQueryBus/index.d.ts.map +1 -0
  61. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.cts +14 -0
  62. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.cts.map +1 -0
  63. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.mts +14 -0
  64. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.mts.map +1 -0
  65. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.ts +14 -0
  66. package/dist/neutral/AsyncQueryBus/model/BaseConfig.d.ts.map +1 -0
  67. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.cts +9 -0
  68. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.cts.map +1 -0
  69. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.mts +9 -0
  70. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.mts.map +1 -0
  71. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.ts +9 -0
  72. package/dist/neutral/AsyncQueryBus/model/ClientConfig.d.ts.map +1 -0
  73. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.cts +22 -0
  74. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.cts.map +1 -0
  75. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.mts +22 -0
  76. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.mts.map +1 -0
  77. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.ts +22 -0
  78. package/dist/neutral/AsyncQueryBus/model/HostConfig.d.ts.map +1 -0
  79. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.cts +12 -0
  80. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.cts.map +1 -0
  81. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.mts +12 -0
  82. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.mts.map +1 -0
  83. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.ts +12 -0
  84. package/dist/neutral/AsyncQueryBus/model/IntersectConfig.d.ts.map +1 -0
  85. package/dist/neutral/AsyncQueryBus/model/Params.d.cts +12 -0
  86. package/dist/neutral/AsyncQueryBus/model/Params.d.cts.map +1 -0
  87. package/dist/neutral/AsyncQueryBus/model/Params.d.mts +12 -0
  88. package/dist/neutral/AsyncQueryBus/model/Params.d.mts.map +1 -0
  89. package/dist/neutral/AsyncQueryBus/model/Params.d.ts +12 -0
  90. package/dist/neutral/AsyncQueryBus/model/Params.d.ts.map +1 -0
  91. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.cts +3 -0
  92. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.cts.map +1 -0
  93. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.mts +3 -0
  94. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.mts.map +1 -0
  95. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.ts +3 -0
  96. package/dist/neutral/AsyncQueryBus/model/QueryStatus.d.ts.map +1 -0
  97. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.cts +15 -0
  98. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.cts.map +1 -0
  99. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.mts +15 -0
  100. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.mts.map +1 -0
  101. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.ts +15 -0
  102. package/dist/neutral/AsyncQueryBus/model/SearchableStorage.d.ts.map +1 -0
  103. package/dist/neutral/AsyncQueryBus/model/index.d.cts +8 -0
  104. package/dist/neutral/AsyncQueryBus/model/index.d.cts.map +1 -0
  105. package/dist/neutral/AsyncQueryBus/model/index.d.mts +8 -0
  106. package/dist/neutral/AsyncQueryBus/model/index.d.mts.map +1 -0
  107. package/dist/neutral/AsyncQueryBus/model/index.d.ts +8 -0
  108. package/dist/neutral/AsyncQueryBus/model/index.d.ts.map +1 -0
  109. package/dist/neutral/Config.d.cts +15 -0
  110. package/dist/neutral/Config.d.cts.map +1 -0
  111. package/dist/neutral/Config.d.mts +15 -0
  112. package/dist/neutral/Config.d.mts.map +1 -0
  113. package/dist/neutral/Config.d.ts +15 -0
  114. package/dist/neutral/Config.d.ts.map +1 -0
  115. package/dist/neutral/Params.d.cts +8 -0
  116. package/dist/neutral/Params.d.cts.map +1 -0
  117. package/dist/neutral/Params.d.mts +8 -0
  118. package/dist/neutral/Params.d.mts.map +1 -0
  119. package/dist/neutral/Params.d.ts +8 -0
  120. package/dist/neutral/Params.d.ts.map +1 -0
  121. package/dist/neutral/PubSubBridge.d.cts +34 -0
  122. package/dist/neutral/PubSubBridge.d.cts.map +1 -0
  123. package/dist/neutral/PubSubBridge.d.mts +34 -0
  124. package/dist/neutral/PubSubBridge.d.mts.map +1 -0
  125. package/dist/neutral/PubSubBridge.d.ts +34 -0
  126. package/dist/neutral/PubSubBridge.d.ts.map +1 -0
  127. package/dist/neutral/PubSubBridgeModuleResolver.d.cts +10 -0
  128. package/dist/neutral/PubSubBridgeModuleResolver.d.cts.map +1 -0
  129. package/dist/neutral/PubSubBridgeModuleResolver.d.mts +10 -0
  130. package/dist/neutral/PubSubBridgeModuleResolver.d.mts.map +1 -0
  131. package/dist/neutral/PubSubBridgeModuleResolver.d.ts +10 -0
  132. package/dist/neutral/PubSubBridgeModuleResolver.d.ts.map +1 -0
  133. package/dist/neutral/Schema.d.cts +3 -0
  134. package/dist/neutral/Schema.d.cts.map +1 -0
  135. package/dist/neutral/Schema.d.mts +3 -0
  136. package/dist/neutral/Schema.d.mts.map +1 -0
  137. package/dist/neutral/Schema.d.ts +3 -0
  138. package/dist/neutral/Schema.d.ts.map +1 -0
  139. package/dist/neutral/index.cjs +875 -0
  140. package/dist/neutral/index.cjs.map +1 -0
  141. package/dist/neutral/index.d.cts +8 -0
  142. package/dist/neutral/index.d.cts.map +1 -0
  143. package/dist/neutral/index.d.mts +8 -0
  144. package/dist/neutral/index.d.mts.map +1 -0
  145. package/dist/neutral/index.d.ts +8 -0
  146. package/dist/neutral/index.d.ts.map +1 -0
  147. package/dist/neutral/index.js +854 -0
  148. package/dist/neutral/index.js.map +1 -0
  149. package/package.json +32 -32
@@ -0,0 +1,854 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/AbstractModuleHost/AbstractModuleHost.ts
5
+ import { Base } from "@xylabs/object";
6
+ var AbstractModuleHost = class extends Base {
7
+ static {
8
+ __name(this, "AbstractModuleHost");
9
+ }
10
+ };
11
+
12
+ // src/AsyncQueryBus/AsyncQueryBusClient.ts
13
+ import { assertEx as assertEx2 } from "@xylabs/assert";
14
+ import { delay } from "@xylabs/delay";
15
+ import { forget } from "@xylabs/forget";
16
+ import { clearTimeoutEx, setTimeoutEx } from "@xylabs/timer";
17
+ import { isBoundWitnessWithMeta } from "@xyo-network/boundwitness-model";
18
+ import { BoundWitnessDivinerQuerySchema } from "@xyo-network/diviner-boundwitness-model";
19
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
20
+ import { LRUCache as LRUCache2 } from "lru-cache";
21
+
22
+ // src/AsyncQueryBus/AsyncQueryBusBase.ts
23
+ import { assertEx } from "@xylabs/assert";
24
+ import { Base as Base2 } from "@xylabs/object";
25
+ import { isArchivistInstance } from "@xyo-network/archivist-model";
26
+ import { isDivinerInstance } from "@xyo-network/diviner-model";
27
+ import { ResolveHelper } from "@xyo-network/module-model";
28
+ import { Mutex } from "async-mutex";
29
+ import { LRUCache } from "lru-cache";
30
+ var POLLING_FREQUENCY_MIN = 100;
31
+ var POLLING_FREQUENCY_MAX = 6e4;
32
+ var POLLING_FREQUENCY_DEFAULT = 1e3;
33
+ var AsyncQueryBusBase = class extends Base2 {
34
+ static {
35
+ __name(this, "AsyncQueryBusBase");
36
+ }
37
+ _lastState;
38
+ _targetConfigs = {};
39
+ _targetQueries = {};
40
+ _lastResolveFailure = {};
41
+ _queriesArchivist;
42
+ _queriesDiviner;
43
+ _reResolveDelay = 1e3 * 5;
44
+ _resolveMutex = new Mutex();
45
+ _responsesArchivist;
46
+ _responsesDiviner;
47
+ constructor(params) {
48
+ super(params);
49
+ }
50
+ get config() {
51
+ return this.params.config;
52
+ }
53
+ get pollFrequency() {
54
+ const frequency = this.config?.pollFrequency ?? POLLING_FREQUENCY_DEFAULT;
55
+ if (frequency < POLLING_FREQUENCY_MIN || frequency > POLLING_FREQUENCY_MAX) {
56
+ return POLLING_FREQUENCY_DEFAULT;
57
+ }
58
+ return frequency;
59
+ }
60
+ get rootModule() {
61
+ return this.params.rootModule;
62
+ }
63
+ /**
64
+ * A cache of the last offset of the Diviner process per address
65
+ */
66
+ get lastState() {
67
+ const requiredConfig = {
68
+ max: 1e3,
69
+ ttl: 0
70
+ };
71
+ this._lastState = this._lastState ?? new LRUCache(requiredConfig);
72
+ return this._lastState;
73
+ }
74
+ async queriesArchivist() {
75
+ return await this._resolveMutex.runExclusive(async () => {
76
+ this._queriesArchivist = this._queriesArchivist ?? await this.resolve(assertEx(this.config?.intersect?.queries?.archivist, () => "No queries Archivist defined"), isArchivistInstance);
77
+ return this._queriesArchivist;
78
+ });
79
+ }
80
+ async queriesDiviner() {
81
+ return await this._resolveMutex.runExclusive(async () => {
82
+ this._queriesDiviner = this._queriesDiviner ?? await this.resolve(assertEx(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined"), isDivinerInstance);
83
+ return this._queriesDiviner;
84
+ });
85
+ }
86
+ async responsesArchivist() {
87
+ return await this._resolveMutex.runExclusive(async () => {
88
+ this._responsesArchivist = this._responsesArchivist ?? await this.resolve(assertEx(this.config?.intersect?.responses?.archivist, () => "No responses Archivist defined"), isArchivistInstance);
89
+ return this._responsesArchivist;
90
+ });
91
+ }
92
+ async responsesDiviner() {
93
+ return await this._resolveMutex.runExclusive(async () => {
94
+ this._responsesDiviner = this._responsesDiviner ?? await this.resolve(assertEx(this.config?.intersect?.responses?.boundWitnessDiviner, () => "No responses Diviner defined"), isDivinerInstance);
95
+ return this._responsesDiviner;
96
+ });
97
+ }
98
+ /**
99
+ * Commit the internal state of the process. This is similar
100
+ * to a transaction completion in a database and should only be called
101
+ * when results have been successfully persisted to the appropriate
102
+ * external stores.
103
+ * @param address The module address to commit the state for
104
+ * @param nextState The state to commit
105
+ */
106
+ async commitState(address, nextState) {
107
+ await Promise.resolve();
108
+ const lastState = this.lastState.get(address);
109
+ if (lastState && lastState >= nextState)
110
+ return;
111
+ this.lastState.set(address, nextState);
112
+ }
113
+ /**
114
+ * Retrieves the last state of the process. Used to recover state after
115
+ * preemptions, reboots, etc.
116
+ */
117
+ async retrieveState(address) {
118
+ await Promise.resolve();
119
+ const state = this.lastState.get(address);
120
+ if (state === void 0) {
121
+ const newState = Date.now() - 1e3;
122
+ this.lastState.set(address, newState);
123
+ return newState;
124
+ } else {
125
+ return state;
126
+ }
127
+ }
128
+ async resolve(id, typeCheck) {
129
+ if (Date.now() - (this._lastResolveFailure[id] ?? 0) < this._reResolveDelay) {
130
+ return;
131
+ }
132
+ this._lastResolveFailure[id] = Date.now();
133
+ const resolved = await ResolveHelper.resolveModuleIdentifier(this.rootModule, id);
134
+ if (resolved) {
135
+ if (typeCheck(resolved)) {
136
+ delete this._lastResolveFailure[id];
137
+ return resolved;
138
+ } else {
139
+ this.logger?.warn(`Unable to resolve responsesDiviner as correct type [${id}][${resolved?.constructor?.name}]: ${resolved.id}`);
140
+ }
141
+ } else {
142
+ this.logger?.debug(`Unable to resolve queriesArchivist [${id}] [${await ResolveHelper.traceModuleIdentifier(this.rootModule, id)}]`);
143
+ }
144
+ }
145
+ };
146
+
147
+ // src/AsyncQueryBus/model/QueryStatus.ts
148
+ var Pending = "pending";
149
+
150
+ // src/AsyncQueryBus/AsyncQueryBusClient.ts
151
+ var AsyncQueryBusClient = class extends AsyncQueryBusBase {
152
+ static {
153
+ __name(this, "AsyncQueryBusClient");
154
+ }
155
+ _queryCache;
156
+ _pollCount = 0;
157
+ _pollId;
158
+ constructor(params) {
159
+ super(params);
160
+ }
161
+ get queryCacheConfig() {
162
+ const queryCacheConfig = this.config?.queryCache === true ? {} : this.config?.queryCache;
163
+ return {
164
+ max: 100,
165
+ ttl: 1e3 * 60,
166
+ ...queryCacheConfig
167
+ };
168
+ }
169
+ get started() {
170
+ return !!this._pollId;
171
+ }
172
+ /**
173
+ * A cache of queries that have been issued
174
+ */
175
+ get queryCache() {
176
+ const config = this.queryCacheConfig;
177
+ const requiredConfig = {
178
+ noUpdateTTL: false,
179
+ ttlAutopurge: true
180
+ };
181
+ this._queryCache = this._queryCache ?? new LRUCache2({
182
+ ...config,
183
+ ...requiredConfig
184
+ });
185
+ return this._queryCache;
186
+ }
187
+ listeningAddresses() {
188
+ return this._queryCache?.keys();
189
+ }
190
+ async send(address, query, payloads) {
191
+ this.logger?.debug(`Begin issuing query to: ${address}`);
192
+ const $meta = {
193
+ ...query?.$meta,
194
+ destination: [
195
+ address
196
+ ]
197
+ };
198
+ const routedQuery = await PayloadBuilder.build({
199
+ ...query,
200
+ $meta
201
+ });
202
+ const queryArchivist = assertEx2(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
203
+ const routedQueryHash = (
204
+ // Trust the signed hash if it's there
205
+ routedQuery?.$hash ?? // TODO: What is the right way to find the dataHash
206
+ Object.keys(await PayloadBuilder.toDataHashMap([
207
+ routedQuery
208
+ ]))[0]
209
+ );
210
+ this.logger?.debug(`Issuing query: ${routedQueryHash} to: ${address}`);
211
+ const data = payloads ? [
212
+ routedQuery,
213
+ ...payloads
214
+ ] : [
215
+ routedQuery
216
+ ];
217
+ const insertResult = await queryArchivist.insert?.(data);
218
+ this.logger?.debug(`Issued query: ${routedQueryHash} to: ${address}`);
219
+ this.queryCache.set(routedQueryHash, Pending);
220
+ if (!insertResult)
221
+ throw new Error("Unable to issue query to queryArchivist");
222
+ const context = new Promise((resolve, reject) => {
223
+ this.logger?.debug(`Polling for response to query: ${routedQueryHash}`);
224
+ let nextDelay = 100;
225
+ const pollForResponse = /* @__PURE__ */ __name(async () => {
226
+ try {
227
+ this.start();
228
+ let response = this.queryCache.get(routedQueryHash);
229
+ while (response !== void 0) {
230
+ await delay(nextDelay);
231
+ response = this.queryCache.get(routedQueryHash);
232
+ if (response && response !== Pending) {
233
+ this.logger?.log(`Returning response to query: ${routedQueryHash}`);
234
+ resolve(response);
235
+ return;
236
+ }
237
+ nextDelay = Math.floor(nextDelay * 1.2);
238
+ if (nextDelay > 1e3)
239
+ nextDelay = 1e3;
240
+ }
241
+ this.logger?.error("Timeout waiting for query response");
242
+ const error = {
243
+ message: "Timeout waiting for query response",
244
+ query: "network.xyo.boundwitness",
245
+ schema: "network.xyo.error.module",
246
+ sources: [
247
+ routedQueryHash
248
+ ]
249
+ };
250
+ reject(error);
251
+ return;
252
+ } finally {
253
+ this.stop();
254
+ }
255
+ }, "pollForResponse");
256
+ forget(pollForResponse());
257
+ });
258
+ return context;
259
+ }
260
+ /**
261
+ * Runs the background divine process on a loop with a delay
262
+ * specified by the `config.pollFrequency`
263
+ */
264
+ poll() {
265
+ this._pollId = setTimeoutEx(async () => {
266
+ try {
267
+ await this.processIncomingResponses();
268
+ } catch (e) {
269
+ this.logger?.error?.(`Error in main loop: ${e}`);
270
+ } finally {
271
+ if (this._pollId)
272
+ clearTimeoutEx(this._pollId);
273
+ this._pollId = void 0;
274
+ this.poll();
275
+ }
276
+ }, this.pollFrequency);
277
+ }
278
+ /**
279
+ * Background process for processing incoming responses to previously issued queries
280
+ */
281
+ processIncomingResponses = async () => {
282
+ const responseArchivist = await this.responsesArchivist();
283
+ if (responseArchivist) {
284
+ const responseBoundWitnessDiviner = await this.responsesDiviner();
285
+ if (responseBoundWitnessDiviner) {
286
+ const pendingCommands = [
287
+ ...this.queryCache.entries()
288
+ ].filter(([_, status]) => status === Pending);
289
+ await Promise.allSettled(pendingCommands.map(async ([sourceQuery, status]) => {
290
+ if (status === Pending) {
291
+ const divinerQuery = {
292
+ limit: 1,
293
+ order: "desc",
294
+ schema: BoundWitnessDivinerQuerySchema,
295
+ sourceQuery
296
+ };
297
+ const result = await responseBoundWitnessDiviner.divine([
298
+ divinerQuery
299
+ ]);
300
+ if (result && result.length > 0) {
301
+ const response = result.find(isBoundWitnessWithMeta);
302
+ if (response && response?.$meta?.sourceQuery === sourceQuery) {
303
+ this.logger?.debug(`Found response to query: ${sourceQuery}`);
304
+ const payloads = response.payload_hashes?.length > 0 ? await responseArchivist.get(response.payload_hashes) : [];
305
+ this.queryCache.set(sourceQuery, [
306
+ response,
307
+ payloads,
308
+ []
309
+ ]);
310
+ }
311
+ }
312
+ }
313
+ }));
314
+ }
315
+ }
316
+ };
317
+ start() {
318
+ if (this._pollCount === 0) {
319
+ this.poll();
320
+ }
321
+ this._pollCount++;
322
+ }
323
+ stop() {
324
+ this._pollCount--;
325
+ if (this._pollCount <= 0) {
326
+ if (this._pollId)
327
+ clearTimeoutEx(this._pollId);
328
+ this._pollId = void 0;
329
+ this._pollCount = 0;
330
+ }
331
+ }
332
+ };
333
+
334
+ // src/AsyncQueryBus/AsyncQueryBusHost.ts
335
+ import { containsAll } from "@xylabs/array";
336
+ import { assertEx as assertEx3 } from "@xylabs/assert";
337
+ import { clearTimeoutEx as clearTimeoutEx2, setTimeoutEx as setTimeoutEx2 } from "@xylabs/timer";
338
+ import { isQueryBoundWitnessWithMeta } from "@xyo-network/boundwitness-model";
339
+ import { isBridgeInstance } from "@xyo-network/bridge-model";
340
+ import { BoundWitnessDivinerQuerySchema as BoundWitnessDivinerQuerySchema2 } from "@xyo-network/diviner-boundwitness-model";
341
+ import { asModuleInstance, ModuleConfigSchema, resolveAddressToInstance, ResolveHelper as ResolveHelper2 } from "@xyo-network/module-model";
342
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
343
+ var IDLE_POLLING_FREQUENCY_RATIO_MIN = 4;
344
+ var IDLE_POLLING_FREQUENCY_RATIO_MAX = 64;
345
+ var IDLE_POLLING_FREQUENCY_RATIO_DEFAULT = 16;
346
+ var IDLE_THRESHOLD_RATIO_MIN = 4;
347
+ var IDLE_THRESHOLD_RATIO_MAX = 64;
348
+ var IDLE_THRESHOLD_RATIO_DEFAULT = 16;
349
+ var AsyncQueryBusHost = class extends AsyncQueryBusBase {
350
+ static {
351
+ __name(this, "AsyncQueryBusHost");
352
+ }
353
+ _exposedAddresses = /* @__PURE__ */ new Set();
354
+ _exposeOptions = {};
355
+ _idle = false;
356
+ _lastQueryTime;
357
+ _pollId;
358
+ constructor(params) {
359
+ super(params);
360
+ }
361
+ get exposedAddresses() {
362
+ return this._exposedAddresses;
363
+ }
364
+ get idlePollFrequency() {
365
+ const frequency = this.config?.idlePollFrequency ?? IDLE_POLLING_FREQUENCY_RATIO_DEFAULT * this.pollFrequency;
366
+ if (frequency < this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MIN) {
367
+ return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
368
+ }
369
+ if (frequency > this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MAX) {
370
+ return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
371
+ }
372
+ return frequency;
373
+ }
374
+ get idleThreshold() {
375
+ const threshold = this.config?.idleThreshold ?? IDLE_THRESHOLD_RATIO_DEFAULT * this.idlePollFrequency;
376
+ if (threshold < this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MIN) {
377
+ return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
378
+ }
379
+ if (threshold > this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MAX) {
380
+ return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
381
+ }
382
+ return threshold;
383
+ }
384
+ get perAddressBatchQueryLimit() {
385
+ return this.config?.perAddressBatchQueryLimit ?? 10;
386
+ }
387
+ get started() {
388
+ return !!this._pollId;
389
+ }
390
+ expose(module, options) {
391
+ const { failOnAlreadyExposed } = options ?? {};
392
+ if (isBridgeInstance(module)) {
393
+ this.logger?.warn(`Attempted to expose a BridgeModule [${module.id}] - Not exposing`);
394
+ } else {
395
+ assertEx3(!failOnAlreadyExposed || !this._exposedAddresses.has(module.address), () => `Address already exposed: ${module.id} [${module.address}]`);
396
+ this._exposedAddresses.add(module.address);
397
+ this._exposeOptions[module.address] = {
398
+ ...options
399
+ };
400
+ this.logger?.debug(`${module.id} exposed [${module.address}]`);
401
+ return module;
402
+ }
403
+ }
404
+ async listeningModules() {
405
+ const exposedModules = [
406
+ ...this.config?.listeningModules ?? [],
407
+ ...this.exposedAddresses.values()
408
+ ];
409
+ const mods = await Promise.all(exposedModules.map(async (exposedModule) => assertEx3(asModuleInstance(await resolveAddressToInstance(this.rootModule, exposedModule)), () => `Unable to resolve listeningModule [${exposedModule}]`)));
410
+ return mods;
411
+ }
412
+ start() {
413
+ if (this.started) {
414
+ console.warn("AsyncQueryBus starting when already started");
415
+ }
416
+ this.poll();
417
+ }
418
+ stop() {
419
+ if (!this.started) {
420
+ console.warn("AsyncQueryBus stopping when already stopped");
421
+ }
422
+ if (this._pollId)
423
+ clearTimeoutEx2(this._pollId);
424
+ this._pollId = void 0;
425
+ }
426
+ async unexpose(id, validate = true) {
427
+ const module = asModuleInstance(await this.rootModule.resolve(id, {
428
+ maxDepth: 10
429
+ }));
430
+ if (module) {
431
+ assertEx3(!validate || this._exposedAddresses.has(module.address), () => `Address not exposed [${module.address}][${module.id}]`);
432
+ this._exposedAddresses.delete(module.address);
433
+ delete this._exposeOptions[module.address];
434
+ this.logger?.debug(`${module.address} [${module.id}] unexposed`);
435
+ }
436
+ return module;
437
+ }
438
+ callLocalModule = async (localModule, query) => {
439
+ this._idle = false;
440
+ this._lastQueryTime = Date.now();
441
+ const localModuleName = localModule.config.name ?? localModule.address;
442
+ const queryArchivist = assertEx3(await this.queriesArchivist(), () => `Unable to contact queriesArchivist [${this.config?.intersect?.queries?.archivist}]`);
443
+ const responsesArchivist = assertEx3(await this.responsesArchivist(), () => `Unable to contact responsesArchivist [${this.config?.intersect?.queries?.archivist}]`);
444
+ const queryDestination = query.$meta?.destination;
445
+ if (queryDestination && queryDestination?.includes(localModule.address)) {
446
+ const queryIndex = query.payload_hashes.indexOf(query.query);
447
+ if (queryIndex !== -1) {
448
+ const querySchema = query.payload_schemas[queryIndex];
449
+ if (localModule.queries.includes(querySchema)) {
450
+ const queryPayloads = await queryArchivist.get(query.payload_hashes);
451
+ const queryPayloadsDict = await PayloadBuilder2.toAllHashMap(queryPayloads);
452
+ const queryHash = (await PayloadBuilder2.build(query)).$hash;
453
+ if (!containsAll(Object.keys(queryPayloadsDict), query.payload_hashes)) {
454
+ this.logger?.error(`Error processing command ${queryHash} for module ${localModuleName}, missing payloads`);
455
+ return;
456
+ }
457
+ try {
458
+ const querySchema2 = queryPayloadsDict[query.query].schema;
459
+ this.logger?.debug(`Issuing query ${querySchema2} (${queryHash}) addressed to module: ${localModuleName}`);
460
+ const response = await localModule.query(query, queryPayloads, {
461
+ allowedQueries: this._exposeOptions[localModule.address]?.allowedQueries,
462
+ schema: ModuleConfigSchema
463
+ });
464
+ const [bw, payloads, errors] = response;
465
+ this.logger?.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`);
466
+ const insertResult = await responsesArchivist.insert([
467
+ bw,
468
+ ...payloads,
469
+ ...errors
470
+ ]);
471
+ if (insertResult.length === 0) {
472
+ this.logger?.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`);
473
+ }
474
+ if (query?.timestamp) {
475
+ await this.commitState(localModule.address, query.timestamp);
476
+ }
477
+ } catch (error) {
478
+ this.logger?.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
479
+ }
480
+ }
481
+ }
482
+ }
483
+ };
484
+ /**
485
+ * Finds unprocessed commands addressed to the supplied address
486
+ * @param address The address to find commands for
487
+ */
488
+ findQueriesToAddress = async (address) => {
489
+ const queriesDivinerId = assertEx3(this.config?.intersect?.queries?.boundWitnessDiviner, () => "No queries Diviner defined");
490
+ const queriesBoundWitnessDiviner = await this.queriesDiviner();
491
+ if (queriesBoundWitnessDiviner) {
492
+ const timestamp = await this.retrieveState(address);
493
+ const destination = [
494
+ address
495
+ ];
496
+ const limit = this.perAddressBatchQueryLimit;
497
+ const divinerQuery = {
498
+ destination,
499
+ limit,
500
+ order: "asc",
501
+ schema: BoundWitnessDivinerQuerySchema2,
502
+ timestamp
503
+ };
504
+ const result = await queriesBoundWitnessDiviner.divine([
505
+ divinerQuery
506
+ ]);
507
+ const queries = result.filter(isQueryBoundWitnessWithMeta);
508
+ const nextState = queries.length > 0 ? Math.max(...queries.map((c) => c.timestamp ?? 0)) + 1 : timestamp;
509
+ await this.commitState(address, nextState);
510
+ return queries;
511
+ } else {
512
+ this.logger?.warn(`Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper2.traceModuleIdentifier(this.rootModule, queriesDivinerId)}]`);
513
+ }
514
+ };
515
+ /**
516
+ * Runs the background divine process on a loop with a delay
517
+ * specified by the `config.pollFrequency`
518
+ */
519
+ poll() {
520
+ this._pollId = setTimeoutEx2(async () => {
521
+ try {
522
+ await this.processIncomingQueries();
523
+ } catch (e) {
524
+ this.logger?.error?.(`Error in main loop: ${e}`);
525
+ } finally {
526
+ if (this._pollId)
527
+ clearTimeoutEx2(this._pollId);
528
+ this._pollId = void 0;
529
+ this.poll();
530
+ }
531
+ const now = Date.now();
532
+ if (this.idleThreshold < now - (this._lastQueryTime ?? now)) {
533
+ this._idle = true;
534
+ }
535
+ }, this._idle ? this.idlePollFrequency : this.pollFrequency);
536
+ }
537
+ /**
538
+ * Background process for checking for inbound queries
539
+ */
540
+ processIncomingQueries = async () => {
541
+ this.logger?.debug("Checking for inbound queries");
542
+ const localModules = await this.listeningModules();
543
+ await Promise.allSettled(localModules.map(async (localModule) => {
544
+ try {
545
+ const localModuleName = localModule.config.name ?? localModule.address;
546
+ this.logger?.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`);
547
+ const queries = await this.findQueriesToAddress(localModule.address) ?? [];
548
+ if (queries.length === 0)
549
+ return;
550
+ this.logger?.debug(`Found queries addressed to local module: ${localModuleName}`);
551
+ for (const query of queries) {
552
+ await this.callLocalModule(localModule, query);
553
+ }
554
+ } catch (error) {
555
+ this.logger?.error(`Error processing queries for address ${localModule.address}: ${error}`);
556
+ }
557
+ }));
558
+ };
559
+ };
560
+
561
+ // src/AsyncQueryBus/ModuleHost/ModuleHost.ts
562
+ var AsyncQueryBusModuleHost = class extends AbstractModuleHost {
563
+ static {
564
+ __name(this, "AsyncQueryBusModuleHost");
565
+ }
566
+ _busHost;
567
+ constructor(params) {
568
+ super(params);
569
+ }
570
+ async start() {
571
+ const listeningModules = this.params.config.listeningModules ?? (await this.params.module.resolve("*", {
572
+ direction: "down"
573
+ })).map((m) => m.address);
574
+ this._busHost = new AsyncQueryBusHost({
575
+ config: {
576
+ ...this.params.config,
577
+ listeningModules
578
+ },
579
+ logger: this.params.logger,
580
+ rootModule: this.params.module
581
+ });
582
+ this._busHost?.start();
583
+ }
584
+ stop() {
585
+ this._busHost?.stop();
586
+ }
587
+ };
588
+
589
+ // src/AsyncQueryBus/ModuleProxy/ModuleProxy.ts
590
+ import { AbstractModuleProxy } from "@xyo-network/abstract-bridge";
591
+ var AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends AbstractModuleProxy {
592
+ static {
593
+ __name(this, "AsyncQueryBusModuleProxy");
594
+ }
595
+ static createCount = 0;
596
+ constructor(params) {
597
+ _AsyncQueryBusModuleProxy.createCount = _AsyncQueryBusModuleProxy.createCount + 1;
598
+ if (Math.floor(_AsyncQueryBusModuleProxy.createCount / 10) === _AsyncQueryBusModuleProxy.createCount / 10) {
599
+ console.log(`AsyncQueryBusModuleProxy.createCount: ${_AsyncQueryBusModuleProxy.createCount}`);
600
+ }
601
+ super(params);
602
+ }
603
+ async proxyQueryHandler(query, payloads) {
604
+ return await this.params.busClient.send(this.address, query, payloads);
605
+ }
606
+ async startHandler() {
607
+ return await super.startHandler();
608
+ }
609
+ };
610
+
611
+ // src/Schema.ts
612
+ var PubSubBridgeSchema = "network.xyo.bridge.pubsub";
613
+
614
+ // src/Config.ts
615
+ var PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`;
616
+
617
+ // src/PubSubBridge.ts
618
+ import { assertEx as assertEx5 } from "@xylabs/assert";
619
+ import { exists } from "@xylabs/exists";
620
+ import { toJsonString } from "@xylabs/object";
621
+ import { AbstractBridge } from "@xyo-network/abstract-bridge";
622
+ import { AddressSchema } from "@xyo-network/address-payload-plugin";
623
+ import { creatableModule, resolveAddressToInstanceUp, ResolveHelper as ResolveHelper3 } from "@xyo-network/module-model";
624
+ import { asNodeInstance } from "@xyo-network/node-model";
625
+ import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
626
+
627
+ // src/PubSubBridgeModuleResolver.ts
628
+ import { assertEx as assertEx4 } from "@xylabs/assert";
629
+ import { isAddress } from "@xylabs/hex";
630
+ import { AbstractBridgeModuleResolver, wrapModuleWithType } from "@xyo-network/abstract-bridge";
631
+ import { Account } from "@xyo-network/account";
632
+ import { ConfigSchema } from "@xyo-network/config-payload-plugin";
633
+ import { asModuleInstance as asModuleInstance2, ModuleConfigSchema as ModuleConfigSchema2 } from "@xyo-network/module-model";
634
+ var PubSubBridgeModuleResolver = class extends AbstractBridgeModuleResolver {
635
+ static {
636
+ __name(this, "PubSubBridgeModuleResolver");
637
+ }
638
+ async resolveHandler(id, options) {
639
+ const parentResult = await super.resolveHandler(id, options);
640
+ if (parentResult) {
641
+ return parentResult;
642
+ }
643
+ const idParts = id.split(":");
644
+ const firstPart = idParts.shift();
645
+ assertEx4(isAddress(firstPart), () => `Invalid module address: ${firstPart}`);
646
+ const remainderParts = idParts.join(":");
647
+ const account = Account.randomSync();
648
+ const params = {
649
+ account,
650
+ busClient: this.params.busClient,
651
+ config: {
652
+ schema: ModuleConfigSchema2
653
+ },
654
+ host: this.params.bridge,
655
+ moduleAddress: firstPart
656
+ };
657
+ const proxy = new AsyncQueryBusModuleProxy(params);
658
+ if (proxy) {
659
+ const state = await proxy.state();
660
+ if (state) {
661
+ const configSchema = state.find((payload) => payload.schema === ConfigSchema)?.config;
662
+ const config = assertEx4(state.find((payload) => payload.schema === configSchema), () => "Unable to locate config");
663
+ proxy.setConfig(config);
664
+ }
665
+ }
666
+ await proxy.start?.();
667
+ const wrapped = wrapModuleWithType(proxy, account);
668
+ const as = assertEx4(asModuleInstance2(wrapped, {}), () => `Failed to asModuleInstance [${id}]`);
669
+ proxy.upResolver.add(as);
670
+ proxy.downResolver.add(as);
671
+ this.add(as);
672
+ return remainderParts.length > 0 ? await proxy.resolve(remainderParts, options) : as;
673
+ }
674
+ };
675
+
676
+ // src/PubSubBridge.ts
677
+ function _ts_decorate(decorators, target, key, desc) {
678
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
679
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
680
+ r = Reflect.decorate(decorators, target, key, desc);
681
+ else
682
+ for (var i = decorators.length - 1; i >= 0; i--)
683
+ if (d = decorators[i])
684
+ r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
685
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
686
+ }
687
+ __name(_ts_decorate, "_ts_decorate");
688
+ var moduleName = "PubSubBridge";
689
+ var PubSubBridge = class extends AbstractBridge {
690
+ static {
691
+ __name(this, "PubSubBridge");
692
+ }
693
+ static configSchemas = [
694
+ ...super.configSchemas,
695
+ PubSubBridgeConfigSchema
696
+ ];
697
+ static defaultConfigSchema = PubSubBridgeConfigSchema;
698
+ _configRootAddress = "";
699
+ _configStateStoreArchivist = "";
700
+ _configStateStoreBoundWitnessDiviner = "";
701
+ _exposedAddresses = [];
702
+ _lastState;
703
+ _busClient;
704
+ _busHost;
705
+ _resolver;
706
+ get resolver() {
707
+ this._resolver = this._resolver ?? new PubSubBridgeModuleResolver({
708
+ bridge: this,
709
+ busClient: assertEx5(this.busClient(), () => "busClient not configured"),
710
+ root: this,
711
+ wrapperAccount: this.account
712
+ });
713
+ return this._resolver;
714
+ }
715
+ get moduleName() {
716
+ return `${this.config.name ?? moduleName}`;
717
+ }
718
+ async connect(id, maxDepth = 5) {
719
+ const transformedId = assertEx5(await ResolveHelper3.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
720
+ const existingInstance = await this.resolve(transformedId);
721
+ if (existingInstance) {
722
+ return existingInstance.address;
723
+ }
724
+ const instance = await this.resolver.resolve(id);
725
+ return await this.connectInstance(instance, maxDepth);
726
+ }
727
+ async disconnect(id) {
728
+ const transformedId = assertEx5(await ResolveHelper3.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
729
+ const instance = await this.resolve(transformedId);
730
+ if (instance) {
731
+ this.downResolver.remove(instance.address);
732
+ return instance.address;
733
+ }
734
+ }
735
+ async discoverRoots() {
736
+ const rootAddresses = (await Promise.all((this.config.roots ?? []).map((id) => ResolveHelper3.transformModuleIdentifier(id)))).filter(exists);
737
+ const rootInstances = (await Promise.all(rootAddresses.map(async (root) => await this.resolver.resolve(root)))).filter(exists);
738
+ for (const instance of rootInstances) {
739
+ this.downResolver.add(instance);
740
+ }
741
+ this._roots = rootInstances;
742
+ return rootInstances;
743
+ }
744
+ async exposeHandler(address, options) {
745
+ const { maxDepth = 5, required = true } = options ?? {};
746
+ const host = assertEx5(this.busHost(), () => "Not configured as a host");
747
+ const module = await resolveAddressToInstanceUp(this, address);
748
+ if (required && !module) {
749
+ throw new Error(`Unable to find required module: ${address}`);
750
+ }
751
+ if (module) {
752
+ host.expose(module);
753
+ const children = maxDepth > 0 ? await module.publicChildren?.() ?? [] : [];
754
+ console.log(`childrenToExpose [${module.id}]: ${toJsonString(children.map((child) => child.id))}`);
755
+ const exposedChildren = (await Promise.all(children.map((child) => this.exposeHandler(child.address, {
756
+ maxDepth: maxDepth - 1,
757
+ required: false
758
+ })))).flat().filter(exists);
759
+ const allExposed = [
760
+ module,
761
+ ...exposedChildren
762
+ ];
763
+ for (const mod of allExposed)
764
+ this.logger?.log(`exposed: ${mod.address} [${mod.id}]`);
765
+ return [
766
+ module,
767
+ ...exposedChildren
768
+ ];
769
+ }
770
+ return [];
771
+ }
772
+ exposedHandler() {
773
+ const exposedSet = this.busHost()?.exposedAddresses;
774
+ return exposedSet ? [
775
+ ...exposedSet
776
+ ] : [];
777
+ }
778
+ async startHandler() {
779
+ this.busHost()?.start();
780
+ return await super.startHandler();
781
+ }
782
+ async unexposeHandler(id, options) {
783
+ const { maxDepth = 2, required = true } = options ?? {};
784
+ const host = assertEx5(this.busHost(), () => "Not configured as a host");
785
+ const module = await host.unexpose(id, required);
786
+ if (module) {
787
+ const children = maxDepth > 0 ? await module.publicChildren?.() ?? [] : [];
788
+ const exposedChildren = (await Promise.all(children.map((child) => this.unexposeHandler(child.address, {
789
+ maxDepth: maxDepth - 1,
790
+ required: false
791
+ })))).flat().filter(exists);
792
+ return [
793
+ module,
794
+ ...exposedChildren
795
+ ];
796
+ }
797
+ return [];
798
+ }
799
+ busClient() {
800
+ if (!this._busClient && this.config.client) {
801
+ this._busClient = new AsyncQueryBusClient({
802
+ config: this.config.client,
803
+ logger: this.logger,
804
+ rootModule: this
805
+ });
806
+ }
807
+ return this._busClient;
808
+ }
809
+ busHost() {
810
+ if (!this._busHost && this.config.host) {
811
+ this._busHost = new AsyncQueryBusHost({
812
+ config: this.config.host,
813
+ logger: this.logger,
814
+ rootModule: this
815
+ });
816
+ }
817
+ return this._busHost;
818
+ }
819
+ async connectInstance(instance, maxDepth = 5) {
820
+ if (instance) {
821
+ this.downResolver.add(instance);
822
+ if (maxDepth > 0) {
823
+ const node = asNodeInstance(instance);
824
+ if (node) {
825
+ const state = await node.state();
826
+ const children = (state?.filter(isPayloadOfSchemaType(AddressSchema)).map((s) => s.address) ?? []).filter((a) => a !== instance.address);
827
+ await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
828
+ }
829
+ }
830
+ this.logger?.log(`Connect: ${instance.config.name ?? instance.address}`);
831
+ return instance.address;
832
+ }
833
+ }
834
+ stopHandler(_timeout) {
835
+ this.busHost()?.stop();
836
+ return true;
837
+ }
838
+ };
839
+ PubSubBridge = _ts_decorate([
840
+ creatableModule()
841
+ ], PubSubBridge);
842
+ export {
843
+ AbstractModuleHost,
844
+ AsyncQueryBusClient,
845
+ AsyncQueryBusHost,
846
+ AsyncQueryBusModuleHost,
847
+ AsyncQueryBusModuleProxy,
848
+ Pending,
849
+ PubSubBridge,
850
+ PubSubBridgeConfigSchema,
851
+ PubSubBridgeModuleResolver,
852
+ PubSubBridgeSchema
853
+ };
854
+ //# sourceMappingURL=index.js.map