@xyo-network/module-abstract 2.75.0 → 2.75.1

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 (88) hide show
  1. package/dist/browser/AbstractModule.d.cts +84 -0
  2. package/dist/browser/AbstractModule.d.cts.map +1 -0
  3. package/dist/browser/AbstractModule.js +16 -182
  4. package/dist/browser/AbstractModule.js.map +1 -1
  5. package/dist/browser/AbstractModuleInstance.d.cts +14 -0
  6. package/dist/browser/AbstractModuleInstance.d.cts.map +1 -0
  7. package/dist/browser/AbstractModuleInstance.js +4 -738
  8. package/dist/browser/AbstractModuleInstance.js.map +1 -1
  9. package/dist/browser/BaseEmitter.d.cts +17 -0
  10. package/dist/browser/BaseEmitter.d.cts.map +1 -0
  11. package/dist/browser/BaseEmitter.js +2 -4
  12. package/dist/browser/BaseEmitter.js.map +1 -1
  13. package/dist/browser/Error.d.cts +15 -0
  14. package/dist/browser/Error.d.cts.map +1 -0
  15. package/dist/browser/Error.js +2 -4
  16. package/dist/browser/Error.js.map +1 -1
  17. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.d.cts +15 -0
  18. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.d.cts.map +1 -0
  19. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.js +4 -6
  20. package/dist/browser/QueryValidator/ModuleConfigQueryValidator.js.map +1 -1
  21. package/dist/browser/QueryValidator/QueryValidator.d.cts +8 -0
  22. package/dist/browser/QueryValidator/QueryValidator.d.cts.map +1 -0
  23. package/dist/browser/QueryValidator/SupportedQueryValidator.d.cts +22 -0
  24. package/dist/browser/QueryValidator/SupportedQueryValidator.d.cts.map +1 -0
  25. package/dist/browser/QueryValidator/SupportedQueryValidator.js +3 -5
  26. package/dist/browser/QueryValidator/SupportedQueryValidator.js.map +1 -1
  27. package/dist/browser/QueryValidator/index.d.cts +4 -0
  28. package/dist/browser/QueryValidator/index.d.cts.map +1 -0
  29. package/dist/browser/QueryValidator/index.js +3 -86
  30. package/dist/browser/QueryValidator/index.js.map +1 -1
  31. package/dist/browser/index.d.cts +6 -0
  32. package/dist/browser/index.d.cts.map +1 -0
  33. package/dist/browser/index.js +5 -782
  34. package/dist/browser/index.js.map +1 -1
  35. package/dist/docs.json +42701 -0
  36. package/dist/node/AbstractModule.d.cts +84 -0
  37. package/dist/node/AbstractModule.d.cts.map +1 -0
  38. package/dist/node/AbstractModule.js +240 -56
  39. package/dist/node/AbstractModule.js.map +1 -1
  40. package/dist/node/AbstractModule.mjs +232 -48
  41. package/dist/node/AbstractModule.mjs.map +1 -1
  42. package/dist/node/AbstractModuleInstance.d.cts +14 -0
  43. package/dist/node/AbstractModuleInstance.d.cts.map +1 -0
  44. package/dist/node/AbstractModuleInstance.js +757 -6
  45. package/dist/node/AbstractModuleInstance.js.map +1 -1
  46. package/dist/node/AbstractModuleInstance.mjs +757 -6
  47. package/dist/node/AbstractModuleInstance.mjs.map +1 -1
  48. package/dist/node/BaseEmitter.d.cts +17 -0
  49. package/dist/node/BaseEmitter.d.cts.map +1 -0
  50. package/dist/node/BaseEmitter.js +6 -5
  51. package/dist/node/BaseEmitter.js.map +1 -1
  52. package/dist/node/BaseEmitter.mjs +6 -5
  53. package/dist/node/BaseEmitter.mjs.map +1 -1
  54. package/dist/node/Error.d.cts +15 -0
  55. package/dist/node/Error.d.cts.map +1 -0
  56. package/dist/node/Error.js +6 -5
  57. package/dist/node/Error.js.map +1 -1
  58. package/dist/node/Error.mjs +6 -5
  59. package/dist/node/Error.mjs.map +1 -1
  60. package/dist/node/QueryValidator/ModuleConfigQueryValidator.d.cts +15 -0
  61. package/dist/node/QueryValidator/ModuleConfigQueryValidator.d.cts.map +1 -0
  62. package/dist/node/QueryValidator/ModuleConfigQueryValidator.js +23 -14
  63. package/dist/node/QueryValidator/ModuleConfigQueryValidator.js.map +1 -1
  64. package/dist/node/QueryValidator/ModuleConfigQueryValidator.mjs +23 -14
  65. package/dist/node/QueryValidator/ModuleConfigQueryValidator.mjs.map +1 -1
  66. package/dist/node/QueryValidator/QueryValidator.d.cts +8 -0
  67. package/dist/node/QueryValidator/QueryValidator.d.cts.map +1 -0
  68. package/dist/node/QueryValidator/QueryValidator.js +2 -0
  69. package/dist/node/QueryValidator/QueryValidator.js.map +1 -1
  70. package/dist/node/QueryValidator/SupportedQueryValidator.d.cts +22 -0
  71. package/dist/node/QueryValidator/SupportedQueryValidator.d.cts.map +1 -0
  72. package/dist/node/QueryValidator/SupportedQueryValidator.js +7 -6
  73. package/dist/node/QueryValidator/SupportedQueryValidator.js.map +1 -1
  74. package/dist/node/QueryValidator/SupportedQueryValidator.mjs +7 -6
  75. package/dist/node/QueryValidator/SupportedQueryValidator.mjs.map +1 -1
  76. package/dist/node/QueryValidator/index.d.cts +4 -0
  77. package/dist/node/QueryValidator/index.d.cts.map +1 -0
  78. package/dist/node/QueryValidator/index.js +100 -7
  79. package/dist/node/QueryValidator/index.js.map +1 -1
  80. package/dist/node/QueryValidator/index.mjs +92 -3
  81. package/dist/node/QueryValidator/index.mjs.map +1 -1
  82. package/dist/node/index.d.cts +6 -0
  83. package/dist/node/index.d.cts.map +1 -0
  84. package/dist/node/index.js +811 -11
  85. package/dist/node/index.js.map +1 -1
  86. package/dist/node/index.mjs +799 -5
  87. package/dist/node/index.mjs.map +1 -1
  88. package/package.json +26 -26
