@xyo-network/module-abstract 2.99.1 → 2.99.3

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 (65) hide show
  1. package/dist/neutral/AbstractModule.d.cts +108 -0
  2. package/dist/neutral/AbstractModule.d.cts.map +1 -0
  3. package/dist/neutral/AbstractModule.d.mts +108 -0
  4. package/dist/neutral/AbstractModule.d.mts.map +1 -0
  5. package/dist/neutral/AbstractModule.d.ts +108 -0
  6. package/dist/neutral/AbstractModule.d.ts.map +1 -0
  7. package/dist/neutral/AbstractModuleInstance.d.cts +53 -0
  8. package/dist/neutral/AbstractModuleInstance.d.cts.map +1 -0
  9. package/dist/neutral/AbstractModuleInstance.d.mts +53 -0
  10. package/dist/neutral/AbstractModuleInstance.d.mts.map +1 -0
  11. package/dist/neutral/AbstractModuleInstance.d.ts +53 -0
  12. package/dist/neutral/AbstractModuleInstance.d.ts.map +1 -0
  13. package/dist/neutral/BaseEmitter.d.cts +17 -0
  14. package/dist/neutral/BaseEmitter.d.cts.map +1 -0
  15. package/dist/neutral/BaseEmitter.d.mts +17 -0
  16. package/dist/neutral/BaseEmitter.d.mts.map +1 -0
  17. package/dist/neutral/BaseEmitter.d.ts +17 -0
  18. package/dist/neutral/BaseEmitter.d.ts.map +1 -0
  19. package/dist/neutral/Error.d.cts +16 -0
  20. package/dist/neutral/Error.d.cts.map +1 -0
  21. package/dist/neutral/Error.d.mts +16 -0
  22. package/dist/neutral/Error.d.mts.map +1 -0
  23. package/dist/neutral/Error.d.ts +16 -0
  24. package/dist/neutral/Error.d.ts.map +1 -0
  25. package/dist/neutral/QueryValidator/ModuleConfigQueryValidator.d.cts +17 -0
  26. package/dist/neutral/QueryValidator/ModuleConfigQueryValidator.d.cts.map +1 -0
  27. package/dist/neutral/QueryValidator/ModuleConfigQueryValidator.d.mts +17 -0
  28. package/dist/neutral/QueryValidator/ModuleConfigQueryValidator.d.mts.map +1 -0
  29. package/dist/neutral/QueryValidator/ModuleConfigQueryValidator.d.ts +17 -0
  30. package/dist/neutral/QueryValidator/ModuleConfigQueryValidator.d.ts.map +1 -0
  31. package/dist/neutral/QueryValidator/QueryValidator.d.cts +8 -0
  32. package/dist/neutral/QueryValidator/QueryValidator.d.cts.map +1 -0
  33. package/dist/neutral/QueryValidator/QueryValidator.d.mts +8 -0
  34. package/dist/neutral/QueryValidator/QueryValidator.d.mts.map +1 -0
  35. package/dist/neutral/QueryValidator/QueryValidator.d.ts +8 -0
  36. package/dist/neutral/QueryValidator/QueryValidator.d.ts.map +1 -0
  37. package/dist/neutral/QueryValidator/SupportedQueryValidator.d.cts +22 -0
  38. package/dist/neutral/QueryValidator/SupportedQueryValidator.d.cts.map +1 -0
  39. package/dist/neutral/QueryValidator/SupportedQueryValidator.d.mts +22 -0
  40. package/dist/neutral/QueryValidator/SupportedQueryValidator.d.mts.map +1 -0
  41. package/dist/neutral/QueryValidator/SupportedQueryValidator.d.ts +22 -0
  42. package/dist/neutral/QueryValidator/SupportedQueryValidator.d.ts.map +1 -0
  43. package/dist/neutral/QueryValidator/index.d.cts +4 -0
  44. package/dist/neutral/QueryValidator/index.d.cts.map +1 -0
  45. package/dist/neutral/QueryValidator/index.d.mts +4 -0
  46. package/dist/neutral/QueryValidator/index.d.mts.map +1 -0
  47. package/dist/neutral/QueryValidator/index.d.ts +4 -0
  48. package/dist/neutral/QueryValidator/index.d.ts.map +1 -0
  49. package/dist/neutral/determineAccount.d.cts +14 -0
  50. package/dist/neutral/determineAccount.d.cts.map +1 -0
  51. package/dist/neutral/determineAccount.d.mts +14 -0
  52. package/dist/neutral/determineAccount.d.mts.map +1 -0
  53. package/dist/neutral/determineAccount.d.ts +14 -0
  54. package/dist/neutral/determineAccount.d.ts.map +1 -0
  55. package/dist/neutral/index.cjs +1059 -0
  56. package/dist/neutral/index.cjs.map +1 -0
  57. package/dist/neutral/index.d.cts +6 -0
  58. package/dist/neutral/index.d.cts.map +1 -0
  59. package/dist/neutral/index.d.mts +6 -0
  60. package/dist/neutral/index.d.mts.map +1 -0
  61. package/dist/neutral/index.d.ts +6 -0
  62. package/dist/neutral/index.d.ts.map +1 -0
  63. package/dist/neutral/index.js +1038 -0
  64. package/dist/neutral/index.js.map +1 -0
  65. package/package.json +28 -28
