@xyo-network/module-abstract 2.75.15 → 2.75.16

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