openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2 lines • 2.24 kB
JavaScript
//!src/shared/global-singleton.ts
const GLOBAL_SINGLETON_RESETS_KEY=Symbol.for(`openclaw.globalSingletonLifecycleResets`);function resolveGlobalSingletonResetRegistry(){const e=globalThis;const t=e[GLOBAL_SINGLETON_RESETS_KEY];if(t instanceof Map)return t;const n=/* @__PURE__ */ new Map;e[GLOBAL_SINGLETON_RESETS_KEY]=n;return n}function readGlobalSingleton(e){const t=globalThis;return Object.hasOwn(t,e)?t[e]:void 0}async function resetGlobalSingletonLifecycleState(e){await resolveGlobalSingletonResetRegistry().get(e)?.reset()}function resolveGlobalSingleton(e,t,n,r=`close-and-restart`){const i=globalThis;let a;if(Object.hasOwn(i,e))a=i[e];else{a=t();i[e]=a}if(n)resolveGlobalSingletonResetRegistry().set(e,{lifecycle:r,reset:()=>n(a)});return a}function resolveGlobalMap(e,t,n){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Map,typeof t===`string`?e=>e.clear():t,typeof t===`string`?t:n)}function resolveGlobalSet(e,t){return resolveGlobalSingleton(e,()=>/* @__PURE__ */ new Set,e=>e.clear(),t)}async function drainGlobalSingletonLifecycleState(e=`close`,t={}){const n=[...resolveGlobalSingletonResetRegistry().entries()].filter(([,{lifecycle:n}])=>{if(e===`shared-state`)return n===`shared-state`;if(n===`shared-state`)return e!==`plugin-registry`&&!t.retainSharedState;if(e===`plugin-registry`)return n===`plugin-registry`;if(n===`plugin-registry`)return false;return e===`close`||n===`close-and-restart`||n===`native-workers`});const r=[n.filter(([,{lifecycle:e}])=>e!==`native-workers`),n.filter(([,{lifecycle:e}])=>e===`native-workers`)];const i=[];for(const e of r){const n=e.map(([e,{reset:n}])=>{const runReset=()=>{try{return Promise.resolve(n())}catch(e){return Promise.reject(e instanceof Error?e:new Error(`Global singleton reset failed`,{cause:e}))}};return t.measureReset?t.measureReset(e.description??String(e),runReset):runReset()});i.push(...await Promise.allSettled(n))}const a=i.flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(a.length>0)throw new AggregateError(a,`Failed to reset global singleton lifecycle state`)}export{resolveGlobalSet as a,resolveGlobalMap as i,readGlobalSingleton as n,resolveGlobalSingleton as o,resetGlobalSingletonLifecycleState as r,drainGlobalSingletonLifecycleState as t};