@@ -0,0 +1,1059 @@
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 __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+
21
+ // src/index.ts
22
+ var src_exports = {};
23
+ __export(src_exports, {
24
+ AbstractModule: () => AbstractModule,
25
+ AbstractModuleInstance: () => AbstractModuleInstance,
26
+ BaseEmitter: () => BaseEmitter,
27
+ ModuleConfigQueryValidator: () => ModuleConfigQueryValidator,
28
+ ModuleErrorBuilder: () => ModuleErrorBuilder,
29
+ SupportedQueryValidator: () => SupportedQueryValidator,
30
+ isQuerySupportedByModule: () => isQuerySupportedByModule
31
+ });
32
+ module.exports = __toCommonJS(src_exports);
33
+
34
+ // src/AbstractModule.ts
35
+ var import_assert2 = require("@xylabs/assert");
36
+ var import_error = require("@xylabs/error");
37
+ var import_exists = require("@xylabs/exists");
38
+ var import_lodash = require("@xylabs/lodash");
39
+ var import_logger = require("@xylabs/logger");
40
+ var import_object2 = require("@xylabs/object");
41
+ var import_promise = require("@xylabs/promise");
42
+ var import_account2 = require("@xyo-network/account");
43
+ var import_address_payload_plugin = require("@xyo-network/address-payload-plugin");
44
+ var import_archivist_model = require("@xyo-network/archivist-model");
45
+ var import_boundwitness_builder = require("@xyo-network/boundwitness-builder");
46
+ var import_boundwitness_wrapper3 = require("@xyo-network/boundwitness-wrapper");
47
+ var import_config_payload_plugin = require("@xyo-network/config-payload-plugin");
48
+ var import_module_model = require("@xyo-network/module-model");
49
+ var import_payload_builder2 = require("@xyo-network/payload-builder");
50
+ var import_query_payload_plugin = require("@xyo-network/query-payload-plugin");
51
+ var import_lru_cache = require("lru-cache");
52
+
53
+ // src/BaseEmitter.ts
54
+ var import_object = require("@xylabs/object");
55
+ var import_module_events = require("@xyo-network/module-events");
56
+ var BaseEmitter = class extends import_object.Base {
57
+ static {
58
+ __name(this, "BaseEmitter");
59
+ }
60
+ //just here to query types
61
+ eventData = {};
62
+ events;
63
+ constructor(params) {
64
+ super(params);
65
+ this.events = new import_module_events.Events();
66
+ }
67
+ clearListeners(eventNames) {
68
+ return this.events.clearListeners(eventNames);
69
+ }
70
+ emit(eventName, eventArgs) {
71
+ return this.events.emit(eventName, eventArgs);
72
+ }
73
+ emitSerial(eventName, eventArgs) {
74
+ return this.events.emitSerial(eventName, eventArgs);
75
+ }
76
+ listenerCount(eventNames) {
77
+ return this.events.listenerCount(eventNames);
78
+ }
79
+ off(eventNames, listener) {
80
+ return this.events.off(eventNames, listener);
81
+ }
82
+ offAny(listener) {
83
+ return this.events.offAny(listener);
84
+ }
85
+ on(eventNames, listener) {
86
+ return this.events.on(eventNames, listener);
87
+ }
88
+ onAny(listener) {
89
+ return this.events.onAny(listener);
90
+ }
91
+ once(eventName, listener) {
92
+ return this.events.once(eventName, listener);
93
+ }
94
+ };
95
+
96
+ // src/determineAccount.ts
97
+ var import_assert = require("@xylabs/assert");
98
+ var import_account = require("@xyo-network/account");
99
+ var isDetermineAccountFromAccountParams = /* @__PURE__ */ __name((params) => {
100
+ (0, import_assert.assertEx)(!params.accountPath, () => "accountPath may not be provided when account is provided");
101
+ return !!params.account;
102
+ }, "isDetermineAccountFromAccountParams");
103
+ var isDetermineAccountFromWalletParams = /* @__PURE__ */ __name((params) => {
104
+ return !!params.wallet;
105
+ }, "isDetermineAccountFromWalletParams");
106
+ async function determineAccount(params, allowRandomAccount = true) {
107
+ if (isDetermineAccountFromAccountParams(params)) {
108
+ if (params.account === "random") {
109
+ (0, import_assert.assertEx)(allowRandomAccount, () => "Random address not allowed");
110
+ return import_account.Account.randomSync();
111
+ }
112
+ return params.account;
113
+ }
114
+ if (isDetermineAccountFromWalletParams(params)) {
115
+ return (0, import_assert.assertEx)(params.accountPath ? await params.wallet.derivePath(params.accountPath) : params.wallet, () => "Failed to derive account from path");
116
+ }
117
+ console.warn("AbstractModule.determineAccount: No account or wallet provided - Creating Random account");
118
+ return import_account.Account.randomSync();
119
+ }
120
+ __name(determineAccount, "determineAccount");
121
+
122
+ // src/Error.ts
123
+ var import_payload_builder = require("@xyo-network/payload-builder");
124
+ var import_payload_model = require("@xyo-network/payload-model");
125
+ var ModuleErrorBuilder = class extends import_payload_builder.PayloadBuilder {
126
+ static {
127
+ __name(this, "ModuleErrorBuilder");
128
+ }
129
+ _message;
130
+ _name;
131
+ _query;
132
+ _sources;
133
+ constructor() {
134
+ super({
135
+ schema: import_payload_model.ModuleErrorSchema
136
+ });
137
+ }
138
+ build() {
139
+ this.fields({
140
+ message: this._message,
141
+ name: this._name,
142
+ query: this._query,
143
+ schema: import_payload_model.ModuleErrorSchema,
144
+ sources: this._sources
145
+ });
146
+ return super.build();
147
+ }
148
+ message(message) {
149
+ this._message = message;
150
+ return this;
151
+ }
152
+ name(name) {
153
+ this._name = name;
154
+ return this;
155
+ }
156
+ query(query) {
157
+ this._query = query;
158
+ return this;
159
+ }
160
+ sources(sources) {
161
+ this._sources = sources;
162
+ return this;
163
+ }
164
+ };
165
+
166
+ // src/QueryValidator/ModuleConfigQueryValidator.ts
167
+ var import_boundwitness_wrapper = require("@xyo-network/boundwitness-wrapper");
168
+ var delimiter = "";
169
+ var ModuleConfigQueryValidator = class {
170
+ static {
171
+ __name(this, "ModuleConfigQueryValidator");
172
+ }
173
+ allowed = {};
174
+ disallowed = {};
175
+ hasAllowedRules;
176
+ hasDisallowedRules;
177
+ hasRules;
178
+ constructor(config) {
179
+ if (config?.security?.allowed) {
180
+ for (const [schema, addresses] of Object.entries(config.security?.allowed)) {
181
+ this.allowed[schema] = addresses.map(toAddressesString);
182
+ }
183
+ }
184
+ if (config?.security?.disallowed) {
185
+ for (const [schema, addresses] of Object.entries(config.security?.disallowed)) {
186
+ this.disallowed[schema] = addresses.map(toAddressesString);
187
+ }
188
+ }
189
+ this.hasAllowedRules = Object.keys(this.allowed).length > 0;
190
+ this.hasDisallowedRules = Object.keys(this.disallowed).length > 0;
191
+ this.hasRules = this.hasAllowedRules || this.hasDisallowedRules;
192
+ }
193
+ queryable = async (query, payloads) => {
194
+ if (!this.hasRules)
195
+ return true;
196
+ const addresses = query.addresses;
197
+ if (addresses.length === 0)
198
+ return false;
199
+ const wrapper = await import_boundwitness_wrapper.QueryBoundWitnessWrapper.parseQuery(query, payloads);
200
+ const schema = (await wrapper.getQuery()).schema;
201
+ return this.queryAllowed(schema, addresses) && !this.queryDisallowed(schema, addresses);
202
+ };
203
+ queryAllowed = (schema, addresses) => {
204
+ if (!this.hasAllowedRules)
205
+ return true;
206
+ if (addresses.length > 1) {
207
+ const signatories = toAddressesString(addresses);
208
+ const validCosigners = this.allowed?.[schema]?.includes(signatories);
209
+ if (validCosigners)
210
+ return true;
211
+ }
212
+ return addresses.every((address) => this.allowed?.[schema]?.includes(address) || false);
213
+ };
214
+ queryDisallowed = (schema, addresses) => {
215
+ if (!this.hasDisallowedRules)
216
+ return false;
217
+ return addresses.some((address) => this.disallowed?.[schema]?.includes(address));
218
+ };
219
+ };
220
+ var toAddressesString = /* @__PURE__ */ __name((addresses) => {
221
+ return Array.isArray(addresses) ? addresses.sort().map((address) => address.toLowerCase()).join(delimiter) : addresses.toLowerCase();
222
+ }, "toAddressesString");
223
+
224
+ // src/QueryValidator/SupportedQueryValidator.ts
225
+ var import_boundwitness_wrapper2 = require("@xyo-network/boundwitness-wrapper");
226
+ var isQuerySupportedByModule = /* @__PURE__ */ __name(async (mod, query, payloads) => {
227
+ const wrapper = await import_boundwitness_wrapper2.QueryBoundWitnessWrapper.parseQuery(query, payloads);
228
+ const schema = (await wrapper.getQuery()).schema;
229
+ return mod.queries.includes(schema);
230
+ }, "isQuerySupportedByModule");
231
+ var SupportedQueryValidator = class {
232
+ static {
233
+ __name(this, "SupportedQueryValidator");
234
+ }
235
+ mod;
236
+ constructor(mod) {
237
+ this.mod = mod;
238
+ this.queryable = (query, payloads) => {
239
+ return isQuerySupportedByModule(this.mod, query, payloads);
240
+ };
241
+ }
242
+ queryable;
243
+ };
244
+
245
+ // src/AbstractModule.ts
246
+ var AbstractModule = class _AbstractModule extends BaseEmitter {
247
+ static {
248
+ __name(this, "AbstractModule");
249
+ }
250
+ static allowRandomAccount = true;
251
+ static configSchemas = [
252
+ import_module_model.ModuleConfigSchema
253
+ ];
254
+ static defaultConfigSchema = import_module_model.ModuleConfigSchema;
255
+ static defaultLogger = new import_logger.ConsoleLogger(import_logger.LogLevel.warn);
256
+ static enableLazyLoad = false;
257
+ static labels = {};
258
+ static uniqueName = (0, import_object2.globallyUnique)("AbstractModule", _AbstractModule, "xyo");
259
+ static privateConstructorKey = Date.now().toString();
260
+ _account = void 0;
261
+ _baseModuleQueryAccountPaths = {
262
+ [import_module_model.ModuleAddressQuerySchema]: "1",
263
+ [import_module_model.ModuleManifestQuerySchema]: "5",
264
+ [import_module_model.ModuleStateQuerySchema]: "6",
265
+ [import_module_model.ModuleSubscribeQuerySchema]: "3"
266
+ };
267
+ //cache manifest based on maxDepth
268
+ _cachedManifests = new import_lru_cache.LRUCache({
269
+ max: 10,
270
+ ttl: 1e3 * 60 * 5
271
+ });
272
+ _lastError;
273
+ _queryAccounts = {
274
+ [import_module_model.ModuleAddressQuerySchema]: void 0,
275
+ [import_module_model.ModuleManifestQuerySchema]: void 0,
276
+ [import_module_model.ModuleStateQuerySchema]: void 0,
277
+ [import_module_model.ModuleSubscribeQuerySchema]: void 0
278
+ };
279
+ _startPromise = void 0;
280
+ _started = void 0;
281
+ moduleConfigQueryValidator;
282
+ supportedQueryValidator;
283
+ _busyCount = 0;
284
+ _status = "stopped";
285
+ constructor(privateConstructorKey, params, account) {
286
+ (0, import_assert2.assertEx)(_AbstractModule.privateConstructorKey === privateConstructorKey, () => "Use create function instead of constructor");
287
+ const mutatedParams = {
288
+ ...params
289
+ };
290
+ super(mutatedParams);
291
+ this._account = account;
292
+ this.supportedQueryValidator = new SupportedQueryValidator(this).queryable;
293
+ this.moduleConfigQueryValidator = new ModuleConfigQueryValidator(mutatedParams?.config).queryable;
294
+ }
295
+ get account() {
296
+ return (0, import_assert2.assertEx)(this._account, () => "Missing account");
297
+ }
298
+ get address() {
299
+ return this.account.address;
300
+ }
301
+ get allowAnonymous() {
302
+ return !!this.config.security?.allowAnonymous;
303
+ }
304
+ get allowNameResolution() {
305
+ return this.params.allowNameResolution ?? true;
306
+ }
307
+ get archiving() {
308
+ return this.config.archiving;
309
+ }
310
+ get archivist() {
311
+ return this.config.archivist;
312
+ }
313
+ get config() {
314
+ return this.params.config;
315
+ }
316
+ get dead() {
317
+ return this.status === "dead";
318
+ }
319
+ get ephemeralQueryAccountEnabled() {
320
+ return !!this.params.ephemeralQueryAccountEnabled;
321
+ }
322
+ get id() {
323
+ return this.config.name ?? this.address;
324
+ }
325
+ get logger() {
326
+ return this.params?.logger ?? _AbstractModule.defaultLogger ?? import_object2.Base.defaultLogger;
327
+ }
328
+ get priority() {
329
+ return import_module_model.ObjectResolverPriority.Normal;
330
+ }
331
+ get queries() {
332
+ return [
333
+ import_module_model.ModuleAddressQuerySchema,
334
+ import_module_model.ModuleSubscribeQuerySchema,
335
+ import_module_model.ModuleManifestQuerySchema,
336
+ import_module_model.ModuleStateQuerySchema
337
+ ];
338
+ }
339
+ get queryAccountPaths() {
340
+ return {
341
+ ...this._baseModuleQueryAccountPaths,
342
+ ...this._queryAccountPaths
343
+ };
344
+ }
345
+ get queryAccounts() {
346
+ return this._queryAccounts;
347
+ }
348
+ get status() {
349
+ return this._status;
350
+ }
351
+ get timestamp() {
352
+ return this.config.timestamp ?? false;
353
+ }
354
+ get baseModuleQueryAccountPaths() {
355
+ return this._baseModuleQueryAccountPaths;
356
+ }
357
+ set status(value) {
358
+ if (this._status !== "dead") {
359
+ this._status = value;
360
+ }
361
+ }
362
+ static _getRootFunction(funcName) {
363
+ let anyThis = this;
364
+ while (anyThis.__proto__[funcName]) {
365
+ anyThis = anyThis.__proto__;
366
+ }
367
+ return anyThis[funcName];
368
+ }
369
+ static _noOverride(functionName) {
370
+ const thisFunc = this[functionName];
371
+ const rootFunc = this._getRootFunction(functionName);
372
+ (0, import_assert2.assertEx)(thisFunc === rootFunc, () => `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
373
+ }
374
+ static async create(params) {
375
+ this._noOverride("create");
376
+ if (!this.configSchemas || this.configSchemas.length === 0) {
377
+ throw new Error(`Missing configSchema [${params?.config?.schema}][${this.name}]`);
378
+ }
379
+ if (!this.defaultConfigSchema) {
380
+ throw new Error(`Missing defaultConfigSchema [${params?.config?.schema}][${this.name}]`);
381
+ }
382
+ (0, import_assert2.assertEx)(params?.config?.name === void 0 || (0, import_module_model.isModuleName)(params.config.name), () => `Invalid module name: ${params?.config?.name}`);
383
+ const { account } = params ?? {};
384
+ const schema = params?.config?.schema ?? this.defaultConfigSchema;
385
+ const allowedSchemas = this.configSchemas;
386
+ (0, import_assert2.assertEx)(allowedSchemas.includes(schema), () => `Bad Config Schema [Received ${schema}] [Expected ${JSON.stringify(allowedSchemas)}]`);
387
+ const mutatedConfig = {
388
+ ...params?.config,
389
+ schema
390
+ };
391
+ params?.logger?.debug(`config: ${JSON.stringify(mutatedConfig, null, 2)}`);
392
+ const mutatedParams = {
393
+ ...params,
394
+ config: mutatedConfig
395
+ };
396
+ const activeLogger = params?.logger ?? _AbstractModule.defaultLogger;
397
+ const generatedAccount = await _AbstractModule.determineAccount({
398
+ account
399
+ });
400
+ const address = generatedAccount.address;
401
+ mutatedParams.logger = activeLogger ? new import_logger.IdLogger(activeLogger, () => `0x${address}`) : void 0;
402
+ const newModule = new this(_AbstractModule.privateConstructorKey, mutatedParams, generatedAccount);
403
+ if (!_AbstractModule.enableLazyLoad) {
404
+ await newModule.start?.();
405
+ }
406
+ return newModule;
407
+ }
408
+ static async determineAccount(params) {
409
+ return await determineAccount(params, this.allowRandomAccount);
410
+ }
411
+ static factory(params) {
412
+ return import_module_model.ModuleFactory.withParams(this, params);
413
+ }
414
+ _getRootFunction(funcName) {
415
+ let anyThis = this;
416
+ while (anyThis.__proto__[funcName]) {
417
+ anyThis = anyThis.__proto__;
418
+ }
419
+ return anyThis[funcName];
420
+ }
421
+ async busy(closure) {
422
+ if (this._busyCount <= 0) {
423
+ this._busyCount = 0;
424
+ const args = {
425
+ busy: true,
426
+ module: this
427
+ };
428
+ await this.emit("moduleBusy", args);
429
+ }
430
+ this._busyCount++;
431
+ try {
432
+ return await closure();
433
+ } finally {
434
+ this._busyCount--;
435
+ if (this._busyCount <= 0) {
436
+ this._busyCount = 0;
437
+ const args = {
438
+ busy: false,
439
+ module: this
440
+ };
441
+ await this.emit("moduleBusy", args);
442
+ }
443
+ }
444
+ }
445
+ emit(eventName, eventArgs) {
446
+ return super.emit(eventName, eventArgs);
447
+ }
448
+ previousHash() {
449
+ this._checkDead();
450
+ return this.account.previousHash;
451
+ }
452
+ async query(query, payloads, queryConfig) {
453
+ this._checkDead();
454
+ this._noOverride("query");
455
+ const sourceQuery = await import_payload_builder2.PayloadBuilder.build((0, import_assert2.assertEx)(import_boundwitness_wrapper3.QueryBoundWitnessWrapper.unwrap(query), () => "Invalid query"));
456
+ return await this.busy(async () => {
457
+ const resultPayloads = [];
458
+ const errorPayloads = [];
459
+ const queryAccount = this.ephemeralQueryAccountEnabled ? import_account2.Account.randomSync() : void 0;
460
+ try {
461
+ await this.started("throw");
462
+ if (!this.allowAnonymous && query.addresses.length === 0) {
463
+ throw new Error(`Anonymous Queries not allowed, but running anyway [${this.config.name}], [${this.address}]`);
464
+ }
465
+ if (queryConfig?.allowedQueries) {
466
+ (0, import_assert2.assertEx)(queryConfig?.allowedQueries.includes(sourceQuery.schema), () => `Query not allowed [${sourceQuery.schema}]`);
467
+ }
468
+ resultPayloads.push(...await this.queryHandler(sourceQuery, payloads, queryConfig));
469
+ } catch (ex) {
470
+ await (0, import_error.handleErrorAsync)(ex, async (error) => {
471
+ this._lastError = error;
472
+ errorPayloads.push(await new ModuleErrorBuilder().sources([
473
+ sourceQuery.$hash
474
+ ]).name(this.config.name ?? "<Unknown>").query(sourceQuery.schema).message(error.message).build());
475
+ });
476
+ }
477
+ if (this.timestamp) {
478
+ const timestamp = {
479
+ schema: "network.xyo.timestamp",
480
+ timestamp: Date.now()
481
+ };
482
+ resultPayloads.push(timestamp);
483
+ }
484
+ const result = await this.bindQueryResult(sourceQuery, resultPayloads, queryAccount ? [
485
+ queryAccount
486
+ ] : [], errorPayloads);
487
+ const args = {
488
+ module: this,
489
+ payloads,
490
+ query: sourceQuery,
491
+ result
492
+ };
493
+ await this.emit("moduleQueried", args);
494
+ return result;
495
+ });
496
+ }
497
+ async queryable(query, payloads, queryConfig) {
498
+ if (this.dead) {
499
+ return false;
500
+ }
501
+ if (!await this.started("warn"))
502
+ return false;
503
+ const configValidator = queryConfig ? new ModuleConfigQueryValidator(Object.assign({}, this.config, queryConfig)).queryable : this.moduleConfigQueryValidator;
504
+ const validators = [
505
+ this.supportedQueryValidator,
506
+ configValidator
507
+ ];
508
+ return validators.every((validator) => validator(query, payloads));
509
+ }
510
+ start(_timeout) {
511
+ this._startPromise = this._startPromise ?? this.startHandler();
512
+ const result = this._startPromise;
513
+ this.status = result ? "started" : "dead";
514
+ return result;
515
+ }
516
+ async started(notStartedAction = "log", tryStart = true) {
517
+ const started = await this._started;
518
+ if (started === true) {
519
+ return true;
520
+ }
521
+ if (!started) {
522
+ this._started = (async () => {
523
+ if (tryStart) {
524
+ try {
525
+ await this.start();
526
+ return true;
527
+ } catch (ex) {
528
+ (0, import_error.handleError)(ex, (error) => {
529
+ this.logger?.warn(`Autostart of Module Failed: ${error.message})`);
530
+ this._started = void 0;
531
+ });
532
+ }
533
+ }
534
+ switch (notStartedAction) {
535
+ case "throw": {
536
+ throw new Error(`Module not Started [${this.address}]`);
537
+ }
538
+ case "warn": {
539
+ this.logger?.warn("Module not started");
540
+ break;
541
+ }
542
+ case "error": {
543
+ this.logger?.error("Module not started");
544
+ break;
545
+ }
546
+ case "none": {
547
+ break;
548
+ }
549
+ default: {
550
+ this.logger?.log("Module not started");
551
+ break;
552
+ }
553
+ }
554
+ return false;
555
+ })();
556
+ }
557
+ if (!this._started) {
558
+ throw "Failed to create start promise";
559
+ }
560
+ return await this._started;
561
+ }
562
+ async stop(_timeout) {
563
+ return await this.busy(async () => {
564
+ const result = await this.stopHandler();
565
+ this._started = void 0;
566
+ this._startPromise = void 0;
567
+ this.status = result ? "stopped" : "dead";
568
+ return result;
569
+ });
570
+ }
571
+ _checkDead() {
572
+ if (this.dead) {
573
+ throw new import_module_model.DeadModuleError(this.id, this._lastError);
574
+ }
575
+ }
576
+ _noOverride(functionName) {
577
+ const thisFunc = this[functionName];
578
+ const rootFunc = this._getRootFunction(functionName);
579
+ (0, import_assert2.assertEx)(thisFunc === rootFunc, () => `Override not allowed for [${functionName}] - override ${functionName}Handler instead`);
580
+ }
581
+ async archivistInstance(required = false) {
582
+ const archivist = this.archivist;
583
+ if (!archivist) {
584
+ if (required) {
585
+ throw new Error("No archivist specified");
586
+ }
587
+ return void 0;
588
+ }
589
+ const resolved = await this.upResolver.resolve(archivist) ?? await this.downResolver.resolve(archivist);
590
+ if (required) {
591
+ (0, import_assert2.assertEx)(resolved, () => `Unable to resolve archivist [${archivist}]`);
592
+ }
593
+ return resolved ? (0, import_archivist_model.asArchivistInstance)(resolved, () => `Specified archivist is not an Archivist [${archivist}]`) : void 0;
594
+ }
595
+ bindHashes(hashes, schema, account) {
596
+ const promise = new import_promise.PromiseEx((resolve) => {
597
+ const result = this.bindHashesInternal(hashes, schema, account);
598
+ resolve?.(result);
599
+ return result;
600
+ }, account);
601
+ return promise;
602
+ }
603
+ async bindHashesInternal(hashes, schema, account) {
604
+ const builder = new import_boundwitness_builder.BoundWitnessBuilder().hashes(hashes, schema).witness(this.account);
605
+ const result = (await (account ? builder.witness(account) : builder).build())[0];
606
+ this.logger?.debug(`result: ${JSON.stringify(result, null, 2)}`);
607
+ return result;
608
+ }
609
+ bindQuery(query, payloads, account) {
610
+ const promise = new import_promise.PromiseEx(async (resolve) => {
611
+ const result = await this.bindQueryInternal(query, payloads, account);
612
+ resolve?.(result);
613
+ return result;
614
+ }, account);
615
+ return promise;
616
+ }
617
+ async bindQueryInternal(query, payloads, account) {
618
+ const builder = await new import_boundwitness_builder.QueryBoundWitnessBuilder().payloads(payloads).witness(this.account).query(query);
619
+ const result = await (account ? builder.witness(account) : builder).build();
620
+ return result;
621
+ }
622
+ async bindQueryResult(query, payloads, additionalWitnesses = [], errors) {
623
+ const builder = new import_boundwitness_builder.BoundWitnessBuilder().payloads(payloads).errors(errors).sourceQuery(query.$hash);
624
+ const queryWitnessAccount = this.queryAccounts[query.schema];
625
+ const witnesses = [
626
+ this.account,
627
+ queryWitnessAccount,
628
+ ...additionalWitnesses
629
+ ].filter(import_exists.exists);
630
+ builder.witnesses(witnesses);
631
+ const result = [
632
+ (await builder.build())[0],
633
+ await Promise.all(payloads.map((payload) => import_payload_builder2.PayloadBuilder.build(payload))),
634
+ await Promise.all((errors ?? [])?.map((error) => import_payload_builder2.PayloadBuilder.build(error)))
635
+ ];
636
+ if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
637
+ await this.storeToArchivists(result.flat());
638
+ }
639
+ return result;
640
+ }
641
+ async generateConfigAndAddress(_maxDepth) {
642
+ const config = await import_payload_builder2.PayloadBuilder.build(this.config);
643
+ const address = await new import_payload_builder2.PayloadBuilder({
644
+ schema: import_address_payload_plugin.AddressSchema
645
+ }).fields({
646
+ address: this.address,
647
+ name: this.config?.name
648
+ }).build();
649
+ const queries = await Promise.all(this.queries.map(async (query) => {
650
+ return await new import_payload_builder2.PayloadBuilder({
651
+ schema: import_query_payload_plugin.QuerySchema
652
+ }).fields({
653
+ query
654
+ }).build();
655
+ }));
656
+ const configSchema = await import_payload_builder2.PayloadBuilder.build({
657
+ config: config.schema,
658
+ schema: import_config_payload_plugin.ConfigSchema
659
+ });
660
+ return (0, import_lodash.compact)([
661
+ config,
662
+ configSchema,
663
+ address,
664
+ ...queries
665
+ ]);
666
+ }
667
+ async generateDescribe() {
668
+ const description = {
669
+ address: this.address,
670
+ queries: this.queries,
671
+ schema: import_module_model.ModuleDescriptionSchema
672
+ };
673
+ if (this.config?.name) {
674
+ description.name = this.config.name;
675
+ }
676
+ const discover = await this.generateConfigAndAddress();
677
+ description.children = (0, import_lodash.compact)(discover?.map((payload) => {
678
+ const address = payload.schema === import_address_payload_plugin.AddressSchema ? payload.address : void 0;
679
+ return address == this.address ? void 0 : address;
680
+ }) ?? []);
681
+ return description;
682
+ }
683
+ /** @deprecated use archivistInstance() instead */
684
+ async getArchivist() {
685
+ return await this.archivistInstance();
686
+ }
687
+ async initializeQueryAccounts() {
688
+ const paths = Object.values(this.queryAccountPaths).filter(import_exists.exists);
689
+ const distinctPaths = new Set(paths);
690
+ (0, import_assert2.assertEx)(distinctPaths.size === paths.length, () => `${this.config?.name ? this.config.name + ": " : ""}Duplicate query account paths`);
691
+ const wallet = this.account;
692
+ if (wallet?.derivePath) {
693
+ for (const key in this.queryAccountPaths) {
694
+ if (Object.prototype.hasOwnProperty.call(this.queryAccountPaths, key)) {
695
+ const query = key;
696
+ const queryAccountPath = this.queryAccountPaths[query];
697
+ if (queryAccountPath) {
698
+ this._queryAccounts[query] = await wallet.derivePath?.(queryAccountPath);
699
+ }
700
+ }
701
+ }
702
+ }
703
+ }
704
+ manifestHandler(_maxDepth = 1, _ignoreAddresses = []) {
705
+ throw new Error("Not supported");
706
+ }
707
+ moduleAddressHandler() {
708
+ const queryAccounts = Object.entries(this.queryAccounts).filter((value) => {
709
+ return (0, import_exists.exists)(value[1]);
710
+ }).map(([name2, account]) => {
711
+ const address2 = account.address;
712
+ const previousHash2 = account.previousHash;
713
+ return [
714
+ {
715
+ address: address2,
716
+ name: name2,
717
+ schema: import_address_payload_plugin.AddressSchema
718
+ },
719
+ {
720
+ address: address2,
721
+ previousHash: previousHash2,
722
+ schema: import_module_model.AddressPreviousHashSchema
723
+ }
724
+ ];
725
+ });
726
+ const address = this.address;
727
+ const name = this.config.name;
728
+ const previousHash = this.address;
729
+ const moduleAccount = name ? {
730
+ address,
731
+ name,
732
+ schema: import_address_payload_plugin.AddressSchema
733
+ } : {
734
+ address,
735
+ schema: import_address_payload_plugin.AddressSchema
736
+ };
737
+ const moduleAccountPreviousHash = previousHash ? {
738
+ address,
739
+ previousHash,
740
+ schema: import_module_model.AddressPreviousHashSchema
741
+ } : {
742
+ address,
743
+ schema: import_module_model.AddressPreviousHashSchema
744
+ };
745
+ return [
746
+ moduleAccount,
747
+ moduleAccountPreviousHash,
748
+ ...queryAccounts
749
+ ].flat();
750
+ }
751
+ async queryHandler(query, payloads, queryConfig) {
752
+ await this.started("throw");
753
+ const wrapper = await import_boundwitness_wrapper3.QueryBoundWitnessWrapper.parseQuery(query, payloads);
754
+ const queryPayload = await wrapper.getQuery();
755
+ (0, import_assert2.assertEx)(await this.queryable(query, payloads, queryConfig));
756
+ const resultPayloads = [];
757
+ switch (queryPayload.schema) {
758
+ case import_module_model.ModuleManifestQuerySchema: {
759
+ resultPayloads.push(await this.manifestHandler(queryPayload.maxDepth));
760
+ break;
761
+ }
762
+ case import_module_model.ModuleAddressQuerySchema: {
763
+ resultPayloads.push(...await this.moduleAddressHandler());
764
+ break;
765
+ }
766
+ case import_module_model.ModuleStateQuerySchema: {
767
+ resultPayloads.push(...await this.stateHandler());
768
+ break;
769
+ }
770
+ case import_module_model.ModuleSubscribeQuerySchema: {
771
+ this.subscribeHandler();
772
+ break;
773
+ }
774
+ default: {
775
+ throw new Error(`Unsupported Query [${queryPayload.schema}]`);
776
+ }
777
+ }
778
+ return resultPayloads;
779
+ }
780
+ async startHandler() {
781
+ this.validateConfig();
782
+ await this.initializeQueryAccounts();
783
+ this._started = true;
784
+ return true;
785
+ }
786
+ async stateHandler() {
787
+ return [
788
+ await this.manifestHandler(),
789
+ ...await this.generateConfigAndAddress(),
790
+ await this.generateDescribe()
791
+ ];
792
+ }
793
+ stopHandler(_timeout) {
794
+ this._started = void 0;
795
+ return true;
796
+ }
797
+ subscribeHandler() {
798
+ return;
799
+ }
800
+ validateConfig(config, parents = []) {
801
+ return Object.entries(config ?? this.config ?? {}).reduce((valid, [key, value]) => {
802
+ switch (typeof value) {
803
+ case "function": {
804
+ this.logger?.warn(`Fields of type function not allowed in config [${parents?.join(".")}.${key}]`);
805
+ return false;
806
+ }
807
+ case "object": {
808
+ if (Array.isArray(value)) {
809
+ return (
810
+ // eslint-disable-next-line unicorn/no-array-reduce
811
+ value.reduce((valid2, value2) => {
812
+ return this.validateConfig(value2, [
813
+ ...parents,
814
+ key
815
+ ]) && valid2;
816
+ }, true) && valid
817
+ );
818
+ }
819
+ if (!(0, import_module_model.serializableField)(value)) {
820
+ this.logger?.warn(`Fields that are not serializable to JSON are not allowed in config [${parents?.join(".")}.${key}]`);
821
+ return false;
822
+ }
823
+ return value ? this.validateConfig(value, [
824
+ ...parents,
825
+ key
826
+ ]) && valid : true;
827
+ }
828
+ default: {
829
+ return valid;
830
+ }
831
+ }
832
+ }, true);
833
+ }
834
+ isAllowedArchivingQuery(schema) {
835
+ const queries = this.archiving?.queries;
836
+ if (queries) {
837
+ return queries.includes(schema);
838
+ }
839
+ return true;
840
+ }
841
+ };
842
+
843
+ // src/AbstractModuleInstance.ts
844
+ var import_assert3 = require("@xylabs/assert");
845
+ var import_lodash2 = require("@xylabs/lodash");
846
+ var import_object3 = require("@xylabs/object");
847
+ var import_archivist_model2 = require("@xyo-network/archivist-model");
848
+ var import_manifest_model = require("@xyo-network/manifest-model");
849
+ var import_module_model2 = require("@xyo-network/module-model");
850
+ var import_module_resolver = require("@xyo-network/module-resolver");
851
+ var AbstractModuleInstance = class _AbstractModuleInstance extends AbstractModule {
852
+ static {
853
+ __name(this, "AbstractModuleInstance");
854
+ }
855
+ static uniqueName = (0, import_object3.globallyUnique)("AbstractModuleInstance", _AbstractModuleInstance, "xyo");
856
+ _downResolver;
857
+ _parents = [];
858
+ _privateResolver;
859
+ _upResolver;
860
+ constructor(privateConstructorKey, params, account) {
861
+ (0, import_assert3.assertEx)(AbstractModule.privateConstructorKey === privateConstructorKey, () => "Use create function instead of constructor");
862
+ const mutatedParams = {
863
+ ...params
864
+ };
865
+ const addToResolvers = mutatedParams.addToResolvers ?? true;
866
+ super(privateConstructorKey, mutatedParams, account);
867
+ if (addToResolvers) {
868
+ this.upResolver.add(this);
869
+ this.downResolver.add(this);
870
+ }
871
+ }
872
+ get downResolver() {
873
+ this._downResolver = this._downResolver ?? new import_module_resolver.CompositeModuleResolver({
874
+ allowNameResolution: this.allowNameResolution,
875
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers,
876
+ root: this
877
+ });
878
+ return this._downResolver;
879
+ }
880
+ get localName() {
881
+ return this.config.name;
882
+ }
883
+ get moduleIdentifierTransformers() {
884
+ return this.params.moduleIdentifierTransformers ?? import_module_model2.ResolveHelper.transformers;
885
+ }
886
+ get privateResolver() {
887
+ this._privateResolver = this._privateResolver ?? new import_module_resolver.CompositeModuleResolver({
888
+ allowNameResolution: this.allowNameResolution,
889
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers,
890
+ root: this
891
+ });
892
+ return this._privateResolver;
893
+ }
894
+ get root() {
895
+ return this;
896
+ }
897
+ get upResolver() {
898
+ this._upResolver = this._upResolver ?? new import_module_resolver.CompositeModuleResolver({
899
+ allowNameResolution: this.allowNameResolution,
900
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers,
901
+ root: this
902
+ });
903
+ return this._upResolver;
904
+ }
905
+ addParent(module2) {
906
+ const existingEntry = this._parents.find((parent) => parent.address === module2.address);
907
+ if (!existingEntry) {
908
+ this._parents.push(module2);
909
+ }
910
+ }
911
+ manifest(maxDepth) {
912
+ this._checkDead();
913
+ return this.busy(async () => {
914
+ return await this.manifestHandler(maxDepth);
915
+ });
916
+ }
917
+ async manifestQuery(account, maxDepth) {
918
+ const queryPayload = {
919
+ schema: import_module_model2.ModuleManifestQuerySchema,
920
+ ...maxDepth === void 0 ? {} : {
921
+ maxDepth
922
+ }
923
+ };
924
+ return await this.sendQueryRaw(queryPayload, void 0, account);
925
+ }
926
+ moduleAddress() {
927
+ this._checkDead();
928
+ return this.busy(async () => {
929
+ return await this.moduleAddressHandler();
930
+ });
931
+ }
932
+ parents() {
933
+ return this._parents;
934
+ }
935
+ privateChildren() {
936
+ return [];
937
+ }
938
+ publicChildren() {
939
+ return [];
940
+ }
941
+ removeParent(address) {
942
+ this._parents = this._parents.filter((item) => item.address !== address);
943
+ }
944
+ async resolve(idOrFilter = "*", options = {}) {
945
+ const config = {
946
+ address: this.address,
947
+ dead: this.dead,
948
+ downResolver: this.downResolver,
949
+ logger: this.logger,
950
+ module: this,
951
+ transformers: this.moduleIdentifierTransformers,
952
+ upResolver: this.upResolver
953
+ };
954
+ if (idOrFilter === "*") {
955
+ return (await import_module_model2.ResolveHelper.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
956
+ }
957
+ switch (typeof idOrFilter) {
958
+ case "string": {
959
+ return await import_module_model2.ResolveHelper.resolve(config, idOrFilter, options);
960
+ }
961
+ case "object": {
962
+ return (await import_module_model2.ResolveHelper.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
963
+ }
964
+ default: {
965
+ return (await import_module_model2.ResolveHelper.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
966
+ }
967
+ }
968
+ }
969
+ resolveIdentifier(id, options) {
970
+ const { direction = "all" } = options ?? {};
971
+ switch (direction) {
972
+ case "down": {
973
+ return this.downResolver.resolveIdentifier(id, options);
974
+ }
975
+ default: {
976
+ const mutatedOptions = {
977
+ ...options,
978
+ direction: "all"
979
+ };
980
+ return this.upResolver.resolveIdentifier(id, mutatedOptions);
981
+ }
982
+ }
983
+ }
984
+ async resolvePrivate(id = "*", options = {}) {
985
+ return await this.privateResolver.resolve(id, options) ?? await this.upResolver.resolve(id, options) ?? await this.downResolver.resolve(id, options);
986
+ }
987
+ async siblings() {
988
+ return (await Promise.all((await this.parents()).map((parent) => parent.publicChildren()))).flat().filter(import_module_model2.duplicateModules);
989
+ }
990
+ state() {
991
+ this._checkDead();
992
+ return this.busy(async () => {
993
+ return await this.stateHandler();
994
+ });
995
+ }
996
+ async stateQuery(account) {
997
+ const queryPayload = {
998
+ schema: import_module_model2.ModuleStateQuerySchema
999
+ };
1000
+ return await this.sendQueryRaw(queryPayload, void 0, account);
1001
+ }
1002
+ subscribe(_queryAccount) {
1003
+ this._checkDead();
1004
+ return this.subscribeHandler();
1005
+ }
1006
+ async manifestHandler(maxDepth = 1, _ignoreAddresses = []) {
1007
+ const cachedResult = this._cachedManifests.get(maxDepth);
1008
+ if (cachedResult) {
1009
+ return cachedResult;
1010
+ }
1011
+ const name = this.config.name ?? "Anonymous";
1012
+ const children = await this.publicChildren();
1013
+ const childAddressToName = {};
1014
+ for (const child of children) {
1015
+ if (child.address !== this.address) {
1016
+ childAddressToName[child.address] = child.config.name ?? null;
1017
+ }
1018
+ }
1019
+ const result = {
1020
+ config: {
1021
+ name,
1022
+ ...this.config
1023
+ },
1024
+ schema: import_manifest_model.ModuleManifestPayloadSchema,
1025
+ status: {
1026
+ address: this.address,
1027
+ children: childAddressToName
1028
+ }
1029
+ };
1030
+ this._cachedManifests.set(maxDepth, result);
1031
+ return result;
1032
+ }
1033
+ async resolveArchivingArchivists() {
1034
+ const archivists = this.config.archiving?.archivists;
1035
+ if (!archivists)
1036
+ return [];
1037
+ const resolved = await Promise.all(archivists.map((archivist) => this.resolve(archivist)));
1038
+ return (0, import_lodash2.compact)(resolved.map((mod) => (0, import_archivist_model2.asArchivistInstance)(mod)));
1039
+ }
1040
+ async sendQuery(queryPayload, payloads, account) {
1041
+ const queryResults = await this.sendQueryRaw(queryPayload, payloads, account);
1042
+ const [, resultPayloads, errors] = queryResults;
1043
+ if (errors && errors.length > 0) {
1044
+ throw errors[0];
1045
+ }
1046
+ return resultPayloads;
1047
+ }
1048
+ async sendQueryRaw(queryPayload, payloads, account) {
1049
+ const query = await this.bindQuery(queryPayload, payloads, account);
1050
+ return await this.query(query[0], query[1]);
1051
+ }
1052
+ async storeToArchivists(payloads) {
1053
+ const archivists = await this.resolveArchivingArchivists();
1054
+ return (await Promise.all(archivists.map((archivist) => {
1055
+ return archivist.insert?.(payloads);
1056
+ }))).map(([bw]) => bw);
1057
+ }
1058
+ };
1059
+ //# sourceMappingURL=index.cjs.map