@xyo-network/bridge-pub-sub 2.107.1 → 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,1077 @@
1
- var se=Object.defineProperty;var _e=Object.getPrototypeOf;var xe=Reflect.get;var Ae=(g,e,s)=>e in g?se(g,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):g[e]=s;var l=(g,e)=>se(g,"name",{value:e,configurable:!0});var E=(g,e,s)=>Ae(g,typeof e!="symbol"?e+"":e,s);var te=(g,e,s)=>xe(_e(g),s,e);import{Base as qe}from"@xylabs/object";var j=class j extends qe{};l(j,"AbstractModuleHost");var H=j;import{assertEx as De}from"@xylabs/assert";import{delay as Me}from"@xylabs/delay";import{forget as Re}from"@xylabs/forget";import{clearTimeoutEx as ae,setTimeoutEx as Ee}from"@xylabs/timer";import{isBoundWitnessWithMeta as Fe}from"@xyo-network/boundwitness-model";import{BoundWitnessDivinerQuerySchema as He}from"@xyo-network/diviner-boundwitness-model";import{PayloadBuilder as le}from"@xyo-network/payload-builder";import{LRUCache as Te}from"lru-cache";import{assertEx as T}from"@xylabs/assert";import{Base as Ce}from"@xylabs/object";import{isArchivistInstance as re}from"@xyo-network/archivist-model";import{isDivinerInstance as ie}from"@xyo-network/diviner-model";import{ResolveHelper as oe}from"@xyo-network/module-model";import{Mutex as be}from"async-mutex";import{LRUCache as Ie}from"lru-cache";var $e=100,Se=6e4,ne=1e3,G=class G extends Ce{_lastState;_targetConfigs={};_targetQueries={};_lastResolveFailure={};_queriesArchivist;_queriesDiviner;_reResolveDelay=1e3*5;_resolveMutex=new be;_responsesArchivist;_responsesDiviner;constructor(e){super(e)}get config(){return this.params.config}get pollFrequency(){var s;let e=((s=this.config)==null?void 0:s.pollFrequency)??ne;return e<$e||e>Se?ne:e}get rootModule(){return this.params.rootModule}get lastState(){let e={max:1e3,ttl:0};return this._lastState=this._lastState??new Ie(e),this._lastState}async queriesArchivist(){return await this._resolveMutex.runExclusive(async()=>{var e,s,t;return this._queriesArchivist=this._queriesArchivist??await this.resolve(T((t=(s=(e=this.config)==null?void 0:e.intersect)==null?void 0:s.queries)==null?void 0:t.archivist,()=>"No queries Archivist defined"),re),this._queriesArchivist})}async queriesDiviner(){return await this._resolveMutex.runExclusive(async()=>{var e,s,t;return this._queriesDiviner=this._queriesDiviner??await this.resolve(T((t=(s=(e=this.config)==null?void 0:e.intersect)==null?void 0:s.queries)==null?void 0:t.boundWitnessDiviner,()=>"No queries Diviner defined"),ie),this._queriesDiviner})}async responsesArchivist(){return await this._resolveMutex.runExclusive(async()=>{var e,s,t;return this._responsesArchivist=this._responsesArchivist??await this.resolve(T((t=(s=(e=this.config)==null?void 0:e.intersect)==null?void 0:s.responses)==null?void 0:t.archivist,()=>"No responses Archivist defined"),re),this._responsesArchivist})}async responsesDiviner(){return await this._resolveMutex.runExclusive(async()=>{var e,s,t;return this._responsesDiviner=this._responsesDiviner??await this.resolve(T((t=(s=(e=this.config)==null?void 0:e.intersect)==null?void 0:s.responses)==null?void 0:t.boundWitnessDiviner,()=>"No responses Diviner defined"),ie),this._responsesDiviner})}async commitState(e,s){await Promise.resolve();let t=this.lastState.get(e);t&&t>=s||this.lastState.set(e,s)}async retrieveState(e){await Promise.resolve();let s=this.lastState.get(e);if(s===void 0){let t=Date.now()-1e3;return this.lastState.set(e,t),t}else return s}async resolve(e,s){var r,i,o;if(Date.now()-(this._lastResolveFailure[e]??0)<this._reResolveDelay)return;this._lastResolveFailure[e]=Date.now();let t=await oe.resolveModuleIdentifier(this.rootModule,e);if(t){if(s(t))return delete this._lastResolveFailure[e],t;(i=this.logger)==null||i.warn(`Unable to resolve responsesDiviner as correct type [${e}][${(r=t==null?void 0:t.constructor)==null?void 0:r.name}]: ${t.id}`)}else(o=this.logger)==null||o.debug(`Unable to resolve queriesArchivist [${e}] [${await oe.traceModuleIdentifier(this.rootModule,e)}]`)}};l(G,"AsyncQueryBusBase");var I=G;var F="pending";var Y=class Y extends I{_queryCache;_pollCount=0;_pollId;constructor(e){super(e)}get queryCacheConfig(){var s,t;let e=((s=this.config)==null?void 0:s.queryCache)===!0?{}:(t=this.config)==null?void 0:t.queryCache;return{max:100,ttl:1e3*60,...e}}get started(){return!!this._pollId}get queryCache(){let e=this.queryCacheConfig,s={noUpdateTTL:!1,ttlAutopurge:!0};return this._queryCache=this._queryCache??new Te({...e,...s}),this._queryCache}listeningAddresses(){var e;return(e=this._queryCache)==null?void 0:e.keys()}async send(e,s,t){var h,_,v,y;(h=this.logger)==null||h.debug(`Begin issuing query to: ${e}`);let r={...s==null?void 0:s.$meta,destination:[e]},i=await le.build({...s,$meta:r}),o=De(await this.queriesArchivist(),()=>{var p,w,m;return`Unable to contact queriesArchivist [${(m=(w=(p=this.config)==null?void 0:p.intersect)==null?void 0:w.queries)==null?void 0:m.archivist}]`}),n=(i==null?void 0:i.$hash)??Object.keys(await le.toDataHashMap([i]))[0];(_=this.logger)==null||_.debug(`Issuing query: ${n} to: ${e}`);let a=t?[i,...t]:[i],c=await((v=o.insert)==null?void 0:v.call(o,a));if((y=this.logger)==null||y.debug(`Issued query: ${n} to: ${e}`),this.queryCache.set(n,F),!c)throw new Error("Unable to issue query to queryArchivist");return new Promise((p,w)=>{var q;(q=this.logger)==null||q.debug(`Polling for response to query: ${n}`);let m=100;Re(l(async()=>{var f,x;try{this.start();let u=this.queryCache.get(n);for(;u!==void 0;){if(await Me(m),u=this.queryCache.get(n),u&&u!==F){(f=this.logger)==null||f.log(`Returning response to query: ${n}`),p(u);return}m=Math.floor(m*1.2),m>1e3&&(m=1e3)}(x=this.logger)==null||x.error("Timeout waiting for query response"),w({message:"Timeout waiting for query response",query:"network.xyo.boundwitness",schema:"network.xyo.error.module",sources:[n]});return}finally{this.stop()}},"pollForResponse")())})}poll(){this._pollId=Ee(async()=>{var e,s;try{await this.processIncomingResponses()}catch(t){(s=(e=this.logger)==null?void 0:e.error)==null||s.call(e,`Error in main loop: ${t}`)}finally{this._pollId&&ae(this._pollId),this._pollId=void 0,this.poll()}},this.pollFrequency)}processIncomingResponses=l(async()=>{let e=await this.responsesArchivist();if(e){let s=await this.responsesDiviner();if(s){let t=[...this.queryCache.entries()].filter(([r,i])=>i===F);await Promise.allSettled(t.map(async([r,i])=>{var o,n,a;if(i===F){let c={limit:1,order:"desc",schema:He,sourceQuery:r},d=await s.divine([c]);if(d&&d.length>0){let h=d.find(Fe);if(h&&((o=h==null?void 0:h.$meta)==null?void 0:o.sourceQuery)===r){(n=this.logger)==null||n.debug(`Found response to query: ${r}`);let _=((a=h.payload_hashes)==null?void 0:a.length)>0?await e.get(h.payload_hashes):[];this.queryCache.set(r,[h,_,[]])}}}}))}}},"processIncomingResponses");start(){this._pollCount===0&&this.poll(),this._pollCount++}stop(){this._pollCount--,this._pollCount<=0&&(this._pollId&&ae(this._pollId),this._pollId=void 0,this._pollCount=0)}};l(Y,"AsyncQueryBusClient");var P=Y;import{containsAll as Pe}from"@xylabs/array";import{assertEx as $}from"@xylabs/assert";import{clearTimeoutEx as ce,setTimeoutEx as Qe}from"@xylabs/timer";import{isQueryBoundWitnessWithMeta as Le}from"@xyo-network/boundwitness-model";import{isBridgeInstance as Ne}from"@xyo-network/bridge-model";import{BoundWitnessDivinerQuerySchema as Ue}from"@xyo-network/diviner-boundwitness-model";import{asModuleInstance as de,ModuleConfigSchema as Oe,resolveAddressToInstance as Be,ResolveHelper as We}from"@xyo-network/module-model";import{PayloadBuilder as he}from"@xyo-network/payload-builder";var k=4,X=64,je=16,Ge=4,Ye=64,ke=16,J=class J extends I{_exposedAddresses=new Set;_exposeOptions={};_idle=!1;_lastQueryTime;_pollId;constructor(e){super(e)}get exposedAddresses(){return this._exposedAddresses}get idlePollFrequency(){var s;let e=((s=this.config)==null?void 0:s.idlePollFrequency)??je*this.pollFrequency;return e<this.pollFrequency*k?k*this.pollFrequency:e>this.pollFrequency*X?X*this.pollFrequency:e}get idleThreshold(){var s;let e=((s=this.config)==null?void 0:s.idleThreshold)??ke*this.idlePollFrequency;return e<this.idlePollFrequency*Ge?k*this.pollFrequency:e>this.idlePollFrequency*Ye?X*this.pollFrequency:e}get perAddressBatchQueryLimit(){var e;return((e=this.config)==null?void 0:e.perAddressBatchQueryLimit)??10}get started(){return!!this._pollId}expose(e,s){var r,i;let{failOnAlreadyExposed:t}=s??{};if(Ne(e))(r=this.logger)==null||r.warn(`Attempted to expose a BridgeModule [${e.id}] - Not exposing`);else return $(!t||!this._exposedAddresses.has(e.address),()=>`Address already exposed: ${e.id} [${e.address}]`),this._exposedAddresses.add(e.address),this._exposeOptions[e.address]={...s},(i=this.logger)==null||i.debug(`${e.id} exposed [${e.address}]`),e}async listeningModules(){var t;let e=[...((t=this.config)==null?void 0:t.listeningModules)??[],...this.exposedAddresses.values()];return await Promise.all(e.map(async r=>$(de(await Be(this.rootModule,r)),()=>`Unable to resolve listeningModule [${r}]`)))}start(){this.started&&console.warn("AsyncQueryBus starting when already started"),this.poll()}stop(){this.started||console.warn("AsyncQueryBus stopping when already stopped"),this._pollId&&ce(this._pollId),this._pollId=void 0}async unexpose(e,s=!0){var r;let t=de(await this.rootModule.resolve(e,{maxDepth:10}));return t&&($(!s||this._exposedAddresses.has(t.address),()=>`Address not exposed [${t.address}][${t.id}]`),this._exposedAddresses.delete(t.address),delete this._exposeOptions[t.address],(r=this.logger)==null||r.debug(`${t.address} [${t.id}] unexposed`)),t}callLocalModule=l(async(e,s)=>{var n,a,c,d,h,_,v,y,p,w,m,b,q;this._idle=!1,this._lastQueryTime=Date.now();let t=e.id,r=$(await this.queriesArchivist(),()=>{var f,x,u;return`Unable to contact queriesArchivist [${(u=(x=(f=this.config)==null?void 0:f.intersect)==null?void 0:x.queries)==null?void 0:u.archivist}]`}),i=$(await this.responsesArchivist(),()=>{var f,x,u;return`Unable to contact responsesArchivist [${(u=(x=(f=this.config)==null?void 0:f.intersect)==null?void 0:x.queries)==null?void 0:u.archivist}]`}),o=(n=s.$meta)==null?void 0:n.destination;if(o&&(o!=null&&o.includes(e.address))){let f=s.payload_hashes.indexOf(s.query);if(f!==-1){let x=s.payload_schemas[f];if(e.queries.includes(x)){let u=await r.get(s.payload_hashes);(c=(a=this.params).onQueryFulfillStarted)==null||c.call(a,{payloads:u,query:s});let B=await he.toAllHashMap(u),R=(await he.build(s)).$hash;if(!Pe(Object.keys(B),s.payload_hashes)){(d=this.logger)==null||d.error(`Error processing command ${R} for module ${t}, missing payloads`);return}try{let W=B[s.query].schema;(h=this.logger)==null||h.debug(`Issuing query ${W} (${R}) addressed to module: ${t}`);let ee=await e.query(s,u,{allowedQueries:(_=this._exposeOptions[e.address])==null?void 0:_.allowedQueries,schema:Oe}),[ve,ye,we]=ee;(v=this.logger)==null||v.debug(`Replying to query ${R} addressed to module: ${t}`),(await i.insert([ve,...ye,...we])).length===0&&((y=this.logger)==null||y.error(`Error replying to query ${R} addressed to module: ${t}`)),s!=null&&s.timestamp&&await this.commitState(e.address,s.timestamp),(w=(p=this.params).onQueryFulfillFinished)==null||w.call(p,{payloads:u,query:s,result:ee,status:"success"})}catch(W){(b=(m=this.params).onQueryFulfillFinished)==null||b.call(m,{payloads:u,query:s,status:"failure"}),(q=this.logger)==null||q.error(`Error processing query ${R} for module ${t}: ${W}`)}}}}},"callLocalModule");findQueriesToAddress=l(async e=>{var r,i,o,n,a;let s=$((o=(i=(r=this.config)==null?void 0:r.intersect)==null?void 0:i.queries)==null?void 0:o.boundWitnessDiviner,()=>"No queries Diviner defined"),t=await this.queriesDiviner();if(t){let c=await this.retrieveState(e),d=[e],h=this.perAddressBatchQueryLimit,_={destination:d,limit:h,order:"asc",schema:Ue,timestamp:c+1},y=(await t.divine([_])).filter(Le),p=y.length>0?Math.max(...y.map(w=>w.timestamp??c))+1:Date.now();return await this.commitState(e,p),(n=this.logger)==null||n.debug("findQueriesToAddress",e,c,p),y}else(a=this.logger)==null||a.warn(`Unable to resolve queriesBoundWitnessDiviner [${s}] [${await We.traceModuleIdentifier(this.rootModule,s)}]`)},"findQueriesToAddress");poll(){this._pollId=Qe(async()=>{var s,t;try{await this.processIncomingQueries()}catch(r){(t=(s=this.logger)==null?void 0:s.error)==null||t.call(s,`Error in main loop: ${r}`)}finally{this._pollId&&ce(this._pollId),this._pollId=void 0,this.poll()}let e=Date.now();this.idleThreshold<e-(this._lastQueryTime??e)&&(this._idle=!0)},this._idle?this.idlePollFrequency:this.pollFrequency)}processIncomingQueries=l(async()=>{var s;(s=this.logger)==null||s.debug("Checking for inbound queries");let e=await this.listeningModules();await Promise.allSettled(e.map(async t=>{var r,i,o;try{let n=t.id;(r=this.logger)==null||r.debug(`Checking for inbound queries to ${n} [${t.address}]`);let a=await this.findQueriesToAddress(t.address)??[];if(a.length===0)return;(i=this.logger)==null||i.debug(`Found queries addressed to local module: ${n}`);for(let c of a)await this.callLocalModule(t,c)}catch(n){(o=this.logger)==null||o.error(`Error processing queries for address ${t.address}: ${n}`)}}))},"processIncomingQueries")};l(J,"AsyncQueryBusHost");var S=J;var z=class z extends H{_busHost;constructor(e){super(e)}async start(){var s;let e=this.params.config.listeningModules??(await this.params.module.resolve("*",{direction:"down"})).map(t=>t.address);this._busHost=new S({config:{...this.params.config,listeningModules:e},logger:this.params.logger,rootModule:this.params.module}),(s=this._busHost)==null||s.start()}stop(){var e;(e=this._busHost)==null||e.stop()}};l(z,"AsyncQueryBusModuleHost");var ue=z;import{assertEx as Xe}from"@xylabs/assert";import{exists as pe}from"@xylabs/exists";import{forget as fe}from"@xylabs/forget";import{isAddress as Je}from"@xylabs/hex";import{AbstractModuleProxy as ze}from"@xyo-network/bridge-abstract";import{ResolveHelper as me}from"@xyo-network/module-model";var A=class A extends ze{constructor(e){A.createCount=A.createCount+1,Math.floor(A.createCount/10)===A.createCount/10&&console.log(`AsyncQueryBusModuleProxy.createCount: ${A.createCount}`),super(e)}get id(){return this.address}get modName(){}async proxyQueryHandler(e,s){this.archiving&&this.isAllowedArchivingQuery(e.schema)&&fe(this.storeToArchivists([e,...s??[]]));let t=await this.params.busClient.send(this.address,e,s);return this.archiving&&this.isAllowedArchivingQuery(e.schema)&&fe(this.storeToArchivists(t.flat())),t}async publicChildren(){return(await Promise.all(Object.values(await this.childAddressMap()).filter(pe).map(e=>this.resolve(e)))).filter(pe)}async resolve(e="*",s={}){let t={address:this.address,dead:this.dead,downResolver:this.downResolver,logger:this.logger,module:this,transformers:this.moduleIdentifierTransformers,upResolver:this.upResolver};if(e==="*")return await this.publicChildren();switch(typeof e){case"string":{let r=e.split(":"),i=Xe(r.shift(),()=>"Missing first"),o=r.join(":"),n=Je(i)?i:this.childAddressByName(i);if(!n)return;let a=await this.params.host.resolve(n);return o?await(a==null?void 0:a.resolve(o)):a}case"object":return(await me.resolve(t,e,s)).filter(r=>r.address!==this.address);default:return(await me.resolve(t,e,s)).filter(r=>r.address!==this.address)}}async startHandler(){return await super.startHandler()}};l(A,"AsyncQueryBusModuleProxy"),E(A,"createCount",0);var Q=A;var ge="network.xyo.bridge.pubsub";var K=`${ge}.config`;import{assertEx as D}from"@xylabs/assert";import{exists as U}from"@xylabs/exists";import{forget as M}from"@xylabs/forget";import{isAddress as ls}from"@xylabs/hex";import{toJsonString as cs}from"@xylabs/object";import{AbstractBridge as ds}from"@xyo-network/bridge-abstract";import{AddressSchema as hs,creatableModule as us,isAddressModuleFilter as ps,resolveAddressToInstance as fs,resolveAddressToInstanceUp as ms,ResolveHelper as Z}from"@xyo-network/module-model";import{asNodeInstance as gs}from"@xyo-network/node-model";import{isPayloadOfSchemaType as vs}from"@xyo-network/payload-model";import{Mutex as ys}from"async-mutex";import{assertEx as L}from"@xylabs/assert";import{isAddress as Ke}from"@xylabs/hex";import{Account as Ve}from"@xyo-network/account";import{AbstractBridgeModuleResolver as Ze,wrapModuleWithType as es}from"@xyo-network/bridge-abstract";import{ConfigSchema as ss}from"@xyo-network/config-payload-plugin";import{asModuleInstance as ts,ModuleConfigSchema as rs,ResolveHelper as is}from"@xyo-network/module-model";import{Mutex as os}from"async-mutex";import{LRUCache as ns}from"lru-cache";var V=class V extends Ze{_resolvedCache=new ns({max:1e3});_resolvedCacheMutex=new os;async resolveHandler(e,s){let t=await super.resolveHandler(e,s);if(t.length>0)return t;let r=e.split(":"),i=L(r.shift(),()=>"Missing module identifier"),o=await is.transformModuleIdentifier(i);L(Ke(o),()=>`Invalid module address: ${o}`);let n=r.join(":"),a=await this._resolvedCacheMutex.runExclusive(async()=>{var w,m;let d=this._resolvedCache.get(o);if(d)return r.length<=0?d:d.resolve(n,{...s,maxDepth:((s==null?void 0:s.maxDepth)??5)-1});let h=Ve.randomSync(),_={account:h,archiving:this.params.archiving,busClient:this.params.busClient,config:{schema:rs},host:this,moduleAddress:o,onQuerySendFinished:this.params.onQuerySendFinished,onQuerySendStarted:this.params.onQuerySendStarted},v=new Q(_),y=await v.state();if(y){let b=(w=y.find(f=>f.schema===ss))==null?void 0:w.config,q=L(y.find(f=>f.schema===b),()=>"Unable to locate config");v.setConfig(q)}await((m=v.start)==null?void 0:m.call(v));let p=es(v,h);return L(ts(p,{}),()=>`Failed to asModuleInstance [${e}]`),this._resolvedCache.set(p.address,p),p}),c=n.length>0?await a.resolve(n,s):a;return c?[c]:[]}};l(V,"PubSubBridgeModuleResolver");var N=V;function as(g,e,s,t){var r=arguments.length,i=r<3?e:t===null?t=Object.getOwnPropertyDescriptor(e,s):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(g,e,s,t);else for(var n=g.length-1;n>=0;n--)(o=g[n])&&(i=(r<3?o(i):r>3?o(e,s,i):o(e,s))||i);return r>3&&i&&Object.defineProperty(e,s,i),i}l(as,"_ts_decorate");var ws="PubSubBridge",C=class C extends ds{_configRootAddress="";_configStateStoreArchivist="";_configStateStoreBoundWitnessDiviner="";_exposedAddresses=[];_lastState;_busClient;_busHost;_discoverRootsMutex=new ys;_resolver;get resolver(){return this._resolver=this._resolver??new N({additionalSigners:this.additionalSigners,archiving:{...this.archiving,resolveArchivists:this.resolveArchivingArchivists.bind(this)},bridge:this,busClient:D(this.busClient(),()=>"busClient not configured"),onQuerySendFinished:l(e=>{M(this.emit("querySendFinished",{module:this,...e}))},"onQuerySendFinished"),onQuerySendStarted:l(e=>{M(this.emit("querySendStarted",{module:this,...e}))},"onQuerySendStarted"),root:this,wrapperAccount:this.account}),this._resolver}get moduleName(){return this.modName??ws}async connect(e,s=5){let t=D(await Z.transformModuleIdentifier(e),()=>`Unable to transform module identifier: ${e}`),r=await this.resolve(t);if(r)return r.address;let[i]=await this.resolver.resolveHandler(e);return await this.connectInstance(i,s)}async disconnect(e){let s=D(await Z.transformModuleIdentifier(e),()=>`Unable to transform module identifier: ${e}`),t=await this.resolve(s);if(t)return this.downResolver.remove(t.address),t.address}async exposeChild(e,s){var a,c;let{maxDepth:t=5}=s??{};console.log(`exposeChild: ${e.address} ${e==null?void 0:e.id} ${t}`),D(this.busHost(),()=>"Not configured as a host").expose(e);let i=t>0?await((a=e.publicChildren)==null?void 0:a.call(e))??[]:[];this.logger.log(`childrenToExpose [${e.id}][${e.address}]: ${cs(i.map(d=>d.id))}`);let o=(await Promise.all(i.map(d=>this.exposeChild(d,{maxDepth:t-1,required:!1})))).flat().filter(U),n=[e,...o];for(let d of n)(c=this.logger)==null||c.log(`exposed: ${d.address} [${e.id}]`);return n}async exposeHandler(e,s){let{required:t=!0}=s??{},r=await ms(this,e);if(console.log(`exposeHandler: ${e} ${r==null?void 0:r.id}`),t&&!r)throw new Error(`Unable to find required module: ${e}`);return r?this.exposeChild(r,s):[]}exposedHandler(){var s;let e=(s=this.busHost())==null?void 0:s.exposedAddresses;return e?[...e]:[]}async getRoots(e){return await this._discoverRootsMutex.runExclusive(async()=>{if(this._roots===void 0||e){let s=(await Promise.all((this.config.roots??[]).map(r=>{var i;try{return Z.transformModuleIdentifier(r)}catch(o){(i=this.logger)==null||i.warn("Unable to transform module identifier:",r,o);return}}))).filter(U),t=(await Promise.all(s.map(async r=>{var i;try{return await this.resolver.resolveHandler(r)}catch(o){(i=this.logger)==null||i.warn("Unable to resolve root:",r,o);return}}))).flat().filter(U);for(let r of t)this.downResolver.add(r);this._roots=t}return this._roots})}async resolve(e="*",s={}){var i;let t=this._roots??[],r=s.direction==="up"?[this]:[...t,this];if(e==="*"){let o=(s.maxDepth??1)-1;return o<=0?r:[...r,...(await Promise.all(t.map(n=>n.resolve("*",{...s,maxDepth:o})))).flat()]}switch(typeof e){case"string":{let o=e.split(":"),n=D(o.shift(),()=>"Missing first part"),a=ls(n)?await fs(this,n,void 0,[],s.direction):(i=this._roots)==null?void 0:i.find(c=>c.id===n);return o.length===0?a:a==null?void 0:a.resolve(o.join(":"),s)}case"object":{let o=[];if(ps(e))for(let n of r)n.modName&&e.address.includes(n.address)&&o.push(n);return o}default:return}}async startHandler(){var e;return(e=this.busHost())==null||e.start(),await super.startHandler()}async unexposeHandler(e,s){var n;let{maxDepth:t=2,required:r=!0}=s??{},o=await D(this.busHost(),()=>"Not configured as a host").unexpose(e,r);if(o){let a=t>0?await((n=o.publicChildren)==null?void 0:n.call(o))??[]:[],c=(await Promise.all(a.map(d=>this.unexposeHandler(d.address,{maxDepth:t-1,required:!1})))).flat().filter(U);return[o,...c]}return[]}busClient(){return!this._busClient&&this.config.client&&(this._busClient=new P({config:this.config.client,logger:this.logger,rootModule:this})),this._busClient}busHost(){return!this._busHost&&this.config.host&&(this._busHost=new S({config:this.config.host,logger:this.logger,onQueryFulfillFinished:l(e=>{var s;this.archiving&&this.isAllowedArchivingQuery(e.query.schema)&&M(this.storeToArchivists(((s=e.result)==null?void 0:s.flat())??[])),M(this.emit("queryFulfillFinished",{module:this,...e}))},"onQueryFulfillFinished"),onQueryFulfillStarted:l(e=>{this.archiving&&this.isAllowedArchivingQuery(e.query.schema)&&M(this.storeToArchivists([e.query,...e.payloads??[]])),M(this.emit("queryFulfillStarted",{module:this,...e}))},"onQueryFulfillStarted"),rootModule:this})),this._busHost}async connectInstance(e,s=5){var t;if(e){if(this.downResolver.add(e),s>0){let r=gs(e);if(r){let i=await r.state(),o=((i==null?void 0:i.filter(vs(hs)).map(n=>n.address))??[]).filter(n=>n!==e.address);await Promise.all(o.map(n=>this.connect(n,s-1)))}}return(t=this.logger)==null||t.log(`Connect: ${e.id}`),e.address}}stopHandler(e){var s;return(s=this.busHost())==null||s.stop(),!0}};l(C,"PubSubBridge"),E(C,"configSchemas",[...te(C,C,"configSchemas"),K]),E(C,"defaultConfigSchema",K);var O=C;O=as([us()],O);export{H as AbstractModuleHost,P as AsyncQueryBusClient,S as AsyncQueryBusHost,ue as AsyncQueryBusModuleHost,Q as AsyncQueryBusModuleProxy,F as Pending,O as PubSubBridge,K as PubSubBridgeConfigSchema,N as PubSubBridgeModuleResolver,ge as PubSubBridgeSchema};
1
+ var __defProp = Object.defineProperty;
2
+ var __getProtoOf = Object.getPrototypeOf;
3
+ var __reflectGet = Reflect.get;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
7
+ var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj);
8
+
9
+ // src/AbstractModuleHost/AbstractModuleHost.ts
10
+ import { Base } from "@xylabs/object";
11
+ var _AbstractModuleHost = class _AbstractModuleHost extends Base {
12
+ };
13
+ __name(_AbstractModuleHost, "AbstractModuleHost");
14
+ var AbstractModuleHost = _AbstractModuleHost;
15
+
16
+ // src/AsyncQueryBus/AsyncQueryBusClient.ts
17
+ import { assertEx as assertEx2 } from "@xylabs/assert";
18
+ import { delay } from "@xylabs/delay";
19
+ import { forget } from "@xylabs/forget";
20
+ import { clearTimeoutEx, setTimeoutEx } from "@xylabs/timer";
21
+ import { isBoundWitnessWithMeta } from "@xyo-network/boundwitness-model";
22
+ import { BoundWitnessDivinerQuerySchema } from "@xyo-network/diviner-boundwitness-model";
23
+ import { PayloadBuilder } from "@xyo-network/payload-builder";
24
+ import { LRUCache as LRUCache2 } from "lru-cache";
25
+
26
+ // src/AsyncQueryBus/AsyncQueryBusBase.ts
27
+ import { assertEx } from "@xylabs/assert";
28
+ import { Base as Base2 } from "@xylabs/object";
29
+ import { isArchivistInstance } from "@xyo-network/archivist-model";
30
+ import { isDivinerInstance } from "@xyo-network/diviner-model";
31
+ import { ResolveHelper } from "@xyo-network/module-model";
32
+ import { Mutex } from "async-mutex";
33
+ import { LRUCache } from "lru-cache";
34
+ var POLLING_FREQUENCY_MIN = 100;
35
+ var POLLING_FREQUENCY_MAX = 6e4;
36
+ var POLLING_FREQUENCY_DEFAULT = 1e3;
37
+ var _AsyncQueryBusBase = class _AsyncQueryBusBase extends Base2 {
38
+ _lastState;
39
+ _targetConfigs = {};
40
+ _targetQueries = {};
41
+ _lastResolveFailure = {};
42
+ _queriesArchivist;
43
+ _queriesDiviner;
44
+ _reResolveDelay = 1e3 * 5;
45
+ _resolveMutex = new Mutex();
46
+ _responsesArchivist;
47
+ _responsesDiviner;
48
+ constructor(params) {
49
+ super(params);
50
+ }
51
+ get config() {
52
+ return this.params.config;
53
+ }
54
+ get pollFrequency() {
55
+ var _a;
56
+ const frequency = ((_a = this.config) == null ? void 0 : _a.pollFrequency) ?? POLLING_FREQUENCY_DEFAULT;
57
+ if (frequency < POLLING_FREQUENCY_MIN || frequency > POLLING_FREQUENCY_MAX) {
58
+ return POLLING_FREQUENCY_DEFAULT;
59
+ }
60
+ return frequency;
61
+ }
62
+ get rootModule() {
63
+ return this.params.rootModule;
64
+ }
65
+ /**
66
+ * A cache of the last offset of the Diviner process per address
67
+ */
68
+ get lastState() {
69
+ const requiredConfig = {
70
+ max: 1e3,
71
+ ttl: 0
72
+ };
73
+ this._lastState = this._lastState ?? new LRUCache(requiredConfig);
74
+ return this._lastState;
75
+ }
76
+ async queriesArchivist() {
77
+ return await this._resolveMutex.runExclusive(async () => {
78
+ var _a, _b, _c;
79
+ this._queriesArchivist = this._queriesArchivist ?? await this.resolve(assertEx((_c = (_b = (_a = this.config) == null ? void 0 : _a.intersect) == null ? void 0 : _b.queries) == null ? void 0 : _c.archivist, () => "No queries Archivist defined"), isArchivistInstance);
80
+ return this._queriesArchivist;
81
+ });
82
+ }
83
+ async queriesDiviner() {
84
+ return await this._resolveMutex.runExclusive(async () => {
85
+ var _a, _b, _c;
86
+ this._queriesDiviner = this._queriesDiviner ?? await this.resolve(assertEx((_c = (_b = (_a = this.config) == null ? void 0 : _a.intersect) == null ? void 0 : _b.queries) == null ? void 0 : _c.boundWitnessDiviner, () => "No queries Diviner defined"), isDivinerInstance);
87
+ return this._queriesDiviner;
88
+ });
89
+ }
90
+ async responsesArchivist() {
91
+ return await this._resolveMutex.runExclusive(async () => {
92
+ var _a, _b, _c;
93
+ this._responsesArchivist = this._responsesArchivist ?? await this.resolve(assertEx((_c = (_b = (_a = this.config) == null ? void 0 : _a.intersect) == null ? void 0 : _b.responses) == null ? void 0 : _c.archivist, () => "No responses Archivist defined"), isArchivistInstance);
94
+ return this._responsesArchivist;
95
+ });
96
+ }
97
+ async responsesDiviner() {
98
+ return await this._resolveMutex.runExclusive(async () => {
99
+ var _a, _b, _c;
100
+ this._responsesDiviner = this._responsesDiviner ?? await this.resolve(assertEx((_c = (_b = (_a = this.config) == null ? void 0 : _a.intersect) == null ? void 0 : _b.responses) == null ? void 0 : _c.boundWitnessDiviner, () => "No responses Diviner defined"), isDivinerInstance);
101
+ return this._responsesDiviner;
102
+ });
103
+ }
104
+ /**
105
+ * Commit the internal state of the process. This is similar
106
+ * to a transaction completion in a database and should only be called
107
+ * when results have been successfully persisted to the appropriate
108
+ * external stores.
109
+ * @param address The module address to commit the state for
110
+ * @param nextState The state to commit
111
+ */
112
+ async commitState(address, nextState) {
113
+ await Promise.resolve();
114
+ const lastState = this.lastState.get(address);
115
+ if (lastState && lastState >= nextState) return;
116
+ this.lastState.set(address, nextState);
117
+ }
118
+ /**
119
+ * Retrieves the last state of the process. Used to recover state after
120
+ * preemptions, reboots, etc.
121
+ */
122
+ async retrieveState(address) {
123
+ await Promise.resolve();
124
+ const state = this.lastState.get(address);
125
+ if (state === void 0) {
126
+ const newState = Date.now() - 1e3;
127
+ this.lastState.set(address, newState);
128
+ return newState;
129
+ } else {
130
+ return state;
131
+ }
132
+ }
133
+ async resolve(id, typeCheck) {
134
+ var _a, _b, _c;
135
+ if (Date.now() - (this._lastResolveFailure[id] ?? 0) < this._reResolveDelay) {
136
+ return;
137
+ }
138
+ this._lastResolveFailure[id] = Date.now();
139
+ const resolved = await ResolveHelper.resolveModuleIdentifier(this.rootModule, id);
140
+ if (resolved) {
141
+ if (typeCheck(resolved)) {
142
+ delete this._lastResolveFailure[id];
143
+ return resolved;
144
+ } else {
145
+ (_b = this.logger) == null ? void 0 : _b.warn(`Unable to resolve responsesDiviner as correct type [${id}][${(_a = resolved == null ? void 0 : resolved.constructor) == null ? void 0 : _a.name}]: ${resolved.id}`);
146
+ }
147
+ } else {
148
+ (_c = this.logger) == null ? void 0 : _c.debug(`Unable to resolve queriesArchivist [${id}] [${await ResolveHelper.traceModuleIdentifier(this.rootModule, id)}]`);
149
+ }
150
+ }
151
+ };
152
+ __name(_AsyncQueryBusBase, "AsyncQueryBusBase");
153
+ var AsyncQueryBusBase = _AsyncQueryBusBase;
154
+
155
+ // src/AsyncQueryBus/model/QueryStatus.ts
156
+ var Pending = "pending";
157
+
158
+ // src/AsyncQueryBus/AsyncQueryBusClient.ts
159
+ var _AsyncQueryBusClient = class _AsyncQueryBusClient extends AsyncQueryBusBase {
160
+ _queryCache;
161
+ _pollCount = 0;
162
+ _pollId;
163
+ constructor(params) {
164
+ super(params);
165
+ }
166
+ get queryCacheConfig() {
167
+ var _a, _b;
168
+ const queryCacheConfig = ((_a = this.config) == null ? void 0 : _a.queryCache) === true ? {} : (_b = this.config) == null ? void 0 : _b.queryCache;
169
+ return {
170
+ max: 100,
171
+ ttl: 1e3 * 60,
172
+ ...queryCacheConfig
173
+ };
174
+ }
175
+ get started() {
176
+ return !!this._pollId;
177
+ }
178
+ /**
179
+ * A cache of queries that have been issued
180
+ */
181
+ get queryCache() {
182
+ const config = this.queryCacheConfig;
183
+ const requiredConfig = {
184
+ noUpdateTTL: false,
185
+ ttlAutopurge: true
186
+ };
187
+ this._queryCache = this._queryCache ?? new LRUCache2({
188
+ ...config,
189
+ ...requiredConfig
190
+ });
191
+ return this._queryCache;
192
+ }
193
+ listeningAddresses() {
194
+ var _a;
195
+ return (_a = this._queryCache) == null ? void 0 : _a.keys();
196
+ }
197
+ async send(address, query, payloads) {
198
+ var _a, _b, _c, _d;
199
+ (_a = this.logger) == null ? void 0 : _a.debug(`Begin issuing query to: ${address}`);
200
+ const $meta = {
201
+ ...query == null ? void 0 : query.$meta,
202
+ destination: [
203
+ address
204
+ ]
205
+ };
206
+ const routedQuery = await PayloadBuilder.build({
207
+ ...query,
208
+ $meta
209
+ });
210
+ const queryArchivist = assertEx2(await this.queriesArchivist(), () => {
211
+ var _a2, _b2, _c2;
212
+ return `Unable to contact queriesArchivist [${(_c2 = (_b2 = (_a2 = this.config) == null ? void 0 : _a2.intersect) == null ? void 0 : _b2.queries) == null ? void 0 : _c2.archivist}]`;
213
+ });
214
+ const routedQueryHash = (
215
+ // Trust the signed hash if it's there
216
+ (routedQuery == null ? void 0 : routedQuery.$hash) ?? // TODO: What is the right way to find the dataHash
217
+ Object.keys(await PayloadBuilder.toDataHashMap([
218
+ routedQuery
219
+ ]))[0]
220
+ );
221
+ (_b = this.logger) == null ? void 0 : _b.debug(`Issuing query: ${routedQueryHash} to: ${address}`);
222
+ const data = payloads ? [
223
+ routedQuery,
224
+ ...payloads
225
+ ] : [
226
+ routedQuery
227
+ ];
228
+ const insertResult = await ((_c = queryArchivist.insert) == null ? void 0 : _c.call(queryArchivist, data));
229
+ (_d = this.logger) == null ? void 0 : _d.debug(`Issued query: ${routedQueryHash} to: ${address}`);
230
+ this.queryCache.set(routedQueryHash, Pending);
231
+ if (!insertResult) throw new Error("Unable to issue query to queryArchivist");
232
+ const context = new Promise((resolve, reject) => {
233
+ var _a2;
234
+ (_a2 = this.logger) == null ? void 0 : _a2.debug(`Polling for response to query: ${routedQueryHash}`);
235
+ let nextDelay = 100;
236
+ const pollForResponse = /* @__PURE__ */ __name(async () => {
237
+ var _a3, _b2;
238
+ try {
239
+ this.start();
240
+ let response = this.queryCache.get(routedQueryHash);
241
+ while (response !== void 0) {
242
+ await delay(nextDelay);
243
+ response = this.queryCache.get(routedQueryHash);
244
+ if (response && response !== Pending) {
245
+ (_a3 = this.logger) == null ? void 0 : _a3.log(`Returning response to query: ${routedQueryHash}`);
246
+ resolve(response);
247
+ return;
248
+ }
249
+ nextDelay = Math.floor(nextDelay * 1.2);
250
+ if (nextDelay > 1e3) nextDelay = 1e3;
251
+ }
252
+ (_b2 = this.logger) == null ? void 0 : _b2.error("Timeout waiting for query response");
253
+ const error = {
254
+ message: "Timeout waiting for query response",
255
+ query: "network.xyo.boundwitness",
256
+ schema: "network.xyo.error.module",
257
+ sources: [
258
+ routedQueryHash
259
+ ]
260
+ };
261
+ reject(error);
262
+ return;
263
+ } finally {
264
+ this.stop();
265
+ }
266
+ }, "pollForResponse");
267
+ forget(pollForResponse());
268
+ });
269
+ return context;
270
+ }
271
+ /**
272
+ * Runs the background divine process on a loop with a delay
273
+ * specified by the `config.pollFrequency`
274
+ */
275
+ poll() {
276
+ this._pollId = setTimeoutEx(async () => {
277
+ var _a, _b;
278
+ try {
279
+ await this.processIncomingResponses();
280
+ } catch (e) {
281
+ (_b = (_a = this.logger) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, `Error in main loop: ${e}`);
282
+ } finally {
283
+ if (this._pollId) clearTimeoutEx(this._pollId);
284
+ this._pollId = void 0;
285
+ this.poll();
286
+ }
287
+ }, this.pollFrequency);
288
+ }
289
+ /**
290
+ * Background process for processing incoming responses to previously issued queries
291
+ */
292
+ processIncomingResponses = /* @__PURE__ */ __name(async () => {
293
+ const responseArchivist = await this.responsesArchivist();
294
+ if (responseArchivist) {
295
+ const responseBoundWitnessDiviner = await this.responsesDiviner();
296
+ if (responseBoundWitnessDiviner) {
297
+ const pendingCommands = [
298
+ ...this.queryCache.entries()
299
+ ].filter(([_, status]) => status === Pending);
300
+ await Promise.allSettled(pendingCommands.map(async ([sourceQuery, status]) => {
301
+ var _a, _b, _c;
302
+ if (status === Pending) {
303
+ const divinerQuery = {
304
+ limit: 1,
305
+ order: "desc",
306
+ schema: BoundWitnessDivinerQuerySchema,
307
+ sourceQuery
308
+ };
309
+ const result = await responseBoundWitnessDiviner.divine([
310
+ divinerQuery
311
+ ]);
312
+ if (result && result.length > 0) {
313
+ const response = result.find(isBoundWitnessWithMeta);
314
+ if (response && ((_a = response == null ? void 0 : response.$meta) == null ? void 0 : _a.sourceQuery) === sourceQuery) {
315
+ (_b = this.logger) == null ? void 0 : _b.debug(`Found response to query: ${sourceQuery}`);
316
+ const payloads = ((_c = response.payload_hashes) == null ? void 0 : _c.length) > 0 ? await responseArchivist.get(response.payload_hashes) : [];
317
+ this.queryCache.set(sourceQuery, [
318
+ response,
319
+ payloads,
320
+ []
321
+ ]);
322
+ }
323
+ }
324
+ }
325
+ }));
326
+ }
327
+ }
328
+ }, "processIncomingResponses");
329
+ start() {
330
+ if (this._pollCount === 0) {
331
+ this.poll();
332
+ }
333
+ this._pollCount++;
334
+ }
335
+ stop() {
336
+ this._pollCount--;
337
+ if (this._pollCount <= 0) {
338
+ if (this._pollId) clearTimeoutEx(this._pollId);
339
+ this._pollId = void 0;
340
+ this._pollCount = 0;
341
+ }
342
+ }
343
+ };
344
+ __name(_AsyncQueryBusClient, "AsyncQueryBusClient");
345
+ var AsyncQueryBusClient = _AsyncQueryBusClient;
346
+
347
+ // src/AsyncQueryBus/AsyncQueryBusHost.ts
348
+ import { containsAll } from "@xylabs/array";
349
+ import { assertEx as assertEx3 } from "@xylabs/assert";
350
+ import { clearTimeoutEx as clearTimeoutEx2, setTimeoutEx as setTimeoutEx2 } from "@xylabs/timer";
351
+ import { isQueryBoundWitnessWithMeta } from "@xyo-network/boundwitness-model";
352
+ import { isBridgeInstance } from "@xyo-network/bridge-model";
353
+ import { BoundWitnessDivinerQuerySchema as BoundWitnessDivinerQuerySchema2 } from "@xyo-network/diviner-boundwitness-model";
354
+ import { asModuleInstance, ModuleConfigSchema, resolveAddressToInstance, ResolveHelper as ResolveHelper2 } from "@xyo-network/module-model";
355
+ import { PayloadBuilder as PayloadBuilder2 } from "@xyo-network/payload-builder";
356
+ var IDLE_POLLING_FREQUENCY_RATIO_MIN = 4;
357
+ var IDLE_POLLING_FREQUENCY_RATIO_MAX = 64;
358
+ var IDLE_POLLING_FREQUENCY_RATIO_DEFAULT = 16;
359
+ var IDLE_THRESHOLD_RATIO_MIN = 4;
360
+ var IDLE_THRESHOLD_RATIO_MAX = 64;
361
+ var IDLE_THRESHOLD_RATIO_DEFAULT = 16;
362
+ var _AsyncQueryBusHost = class _AsyncQueryBusHost extends AsyncQueryBusBase {
363
+ _exposedAddresses = /* @__PURE__ */ new Set();
364
+ _exposeOptions = {};
365
+ _idle = false;
366
+ _lastQueryTime;
367
+ _pollId;
368
+ constructor(params) {
369
+ super(params);
370
+ }
371
+ get exposedAddresses() {
372
+ return this._exposedAddresses;
373
+ }
374
+ get idlePollFrequency() {
375
+ var _a;
376
+ const frequency = ((_a = this.config) == null ? void 0 : _a.idlePollFrequency) ?? IDLE_POLLING_FREQUENCY_RATIO_DEFAULT * this.pollFrequency;
377
+ if (frequency < this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MIN) {
378
+ return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
379
+ }
380
+ if (frequency > this.pollFrequency * IDLE_POLLING_FREQUENCY_RATIO_MAX) {
381
+ return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
382
+ }
383
+ return frequency;
384
+ }
385
+ get idleThreshold() {
386
+ var _a;
387
+ const threshold = ((_a = this.config) == null ? void 0 : _a.idleThreshold) ?? IDLE_THRESHOLD_RATIO_DEFAULT * this.idlePollFrequency;
388
+ if (threshold < this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MIN) {
389
+ return IDLE_POLLING_FREQUENCY_RATIO_MIN * this.pollFrequency;
390
+ }
391
+ if (threshold > this.idlePollFrequency * IDLE_THRESHOLD_RATIO_MAX) {
392
+ return IDLE_POLLING_FREQUENCY_RATIO_MAX * this.pollFrequency;
393
+ }
394
+ return threshold;
395
+ }
396
+ get perAddressBatchQueryLimit() {
397
+ var _a;
398
+ return ((_a = this.config) == null ? void 0 : _a.perAddressBatchQueryLimit) ?? 10;
399
+ }
400
+ get started() {
401
+ return !!this._pollId;
402
+ }
403
+ expose(module, options) {
404
+ var _a, _b;
405
+ const { failOnAlreadyExposed } = options ?? {};
406
+ if (isBridgeInstance(module)) {
407
+ (_a = this.logger) == null ? void 0 : _a.warn(`Attempted to expose a BridgeModule [${module.id}] - Not exposing`);
408
+ } else {
409
+ assertEx3(!failOnAlreadyExposed || !this._exposedAddresses.has(module.address), () => `Address already exposed: ${module.id} [${module.address}]`);
410
+ this._exposedAddresses.add(module.address);
411
+ this._exposeOptions[module.address] = {
412
+ ...options
413
+ };
414
+ (_b = this.logger) == null ? void 0 : _b.debug(`${module.id} exposed [${module.address}]`);
415
+ return module;
416
+ }
417
+ }
418
+ async listeningModules() {
419
+ var _a;
420
+ const exposedModules = [
421
+ ...((_a = this.config) == null ? void 0 : _a.listeningModules) ?? [],
422
+ ...this.exposedAddresses.values()
423
+ ];
424
+ const mods = await Promise.all(exposedModules.map(async (exposedModule) => assertEx3(asModuleInstance(await resolveAddressToInstance(this.rootModule, exposedModule)), () => `Unable to resolve listeningModule [${exposedModule}]`)));
425
+ return mods;
426
+ }
427
+ start() {
428
+ if (this.started) {
429
+ console.warn("AsyncQueryBus starting when already started");
430
+ }
431
+ this.poll();
432
+ }
433
+ stop() {
434
+ if (!this.started) {
435
+ console.warn("AsyncQueryBus stopping when already stopped");
436
+ }
437
+ if (this._pollId) clearTimeoutEx2(this._pollId);
438
+ this._pollId = void 0;
439
+ }
440
+ async unexpose(id, validate = true) {
441
+ var _a;
442
+ const module = asModuleInstance(await this.rootModule.resolve(id, {
443
+ maxDepth: 10
444
+ }));
445
+ if (module) {
446
+ assertEx3(!validate || this._exposedAddresses.has(module.address), () => `Address not exposed [${module.address}][${module.id}]`);
447
+ this._exposedAddresses.delete(module.address);
448
+ delete this._exposeOptions[module.address];
449
+ (_a = this.logger) == null ? void 0 : _a.debug(`${module.address} [${module.id}] unexposed`);
450
+ }
451
+ return module;
452
+ }
453
+ // eslint-disable-next-line complexity
454
+ callLocalModule = /* @__PURE__ */ __name(async (localModule, query) => {
455
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
456
+ this._idle = false;
457
+ this._lastQueryTime = Date.now();
458
+ const localModuleName = localModule.id;
459
+ const queryArchivist = assertEx3(await this.queriesArchivist(), () => {
460
+ var _a2, _b2, _c2;
461
+ return `Unable to contact queriesArchivist [${(_c2 = (_b2 = (_a2 = this.config) == null ? void 0 : _a2.intersect) == null ? void 0 : _b2.queries) == null ? void 0 : _c2.archivist}]`;
462
+ });
463
+ const responsesArchivist = assertEx3(await this.responsesArchivist(), () => {
464
+ var _a2, _b2, _c2;
465
+ return `Unable to contact responsesArchivist [${(_c2 = (_b2 = (_a2 = this.config) == null ? void 0 : _a2.intersect) == null ? void 0 : _b2.queries) == null ? void 0 : _c2.archivist}]`;
466
+ });
467
+ const queryDestination = (_a = query.$meta) == null ? void 0 : _a.destination;
468
+ if (queryDestination && (queryDestination == null ? void 0 : queryDestination.includes(localModule.address))) {
469
+ const queryIndex = query.payload_hashes.indexOf(query.query);
470
+ if (queryIndex !== -1) {
471
+ const querySchema = query.payload_schemas[queryIndex];
472
+ if (localModule.queries.includes(querySchema)) {
473
+ const queryPayloads = await queryArchivist.get(query.payload_hashes);
474
+ (_c = (_b = this.params).onQueryFulfillStarted) == null ? void 0 : _c.call(_b, {
475
+ payloads: queryPayloads,
476
+ query
477
+ });
478
+ const queryPayloadsDict = await PayloadBuilder2.toAllHashMap(queryPayloads);
479
+ const queryHash = (await PayloadBuilder2.build(query)).$hash;
480
+ if (!containsAll(Object.keys(queryPayloadsDict), query.payload_hashes)) {
481
+ (_d = this.logger) == null ? void 0 : _d.error(`Error processing command ${queryHash} for module ${localModuleName}, missing payloads`);
482
+ return;
483
+ }
484
+ try {
485
+ const querySchema2 = queryPayloadsDict[query.query].schema;
486
+ (_e = this.logger) == null ? void 0 : _e.debug(`Issuing query ${querySchema2} (${queryHash}) addressed to module: ${localModuleName}`);
487
+ const result = await localModule.query(query, queryPayloads, {
488
+ allowedQueries: (_f = this._exposeOptions[localModule.address]) == null ? void 0 : _f.allowedQueries,
489
+ schema: ModuleConfigSchema
490
+ });
491
+ const [bw, payloads, errors] = result;
492
+ (_g = this.logger) == null ? void 0 : _g.debug(`Replying to query ${queryHash} addressed to module: ${localModuleName}`);
493
+ const insertResult = await responsesArchivist.insert([
494
+ bw,
495
+ ...payloads,
496
+ ...errors
497
+ ]);
498
+ if (insertResult.length === 0) {
499
+ (_h = this.logger) == null ? void 0 : _h.error(`Error replying to query ${queryHash} addressed to module: ${localModuleName}`);
500
+ }
501
+ if (query == null ? void 0 : query.timestamp) {
502
+ await this.commitState(localModule.address, query.timestamp);
503
+ }
504
+ (_j = (_i = this.params).onQueryFulfillFinished) == null ? void 0 : _j.call(_i, {
505
+ payloads: queryPayloads,
506
+ query,
507
+ result,
508
+ status: "success"
509
+ });
510
+ } catch (error) {
511
+ (_l = (_k = this.params).onQueryFulfillFinished) == null ? void 0 : _l.call(_k, {
512
+ payloads: queryPayloads,
513
+ query,
514
+ status: "failure"
515
+ });
516
+ (_m = this.logger) == null ? void 0 : _m.error(`Error processing query ${queryHash} for module ${localModuleName}: ${error}`);
517
+ }
518
+ }
519
+ }
520
+ }
521
+ }, "callLocalModule");
522
+ /**
523
+ * Finds unprocessed commands addressed to the supplied address
524
+ * @param address The address to find commands for
525
+ */
526
+ findQueriesToAddress = /* @__PURE__ */ __name(async (address) => {
527
+ var _a, _b, _c, _d, _e;
528
+ const queriesDivinerId = assertEx3((_c = (_b = (_a = this.config) == null ? void 0 : _a.intersect) == null ? void 0 : _b.queries) == null ? void 0 : _c.boundWitnessDiviner, () => "No queries Diviner defined");
529
+ const queriesBoundWitnessDiviner = await this.queriesDiviner();
530
+ if (queriesBoundWitnessDiviner) {
531
+ const prevState = await this.retrieveState(address);
532
+ const destination = [
533
+ address
534
+ ];
535
+ const limit = this.perAddressBatchQueryLimit;
536
+ const divinerQuery = {
537
+ destination,
538
+ limit,
539
+ order: "asc",
540
+ schema: BoundWitnessDivinerQuerySchema2,
541
+ timestamp: prevState + 1
542
+ };
543
+ const result = await queriesBoundWitnessDiviner.divine([
544
+ divinerQuery
545
+ ]);
546
+ const queries = result.filter(isQueryBoundWitnessWithMeta);
547
+ const nextState = queries.length > 0 ? Math.max(...queries.map((c) => c.timestamp ?? prevState)) + 1 : Date.now();
548
+ await this.commitState(address, nextState);
549
+ (_d = this.logger) == null ? void 0 : _d.debug("findQueriesToAddress", address, prevState, nextState);
550
+ return queries;
551
+ } else {
552
+ (_e = this.logger) == null ? void 0 : _e.warn(`Unable to resolve queriesBoundWitnessDiviner [${queriesDivinerId}] [${await ResolveHelper2.traceModuleIdentifier(this.rootModule, queriesDivinerId)}]`);
553
+ }
554
+ }, "findQueriesToAddress");
555
+ /**
556
+ * Runs the background divine process on a loop with a delay
557
+ * specified by the `config.pollFrequency`
558
+ */
559
+ poll() {
560
+ this._pollId = setTimeoutEx2(async () => {
561
+ var _a, _b;
562
+ try {
563
+ await this.processIncomingQueries();
564
+ } catch (e) {
565
+ (_b = (_a = this.logger) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, `Error in main loop: ${e}`);
566
+ } finally {
567
+ if (this._pollId) clearTimeoutEx2(this._pollId);
568
+ this._pollId = void 0;
569
+ this.poll();
570
+ }
571
+ const now = Date.now();
572
+ if (this.idleThreshold < now - (this._lastQueryTime ?? now)) {
573
+ this._idle = true;
574
+ }
575
+ }, this._idle ? this.idlePollFrequency : this.pollFrequency);
576
+ }
577
+ /**
578
+ * Background process for checking for inbound queries
579
+ */
580
+ processIncomingQueries = /* @__PURE__ */ __name(async () => {
581
+ var _a;
582
+ (_a = this.logger) == null ? void 0 : _a.debug("Checking for inbound queries");
583
+ const localModules = await this.listeningModules();
584
+ await Promise.allSettled(localModules.map(async (localModule) => {
585
+ var _a2, _b, _c;
586
+ try {
587
+ const localModuleName = localModule.id;
588
+ (_a2 = this.logger) == null ? void 0 : _a2.debug(`Checking for inbound queries to ${localModuleName} [${localModule.address}]`);
589
+ const queries = await this.findQueriesToAddress(localModule.address) ?? [];
590
+ if (queries.length === 0) return;
591
+ (_b = this.logger) == null ? void 0 : _b.debug(`Found queries addressed to local module: ${localModuleName}`);
592
+ for (const query of queries) {
593
+ await this.callLocalModule(localModule, query);
594
+ }
595
+ } catch (error) {
596
+ (_c = this.logger) == null ? void 0 : _c.error(`Error processing queries for address ${localModule.address}: ${error}`);
597
+ }
598
+ }));
599
+ }, "processIncomingQueries");
600
+ };
601
+ __name(_AsyncQueryBusHost, "AsyncQueryBusHost");
602
+ var AsyncQueryBusHost = _AsyncQueryBusHost;
603
+
604
+ // src/AsyncQueryBus/ModuleHost/ModuleHost.ts
605
+ var _AsyncQueryBusModuleHost = class _AsyncQueryBusModuleHost extends AbstractModuleHost {
606
+ _busHost;
607
+ constructor(params) {
608
+ super(params);
609
+ }
610
+ async start() {
611
+ var _a;
612
+ const listeningModules = this.params.config.listeningModules ?? (await this.params.module.resolve("*", {
613
+ direction: "down"
614
+ })).map((m) => m.address);
615
+ this._busHost = new AsyncQueryBusHost({
616
+ config: {
617
+ ...this.params.config,
618
+ listeningModules
619
+ },
620
+ logger: this.params.logger,
621
+ rootModule: this.params.module
622
+ });
623
+ (_a = this._busHost) == null ? void 0 : _a.start();
624
+ }
625
+ stop() {
626
+ var _a;
627
+ (_a = this._busHost) == null ? void 0 : _a.stop();
628
+ }
629
+ };
630
+ __name(_AsyncQueryBusModuleHost, "AsyncQueryBusModuleHost");
631
+ var AsyncQueryBusModuleHost = _AsyncQueryBusModuleHost;
632
+
633
+ // src/AsyncQueryBus/ModuleProxy/ModuleProxy.ts
634
+ import { assertEx as assertEx4 } from "@xylabs/assert";
635
+ import { exists } from "@xylabs/exists";
636
+ import { forget as forget2 } from "@xylabs/forget";
637
+ import { isAddress } from "@xylabs/hex";
638
+ import { AbstractModuleProxy } from "@xyo-network/bridge-abstract";
639
+ import { ResolveHelper as ResolveHelper3 } from "@xyo-network/module-model";
640
+ var _AsyncQueryBusModuleProxy = class _AsyncQueryBusModuleProxy extends AbstractModuleProxy {
641
+ constructor(params) {
642
+ _AsyncQueryBusModuleProxy.createCount = _AsyncQueryBusModuleProxy.createCount + 1;
643
+ if (Math.floor(_AsyncQueryBusModuleProxy.createCount / 10) === _AsyncQueryBusModuleProxy.createCount / 10) {
644
+ console.log(`AsyncQueryBusModuleProxy.createCount: ${_AsyncQueryBusModuleProxy.createCount}`);
645
+ }
646
+ super(params);
647
+ }
648
+ get id() {
649
+ return this.address;
650
+ }
651
+ get modName() {
652
+ return void 0;
653
+ }
654
+ async proxyQueryHandler(query, payloads) {
655
+ if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
656
+ forget2(this.storeToArchivists([
657
+ query,
658
+ ...payloads ?? []
659
+ ]));
660
+ }
661
+ const result = await this.params.busClient.send(this.address, query, payloads);
662
+ if (this.archiving && this.isAllowedArchivingQuery(query.schema)) {
663
+ forget2(this.storeToArchivists(result.flat()));
664
+ }
665
+ return result;
666
+ }
667
+ async publicChildren() {
668
+ return (await Promise.all(Object.values(await this.childAddressMap()).filter(exists).map((address) => this.resolve(address)))).filter(exists);
669
+ }
670
+ async resolve(idOrFilter = "*", options = {}) {
671
+ const config = {
672
+ address: this.address,
673
+ dead: this.dead,
674
+ downResolver: this.downResolver,
675
+ logger: this.logger,
676
+ module: this,
677
+ transformers: this.moduleIdentifierTransformers,
678
+ upResolver: this.upResolver
679
+ };
680
+ if (idOrFilter === "*") {
681
+ return await this.publicChildren();
682
+ }
683
+ switch (typeof idOrFilter) {
684
+ case "string": {
685
+ const parts = idOrFilter.split(":");
686
+ const first = assertEx4(parts.shift(), () => "Missing first");
687
+ const remainingPath = parts.join(":");
688
+ const address = isAddress(first) ? first : this.childAddressByName(first);
689
+ if (!address) return void 0;
690
+ const firstInstance = await this.params.host.resolve(address);
691
+ return remainingPath ? await (firstInstance == null ? void 0 : firstInstance.resolve(remainingPath)) : firstInstance;
692
+ }
693
+ case "object": {
694
+ return (await ResolveHelper3.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
695
+ }
696
+ default: {
697
+ return (await ResolveHelper3.resolve(config, idOrFilter, options)).filter((mod) => mod.address !== this.address);
698
+ }
699
+ }
700
+ }
701
+ async startHandler() {
702
+ return await super.startHandler();
703
+ }
704
+ };
705
+ __name(_AsyncQueryBusModuleProxy, "AsyncQueryBusModuleProxy");
706
+ __publicField(_AsyncQueryBusModuleProxy, "createCount", 0);
707
+ var AsyncQueryBusModuleProxy = _AsyncQueryBusModuleProxy;
708
+
709
+ // src/Schema.ts
710
+ var PubSubBridgeSchema = "network.xyo.bridge.pubsub";
711
+
712
+ // src/Config.ts
713
+ var PubSubBridgeConfigSchema = `${PubSubBridgeSchema}.config`;
714
+
715
+ // src/PubSubBridge.ts
716
+ import { assertEx as assertEx6 } from "@xylabs/assert";
717
+ import { exists as exists2 } from "@xylabs/exists";
718
+ import { forget as forget3 } from "@xylabs/forget";
719
+ import { isAddress as isAddress3 } from "@xylabs/hex";
720
+ import { toJsonString } from "@xylabs/object";
721
+ import { AbstractBridge } from "@xyo-network/bridge-abstract";
722
+ import { AddressSchema, creatableModule, isAddressModuleFilter, resolveAddressToInstance as resolveAddressToInstance2, resolveAddressToInstanceUp, ResolveHelper as ResolveHelper5 } from "@xyo-network/module-model";
723
+ import { asNodeInstance } from "@xyo-network/node-model";
724
+ import { isPayloadOfSchemaType } from "@xyo-network/payload-model";
725
+ import { Mutex as Mutex3 } from "async-mutex";
726
+
727
+ // src/PubSubBridgeModuleResolver.ts
728
+ import { assertEx as assertEx5 } from "@xylabs/assert";
729
+ import { isAddress as isAddress2 } from "@xylabs/hex";
730
+ import { Account } from "@xyo-network/account";
731
+ import { AbstractBridgeModuleResolver, wrapModuleWithType } from "@xyo-network/bridge-abstract";
732
+ import { ConfigSchema } from "@xyo-network/config-payload-plugin";
733
+ import { asModuleInstance as asModuleInstance2, ModuleConfigSchema as ModuleConfigSchema2, ResolveHelper as ResolveHelper4 } from "@xyo-network/module-model";
734
+ import { Mutex as Mutex2 } from "async-mutex";
735
+ import { LRUCache as LRUCache3 } from "lru-cache";
736
+ var _PubSubBridgeModuleResolver = class _PubSubBridgeModuleResolver extends AbstractBridgeModuleResolver {
737
+ _resolvedCache = new LRUCache3({
738
+ max: 1e3
739
+ });
740
+ _resolvedCacheMutex = new Mutex2();
741
+ async resolveHandler(id, options) {
742
+ const parentResult = await super.resolveHandler(id, options);
743
+ if (parentResult.length > 0) {
744
+ return parentResult;
745
+ }
746
+ const idParts = id.split(":");
747
+ const untransformedFirstPart = assertEx5(idParts.shift(), () => "Missing module identifier");
748
+ const firstPart = await ResolveHelper4.transformModuleIdentifier(untransformedFirstPart);
749
+ assertEx5(isAddress2(firstPart), () => `Invalid module address: ${firstPart}`);
750
+ const remainderParts = idParts.join(":");
751
+ const instance = await this._resolvedCacheMutex.runExclusive(async () => {
752
+ var _a, _b;
753
+ const cachedMod = this._resolvedCache.get(firstPart);
754
+ if (cachedMod) {
755
+ const result2 = idParts.length <= 0 ? cachedMod : cachedMod.resolve(remainderParts, {
756
+ ...options,
757
+ maxDepth: ((options == null ? void 0 : options.maxDepth) ?? 5) - 1
758
+ });
759
+ return result2;
760
+ }
761
+ const account = Account.randomSync();
762
+ const finalParams = {
763
+ account,
764
+ archiving: this.params.archiving,
765
+ busClient: this.params.busClient,
766
+ config: {
767
+ schema: ModuleConfigSchema2
768
+ },
769
+ host: this,
770
+ moduleAddress: firstPart,
771
+ onQuerySendFinished: this.params.onQuerySendFinished,
772
+ onQuerySendStarted: this.params.onQuerySendStarted
773
+ };
774
+ const proxy = new AsyncQueryBusModuleProxy(finalParams);
775
+ const state = await proxy.state();
776
+ if (state) {
777
+ const configSchema = (_a = state.find((payload) => payload.schema === ConfigSchema)) == null ? void 0 : _a.config;
778
+ const config = assertEx5(state.find((payload) => payload.schema === configSchema), () => "Unable to locate config");
779
+ proxy.setConfig(config);
780
+ }
781
+ await ((_b = proxy.start) == null ? void 0 : _b.call(proxy));
782
+ const wrapped = wrapModuleWithType(proxy, account);
783
+ assertEx5(asModuleInstance2(wrapped, {}), () => `Failed to asModuleInstance [${id}]`);
784
+ this._resolvedCache.set(wrapped.address, wrapped);
785
+ return wrapped;
786
+ });
787
+ const result = remainderParts.length > 0 ? await instance.resolve(remainderParts, options) : instance;
788
+ return result ? [
789
+ result
790
+ ] : [];
791
+ }
792
+ };
793
+ __name(_PubSubBridgeModuleResolver, "PubSubBridgeModuleResolver");
794
+ var PubSubBridgeModuleResolver = _PubSubBridgeModuleResolver;
795
+
796
+ // src/PubSubBridge.ts
797
+ function _ts_decorate(decorators, target, key, desc) {
798
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
799
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
800
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
801
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
802
+ }
803
+ __name(_ts_decorate, "_ts_decorate");
804
+ var moduleName = "PubSubBridge";
805
+ var _PubSubBridge = class _PubSubBridge extends AbstractBridge {
806
+ _configRootAddress = "";
807
+ _configStateStoreArchivist = "";
808
+ _configStateStoreBoundWitnessDiviner = "";
809
+ _exposedAddresses = [];
810
+ _lastState;
811
+ _busClient;
812
+ _busHost;
813
+ _discoverRootsMutex = new Mutex3();
814
+ _resolver;
815
+ get resolver() {
816
+ this._resolver = this._resolver ?? new PubSubBridgeModuleResolver({
817
+ additionalSigners: this.additionalSigners,
818
+ archiving: {
819
+ ...this.archiving,
820
+ resolveArchivists: this.resolveArchivingArchivists.bind(this)
821
+ },
822
+ bridge: this,
823
+ busClient: assertEx6(this.busClient(), () => "busClient not configured"),
824
+ onQuerySendFinished: /* @__PURE__ */ __name((args) => {
825
+ forget3(this.emit("querySendFinished", {
826
+ module: this,
827
+ ...args
828
+ }));
829
+ }, "onQuerySendFinished"),
830
+ onQuerySendStarted: /* @__PURE__ */ __name((args) => {
831
+ forget3(this.emit("querySendStarted", {
832
+ module: this,
833
+ ...args
834
+ }));
835
+ }, "onQuerySendStarted"),
836
+ root: this,
837
+ wrapperAccount: this.account
838
+ });
839
+ return this._resolver;
840
+ }
841
+ get moduleName() {
842
+ return this.modName ?? moduleName;
843
+ }
844
+ async connect(id, maxDepth = 5) {
845
+ const transformedId = assertEx6(await ResolveHelper5.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
846
+ const existingInstance = await this.resolve(transformedId);
847
+ if (existingInstance) {
848
+ return existingInstance.address;
849
+ }
850
+ const [instance] = await this.resolver.resolveHandler(id);
851
+ return await this.connectInstance(instance, maxDepth);
852
+ }
853
+ async disconnect(id) {
854
+ const transformedId = assertEx6(await ResolveHelper5.transformModuleIdentifier(id), () => `Unable to transform module identifier: ${id}`);
855
+ const instance = await this.resolve(transformedId);
856
+ if (instance) {
857
+ this.downResolver.remove(instance.address);
858
+ return instance.address;
859
+ }
860
+ }
861
+ async exposeChild(mod, options) {
862
+ var _a, _b;
863
+ const { maxDepth = 5 } = options ?? {};
864
+ console.log(`exposeChild: ${mod.address} ${mod == null ? void 0 : mod.id} ${maxDepth}`);
865
+ const host = assertEx6(this.busHost(), () => "Not configured as a host");
866
+ host.expose(mod);
867
+ const children = maxDepth > 0 ? await ((_a = mod.publicChildren) == null ? void 0 : _a.call(mod)) ?? [] : [];
868
+ this.logger.log(`childrenToExpose [${mod.id}][${mod.address}]: ${toJsonString(children.map((child) => child.id))}`);
869
+ const exposedChildren = (await Promise.all(children.map((child) => this.exposeChild(child, {
870
+ maxDepth: maxDepth - 1,
871
+ required: false
872
+ })))).flat().filter(exists2);
873
+ const allExposed = [
874
+ mod,
875
+ ...exposedChildren
876
+ ];
877
+ for (const exposedMod of allExposed) (_b = this.logger) == null ? void 0 : _b.log(`exposed: ${exposedMod.address} [${mod.id}]`);
878
+ return allExposed;
879
+ }
880
+ async exposeHandler(address, options) {
881
+ const { required = true } = options ?? {};
882
+ const mod = await resolveAddressToInstanceUp(this, address);
883
+ console.log(`exposeHandler: ${address} ${mod == null ? void 0 : mod.id}`);
884
+ if (required && !mod) {
885
+ throw new Error(`Unable to find required module: ${address}`);
886
+ }
887
+ if (mod) {
888
+ return this.exposeChild(mod, options);
889
+ }
890
+ return [];
891
+ }
892
+ exposedHandler() {
893
+ var _a;
894
+ const exposedSet = (_a = this.busHost()) == null ? void 0 : _a.exposedAddresses;
895
+ return exposedSet ? [
896
+ ...exposedSet
897
+ ] : [];
898
+ }
899
+ async getRoots(force) {
900
+ return await this._discoverRootsMutex.runExclusive(async () => {
901
+ if (this._roots === void 0 || force) {
902
+ const rootAddresses = (await Promise.all((this.config.roots ?? []).map((id) => {
903
+ var _a;
904
+ try {
905
+ return ResolveHelper5.transformModuleIdentifier(id);
906
+ } catch (ex) {
907
+ (_a = this.logger) == null ? void 0 : _a.warn("Unable to transform module identifier:", id, ex);
908
+ return;
909
+ }
910
+ }))).filter(exists2);
911
+ const rootInstances = (await Promise.all(rootAddresses.map(async (root) => {
912
+ var _a;
913
+ try {
914
+ return await this.resolver.resolveHandler(root);
915
+ } catch (ex) {
916
+ (_a = this.logger) == null ? void 0 : _a.warn("Unable to resolve root:", root, ex);
917
+ return;
918
+ }
919
+ }))).flat().filter(exists2);
920
+ for (const instance of rootInstances) {
921
+ this.downResolver.add(instance);
922
+ }
923
+ this._roots = rootInstances;
924
+ }
925
+ return this._roots;
926
+ });
927
+ }
928
+ async resolve(idOrFilter = "*", options = {}) {
929
+ var _a;
930
+ const roots = this._roots ?? [];
931
+ const workingSet = options.direction === "up" ? [
932
+ this
933
+ ] : [
934
+ ...roots,
935
+ this
936
+ ];
937
+ if (idOrFilter === "*") {
938
+ const remainingDepth = (options.maxDepth ?? 1) - 1;
939
+ return remainingDepth <= 0 ? workingSet : [
940
+ ...workingSet,
941
+ ...(await Promise.all(roots.map((mod) => mod.resolve("*", {
942
+ ...options,
943
+ maxDepth: remainingDepth
944
+ })))).flat()
945
+ ];
946
+ }
947
+ switch (typeof idOrFilter) {
948
+ case "string": {
949
+ const parts = idOrFilter.split(":");
950
+ const first = assertEx6(parts.shift(), () => "Missing first part");
951
+ const firstInstance = isAddress3(first) ? await resolveAddressToInstance2(this, first, void 0, [], options.direction) : (_a = this._roots) == null ? void 0 : _a.find((mod) => mod.id === first);
952
+ return parts.length === 0 ? firstInstance : firstInstance == null ? void 0 : firstInstance.resolve(parts.join(":"), options);
953
+ }
954
+ case "object": {
955
+ const results = [];
956
+ if (isAddressModuleFilter(idOrFilter)) {
957
+ for (const mod of workingSet) {
958
+ if (mod.modName && idOrFilter.address.includes(mod.address)) results.push(mod);
959
+ }
960
+ }
961
+ return results;
962
+ }
963
+ default: {
964
+ return;
965
+ }
966
+ }
967
+ }
968
+ async startHandler() {
969
+ var _a;
970
+ (_a = this.busHost()) == null ? void 0 : _a.start();
971
+ return await super.startHandler();
972
+ }
973
+ async unexposeHandler(id, options) {
974
+ var _a;
975
+ const { maxDepth = 2, required = true } = options ?? {};
976
+ const host = assertEx6(this.busHost(), () => "Not configured as a host");
977
+ const module = await host.unexpose(id, required);
978
+ if (module) {
979
+ const children = maxDepth > 0 ? await ((_a = module.publicChildren) == null ? void 0 : _a.call(module)) ?? [] : [];
980
+ const exposedChildren = (await Promise.all(children.map((child) => this.unexposeHandler(child.address, {
981
+ maxDepth: maxDepth - 1,
982
+ required: false
983
+ })))).flat().filter(exists2);
984
+ return [
985
+ module,
986
+ ...exposedChildren
987
+ ];
988
+ }
989
+ return [];
990
+ }
991
+ busClient() {
992
+ if (!this._busClient && this.config.client) {
993
+ this._busClient = new AsyncQueryBusClient({
994
+ config: this.config.client,
995
+ logger: this.logger,
996
+ rootModule: this
997
+ });
998
+ }
999
+ return this._busClient;
1000
+ }
1001
+ busHost() {
1002
+ if (!this._busHost && this.config.host) {
1003
+ this._busHost = new AsyncQueryBusHost({
1004
+ config: this.config.host,
1005
+ logger: this.logger,
1006
+ onQueryFulfillFinished: /* @__PURE__ */ __name((args) => {
1007
+ var _a;
1008
+ if (this.archiving && this.isAllowedArchivingQuery(args.query.schema)) {
1009
+ forget3(this.storeToArchivists(((_a = args.result) == null ? void 0 : _a.flat()) ?? []));
1010
+ }
1011
+ forget3(this.emit("queryFulfillFinished", {
1012
+ module: this,
1013
+ ...args
1014
+ }));
1015
+ }, "onQueryFulfillFinished"),
1016
+ onQueryFulfillStarted: /* @__PURE__ */ __name((args) => {
1017
+ if (this.archiving && this.isAllowedArchivingQuery(args.query.schema)) {
1018
+ forget3(this.storeToArchivists([
1019
+ args.query,
1020
+ ...args.payloads ?? []
1021
+ ]));
1022
+ }
1023
+ forget3(this.emit("queryFulfillStarted", {
1024
+ module: this,
1025
+ ...args
1026
+ }));
1027
+ }, "onQueryFulfillStarted"),
1028
+ rootModule: this
1029
+ });
1030
+ }
1031
+ return this._busHost;
1032
+ }
1033
+ async connectInstance(instance, maxDepth = 5) {
1034
+ var _a;
1035
+ if (instance) {
1036
+ this.downResolver.add(instance);
1037
+ if (maxDepth > 0) {
1038
+ const node = asNodeInstance(instance);
1039
+ if (node) {
1040
+ const state = await node.state();
1041
+ const children = ((state == null ? void 0 : state.filter(isPayloadOfSchemaType(AddressSchema)).map((s) => s.address)) ?? []).filter((a) => a !== instance.address);
1042
+ await Promise.all(children.map((child) => this.connect(child, maxDepth - 1)));
1043
+ }
1044
+ }
1045
+ (_a = this.logger) == null ? void 0 : _a.log(`Connect: ${instance.id}`);
1046
+ return instance.address;
1047
+ }
1048
+ }
1049
+ stopHandler(_timeout) {
1050
+ var _a;
1051
+ (_a = this.busHost()) == null ? void 0 : _a.stop();
1052
+ return true;
1053
+ }
1054
+ };
1055
+ __name(_PubSubBridge, "PubSubBridge");
1056
+ __publicField(_PubSubBridge, "configSchemas", [
1057
+ ...__superGet(_PubSubBridge, _PubSubBridge, "configSchemas"),
1058
+ PubSubBridgeConfigSchema
1059
+ ]);
1060
+ __publicField(_PubSubBridge, "defaultConfigSchema", PubSubBridgeConfigSchema);
1061
+ var PubSubBridge = _PubSubBridge;
1062
+ PubSubBridge = _ts_decorate([
1063
+ creatableModule()
1064
+ ], PubSubBridge);
1065
+ export {
1066
+ AbstractModuleHost,
1067
+ AsyncQueryBusClient,
1068
+ AsyncQueryBusHost,
1069
+ AsyncQueryBusModuleHost,
1070
+ AsyncQueryBusModuleProxy,
1071
+ Pending,
1072
+ PubSubBridge,
1073
+ PubSubBridgeConfigSchema,
1074
+ PubSubBridgeModuleResolver,
1075
+ PubSubBridgeSchema
1076
+ };
2
1077
  //# sourceMappingURL=index.js.map