@xyo-network/module-abstract 2.75.0 → 2.75.2

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