@xyo-network/bridge-abstract 2.107.3 → 2.107.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,575 @@
1
- var k=Object.defineProperty;var l=(a,e)=>k(a,"name",{value:e,configurable:!0});import{assertEx as m}from"@xylabs/assert";import{exists as y}from"@xylabs/exists";import{forget as D}from"@xylabs/forget";import{globallyUnique as $}from"@xylabs/object";import{asArchivistInstance as U}from"@xyo-network/archivist-model";import{QueryBoundWitnessWrapper as L}from"@xyo-network/boundwitness-wrapper";import{BridgeConfigSchema as _,BridgeConnectQuerySchema as O,BridgeDisconnectQuerySchema as V,BridgeExposeQuerySchema as Q,BridgeUnexposeQuerySchema as R,ModuleFilterPayloadSchema as b}from"@xyo-network/bridge-model";import{AbstractModuleInstance as z}from"@xyo-network/module-abstract";import{AddressSchema as q,isAddressModuleFilter as J,isNameModuleFilter as K,resolveAddressToInstance as F,resolvePathToAddress as M,transformModuleIdentifier as G}from"@xyo-network/module-model";import{isPayloadOfSchemaType as C}from"@xyo-network/payload-model";var T=class a extends z{static{l(this,"AbstractBridge")}static configSchemas=[...super.configSchemas,_];static defaultConfigSchema=_;static uniqueName=$("AbstractBridge",a,"xyo");_roots;get allowNameResolution(){return this.params.allowNameResolution??!0}get discoverRoots(){return this.config.client?.discoverRoots??this.config.discoverRoots??(this.config.client===void 0?!1:"start")}get queries(){return[O,V,Q,R,...super.queries]}get resolver(){return m(this.params.resolver,()=>"No resolver provided")}async expose(e,s){this._noOverride("expose"),m(e!=="*",()=>"Exposing '*' not supported");let t=m(await M(this,e),()=>`Module to expose not found [${e}]`);console.log(`expose: ${t}`);let r=await this.exposeHandler(t,s);return await this.emit("exposed",{module:this,modules:r}),r}async exposed(){return this._noOverride("exposed"),await this.exposedHandler()}async resolve(e="*",s={}){let t=this._roots??[],r=s.direction==="up"?[this]:[...t,this];if(e==="*"){let o=(s.maxDepth??5)-1;return o<=0?r:[...r,...(await Promise.all(t.map(i=>i.resolve("*",{...s,maxDepth:o})))).flat()]}switch(typeof e){case"string":{let o=e.split(":"),i=m(o.shift(),()=>"Missing module identifier"),n=await G(i,this.moduleIdentifierTransformers),d=r.find(c=>n===c.address||n===c.modName);return o.length===0?d:d?.resolve(o.join(":"),s)}case"object":{let o=[];if(K(e))for(let i of r)i.modName&&e.name.includes(i.modName)&&o.push(i);if(J(e))for(let i of r)i.modName&&e.address.includes(i.address)&&o.push(i);return o}default:return}}async startHandler(){return this.discoverRoots==="lazy"?D(this.getRoots()):this.discoverRoots==="start"&&await this.getRoots(),!0}async unexpose(e,s){this._noOverride("unexpose");let t=m(await M(this,e),()=>`Module to unexpose not found [${e}]`),r=await this.unexposeHandler(t,s);return await this.emit("unexposed",{module:this,modules:r}),r}async queryHandler(e,s){let r=await(await L.parseQuery(e,s)).getQuery(),o=[];switch(r.schema){case Q:{let i=(s??[]).filter(C(b));m(i,()=>"At least one filter is required"),await Promise.all(i.map(async n=>{let{id:d,...c}=n;(await this.expose(d,c)).map(u=>{let g={address:u.address,schema:q};o.push(g)})}));break}case R:{let i=(s??[]).filter(C(b));m(i,()=>"At least one filter is required"),await Promise.all(i.map(async n=>{let{id:d,...c}=n;(await this.unexpose(d,c)).map(u=>{let g={address:u.address,schema:q};o.push(g)})}));break}default:return await super.queryHandler(e,s)}return o}async resolveArchivingArchivists(){let e=this.archiving?.archivists;if(!e)return[];let s=(await Promise.all(e.map(async r=>(await Promise.all((await this.parents()).map(o=>M(o,r)))).filter(y)))).flat().filter(y);return(await Promise.all(s.map(r=>F(this,r)))).filter(y).map(r=>U(r)).filter(y)}};import{ObjectResolverPriority as X}from"@xyo-network/module-model";import{CompositeModuleResolver as Y}from"@xyo-network/module-resolver";var H=class extends Y{static{l(this,"AbstractBridgeModuleResolver")}get priority(){return X.VeryLow}async resolveHandler(e,s,t){return e==="*"?[]:await super.resolveHandler(e,s)}};import{assertEx as f}from"@xylabs/assert";import{forget as P}from"@xylabs/forget";import{asAddress as fe}from"@xylabs/hex";import{compact as ye}from"@xylabs/lodash";import{toJsonString as we}from"@xylabs/object";import{BoundWitnessWrapper as ve,QueryBoundWitnessWrapper as ge}from"@xyo-network/boundwitness-wrapper";import{ModuleManifestPayloadSchema as Me,NodeManifestPayloadSchema as v}from"@xyo-network/manifest-model";import{AbstractModuleInstance as xe}from"@xyo-network/module-abstract";import{AddressPreviousHashSchema as Pe,DeadModuleError as Ae,ModuleAddressQuerySchema as A,ModuleManifestQuerySchema as I,ModuleStateQuerySchema as W}from"@xyo-network/module-model";import{ModuleWrapper as Se}from"@xyo-network/module-wrapper";import{PayloadBuilder as E}from"@xyo-network/payload-builder";import{isPayloadOfSchemaType as h,ModuleErrorSchema as j}from"@xyo-network/payload-model";import{QuerySchema as S}from"@xyo-network/query-payload-plugin";import{LRUCache as _e}from"lru-cache";import{assertEx as le}from"@xylabs/assert";import{exists as x}from"@xylabs/exists";import{Account as ce}from"@xyo-network/account";import{isAddressModuleFilter as ue,isNameModuleFilter as me,ObjectResolverPriority as he}from"@xyo-network/module-model";import{CompositeModuleResolver as pe}from"@xyo-network/module-resolver";import{isArchivistModule as Z}from"@xyo-network/archivist-model";import{ArchivistWrapper as ee}from"@xyo-network/archivist-wrapper";import{isDivinerModule as se}from"@xyo-network/diviner-model";import{DivinerWrapper as re}from"@xyo-network/diviner-wrapper";import{isNodeModule as te}from"@xyo-network/node-model";import{NodeWrapper as ie}from"@xyo-network/node-wrapper";import{isSentinelModule as oe}from"@xyo-network/sentinel-model";import{SentinelWrapper as ae}from"@xyo-network/sentinel-wrapper";import{isWitnessModule as ne}from"@xyo-network/witness-model";import{WitnessWrapper as de}from"@xyo-network/witness-wrapper";var N=l((a,e)=>{if(Z(a))return ee.wrap(a,e);if(se(a))return re.wrap(a,e);if(te(a))return ie.wrap(a,e);if(oe(a))return ae.wrap(a,e);if(ne(a))return de.wrap(a,e);throw"Failed to wrap"},"wrapModuleWithType");var w=class{static{l(this,"ModuleProxyResolver")}options;downResolver;constructor(e){this.options=e,this.downResolver=new pe({moduleIdentifierTransformers:e.moduleIdentifierTransformers,root:this.root})}get priority(){return he.VeryLow}get root(){return this.options.module}get childAddressMap(){return this.options.childAddressMap}get host(){return this.options.host}get module(){return this.options.module}addResolver(e){throw new Error("Not supported")}childManifest(e){return this.options.childManifests?.[e]}childState(e){return this.options.childStates?.[e]}removeResolver(e){throw new Error("Not supported")}async resolve(e="*",s){let t=s?.direction??"all";if(e==="*"){let r=Object.keys(this.childAddressMap);return(await Promise.all(r.map(i=>this.resolve(i,s)))).filter(x)}else if(typeof e=="string"){let r=e.split(":"),o=le(r.shift(),()=>"Invalid module identifier at first position"),i=await this.resolveIdentifier(o);if(i){let n=r.length>0?r.join(":"):void 0;if(t==="down"||t==="all"){let d=await this.downResolver.resolve(i);if(d)return n?d.resolve(n,s):d;let c=Object.keys(this.childAddressMap).includes(i)?i:Object.entries(this.childAddressMap).find(([p,u])=>u===i)?.[0];if(c){let p=await this.host.resolve(c,{...s,direction:"down"});if(p){let u=N(p,ce.randomSync());return n?u?.resolve(n,s):u}return}}}return}else{let r=e;if(ue(r))return(await Promise.all(r.address.map(i=>this.resolve(i,s)))).filter(x);if(me(r))return(await Promise.all(r.name.map(o=>this.resolve(o,s)))).filter(x)}}resolveIdentifier(e,s){if(this.childAddressMap[e])return e;let t=Object.entries(this.childAddressMap).find(([,r])=>r===e)?.[0];if(t)return t}async resolvePrivate(e,s){if(e==="*")return await Promise.resolve([])}};var B=class a extends xe{static{l(this,"AbstractModuleProxy")}static requiredQueries=[W];_config;_publicChildren;_state=void 0;_stateInProcess=!1;_spamTrap=new _e({max:1e3,ttl:1e3*60,ttlAutopurge:!0});constructor(e){e.addToResolvers=!1,super(a.privateConstructorKey,e,e.account)}get address(){return this.params.moduleAddress}get archiving(){return this.params?.archiving}get config(){return f(this._config,()=>"Config not set")}get queries(){return f(this._state,()=>"Module state not found. Make sure proxy has been started").filter(s=>h(S)(s)).map(s=>s.query)}static hasRequiredQueries(e){return this.missingRequiredQueries(e).length===0}static missingRequiredQueries(e){let s=e.queries;return ye(this.requiredQueries.map(t=>s.includes(t)?null:t))}async addressPreviousHash(){let e={schema:A};return f((await this.sendQuery(e,void 0,this.account)).find(h(Pe)),()=>"Result did not include correct payload")}childAddressByName(e){let t=this._state?.filter(h(v))?.flatMap(r=>Object.entries(r.status?.children??{}));return fe(t?.find(([r,o])=>o===e)?.[0])}async childAddressMap(){let e=h(v)(this.params.manifest)?[this.params.manifest]:void 0,s={};e===void 0&&(e=(await this.state()).filter(h(v)));for(let t of e??[]){let r=t.modules?.public??[];for(let o of r)if(typeof o=="object"){let i=o.status?.address;i&&(s[i]=o.config.name??null)}}return s}async manifest(e){let s={schema:I,...e===void 0?{}:{maxDepth:e}};return(await this.sendQuery(s))[0]}async moduleAddress(){let e={schema:A};return await this.sendQuery(e)}async previousHash(){let e={schema:A};return(await this.sendQuery(e)).pop().previousHash}async publicChildren(){return this._publicChildren=this._publicChildren??await super.publicChildren(),this._publicChildren}async query(e,s){return this._checkDead(),await this.busy(async()=>{try{await this.checkSpam(e),this.archiving&&this.isAllowedArchivingQuery(e.schema)&&P(this.storeToArchivists([e,...s??[]])),this.params.onQuerySendStarted?.({payloads:s,query:e});let t=await this.proxyQueryHandler(e,s);return this.params.onQuerySendFinished?.({payloads:s,query:e,result:t,status:"success"}),this.archiving&&this.isAllowedArchivingQuery(e.schema)&&P(this.storeToArchivists(t.flat())),P(this.emit("moduleQueried",{module:this,payloads:s,query:e,result:t})),t}catch(t){this.params.onQuerySendFinished?.({payloads:s,query:e,status:"failure"});let r=t;this._lastError=r;let o=new Ae(this.address,r),i={message:o.message,name:o.name,schema:j},n=await E.build(f(ge.unwrap(e),()=>"Invalid query"));return await this.bindQueryResult(n,[],void 0,[i])}})}queryHandler(e,s,t){throw new Error("queryHandler should never be called")}async queryable(e,s,t){return await Promise.resolve(!0)}async resolveArchivingArchivists(){return await this.params.archiving?.resolveArchivists()??[]}setConfig(e){this._config=e}setState(e){this._state=e}async startHandler(){let e=this.params.manifest;if(!e){let t=(await this.state()).find(r=>h(v)(r)||h(Me)(r));e=f(t,()=>"Can't find manifest payload")}return this.setConfig({...e.config}),this.downResolver.addResolver(new w({childAddressMap:await this.childAddressMap(),host:this.params.host,module:this,moduleIdentifierTransformers:this.params.moduleIdentifierTransformers})),await super.startHandler()}async state(){if(this._state===void 0){let e={query:W,schema:S},s={query:I,schema:S};this._state=[e,s];let t=Se.wrap(this,this.account);this._state=await t.state()}return this._state}async filterErrors(e){return(await ve.wrap(e[0],e[1])).payloadsBySchema(j)}async checkSpam(e){let s=await E.hash(e),t=this._spamTrap.get(s)??0;t>0&&this.logger?.warn(`Spam trap triggered for query: ${s} from ${we(e.addresses)}`),this._spamTrap.set(s,t+1)}};export{T as AbstractBridge,H as AbstractBridgeModuleResolver,B as AbstractModuleProxy,w as ModuleProxyResolver,N as wrapModuleWithType};
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/AbstractBridge.ts
5
+ import { assertEx } from "@xylabs/assert";
6
+ import { exists } from "@xylabs/exists";
7
+ import { forget } from "@xylabs/forget";
8
+ import { globallyUnique } from "@xylabs/object";
9
+ import { asArchivistInstance } from "@xyo-network/archivist-model";
10
+ import { QueryBoundWitnessWrapper } from "@xyo-network/boundwitness-wrapper";
11
+ import { BridgeConfigSchema, BridgeConnectQuerySchema, BridgeDisconnectQuerySchema, BridgeExposeQuerySchema, BridgeUnexposeQuerySchema, ModuleFilterPayloadSchema } from "@xyo-network/bridge-model";
12
+ import { AbstractModuleInstance } from "@xyo-network/module-abstract";
13
+ import { AddressSchema, isAddressModuleFilter, isNameModuleFilter, resolveAddressToInstance, resolvePathToAddress, transformModuleIdentifier } from "@xyo-network/module-model";
14
+ import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
15
+ var AbstractBridge = class _AbstractBridge extends AbstractModuleInstance {
16
+ static {
17
+ __name(this, "AbstractBridge");
18
+ }
19
+ static configSchemas = [
20
+ ...super.configSchemas,
21
+ BridgeConfigSchema
22
+ ];
23
+ static defaultConfigSchema = BridgeConfigSchema;
24
+ static uniqueName = globallyUnique("AbstractBridge", _AbstractBridge, "xyo");
25
+ _roots;
26
+ get allowNameResolution() {
27
+ return this.params.allowNameResolution ?? true;
28
+ }
29
+ get discoverRoots() {
30
+ return this.config.client?.discoverRoots ?? this.config.discoverRoots ?? (this.config.client === void 0 ? false : "start");
31
+ }
32
+ get queries() {
33
+ return [
34
+ BridgeConnectQuerySchema,
35
+ BridgeDisconnectQuerySchema,
36
+ BridgeExposeQuerySchema,
37
+ BridgeUnexposeQuerySchema,
38
+ ...super.queries
39
+ ];
40
+ }
41
+ get resolver() {
42
+ return assertEx(this.params.resolver, () => "No resolver provided");
43
+ }
44
+ async expose(id, options) {
45
+ this._noOverride("expose");
46
+ assertEx(id !== "*", () => "Exposing '*' not supported");
47
+ const addressToExpose = assertEx(await resolvePathToAddress(this, id), () => `Module to expose not found [${id}]`);
48
+ console.log(`expose: ${addressToExpose}`);
49
+ const modules = await this.exposeHandler(addressToExpose, options);
50
+ await this.emit("exposed", {
51
+ module: this,
52
+ modules
53
+ });
54
+ return modules;
55
+ }
56
+ async exposed() {
57
+ this._noOverride("exposed");
58
+ return await this.exposedHandler();
59
+ }
60
+ // eslint-disable-next-line complexity
61
+ async resolve(idOrFilter = "*", options = {}) {
62
+ const roots = this._roots ?? [];
63
+ const workingSet = options.direction === "up" ? [
64
+ this
65
+ ] : [
66
+ ...roots,
67
+ this
68
+ ];
69
+ if (idOrFilter === "*") {
70
+ const remainingDepth = (options.maxDepth ?? 5) - 1;
71
+ return remainingDepth <= 0 ? workingSet : [
72
+ ...workingSet,
73
+ ...(await Promise.all(roots.map((mod) => mod.resolve("*", {
74
+ ...options,
75
+ maxDepth: remainingDepth
76
+ })))).flat()
77
+ ];
78
+ }
79
+ switch (typeof idOrFilter) {
80
+ case "string": {
81
+ const parts = idOrFilter.split(":");
82
+ const first = assertEx(parts.shift(), () => "Missing module identifier");
83
+ const firstId = await transformModuleIdentifier(first, this.moduleIdentifierTransformers);
84
+ const result = workingSet.find((mod) => {
85
+ return firstId === mod.address || firstId === mod.modName;
86
+ });
87
+ return parts.length === 0 ? result : result?.resolve(parts.join(":"), options);
88
+ }
89
+ case "object": {
90
+ const results = [];
91
+ if (isNameModuleFilter(idOrFilter)) {
92
+ for (const mod of workingSet) {
93
+ if (mod.modName && idOrFilter.name.includes(mod.modName)) results.push(mod);
94
+ }
95
+ }
96
+ if (isAddressModuleFilter(idOrFilter)) {
97
+ for (const mod of workingSet) {
98
+ if (mod.modName && idOrFilter.address.includes(mod.address)) results.push(mod);
99
+ }
100
+ }
101
+ return results;
102
+ }
103
+ default: {
104
+ return;
105
+ }
106
+ }
107
+ }
108
+ async startHandler() {
109
+ if (this.discoverRoots === "lazy") {
110
+ forget(this.getRoots());
111
+ } else if (this.discoverRoots === "start") {
112
+ await this.getRoots();
113
+ }
114
+ return true;
115
+ }
116
+ async unexpose(id, options) {
117
+ this._noOverride("unexpose");
118
+ const addressToUnexpose = assertEx(await resolvePathToAddress(this, id), () => `Module to unexpose not found [${id}]`);
119
+ const modules = await this.unexposeHandler(addressToUnexpose, options);
120
+ await this.emit("unexposed", {
121
+ module: this,
122
+ modules
123
+ });
124
+ return modules;
125
+ }
126
+ async queryHandler(query, payloads) {
127
+ const wrapper = await QueryBoundWitnessWrapper.parseQuery(query, payloads);
128
+ const queryPayload = await wrapper.getQuery();
129
+ const resultPayloads = [];
130
+ switch (queryPayload.schema) {
131
+ case BridgeExposeQuerySchema: {
132
+ const filterPayloads = (payloads ?? []).filter(isPayloadOfSchemaType(ModuleFilterPayloadSchema));
133
+ assertEx(filterPayloads, () => "At least one filter is required");
134
+ await Promise.all(filterPayloads.map(async (filter) => {
135
+ const { id, ...options } = filter;
136
+ const modules = await this.expose(id, options);
137
+ modules.map((module) => {
138
+ const addressPayload = {
139
+ address: module.address,
140
+ schema: AddressSchema
141
+ };
142
+ resultPayloads.push(addressPayload);
143
+ });
144
+ }));
145
+ break;
146
+ }
147
+ case BridgeUnexposeQuerySchema: {
148
+ const filterPayloads = (payloads ?? []).filter(isPayloadOfSchemaType(ModuleFilterPayloadSchema));
149
+ assertEx(filterPayloads, () => "At least one filter is required");
150
+ await Promise.all(filterPayloads.map(async (filter) => {
151
+ const { id, ...options } = filter;
152
+ const modules = await this.unexpose(id, options);
153
+ modules.map((module) => {
154
+ const addressPayload = {
155
+ address: module.address,
156
+ schema: AddressSchema
157
+ };
158
+ resultPayloads.push(addressPayload);
159
+ });
160
+ }));
161
+ break;
162
+ }
163
+ default: {
164
+ return await super.queryHandler(query, payloads);
165
+ }
166
+ }
167
+ return resultPayloads;
168
+ }
169
+ async resolveArchivingArchivists() {
170
+ const archivists = this.archiving?.archivists;
171
+ if (!archivists) return [];
172
+ const resolvedAddresses = (await Promise.all(archivists.map(async (archivist) => (await Promise.all((await this.parents()).map((parent) => resolvePathToAddress(parent, archivist)))).filter(exists)))).flat().filter(exists);
173
+ const resolved = (await Promise.all(resolvedAddresses.map((address) => resolveAddressToInstance(this, address)))).filter(exists);
174
+ return resolved.map((mod) => asArchivistInstance(mod)).filter(exists);
175
+ }
176
+ };
177
+
178
+ // src/AbstractBridgeModuleResolver.ts
179
+ import { ObjectResolverPriority } from "@xyo-network/module-model";
180
+ import { CompositeModuleResolver } from "@xyo-network/module-resolver";
181
+ var AbstractBridgeModuleResolver = class extends CompositeModuleResolver {
182
+ static {
183
+ __name(this, "AbstractBridgeModuleResolver");
184
+ }
185
+ get priority() {
186
+ return ObjectResolverPriority.VeryLow;
187
+ }
188
+ async resolveHandler(id, options, _params) {
189
+ if (id === "*") {
190
+ return [];
191
+ }
192
+ return await super.resolveHandler(id, options);
193
+ }
194
+ };
195
+
196
+ // src/AbstractModuleProxy/AbstractModuleProxy.ts
197
+ import { assertEx as assertEx3 } from "@xylabs/assert";
198
+ import { forget as forget2 } from "@xylabs/forget";
199
+ import { asAddress } from "@xylabs/hex";
200
+ import { compact } from "@xylabs/lodash";
201
+ import { toJsonString } from "@xylabs/object";
202
+ import { BoundWitnessWrapper, QueryBoundWitnessWrapper as QueryBoundWitnessWrapper2 } from "@xyo-network/boundwitness-wrapper";
203
+ import { ModuleManifestPayloadSchema, NodeManifestPayloadSchema } from "@xyo-network/manifest-model";
204
+ import { AbstractModuleInstance as AbstractModuleInstance2 } from "@xyo-network/module-abstract";
205
+ import { AddressPreviousHashSchema, DeadModuleError, ModuleAddressQuerySchema, ModuleManifestQuerySchema, ModuleStateQuerySchema } from "@xyo-network/module-model";
206
+ import { ModuleWrapper } from "@xyo-network/module-wrapper";
207
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
208
+ import { isPayloadOfSchemaType as isPayloadOfSchemaType2, ModuleErrorSchema } from "@xyo-network/payload-model";
209
+ import { QuerySchema } from "@xyo-network/query-payload-plugin";
210
+ import { LRUCache } from "lru-cache";
211
+
212
+ // src/AbstractModuleProxy/ModuleProxyResolver.ts
213
+ import { assertEx as assertEx2 } from "@xylabs/assert";
214
+ import { exists as exists2 } from "@xylabs/exists";
215
+ import { Account } from "@xyo-network/account";
216
+ import { isAddressModuleFilter as isAddressModuleFilter2, isNameModuleFilter as isNameModuleFilter2, ObjectResolverPriority as ObjectResolverPriority2 } from "@xyo-network/module-model";
217
+ import { CompositeModuleResolver as CompositeModuleResolver2 } from "@xyo-network/module-resolver";
218
+
219
+ // src/wrapModuleWithType.ts
220
+ import { isArchivistModule } from "@xyo-network/archivist-model";
221
+ import { ArchivistWrapper } from "@xyo-network/archivist-wrapper";
222
+ import { isDivinerModule } from "@xyo-network/diviner-model";
223
+ import { DivinerWrapper } from "@xyo-network/diviner-wrapper";
224
+ import { isNodeModule } from "@xyo-network/node-model";
225
+ import { NodeWrapper } from "@xyo-network/node-wrapper";
226
+ import { isSentinelModule } from "@xyo-network/sentinel-model";
227
+ import { SentinelWrapper } from "@xyo-network/sentinel-wrapper";
228
+ import { isWitnessModule } from "@xyo-network/witness-model";
229
+ import { WitnessWrapper } from "@xyo-network/witness-wrapper";
230
+ var wrapModuleWithType = /* @__PURE__ */ __name((module, account) => {
231
+ if (isArchivistModule(module)) {
232
+ return ArchivistWrapper.wrap(module, account);
233
+ }
234
+ if (isDivinerModule(module)) {
235
+ return DivinerWrapper.wrap(module, account);
236
+ }
237
+ if (isNodeModule(module)) {
238
+ return NodeWrapper.wrap(module, account);
239
+ }
240
+ if (isSentinelModule(module)) {
241
+ return SentinelWrapper.wrap(module, account);
242
+ }
243
+ if (isWitnessModule(module)) {
244
+ return WitnessWrapper.wrap(module, account);
245
+ }
246
+ throw "Failed to wrap";
247
+ }, "wrapModuleWithType");
248
+
249
+ // src/AbstractModuleProxy/ModuleProxyResolver.ts
250
+ var ModuleProxyResolver = class {
251
+ static {
252
+ __name(this, "ModuleProxyResolver");
253
+ }
254
+ options;
255
+ downResolver;
256
+ constructor(options) {
257
+ this.options = options;
258
+ this.downResolver = new CompositeModuleResolver2({
259
+ moduleIdentifierTransformers: options.moduleIdentifierTransformers,
260
+ root: this.root
261
+ });
262
+ }
263
+ get priority() {
264
+ return ObjectResolverPriority2.VeryLow;
265
+ }
266
+ get root() {
267
+ return this.options.module;
268
+ }
269
+ get childAddressMap() {
270
+ return this.options.childAddressMap;
271
+ }
272
+ get host() {
273
+ return this.options.host;
274
+ }
275
+ get module() {
276
+ return this.options.module;
277
+ }
278
+ addResolver(_resolver) {
279
+ throw new Error("Not supported");
280
+ }
281
+ childManifest(address) {
282
+ return this.options.childManifests?.[address];
283
+ }
284
+ childState(address) {
285
+ return this.options.childStates?.[address];
286
+ }
287
+ removeResolver(_resolver) {
288
+ throw new Error("Not supported");
289
+ }
290
+ // eslint-disable-next-line complexity
291
+ async resolve(idOrFilter = "*", options) {
292
+ const direction = options?.direction ?? "all";
293
+ if (idOrFilter === "*") {
294
+ const childAddresses = Object.keys(this.childAddressMap);
295
+ const resolvedChildren = await Promise.all(childAddresses.map((address) => this.resolve(address, options)));
296
+ return resolvedChildren.filter(exists2);
297
+ } else if (typeof idOrFilter === "string") {
298
+ const idParts = idOrFilter.split(":");
299
+ const firstPart = assertEx2(idParts.shift(), () => "Invalid module identifier at first position");
300
+ const firstPartAddress = await this.resolveIdentifier(firstPart);
301
+ if (firstPartAddress) {
302
+ const remainingParts = idParts.length > 0 ? idParts.join(":") : void 0;
303
+ if (direction === "down" || direction === "all") {
304
+ const downResolverModule = await this.downResolver.resolve(firstPartAddress);
305
+ if (downResolverModule) {
306
+ return remainingParts ? downResolverModule.resolve(remainingParts, options) : downResolverModule;
307
+ }
308
+ const addressToProxy = Object.keys(this.childAddressMap).includes(firstPartAddress) ? firstPartAddress : Object.entries(this.childAddressMap).find(([_, value]) => value === firstPartAddress)?.[0];
309
+ if (addressToProxy) {
310
+ const proxy = await this.host.resolve(addressToProxy, {
311
+ ...options,
312
+ direction: "down"
313
+ });
314
+ if (proxy) {
315
+ const wrapped = wrapModuleWithType(proxy, Account.randomSync());
316
+ return remainingParts ? wrapped?.resolve(remainingParts, options) : wrapped;
317
+ }
318
+ return;
319
+ }
320
+ }
321
+ }
322
+ return;
323
+ } else {
324
+ const filter = idOrFilter;
325
+ if (isAddressModuleFilter2(filter)) {
326
+ const results = (await Promise.all(filter.address.map((item) => this.resolve(item, options)))).filter(exists2);
327
+ return results;
328
+ } else if (isNameModuleFilter2(filter)) {
329
+ return (await Promise.all(filter.name.map((item) => this.resolve(item, options)))).filter(exists2);
330
+ }
331
+ }
332
+ }
333
+ resolveIdentifier(id, _options) {
334
+ if (this.childAddressMap[id]) {
335
+ return id;
336
+ }
337
+ const addressFromName = Object.entries(this.childAddressMap).find(([, name]) => name === id)?.[0];
338
+ if (addressFromName) {
339
+ return addressFromName;
340
+ }
341
+ }
342
+ async resolvePrivate(id, _options) {
343
+ if (id === "*") return await Promise.resolve([]);
344
+ }
345
+ };
346
+
347
+ // src/AbstractModuleProxy/AbstractModuleProxy.ts
348
+ var AbstractModuleProxy = class _AbstractModuleProxy extends AbstractModuleInstance2 {
349
+ static {
350
+ __name(this, "AbstractModuleProxy");
351
+ }
352
+ static requiredQueries = [
353
+ ModuleStateQuerySchema
354
+ ];
355
+ _config;
356
+ _publicChildren;
357
+ _state = void 0;
358
+ _stateInProcess = false;
359
+ _spamTrap = new LRUCache({
360
+ max: 1e3,
361
+ ttl: 1e3 * 60,
362
+ ttlAutopurge: true
363
+ });
364
+ constructor(params) {
365
+ params.addToResolvers = false;
366
+ super(_AbstractModuleProxy.privateConstructorKey, params, params.account);
367
+ }
368
+ get address() {
369
+ return this.params.moduleAddress;
370
+ }
371
+ get archiving() {
372
+ return this.params?.archiving;
373
+ }
374
+ get config() {
375
+ return assertEx3(this._config, () => "Config not set");
376
+ }
377
+ get queries() {
378
+ const queryPayloads = assertEx3(this._state, () => "Module state not found. Make sure proxy has been started").filter((item) => isPayloadOfSchemaType2(QuerySchema)(item));
379
+ return queryPayloads.map((payload) => payload.query);
380
+ }
381
+ static hasRequiredQueries(module) {
382
+ return this.missingRequiredQueries(module).length === 0;
383
+ }
384
+ static missingRequiredQueries(module) {
385
+ const moduleQueries = module.queries;
386
+ return compact(this.requiredQueries.map((query) => {
387
+ return moduleQueries.includes(query) ? null : query;
388
+ }));
389
+ }
390
+ async addressPreviousHash() {
391
+ const queryPayload = {
392
+ schema: ModuleAddressQuerySchema
393
+ };
394
+ const result = assertEx3((await this.sendQuery(queryPayload, void 0, this.account)).find(isPayloadOfSchemaType2(AddressPreviousHashSchema)), () => "Result did not include correct payload");
395
+ return result;
396
+ }
397
+ childAddressByName(name) {
398
+ const nodeManifests = this._state?.filter(isPayloadOfSchemaType2(NodeManifestPayloadSchema));
399
+ const childPairs = nodeManifests?.flatMap((nodeManifest) => Object.entries(nodeManifest.status?.children ?? {}));
400
+ return asAddress(childPairs?.find(([_, childName]) => childName === name)?.[0]);
401
+ }
402
+ async childAddressMap() {
403
+ let nodeManifests = isPayloadOfSchemaType2(NodeManifestPayloadSchema)(this.params.manifest) ? [
404
+ this.params.manifest
405
+ ] : void 0;
406
+ const result = {};
407
+ if (nodeManifests === void 0) {
408
+ const state = await this.state();
409
+ nodeManifests = state.filter(isPayloadOfSchemaType2(NodeManifestPayloadSchema));
410
+ }
411
+ for (const manifest of nodeManifests ?? []) {
412
+ const children = manifest.modules?.public ?? [];
413
+ for (const child of children) {
414
+ if (typeof child === "object") {
415
+ const address = child.status?.address;
416
+ if (address) {
417
+ result[address] = child.config.name ?? null;
418
+ }
419
+ }
420
+ }
421
+ }
422
+ return result;
423
+ }
424
+ async manifest(maxDepth) {
425
+ const queryPayload = {
426
+ schema: ModuleManifestQuerySchema,
427
+ ...maxDepth === void 0 ? {} : {
428
+ maxDepth
429
+ }
430
+ };
431
+ return (await this.sendQuery(queryPayload))[0];
432
+ }
433
+ async moduleAddress() {
434
+ const queryPayload = {
435
+ schema: ModuleAddressQuerySchema
436
+ };
437
+ return await this.sendQuery(queryPayload);
438
+ }
439
+ async previousHash() {
440
+ const queryPayload = {
441
+ schema: ModuleAddressQuerySchema
442
+ };
443
+ return (await this.sendQuery(queryPayload)).pop().previousHash;
444
+ }
445
+ async publicChildren() {
446
+ this._publicChildren = this._publicChildren ?? await super.publicChildren();
447
+ return this._publicChildren;
448
+ }
449
+ async query(query, payloads) {
450
+ this._checkDead();
451
+ return await this.busy(async () => {
452
+ try {
453
+ await this.checkSpam(query);
454
+ if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
455
+ forget2(this.storeToArchivists([
456
+ query,
457
+ ...payloads ?? []
458
+ ]));
459
+ }
460
+ this.params.onQuerySendStarted?.({
461
+ payloads,
462
+ query
463
+ });
464
+ const result = await this.proxyQueryHandler(query, payloads);
465
+ this.params.onQuerySendFinished?.({
466
+ payloads,
467
+ query,
468
+ result,
469
+ status: "success"
470
+ });
471
+ if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
472
+ forget2(this.storeToArchivists(result.flat()));
473
+ }
474
+ forget2(this.emit("moduleQueried", {
475
+ module: this,
476
+ payloads,
477
+ query,
478
+ result
479
+ }));
480
+ return result;
481
+ } catch (ex) {
482
+ this.params.onQuerySendFinished?.({
483
+ payloads,
484
+ query,
485
+ status: "failure"
486
+ });
487
+ const error = ex;
488
+ this._lastError = error;
489
+ const deadError = new DeadModuleError(this.address, error);
490
+ const errorPayload = {
491
+ message: deadError.message,
492
+ name: deadError.name,
493
+ schema: ModuleErrorSchema
494
+ };
495
+ const sourceQuery = await PayloadBuilder.build(assertEx3(QueryBoundWitnessWrapper2.unwrap(query), () => "Invalid query"));
496
+ return await this.bindQueryResult(sourceQuery, [], void 0, [
497
+ errorPayload
498
+ ]);
499
+ }
500
+ });
501
+ }
502
+ queryHandler(_query, _payloads, _queryConfig) {
503
+ throw new Error("queryHandler should never be called");
504
+ }
505
+ async queryable(_query, _payloads, _queryConfig) {
506
+ return await Promise.resolve(true);
507
+ }
508
+ async resolveArchivingArchivists() {
509
+ return await this.params.archiving?.resolveArchivists() ?? [];
510
+ }
511
+ setConfig(config) {
512
+ this._config = config;
513
+ }
514
+ setState(state) {
515
+ this._state = state;
516
+ }
517
+ async startHandler() {
518
+ let manifest = this.params.manifest;
519
+ if (!manifest) {
520
+ const state = await this.state();
521
+ const manifestPayload = state.find((payload) => isPayloadOfSchemaType2(NodeManifestPayloadSchema)(payload) || isPayloadOfSchemaType2(ModuleManifestPayloadSchema)(payload));
522
+ manifest = assertEx3(manifestPayload, () => "Can't find manifest payload");
523
+ }
524
+ this.setConfig({
525
+ ...manifest.config
526
+ });
527
+ this.downResolver.addResolver(new ModuleProxyResolver({
528
+ childAddressMap: await this.childAddressMap(),
529
+ host: this.params.host,
530
+ module: this,
531
+ moduleIdentifierTransformers: this.params.moduleIdentifierTransformers
532
+ }));
533
+ return await super.startHandler();
534
+ }
535
+ async state() {
536
+ if (this._state === void 0) {
537
+ const stateQueryPayload = {
538
+ query: ModuleStateQuerySchema,
539
+ schema: QuerySchema
540
+ };
541
+ const manifestQueryPayload = {
542
+ query: ModuleManifestQuerySchema,
543
+ schema: QuerySchema
544
+ };
545
+ this._state = [
546
+ stateQueryPayload,
547
+ manifestQueryPayload
548
+ ];
549
+ const wrapper = ModuleWrapper.wrap(this, this.account);
550
+ this._state = await wrapper.state();
551
+ }
552
+ return this._state;
553
+ }
554
+ async filterErrors(result) {
555
+ const wrapper = await BoundWitnessWrapper.wrap(result[0], result[1]);
556
+ return wrapper.payloadsBySchema(ModuleErrorSchema);
557
+ }
558
+ //this checks and warns if we are getting spammed by the same query
559
+ async checkSpam(query) {
560
+ const hash = await PayloadBuilder.hash(query);
561
+ const previousCount = this._spamTrap.get(hash) ?? 0;
562
+ if (previousCount > 0) {
563
+ this.logger?.warn(`Spam trap triggered for query: ${hash} from ${toJsonString(query.addresses)}`);
564
+ }
565
+ this._spamTrap.set(hash, previousCount + 1);
566
+ }
567
+ };
568
+ export {
569
+ AbstractBridge,
570
+ AbstractBridgeModuleResolver,
571
+ AbstractModuleProxy,
572
+ ModuleProxyResolver,
573
+ wrapModuleWithType
574
+ };
2
575
  //# sourceMappingURL=index.js.map