@@ -1,13 +1,762 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2
3
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
4
+ var __publicField = (obj, key, value) => {
5
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
+ return value;
7
+ };
8
+
9
+ // src/AbstractModuleInstance.ts
10
+ import { assertEx as assertEx2 } from "@xylabs/assert";
11
+
12
+ // src/AbstractModule.ts
3
13
  import { assertEx } from "@xylabs/assert";
4
- import { AbstractModule } from "./AbstractModule";
5
- class AbstractModuleInstance extends AbstractModule {
6
- static {
7
- __name(this, "AbstractModuleInstance");
14
+ import { exists } from "@xylabs/exists";
15
+ import { compact } from "@xylabs/lodash";
16
+ import { HDWallet } from "@xyo-network/account";
17
+ import { AddressSchema } from "@xyo-network/address-payload-plugin";
18
+ import { asArchivistInstance } from "@xyo-network/archivist-model";
19
+ import { BoundWitnessBuilder, QueryBoundWitnessBuilder, QueryBoundWitnessWrapper as QueryBoundWitnessWrapper3 } from "@xyo-network/boundwitness-builder";
20
+ import { ConfigSchema } from "@xyo-network/config-payload-plugin";
21
+ import { PayloadHasher } from "@xyo-network/core";
22
+ import { handleError, handleErrorAsync } from "@xyo-network/error";
23
+ import { ModuleManifestPayloadSchema } from "@xyo-network/manifest-model";
24
+ import { AddressPreviousHashSchema, duplicateModules, ModuleAddressQuerySchema, ModuleDescribeQuerySchema, ModuleDescriptionSchema, ModuleDiscoverQuerySchema, ModuleFactory, ModuleManifestQuerySchema, ModuleSubscribeQuerySchema, serializableField } from "@xyo-network/module-model";
25
+ import { CompositeModuleResolver } from "@xyo-network/module-resolver";
26
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
27
+ import { PromiseEx } from "@xyo-network/promise";
28
+ import { QuerySchema } from "@xyo-network/query-payload-plugin";
29
+ import { IdLogger } from "@xyo-network/shared";
30
+
31
+ // src/BaseEmitter.ts
32
+ import { Base } from "@xyo-network/core";
33
+ import { Events } from "@xyo-network/module-events";
34
+ var _BaseEmitter = class _BaseEmitter extends Base {
35
+ //just here to query types
36
+ eventData = {};
37
+ events;
38
+ constructor(params) {
39
+ super(params);
40
+ this.events = new Events();
41
+ }
42
+ clearListeners(eventNames) {
43
+ return this.events.clearListeners(eventNames);
44
+ }
45
+ emit(eventName, eventArgs) {
46
+ return this.events.emit(eventName, eventArgs);
47
+ }
48
+ emitSerial(eventName, eventArgs) {
49
+ return this.events.emitSerial(eventName, eventArgs);
50
+ }
51
+ listenerCount(eventNames) {
52
+ return this.events.listenerCount(eventNames);
53
+ }
54
+ off(eventNames, listener) {
55
+ return this.events.off(eventNames, listener);
56
+ }
57
+ offAny(listener) {
58
+ return this.events.offAny(listener);
59
+ }
60
+ on(eventNames, listener) {
61
+ return this.events.on(eventNames, listener);
62
+ }
63
+ onAny(listener) {
64
+ return this.events.onAny(listener);
65
+ }
66
+ once(eventName, listener) {
67
+ return this.events.once(eventName, listener);
68
+ }
69
+ };
70
+ __name(_BaseEmitter, "BaseEmitter");
71
+ var BaseEmitter = _BaseEmitter;
72
+
73
+ // src/Error.ts
74
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
75
+ import { ModuleErrorSchema } from "@xyo-network/payload-model";
76
+ var _ModuleErrorBuilder = class _ModuleErrorBuilder extends PayloadBuilder {
77
+ _message;
78
+ _name;
79
+ _query;
80
+ _sources;
81
+ constructor() {
82
+ super({
83
+ schema: ModuleErrorSchema
84
+ });
85
+ }
86
+ build() {
87
+ return {
88
+ message: this._message,
89
+ name: this._name,
90
+ query: this._query,
91
+ schema: ModuleErrorSchema,
92
+ sources: this._sources
93
+ };
94
+ }
95
+ message(message) {
96
+ this._message = message;
97
+ return this;
98
+ }
99
+ name(name) {
100
+ this._name = name;
101
+ return this;
102
+ }
103
+ query(query) {
104
+ this._query = query;
105
+ return this;
106
+ }
107
+ sources(sources) {
108
+ this._sources = sources;
109
+ return this;
110
+ }
111
+ };
112
+ __name(_ModuleErrorBuilder, "ModuleErrorBuilder");
113
+ var ModuleErrorBuilder = _ModuleErrorBuilder;
114
+
115
+ // src/QueryValidator/ModuleConfigQueryValidator.ts
116
+ import { QueryBoundWitnessWrapper } from "@xyo-network/boundwitness-builder";
117
+ var delimiter = "";
118
+ var _ModuleConfigQueryValidator = class _ModuleConfigQueryValidator {
119
+ allowed = {};
120
+ disallowed = {};
121
+ hasAllowedRules;
122
+ hasDisallowedRules;
123
+ hasRules;
124
+ constructor(config) {
125
+ var _a, _b, _c, _d;
126
+ if ((_a = config == null ? void 0 : config.security) == null ? void 0 : _a.allowed) {
127
+ Object.entries((_b = config.security) == null ? void 0 : _b.allowed).forEach(([schema, addresses]) => {
128
+ this.allowed[schema] = addresses.map(toAddressesString);
129
+ });
130
+ }
131
+ if ((_c = config == null ? void 0 : config.security) == null ? void 0 : _c.disallowed) {
132
+ Object.entries((_d = config.security) == null ? void 0 : _d.disallowed).forEach(([schema, addresses]) => {
133
+ this.disallowed[schema] = addresses.map(toAddressesString);
134
+ });
135
+ }
136
+ this.hasAllowedRules = Object.keys(this.allowed).length > 0;
137
+ this.hasDisallowedRules = Object.keys(this.disallowed).length > 0;
138
+ this.hasRules = this.hasAllowedRules || this.hasDisallowedRules;
139
+ }
140
+ queryable = async (query, payloads) => {
141
+ if (!this.hasRules)
142
+ return true;
143
+ const addresses = query.addresses;
144
+ if (!addresses.length)
145
+ return false;
146
+ const wrapper = QueryBoundWitnessWrapper.parseQuery(query, payloads);
147
+ const schema = (await wrapper.getQuery()).schema;
148
+ return this.queryAllowed(schema, addresses) && !this.queryDisallowed(schema, addresses);
149
+ };
150
+ queryAllowed = (schema, addresses) => {
151
+ var _a, _b;
152
+ if (!this.hasAllowedRules)
153
+ return true;
154
+ if (addresses.length > 1) {
155
+ const signatories = toAddressesString(addresses);
156
+ const validCosigners = (_b = (_a = this.allowed) == null ? void 0 : _a[schema]) == null ? void 0 : _b.includes(signatories);
157
+ if (validCosigners)
158
+ return true;
159
+ }
160
+ return addresses.every((address) => {
161
+ var _a2, _b2;
162
+ return ((_b2 = (_a2 = this.allowed) == null ? void 0 : _a2[schema]) == null ? void 0 : _b2.includes(address)) || false;
163
+ });
164
+ };
165
+ queryDisallowed = (schema, addresses) => {
166
+ if (!this.hasDisallowedRules)
167
+ return false;
168
+ return addresses.some((address) => {
169
+ var _a, _b;
170
+ return (_b = (_a = this.disallowed) == null ? void 0 : _a[schema]) == null ? void 0 : _b.includes(address);
171
+ });
172
+ };
173
+ };
174
+ __name(_ModuleConfigQueryValidator, "ModuleConfigQueryValidator");
175
+ var ModuleConfigQueryValidator = _ModuleConfigQueryValidator;
176
+ var toAddressesString = /* @__PURE__ */ __name((addresses) => {
177
+ return Array.isArray(addresses) ? addresses.sort().map((address) => address.toLowerCase()).join(delimiter) : addresses.toLowerCase();
178
+ }, "toAddressesString");
179
+
180
+ // src/QueryValidator/SupportedQueryValidator.ts
181
+ import { QueryBoundWitnessWrapper as QueryBoundWitnessWrapper2 } from "@xyo-network/boundwitness-builder";
182
+ var isQuerySupportedByModule = /* @__PURE__ */ __name(async (mod, query, payloads) => {
183
+ const wrapper = QueryBoundWitnessWrapper2.parseQuery(query, payloads);
184
+ const schema = (await wrapper.getQuery()).schema;
185
+ return mod.queries.includes(schema);
186
+ }, "isQuerySupportedByModule");
187
+ var _SupportedQueryValidator = class _SupportedQueryValidator {
188
+ mod;
189
+ constructor(mod) {
190
+ this.mod = mod;
191
+ this.queryable = (query, payloads) => {
192
+ return isQuerySupportedByModule(this.mod, query, payloads);
193
+ };
194
+ }
195
+ queryable;
196
+ };
197
+ __name(_SupportedQueryValidator, "SupportedQueryValidator");
198
+ var SupportedQueryValidator = _SupportedQueryValidator;
199
+
200
+ // src/AbstractModule.ts
201
+ var _AbstractModule = class _AbstractModule extends BaseEmitter {
202
+ downResolver = new CompositeModuleResolver();
203
+ upResolver = new CompositeModuleResolver();
204
+ _account = void 0;
205
+ _baseModuleQueryAccountPaths = {
206
+ [ModuleAddressQuerySchema]: "1",
207
+ [ModuleDescribeQuerySchema]: "4",
208
+ [ModuleDiscoverQuerySchema]: "2",
209
+ [ModuleManifestQuerySchema]: "5",
210
+ [ModuleSubscribeQuerySchema]: "3"
211
+ };
212
+ _queryAccounts = {
213
+ [ModuleAddressQuerySchema]: void 0,
214
+ [ModuleDescribeQuerySchema]: void 0,
215
+ [ModuleDiscoverQuerySchema]: void 0,
216
+ [ModuleManifestQuerySchema]: void 0,
217
+ [ModuleSubscribeQuerySchema]: void 0
218
+ };
219
+ _startPromise = void 0;
220
+ _started = void 0;
221
+ moduleConfigQueryValidator;
222
+ supportedQueryValidator;
223
+ _busyCount = 0;
224
+ constructor(privateConstructorKey, params, account) {
225
+ assertEx(_AbstractModule.privateConstructorKey === privateConstructorKey, "Use create function instead of constructor");
226
+ const mutatedParams = {
227
+ ...params
228
+ };
229
+ super(mutatedParams);
230
+ this._account = account;
231
+ this.supportedQueryValidator = new SupportedQueryValidator(this).queryable;
232
+ this.moduleConfigQueryValidator = new ModuleConfigQueryValidator(mutatedParams == null ? void 0 : mutatedParams.config).queryable;
233
+ }
234
+ static get configSchema() {
235
+ return this.configSchemas[0];
236
+ }
237
+ get account() {
238
+ return assertEx(this._account, "Missing account");
239
+ }
240
+ get address() {
241
+ return this.account.address;
242
+ }
243
+ get allowAnonymous() {
244
+ var _a;
245
+ return !!((_a = this.config.security) == null ? void 0 : _a.allowAnonymous);
246
+ }
247
+ get config() {
248
+ return this.params.config;
249
+ }
250
+ get ephemeralQueryAccountEnabled() {
251
+ return !!this.params.ephemeralQueryAccountEnabled;
252
+ }
253
+ get queries() {
254
+ return [
255
+ ModuleDiscoverQuerySchema,
256
+ ModuleAddressQuerySchema,
257
+ ModuleSubscribeQuerySchema,
258
+ ModuleDescribeQuerySchema,
259
+ ModuleManifestQuerySchema
260
+ ];
261
+ }
262
+ get queryAccountPaths() {
263
+ return {
264
+ ...this._baseModuleQueryAccountPaths,
265
+ ...this._queryAccountPaths
266
+ };
267
+ }
268
+ get queryAccounts() {
269
+ return this._queryAccounts;
270
+ }
271
+ get timestamp() {
272
+ return this.config.timestamp ?? false;
273
+ }
274
+ static _getRootFunction(funcName) {
275
+ let anyThis = this;
276
+ while (anyThis.__proto__[funcName]) {
277
+ anyThis = anyThis.__proto__;
278
+ }
279
+ return anyThis[funcName];
280
+ }
281
+ static _noOverride(functionName) {
282
+ const thisFunc = this[functionName];
283
+ const rootFunc = this._getRootFunction(functionName);
284
+ assertEx(thisFunc === rootFunc, `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
8
285
  }
286
+ static async create(params) {
287
+ var _a, _b, _c, _d;
288
+ this._noOverride("create");
289
+ if (!this.configSchemas || this.configSchemas.length === 0) {
290
+ throw Error(`Missing configSchema [${(_a = params == null ? void 0 : params.config) == null ? void 0 : _a.schema}][${this.name}]`);
291
+ }
292
+ const { account, config, wallet } = params ?? {};
293
+ const { accountDerivationPath } = config ?? {};
294
+ assertEx(!(!!account && !!wallet), `Specifying both {account} and {wallet} are not allowed [${config == null ? void 0 : config.schema}] [${account === "random" ? "random" : account == null ? void 0 : account.address}, ${wallet == null ? void 0 : wallet.address}]`);
295
+ const schema = ((_b = params == null ? void 0 : params.config) == null ? void 0 : _b.schema) ?? this.configSchema;
296
+ const allowedSchemas = this.configSchemas;
297
+ assertEx(allowedSchemas.filter((allowedSchema) => allowedSchema === schema).length > 0, `Bad Config Schema [Received ${schema}] [Expected ${JSON.stringify(allowedSchemas)}]`);
298
+ const mutatedConfig = {
299
+ ...params == null ? void 0 : params.config,
300
+ schema
301
+ };
302
+ (_c = params == null ? void 0 : params.logger) == null ? void 0 : _c.debug(`config: ${JSON.stringify(mutatedConfig, null, 2)}`);
303
+ const mutatedParams = {
304
+ ...params,
305
+ config: mutatedConfig
306
+ };
307
+ const activeLogger = (params == null ? void 0 : params.logger) ?? _AbstractModule.defaultLogger;
308
+ const generatedAccount = await _AbstractModule.determineAccount({
309
+ account,
310
+ accountDerivationPath,
311
+ wallet
312
+ });
313
+ const address = generatedAccount.address;
314
+ mutatedParams.logger = activeLogger ? new IdLogger(activeLogger, () => `0x${address}`) : void 0;
315
+ const newModule = new this(_AbstractModule.privateConstructorKey, mutatedParams, generatedAccount);
316
+ if (!_AbstractModule.enableLazyLoad) {
317
+ await ((_d = newModule.start) == null ? void 0 : _d.call(newModule));
318
+ }
319
+ return newModule;
320
+ }
321
+ static async determineAccount({ account, accountDerivationPath, wallet }) {
322
+ if (wallet) {
323
+ return assertEx(accountDerivationPath ? await wallet.derivePath(accountDerivationPath) : wallet, "Failed to derive account from path");
324
+ } else if (account === "random") {
325
+ return await HDWallet.random();
326
+ } else if (account) {
327
+ return account;
328
+ } else {
329
+ console.warn("AbstractModule.determineAccount: No account provided - Creating Random account");
330
+ return await HDWallet.random();
331
+ }
332
+ }
333
+ static factory(params) {
334
+ return ModuleFactory.withParams(this, params);
335
+ }
336
+ _getRootFunction(funcName) {
337
+ let anyThis = this;
338
+ while (anyThis.__proto__[funcName]) {
339
+ anyThis = anyThis.__proto__;
340
+ }
341
+ return anyThis[funcName];
342
+ }
343
+ _noOverride(functionName) {
344
+ const thisFunc = this[functionName];
345
+ const rootFunc = this._getRootFunction(functionName);
346
+ assertEx(thisFunc === rootFunc, `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
347
+ }
348
+ async busy(closure) {
349
+ if (this._busyCount <= 0) {
350
+ this._busyCount = 0;
351
+ const args = {
352
+ busy: true,
353
+ module: this
354
+ };
355
+ await this.emit("moduleBusy", args);
356
+ }
357
+ this._busyCount++;
358
+ try {
359
+ return await closure();
360
+ } finally {
361
+ this._busyCount--;
362
+ if (this._busyCount <= 0) {
363
+ this._busyCount = 0;
364
+ const args = {
365
+ busy: false,
366
+ module: this
367
+ };
368
+ await this.emit("moduleBusy", args);
369
+ }
370
+ }
371
+ }
372
+ emit(eventName, eventArgs) {
373
+ return super.emit(eventName, eventArgs);
374
+ }
375
+ previousHash() {
376
+ return this.account.previousHash;
377
+ }
378
+ async query(query, payloads, queryConfig) {
379
+ this._noOverride("query");
380
+ return await this.busy(async () => {
381
+ const resultPayloads = [];
382
+ const errorPayloads = [];
383
+ const queryAccount = this.ephemeralQueryAccountEnabled ? await HDWallet.random() : void 0;
384
+ try {
385
+ await this.started("throw");
386
+ if (!this.allowAnonymous) {
387
+ if (query.addresses.length === 0) {
388
+ throw Error(`Anonymous Queries not allowed, but running anyway [${this.config.name}], [${this.address}]`);
389
+ }
390
+ }
391
+ resultPayloads.push(...await this.queryHandler(assertEx(QueryBoundWitnessWrapper3.unwrap(query)), payloads, queryConfig));
392
+ } catch (ex) {
393
+ await handleErrorAsync(ex, async (error) => {
394
+ errorPayloads.push(new ModuleErrorBuilder().sources([
395
+ await PayloadHasher.hashAsync(query)
396
+ ]).name(this.config.name ?? "<Unknown>").query(query.schema).message(error.message).build());
397
+ });
398
+ }
399
+ if (this.timestamp) {
400
+ const timestamp = {
401
+ schema: "network.xyo.timestamp",
402
+ timestamp: Date.now()
403
+ };
404
+ resultPayloads.push(timestamp);
405
+ }
406
+ const result = await this.bindQueryResult(query, resultPayloads, queryAccount ? [
407
+ queryAccount
408
+ ] : [], errorPayloads);
409
+ const args = {
410
+ module: this,
411
+ payloads,
412
+ query,
413
+ result
414
+ };
415
+ await this.emit("moduleQueried", args);
416
+ return result;
417
+ });
418
+ }
419
+ queryable(query, payloads, queryConfig) {
420
+ if (!this.started("warn"))
421
+ return false;
422
+ const configValidator = queryConfig ? new ModuleConfigQueryValidator(Object.assign({}, this.config, queryConfig)).queryable : this.moduleConfigQueryValidator;
423
+ const validators = [
424
+ this.supportedQueryValidator,
425
+ configValidator
426
+ ];
427
+ return validators.every((validator) => validator(query, payloads));
428
+ }
429
+ async resolve(nameOrAddressOrFilter, options) {
430
+ const direction = (options == null ? void 0 : options.direction) ?? "all";
431
+ const up = direction === "up" || direction === "all";
432
+ const down = direction === "down" || direction === "all";
433
+ switch (typeof nameOrAddressOrFilter) {
434
+ case "string": {
435
+ return (down ? await this.downResolver.resolve(nameOrAddressOrFilter, options) : void 0) ?? (up ? await this.upResolver.resolve(nameOrAddressOrFilter, options) : void 0);
436
+ }
437
+ default: {
438
+ const filter = nameOrAddressOrFilter;
439
+ return [
440
+ ...down ? await this.downResolver.resolve(filter, options) : [],
441
+ ...up ? await this.upResolver.resolve(filter, options) : []
442
+ ].filter(duplicateModules);
443
+ }
444
+ }
445
+ }
446
+ start(_timeout) {
447
+ this._startPromise = this._startPromise ?? this.startHandler();
448
+ return this._startPromise;
449
+ }
450
+ async started(notStartedAction = "log", tryStart = true) {
451
+ const started = await this._started;
452
+ if (started === true) {
453
+ return true;
454
+ }
455
+ if (!started) {
456
+ this._started = (async () => {
457
+ var _a, _b, _c;
458
+ if (tryStart) {
459
+ try {
460
+ await this.start();
461
+ return true;
462
+ } catch (ex) {
463
+ handleError(ex, (error) => {
464
+ var _a2;
465
+ (_a2 = this.logger) == null ? void 0 : _a2.warn(`Autostart of Module Failed: ${error.message})`);
466
+ this._started = void 0;
467
+ });
468
+ }
469
+ }
470
+ switch (notStartedAction) {
471
+ case "throw":
472
+ throw Error(`Module not Started [${this.address}]`);
473
+ case "warn":
474
+ (_a = this.logger) == null ? void 0 : _a.warn("Module not started");
475
+ break;
476
+ case "error":
477
+ (_b = this.logger) == null ? void 0 : _b.error("Module not started");
478
+ break;
479
+ case "none":
480
+ break;
481
+ case "log":
482
+ default: {
483
+ (_c = this.logger) == null ? void 0 : _c.log("Module not started");
484
+ break;
485
+ }
486
+ }
487
+ return false;
488
+ })();
489
+ }
490
+ if (!this._started) {
491
+ throw "Failed to create start promise";
492
+ }
493
+ return await this._started;
494
+ }
495
+ async stop(_timeout) {
496
+ return await this.busy(async () => {
497
+ const result = await this.stopHandler();
498
+ this._started = void 0;
499
+ this._startPromise = void 0;
500
+ return result;
501
+ });
502
+ }
503
+ bindHashes(hashes, schema, account) {
504
+ const promise = new PromiseEx((resolve) => {
505
+ const result = this.bindHashesInternal(hashes, schema, account);
506
+ resolve == null ? void 0 : resolve(result);
507
+ return result;
508
+ }, account);
509
+ return promise;
510
+ }
511
+ async bindHashesInternal(hashes, schema, account) {
512
+ var _a;
513
+ const builder = new BoundWitnessBuilder().hashes(hashes, schema).witness(this.account);
514
+ const result = (await (account ? builder.witness(account) : builder).build())[0];
515
+ (_a = this.logger) == null ? void 0 : _a.debug(`result: ${JSON.stringify(result, null, 2)}`);
516
+ return result;
517
+ }
518
+ bindQuery(query, payloads, account) {
519
+ const promise = new PromiseEx(async (resolve) => {
520
+ const result = await this.bindQueryInternal(query, payloads, account);
521
+ resolve == null ? void 0 : resolve(result);
522
+ return result;
523
+ }, account);
524
+ return promise;
525
+ }
526
+ async bindQueryInternal(query, payloads, account) {
527
+ const builder = new QueryBoundWitnessBuilder().payloads(payloads).witness(this.account).query(query);
528
+ const result = await (account ? builder.witness(account) : builder).build();
529
+ return result;
530
+ }
531
+ async bindQueryResult(query, payloads, additionalWitnesses = [], errors) {
532
+ const builder = new BoundWitnessBuilder().payloads(payloads).errors(errors);
533
+ const queryWitnessAccount = this.queryAccounts[query.schema];
534
+ const witnesses = [
535
+ this.account,
536
+ queryWitnessAccount,
537
+ ...additionalWitnesses
538
+ ].filter(exists);
539
+ builder.witnesses(witnesses);
540
+ const result = [
541
+ (await builder.build())[0],
542
+ payloads,
543
+ errors ?? []
544
+ ];
545
+ return result;
546
+ }
547
+ commitArchivist = () => this.getArchivist("commit");
548
+ async describeHandler() {
549
+ var _a;
550
+ const description = {
551
+ address: this.address,
552
+ queries: this.queries,
553
+ schema: ModuleDescriptionSchema
554
+ };
555
+ if ((_a = this.config) == null ? void 0 : _a.name) {
556
+ description.name = this.config.name;
557
+ }
558
+ const discover = await this.discoverHandler();
559
+ description.children = compact((discover == null ? void 0 : discover.map((payload) => {
560
+ const address = payload.schema === AddressSchema ? payload.address : void 0;
561
+ return address != this.address ? address : void 0;
562
+ })) ?? []);
563
+ return description;
564
+ }
565
+ discoverHandler() {
566
+ var _a;
567
+ const config = this.config;
568
+ const address = new PayloadBuilder2({
569
+ schema: AddressSchema
570
+ }).fields({
571
+ address: this.address,
572
+ name: (_a = this.config) == null ? void 0 : _a.name
573
+ }).build();
574
+ const queries = this.queries.map((query) => {
575
+ return new PayloadBuilder2({
576
+ schema: QuerySchema
577
+ }).fields({
578
+ query
579
+ }).build();
580
+ });
581
+ const configSchema = {
582
+ config: config.schema,
583
+ schema: ConfigSchema
584
+ };
585
+ return compact([
586
+ config,
587
+ configSchema,
588
+ address,
589
+ ...queries
590
+ ]);
591
+ }
592
+ async getArchivist(kind) {
593
+ var _a, _b;
594
+ if (!this.config.archivist)
595
+ return void 0;
596
+ const filter = typeof this.config.archivist === "string" || this.config.archivist instanceof String ? this.config.archivist : (_b = (_a = this.config) == null ? void 0 : _a.archivist) == null ? void 0 : _b[kind];
597
+ const resolved = await this.upResolver.resolve(filter);
598
+ return asArchivistInstance(resolved);
599
+ }
600
+ async initializeQueryAccounts() {
601
+ var _a, _b;
602
+ const paths = Object.values(this.queryAccountPaths).filter(exists);
603
+ const distinctPaths = new Set(paths);
604
+ assertEx(distinctPaths.size === paths.length, `${((_a = this.config) == null ? void 0 : _a.name) ? this.config.name + ": " : ""}Duplicate query account paths`);
605
+ const wallet = this.account;
606
+ if (wallet == null ? void 0 : wallet.derivePath) {
607
+ for (const key in this.queryAccountPaths) {
608
+ if (Object.prototype.hasOwnProperty.call(this.queryAccountPaths, key)) {
609
+ const query = key;
610
+ const queryAccountPath = this.queryAccountPaths[query];
611
+ if (queryAccountPath) {
612
+ this._queryAccounts[query] = await ((_b = wallet.derivePath) == null ? void 0 : _b.call(wallet, queryAccountPath));
613
+ }
614
+ }
615
+ }
616
+ }
617
+ }
618
+ manifestHandler(_ignoreAddresses) {
619
+ const name = this.config.name ?? "Anonymous";
620
+ return {
621
+ config: {
622
+ name,
623
+ ...this.config
624
+ },
625
+ schema: ModuleManifestPayloadSchema
626
+ };
627
+ }
628
+ moduleAddressHandler() {
629
+ const queryAccounts = Object.entries(this.queryAccounts).filter((value) => {
630
+ return exists(value[1]);
631
+ }).map(([name2, account]) => {
632
+ const address2 = account.address;
633
+ const previousHash2 = account.previousHash;
634
+ return [
635
+ {
636
+ address: address2,
637
+ name: name2,
638
+ schema: AddressSchema
639
+ },
640
+ {
641
+ address: address2,
642
+ previousHash: previousHash2,
643
+ schema: AddressPreviousHashSchema
644
+ }
645
+ ];
646
+ });
647
+ const address = this.address;
648
+ const name = this.config.name;
649
+ const previousHash = this.address;
650
+ const moduleAccount = name ? {
651
+ address,
652
+ name,
653
+ schema: AddressSchema
654
+ } : {
655
+ address,
656
+ schema: AddressSchema
657
+ };
658
+ const moduleAccountPreviousHash = previousHash ? {
659
+ address,
660
+ previousHash,
661
+ schema: AddressPreviousHashSchema
662
+ } : {
663
+ address,
664
+ schema: AddressPreviousHashSchema
665
+ };
666
+ return [
667
+ moduleAccount,
668
+ moduleAccountPreviousHash,
669
+ ...queryAccounts
670
+ ].flat();
671
+ }
672
+ async queryHandler(query, payloads, queryConfig) {
673
+ await this.started("throw");
674
+ const wrapper = QueryBoundWitnessWrapper3.parseQuery(query, payloads);
675
+ const queryPayload = await wrapper.getQuery();
676
+ assertEx(this.queryable(query, payloads, queryConfig));
677
+ const resultPayloads = [];
678
+ switch (queryPayload.schema) {
679
+ case ModuleManifestQuerySchema: {
680
+ resultPayloads.push(await this.manifestHandler());
681
+ break;
682
+ }
683
+ case ModuleDiscoverQuerySchema: {
684
+ resultPayloads.push(...await this.discoverHandler());
685
+ break;
686
+ }
687
+ case ModuleDescribeQuerySchema: {
688
+ resultPayloads.push(await this.describeHandler());
689
+ break;
690
+ }
691
+ case ModuleAddressQuerySchema: {
692
+ resultPayloads.push(...await this.moduleAddressHandler());
693
+ break;
694
+ }
695
+ case ModuleSubscribeQuerySchema: {
696
+ this.subscribeHandler();
697
+ break;
698
+ }
699
+ default:
700
+ throw Error(`Unsupported Query [${queryPayload.schema}]`);
701
+ }
702
+ return resultPayloads;
703
+ }
704
+ readArchivist = () => this.getArchivist("read");
705
+ async startHandler() {
706
+ this.validateConfig();
707
+ await this.initializeQueryAccounts();
708
+ this._started = true;
709
+ return true;
710
+ }
711
+ stopHandler(_timeout) {
712
+ this._started = void 0;
713
+ return true;
714
+ }
715
+ subscribeHandler() {
716
+ return;
717
+ }
718
+ validateConfig(config, parents = []) {
719
+ return Object.entries(config ?? this.config ?? {}).reduce((valid, [key, value]) => {
720
+ var _a, _b;
721
+ switch (typeof value) {
722
+ case "function":
723
+ (_a = this.logger) == null ? void 0 : _a.warn(`Fields of type function not allowed in config [${parents == null ? void 0 : parents.join(".")}.${key}]`);
724
+ return false;
725
+ case "object": {
726
+ if (Array.isArray(value)) {
727
+ return value.reduce((valid2, value2) => {
728
+ return this.validateConfig(value2, [
729
+ ...parents,
730
+ key
731
+ ]) && valid2;
732
+ }, true) && valid;
733
+ }
734
+ if (!serializableField(value)) {
735
+ (_b = this.logger) == null ? void 0 : _b.warn(`Fields that are not serializable to JSON are not allowed in config [${parents == null ? void 0 : parents.join(".")}.${key}]`);
736
+ return false;
737
+ }
738
+ return value ? this.validateConfig(value, [
739
+ ...parents,
740
+ key
741
+ ]) && valid : true;
742
+ }
743
+ default:
744
+ return valid;
745
+ }
746
+ }, true);
747
+ }
748
+ writeArchivist = () => this.getArchivist("write");
749
+ };
750
+ __name(_AbstractModule, "AbstractModule");
751
+ __publicField(_AbstractModule, "configSchemas");
752
+ __publicField(_AbstractModule, "enableLazyLoad", false);
753
+ __publicField(_AbstractModule, "privateConstructorKey", Date.now().toString());
754
+ var AbstractModule = _AbstractModule;
755
+
756
+ // src/AbstractModuleInstance.ts
757
+ var _AbstractModuleInstance = class _AbstractModuleInstance extends AbstractModule {
9
758
  constructor(privateConstructorKey, params, account) {
10
- assertEx(AbstractModule.privateConstructorKey === privateConstructorKey, "Use create function instead of constructor");
759
+ assertEx2(AbstractModule.privateConstructorKey === privateConstructorKey, "Use create function instead of constructor");
11
760
  const mutatedParams = {
12
761
  ...params
13
762
  };
@@ -38,7 +787,9 @@ class AbstractModuleInstance extends AbstractModule {
38
787
  subscribe(_queryAccount) {
39
788
  return this.subscribeHandler();
40
789
  }
41
- }
790
+ };
791
+ __name(_AbstractModuleInstance, "AbstractModuleInstance");
792
+ var AbstractModuleInstance = _AbstractModuleInstance;
42
793
  export {
43
794
  AbstractModuleInstance
44
795
  };