@hyperttp/core 3.0.7 → 3.0.9
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.
- package/Core/HyperCore.d.ts.map +1 -1
- package/Core/HyperCore.js +825 -1
- package/Core/HyperCore.js.map +3 -3
- package/Core/index.js +2 -1
- package/Core/index.js.map +1 -1
- package/README.md +1 -2
- package/defaultConfig.js +10 -1
- package/defaultConfig.js.map +1 -1
- package/index.js +5 -1
- package/index.js.map +1 -1
- package/package.json +23 -1
- package/protocols/manager.js +72 -1
- package/protocols/manager.js.map +1 -1
- package/transports/manager.d.ts.map +1 -1
- package/transports/manager.js +182 -1
- package/transports/manager.js.map +2 -2
- package/utils/abort.js +18 -1
- package/utils/abort.js.map +1 -1
- package/utils/errors.js +46 -1
- package/utils/errors.js.map +1 -1
- package/utils/merge.js +18 -1
- package/utils/merge.js.map +1 -1
- package/utils/modules.d.ts.map +1 -1
- package/utils/modules.js +23 -1
- package/utils/modules.js.map +3 -3
package/Core/HyperCore.js
CHANGED
|
@@ -1,2 +1,826 @@
|
|
|
1
|
-
"use strict";import{dynamicImport as j}from"../utils/modules.js";import{defaultCoreConfig as A}from"../defaultConfig.js";import{KNOWN_PROTOCOLS as L,resolveProtocol as F}from"../protocols/manager.js";import{evictCachedTransport as I,resolveTransport as V,resolveTransportForProtocols as B}from"../transports/manager.js";import{HyperClientError as p}from"../utils/errors.js";let b=0,N=Date.now().toString(36)+"-";const z=Object.freeze({START:0,PREPARE:1,CONTROL:2,FORMAT:3,NETWORK:4,DATA:5});function W(){return b=b+1>>>0,b===0&&(N=Date.now().toString(36)+"-"),N+(b>>>0).toString(36)}const S=new WeakMap,C=new WeakMap;function $(h){S.set(h,(S.get(h)??0)+1)}function K(h){const e=(S.get(h)??1)-1;return e<=0?S.delete(h):S.set(h,e),e}class D{requestId=W();startTime=performance.now();signal;requestMeta;requestState;settlementCallbacks=[];finalized=!1;acceptedResponse;onSettled(e){if(this.finalized)throw new Error("[HyperCore] Request settlement has already started.");this.settlementCallbacks.push(e)}acceptFinalResponse(e){if(this.finalized)throw new Error("[HyperCore] Request has already settled.");return this.acceptedResponse=e,e}isFinalResponse(e){return this.acceptedResponse===e}async settle(e,t){if(this.finalized)return;this.finalized=!0;const r=this.settlementCallbacks;this.settlementCallbacks=[];for(const s of r)try{await s(e)}catch(a){t(a)}}constructor(e){this.signal=e}get meta(){return this.requestMeta??={}}set meta(e){this.requestMeta=e}get state(){return this.requestState??={}}set state(e){this.requestState=e}}function U(h){return new D(h.signal)}function G(h){return new D(h.signal)}function _(h,e){const t=h[e]??h[e.toLowerCase()];return Array.isArray(t)?t[0]:t}function J(h){return{status:415,statusText:"Unsupported Media Type",headers:{"content-type":"text/plain; charset=utf-8"},body:new TextEncoder().encode(`Unsupported protocol. Expected one of: ${h.join(", ")}.`)}}function q(h){return typeof h=="object"&&h!==null&&"data"in h&&"status"in h&&!("input"in h)}class Q{protocols=new Map;register(e){this.protocols.set(e.protocol,e)}get(e){return this.protocols.get(e)}has(e){return this.protocols.has(e)}get size(){return this.protocols.size}}export class HyperCore{config;registry=new Q;pluginCtx;plugins=[];servers=new Set;pendingListeners=new Set;flatMethodOwners=new Map;flatMethodValues=new Map;protocolNamespaces=new Set;generatedFlatMethods=new Set;transportPromises=new Map;transports=new Map;listenTransportPromises=new Map;listenTransports=new Map;multiListenTransportPromises=new Map;retainedTransports=new Set;fixedTransport;destroyPromise=null;state="initializing";activeRequests=new Set;get isDestroyed(){return this.state==="destroying"||this.state==="destroyed"}constructor(e={},t,r){this.config={...A,...e,retry:{...A.retry,...e.retry}},this.fixedTransport=t??null,this.pluginCtx={config:this.config,core:this};for(const o of this.config.plugins??[])if(typeof o!="string"&&!o.shared&&C.has(o))throw new p("[HyperCore] Plugin instances cannot be shared across cores. Supply fresh plugins when extending or creating a core.");const s=this.config.protocols;if(s)for(let o=0;o<s.length;o++)this.registerProtocol(s[o]);const a=this.config.senders;if(a)for(let o=0;o<a.length;o++)this.registerSender(a[o]);const n=this.config.customSender;n&&this.registerSender(n);const i=this.config.receivers;if(i)for(let o=0;o<i.length;o++)this.registerReceiver(i[o]);const c=this.config.plugins;if(c)for(let o=0;o<c.length;o++){const u=c[o];if(typeof u=="string")throw new p(`[HyperCore] Plugin module "${u}" cannot be loaded by the synchronous constructor. Import it and pass the plugin instance instead.`);try{this.use(u)}catch(y){for(const f of this.plugins)C.delete(f);throw y}}try{for(const o of this.config.pluginFactories??[])this.use(o())}catch(o){for(const u of this.plugins)C.get(u)===this&&C.delete(u);throw o}const l=this;for(let o=0;o<L.length;o++){const u=L[o];!this.registry.has(u)&&l[u]===void 0&&(l[u]=this.createLazyNamespace(u),this.protocolNamespaces.add(u))}if(t&&!this.retainedTransports.has(t)&&($(t),this.retainedTransports.add(t)),r)for(const[o,u]of r)this.transportPromises.set(o,u.then(y=>this.retainResolvedTransport(o,y)));this.state="running"}getProtocol(e){return this.registry.get(e)}getSender(e){return this.registry.get(e)?.sender}getReceiver(e){return this.registry.get(e)?.receiver}async getTransportName(){return this.assertRunning(),(await this.acquireTransport()).constructor.name}async getSenderName(e="rest"){const r=(await this.resolveRegisteredProtocol(e)).sender;if(!r)throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);return r.constructor.name}async getReceiverName(e="rest"){const r=(await this.resolveRegisteredProtocol(e)).receiver;if(!r)throw new p(`[HyperCore] Protocol "${e}" has no receiver (server role).`);return r.constructor.name}async getProtocolName(e="rest"){const t=await this.resolveRegisteredProtocol(e);if(t.name)return t.name;const r=t.constructor;return r&&r.name&&r.name!=="Object"?r.name:String(t.protocol)}registerProtocol(e){this.assertActive();const t=String(e.protocol),r=this;if(t==="__proto__"||t==="prototype"||t==="constructor"||t in HyperCore.prototype||t in this&&!this.protocolNamespaces.has(t))throw new p(`[HyperCore] Protocol name "${t}" conflicts with the core API.`);for(const[n,i]of this.flatMethodOwners)i===t&&(Object.getOwnPropertyDescriptor(this,n)?.value===this.flatMethodValues.get(n)&&delete r[n],this.flatMethodValues.delete(n),this.flatMethodOwners.delete(n),this.generatedFlatMethods.delete(n));this.protocolNamespaces.has(t)&&(delete r[t],this.protocolNamespaces.delete(t)),this.registry.register(e);const a=e.sender?.methods;if(a&&typeof a=="object"){const n=Object.create(null);for(const i in a){if(!Object.hasOwn(a,i))continue;const c=a[i];if(typeof c!="function")continue;const l=(...u)=>c.apply(a,[this,...u]);n[i]=l,this.generatedFlatMethods.has(i)&&Object.getOwnPropertyDescriptor(this,i)?.value===this.flatMethodValues.get(i)?(r[i]=l,this.flatMethodOwners.set(i,t),this.flatMethodValues.set(i,l)):!(i in HyperCore.prototype)&&!(i in this)&&(r[i]=l,this.generatedFlatMethods.add(i),this.flatMethodOwners.set(i,t),this.flatMethodValues.set(i,l))}r[t]=n,this.protocolNamespaces.add(t)}return this}registerSender(e){const t=this.registry.get(e.protocol);return this.registerProtocol({protocol:e.protocol,sender:e,receiver:t?.receiver})}registerReceiver(e){const t=this.registry.get(e.protocol);return this.registerProtocol({protocol:e.protocol,sender:t?.sender,receiver:e})}createLazyNamespace(e){const t={get:(r,s)=>{if(!(typeof s!="string"||s==="then"))return(...a)=>this.dispatchLazyMethod(e,s,a)}};return new Proxy({},t)}async dispatchLazyMethod(e,t,r){const a=(await this.resolveRegisteredProtocol(e)).sender;if(!a)throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);const n=a.methods,i=n&&Object.hasOwn(n,t)?n[t]:void 0;if(typeof i!="function")throw new TypeError(`[HyperCore] Protocol "${e}" has no method "${t}".`);return i.apply(n,[this,...r])}async send(e){this.assertRunning();let t;const r=new Promise(a=>{t=a});this.activeRequests.add(r);const s=U(e);try{const a=await this.executeRequest(e,s);return await s.settle({ok:!0,response:a},n=>this.log("error","[HyperCore] Settlement callback failed",n)),a}catch(a){throw await s.settle({ok:!1,error:a},n=>this.log("error","[HyperCore] Settlement callback failed",n)),a}finally{t(),this.activeRequests.delete(r)}}async executeRequest(e,t){const r=this.plugins;let s=e;const a=new Map;let n=!1;if(r.length===0){const i=this.registry.get(e.protocol)?.sender;if(i)return this.runSender(i,e,t)}try{let i;for(let c=0;c<r.length;c++){const l=r[c];if(typeof l.onRequest!="function")continue;a.set(l,s);const o=await l.onRequest(s,this.pluginCtx,t);if(o!=null){if(q(o)){i=o;break}s=o,t.signal=s.signal}}if(!i){const c=await this.resolveRequestSender(s.protocol);i=await this.runSender(c,s,t)}return t.isFinalResponse(i)?i:(n=!0,await this.runResponseHooks(i,s,t,r,a))}catch(i){let c;for(const l of r)if(typeof l.onError=="function")try{const o=await l.onError(i,a.get(l)??s,this.pluginCtx,t);!c&&o!=null&&q(o)&&(c=o)}catch(o){this.log("error","[HyperCore] Error hook failed",o)}if(c){if(n)return c;try{return await this.runResponseHooks(c,s,t,r,a)}catch(l){for(const o of r)if(typeof o.onError=="function")try{await o.onError(l,a.get(o)??s,this.pluginCtx,t)}catch(u){this.log("error","[HyperCore] Error hook failed",u)}throw l}}throw i}}assertRunning(){if(this.state==="initializing")throw new p("[HyperCore] Operations cannot start during setup initialization.");this.assertActive()}assertActive(){if(this.isDestroyed)throw new p("[HyperCore] Core instance has been destroyed.")}async resolveRegisteredProtocol(e){this.assertActive();const t=this.registry.get(e);if(t)return t;const r=await F(e);this.assertActive();const s=this.registry.get(e);return s||(this.registerProtocol(r),r)}async resolveRequestSender(e){const r=(await this.resolveRegisteredProtocol(e)).sender;if(!r)throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);return r}async runResponseHooks(e,t,r,s,a){let n=e;for(let i=0;i<s.length;i++){const c=s[i];if(typeof c.onResponse!="function")continue;const l=a.get(c)??t;if(c.mode==="background"){const u={...n,headers:{...n.headers}};Promise.resolve().then(()=>c.onResponse(u,l,this.pluginCtx,r)).catch(y=>this.reportBackgroundPluginError(y));continue}const o=await c.onResponse(n,l,this.pluginCtx,r);o!=null&&q(o)&&(n=o)}return n}reportBackgroundPluginError(e){const t=this.config.onError;if(typeof t=="function")try{t(e);return}catch(r){this.log("error","[HyperCore] Background error handler failed",r)}this.log("error","[HyperCore] Background plugin error",e)}log(e,t,r){try{if(this.config.logger){this.config.logger(e,t,r);return}if(!this.config.verbose&&e!=="error")return;(e==="debug"?console.debug:console[e])(t,r)}catch{}}async acquireTransport(e="rest",t=!1){if(this.isDestroyed)throw new p("[HyperCore] Cannot acquire transport on a destroyed core instance.");const r=t?this.listenTransports:this.transports,s=t?this.listenTransportPromises:this.transportPromises,a=r.get(e);if(a)return a;let n=s.get(e);if(!n){n=this.resolveAndRetainTransport(e,t);let c;c=n.catch(l=>{throw s.get(e)===c&&s.delete(e),l}),s.set(e,c),n=c}const i=await n;if(this.isDestroyed)throw new p("[HyperCore] Core instance was destroyed while resolving transport.");return i}async acquireListenTransport(e){if(this.isDestroyed)throw new p("[HyperCore] Cannot acquire transport on a destroyed core instance.");for(const s of this.listenTransports.values())if(this.transportSupportsAll(s,e))return s;const t=JSON.stringify([...e].sort());let r=this.multiListenTransportPromises.get(t);if(!r){let s;s=this.resolveListenTransport(e).finally(()=>{this.multiListenTransportPromises.get(t)===s&&this.multiListenTransportPromises.delete(t)}),this.multiListenTransportPromises.set(t,s),r=s}return r}async resolveListenTransport(e){const t=this.fixedTransport&&typeof this.fixedTransport.listen=="function"?this.fixedTransport:await B(e,{...this.config,cacheKey:this.config,customTransport:this.fixedTransport??this.config.customTransport,requireListen:!0,logger:this.config.logger,verbose:this.config.verbose});if(!this.transportSupportsAll(t,e))throw new p(`[HyperCore] Transport "${t.constructor.name}" does not support protocols ${e.map(r=>`"${r}"`).join(", ")}.`);for(const r of e)this.retainResolvedTransport(r,t,!0);return t}transportSupportsAll(e,t){return t.every(r=>typeof e.supports=="function"?e.supports(r):e.protocols?.includes(r)??!0)}routeServerRequest(e,t){if((_(t.headers,"content-type")??"").startsWith("application/grpc")&&e.includes("grpc"))return"grpc";if(t.protocol&&e.includes(t.protocol))return t.protocol;if(e.length===1)return e[0];if(e.includes("rest"))return"rest"}async resolveAndRetainTransport(e,t=!1){const r=this.fixedTransport&&(!t||typeof this.fixedTransport.listen=="function")?this.fixedTransport:await V(e,{...this.config,cacheKey:this.config,customTransport:this.fixedTransport??this.config.customTransport,requireListen:t,logger:this.config.logger,verbose:this.config.verbose});if(!(typeof r.supports=="function"?r.supports(e):r.protocols?.includes(e)??!0))throw new p(`[HyperCore] Transport "${r.constructor.name}" does not support protocol "${e}".`);return this.retainResolvedTransport(e,r,t)}retainResolvedTransport(e,t,r=!1){return this.retainedTransports.has(t)||($(t),this.retainedTransports.add(t)),(r?this.listenTransports:this.transports).set(e,t),t}async runSender(e,t,r){this.assertActive();const s=this.transports.get(t.protocol)??await this.acquireTransport(t.protocol),a=e.prepare(t,r),n=await e.send(a,s,r);return e.parse(n,r)}async listen(e){this.assertRunning();const t=this.startListening(e);this.pendingListeners.add(t);try{return await t}finally{this.pendingListeners.delete(t)}}async startListening(e){const t=e.protocols?.length?e.protocols:e.protocol?[e.protocol]:[];if(t.length===0)throw new p("[HyperCore] listen() requires a protocol or a non-empty protocols array.");const r=[...new Set(t)],s=await this.acquireListenTransport(r);if(typeof s.listen!="function")throw new p(`[HyperCore] Transport "${s.constructor.name}" does not support listen() (server role).`);const a=await Promise.all(r.map(f=>this.resolveRegisteredProtocol(f))),n=new Map;for(let f=0;f<r.length;f++){const P=a[f]?.receiver;if(!P)throw new p(`[HyperCore] Protocol "${r[f]}" has no receiver (server role).`);n.set(r[f],P)}const i=e.handler,c=e.route,l=async f=>{const P=c?.(f)??this.routeServerRequest(r,f);if(!P||!n.has(P))return J(r);const H=n.get(P),w=Object.assign(G(f),{protocol:P}),k=this.plugins;let R=f,m,M=!1;const x=async g=>{let d=g;for(const T of k){const v=await T.onServerResponse?.(d,R,this.pluginCtx,w);v!==void 0&&(d=v)}return d},O=async g=>{let d;for(const T of k)try{const v=await T.onServerError?.(g,R,this.pluginCtx,w);d===void 0&&v!==void 0&&(d=v)}catch(v){this.log("error","[HyperCore] Server error hook failed",v)}return d};try{for(const v of k){const E=await v.onServerRequest?.(R,this.pluginCtx,w);E!==void 0&&(R=E,w.signal=R.signal)}const g=await H.receive(R,w),d=i?await i(g,w):await H.handle(g,w),T=await H.respond(d,w);M=!0,m={ok:!0,response:await x(T)}}catch(g){const d=await O(g);if(d===void 0)m={ok:!1,error:g};else if(M)m={ok:!0,response:d};else try{m={ok:!0,response:await x(d)}}catch(T){await O(T),m={ok:!1,error:T}}}for(const g of k)try{await g.onServerSettled?.(m,R,this.pluginCtx,w)}catch(d){this.log("error","[HyperCore] Server settlement hook failed",d)}if(!m.ok)throw m.error;return m.response},o=await s.listen({host:e.host,port:e.port,signal:e.signal,signaling:e.signaling,onRequest:l});if(this.isDestroyed)throw await o.close(),new p("[HyperCore] Core instance was destroyed while starting the server.");let u;const y={close:()=>(u??=Promise.resolve().then(()=>o.close()).then(()=>{this.servers.delete(y)}),u)};return this.servers.add(y),y}static async create(e={}){const t=e.plugins;if(!t?.some(s=>typeof s=="string"))return new HyperCore(e);const r=[];for(const s of t){if(typeof s!="string"){r.push(s);continue}const a=await j(s),n=a.default??a.plugin;if(!n||typeof n!="object")throw new p(`[HyperCore] Plugin module "${s}" must export a plugin object as default or "plugin".`);r.push(n)}return new HyperCore({...e,plugins:r})}use(e){if(this.assertActive(),this.plugins.includes(e))return this;if(this.plugins.some(s=>s.name===e.name))throw new p(`[HyperCore] Plugin "${e.name}" is already registered.`);const t=C.get(e);if(!e.shared&&t&&t!==this)throw new p("[HyperCore] Plugin instances cannot be shared across cores. Supply a fresh instance.");if(e.shared&&e.setup)throw new p("[HyperCore] Shared stateless plugins cannot define setup().");return(e.enabled?e.enabled(this.config):!0)?(e.setup?.(this.pluginCtx),e.shared||C.set(e,this),this.plugins=[...this.plugins,e].sort((s,a)=>(z[s.phase??""]??0)-(z[a.phase??""]??0)),this):this}extend(e){this.assertActive();const t=e.customTransport??this.fixedTransport??void 0,r=e.customTransport?void 0:this.transportPromises;return new HyperCore({...this.config,...e},t,r)}create(e){this.assertActive();const t={...this.config};return delete t.customTransport,new HyperCore({...t,...e})}destroy(e=!0){return this.state==="initializing"?Promise.reject(new p("[HyperCore] Cannot destroy during setup initialization.")):(this.destroyPromise||(this.destroyPromise=this.performDestroy(e)),this.destroyPromise)}async performDestroy(e){this.state="destroying",e&&await Promise.allSettled(this.activeRequests),await Promise.allSettled(this.pendingListeners);for(const r of this.servers)try{await r.close()}catch{}this.servers.clear(),await Promise.allSettled([...this.transportPromises.values(),...this.listenTransportPromises.values(),...this.multiListenTransportPromises.values()]),this.transportPromises.clear(),this.transports.clear(),this.listenTransportPromises.clear(),this.listenTransports.clear(),this.multiListenTransportPromises.clear();const t=[...this.retainedTransports];this.retainedTransports.clear();for(const r of t)if(!(K(r)>0)){I(r);try{e&&typeof r.close=="function"?await r.close():typeof r.destroy=="function"?await r.destroy():typeof r.close=="function"&&await r.close()}catch(s){this.log("error","[HyperCore] Error closing transport during destroy",s)}}this.state="destroyed"}}
|
|
1
|
+
"use strict";
|
|
2
|
+
import { dynamicImport as j } from "../utils/modules.js";
|
|
3
|
+
import { defaultCoreConfig as A } from "../defaultConfig.js";
|
|
4
|
+
import { KNOWN_PROTOCOLS as L, resolveProtocol as F } from "../protocols/manager.js";
|
|
5
|
+
import { evictCachedTransport as I, resolveTransport as V, resolveTransportForProtocols as B } from "../transports/manager.js";
|
|
6
|
+
import { HyperClientError as p } from "../utils/errors.js";
|
|
7
|
+
let b = 0, N = Date.now().toString(36) + "-";
|
|
8
|
+
const z = Object.freeze({
|
|
9
|
+
START: 0,
|
|
10
|
+
PREPARE: 1,
|
|
11
|
+
CONTROL: 2,
|
|
12
|
+
FORMAT: 3,
|
|
13
|
+
NETWORK: 4,
|
|
14
|
+
DATA: 5
|
|
15
|
+
});
|
|
16
|
+
function W() {
|
|
17
|
+
return b = b + 1 >>> 0, b === 0 && (N = Date.now().toString(36) + "-"), N + (b >>> 0).toString(36);
|
|
18
|
+
}
|
|
19
|
+
const S = /* @__PURE__ */ new WeakMap(), C = /* @__PURE__ */ new WeakMap();
|
|
20
|
+
function $(h) {
|
|
21
|
+
S.set(h, (S.get(h) ?? 0) + 1);
|
|
22
|
+
}
|
|
23
|
+
function K(h) {
|
|
24
|
+
const e = (S.get(h) ?? 1) - 1;
|
|
25
|
+
return e <= 0 ? S.delete(h) : S.set(h, e), e;
|
|
26
|
+
}
|
|
27
|
+
class D {
|
|
28
|
+
requestId = W();
|
|
29
|
+
startTime = performance.now();
|
|
30
|
+
signal;
|
|
31
|
+
requestMeta;
|
|
32
|
+
requestState;
|
|
33
|
+
settlementCallbacks = [];
|
|
34
|
+
finalized = !1;
|
|
35
|
+
acceptedResponse;
|
|
36
|
+
onSettled(e) {
|
|
37
|
+
if (this.finalized)
|
|
38
|
+
throw new Error("[HyperCore] Request settlement has already started.");
|
|
39
|
+
this.settlementCallbacks.push(e);
|
|
40
|
+
}
|
|
41
|
+
acceptFinalResponse(e) {
|
|
42
|
+
if (this.finalized)
|
|
43
|
+
throw new Error("[HyperCore] Request has already settled.");
|
|
44
|
+
return this.acceptedResponse = e, e;
|
|
45
|
+
}
|
|
46
|
+
isFinalResponse(e) {
|
|
47
|
+
return this.acceptedResponse === e;
|
|
48
|
+
}
|
|
49
|
+
async settle(e, t) {
|
|
50
|
+
if (this.finalized)
|
|
51
|
+
return;
|
|
52
|
+
this.finalized = !0;
|
|
53
|
+
const r = this.settlementCallbacks;
|
|
54
|
+
this.settlementCallbacks = [];
|
|
55
|
+
for (const s of r)
|
|
56
|
+
try {
|
|
57
|
+
await s(e);
|
|
58
|
+
} catch (n) {
|
|
59
|
+
t(n);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
constructor(e) {
|
|
63
|
+
this.signal = e;
|
|
64
|
+
}
|
|
65
|
+
get meta() {
|
|
66
|
+
return this.requestMeta ??= {};
|
|
67
|
+
}
|
|
68
|
+
set meta(e) {
|
|
69
|
+
this.requestMeta = e;
|
|
70
|
+
}
|
|
71
|
+
get state() {
|
|
72
|
+
return this.requestState ??= {};
|
|
73
|
+
}
|
|
74
|
+
set state(e) {
|
|
75
|
+
this.requestState = e;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function U(h) {
|
|
79
|
+
return new D(h.signal);
|
|
80
|
+
}
|
|
81
|
+
function G(h) {
|
|
82
|
+
return new D(h.signal);
|
|
83
|
+
}
|
|
84
|
+
function _(h, e) {
|
|
85
|
+
const t = h[e] ?? h[e.toLowerCase()];
|
|
86
|
+
return Array.isArray(t) ? t[0] : t;
|
|
87
|
+
}
|
|
88
|
+
function J(h) {
|
|
89
|
+
return {
|
|
90
|
+
status: 415,
|
|
91
|
+
statusText: "Unsupported Media Type",
|
|
92
|
+
headers: { "content-type": "text/plain; charset=utf-8" },
|
|
93
|
+
body: new TextEncoder().encode(`Unsupported protocol. Expected one of: ${h.join(", ")}.`)
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
function q(h) {
|
|
97
|
+
return typeof h == "object" && h !== null && "data" in h && "status" in h && !("input" in h);
|
|
98
|
+
}
|
|
99
|
+
class Q {
|
|
100
|
+
protocols = /* @__PURE__ */ new Map();
|
|
101
|
+
register(e) {
|
|
102
|
+
this.protocols.set(e.protocol, e);
|
|
103
|
+
}
|
|
104
|
+
get(e) {
|
|
105
|
+
return this.protocols.get(e);
|
|
106
|
+
}
|
|
107
|
+
has(e) {
|
|
108
|
+
return this.protocols.has(e);
|
|
109
|
+
}
|
|
110
|
+
get size() {
|
|
111
|
+
return this.protocols.size;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export class HyperCore {
|
|
115
|
+
config;
|
|
116
|
+
registry = new Q();
|
|
117
|
+
pluginCtx;
|
|
118
|
+
plugins = [];
|
|
119
|
+
servers = /* @__PURE__ */ new Set();
|
|
120
|
+
pendingListeners = /* @__PURE__ */ new Set();
|
|
121
|
+
flatMethodOwners = /* @__PURE__ */ new Map();
|
|
122
|
+
flatMethodValues = /* @__PURE__ */ new Map();
|
|
123
|
+
protocolNamespaces = /* @__PURE__ */ new Set();
|
|
124
|
+
generatedFlatMethods = /* @__PURE__ */ new Set();
|
|
125
|
+
transportPromises = /* @__PURE__ */ new Map();
|
|
126
|
+
transports = /* @__PURE__ */ new Map();
|
|
127
|
+
listenTransportPromises = /* @__PURE__ */ new Map();
|
|
128
|
+
listenTransports = /* @__PURE__ */ new Map();
|
|
129
|
+
multiListenTransportPromises = /* @__PURE__ */ new Map();
|
|
130
|
+
retainedTransports = /* @__PURE__ */ new Set();
|
|
131
|
+
fixedTransport;
|
|
132
|
+
destroyPromise = null;
|
|
133
|
+
state = "initializing";
|
|
134
|
+
activeRequests = /* @__PURE__ */ new Set();
|
|
135
|
+
get isDestroyed() {
|
|
136
|
+
return this.state === "destroying" || this.state === "destroyed";
|
|
137
|
+
}
|
|
138
|
+
constructor(e = {}, t, r) {
|
|
139
|
+
this.config = {
|
|
140
|
+
...A,
|
|
141
|
+
...e,
|
|
142
|
+
retry: {
|
|
143
|
+
...A.retry,
|
|
144
|
+
...e.retry
|
|
145
|
+
}
|
|
146
|
+
}, this.fixedTransport = t ?? null, this.pluginCtx = { config: this.config, core: this };
|
|
147
|
+
for (const o of this.config.plugins ?? [])
|
|
148
|
+
if (typeof o != "string" && !o.shared && C.has(o))
|
|
149
|
+
throw new p("[HyperCore] Plugin instances cannot be shared across cores. Supply fresh plugins when extending or creating a core.");
|
|
150
|
+
const s = this.config.protocols;
|
|
151
|
+
if (s)
|
|
152
|
+
for (let o = 0; o < s.length; o++)
|
|
153
|
+
this.registerProtocol(s[o]);
|
|
154
|
+
const n = this.config.senders;
|
|
155
|
+
if (n)
|
|
156
|
+
for (let o = 0; o < n.length; o++)
|
|
157
|
+
this.registerSender(n[o]);
|
|
158
|
+
const i = this.config.customSender;
|
|
159
|
+
i && this.registerSender(i);
|
|
160
|
+
const a = this.config.receivers;
|
|
161
|
+
if (a)
|
|
162
|
+
for (let o = 0; o < a.length; o++)
|
|
163
|
+
this.registerReceiver(a[o]);
|
|
164
|
+
const c = this.config.plugins;
|
|
165
|
+
if (c)
|
|
166
|
+
for (let o = 0; o < c.length; o++) {
|
|
167
|
+
const u = c[o];
|
|
168
|
+
if (typeof u == "string")
|
|
169
|
+
throw new p(`[HyperCore] Plugin module "${u}" cannot be loaded by the synchronous constructor. Import it and pass the plugin instance instead.`);
|
|
170
|
+
try {
|
|
171
|
+
this.use(u);
|
|
172
|
+
} catch (y) {
|
|
173
|
+
for (const f of this.plugins)
|
|
174
|
+
C.delete(f);
|
|
175
|
+
throw y;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
for (const o of this.config.pluginFactories ?? [])
|
|
180
|
+
this.use(o());
|
|
181
|
+
} catch (o) {
|
|
182
|
+
for (const u of this.plugins)
|
|
183
|
+
C.get(u) === this && C.delete(u);
|
|
184
|
+
throw o;
|
|
185
|
+
}
|
|
186
|
+
const l = this;
|
|
187
|
+
for (let o = 0; o < L.length; o++) {
|
|
188
|
+
const u = L[o];
|
|
189
|
+
!this.registry.has(u) && l[u] === void 0 && (l[u] = this.createLazyNamespace(u), this.protocolNamespaces.add(u));
|
|
190
|
+
}
|
|
191
|
+
if (t && !this.retainedTransports.has(t) && ($(t), this.retainedTransports.add(t)), r)
|
|
192
|
+
for (const [o, u] of r)
|
|
193
|
+
this.transportPromises.set(o, u.then((y) => this.retainResolvedTransport(o, y)));
|
|
194
|
+
this.state = "running";
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* @ru Получает зарегистрированный модуль протокола (Sender + Receiver).
|
|
198
|
+
* @en Gets a registered protocol module (Sender + Receiver).
|
|
199
|
+
*/
|
|
200
|
+
getProtocol(e) {
|
|
201
|
+
return this.registry.get(e);
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* @ru Получает зарегистрированный сендер протокола.
|
|
205
|
+
* @en Gets a registered protocol sender.
|
|
206
|
+
*/
|
|
207
|
+
getSender(e) {
|
|
208
|
+
return this.registry.get(e)?.sender;
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* @ru Получает зарегистрированный ресивер протокола.
|
|
212
|
+
* @en Gets a registered protocol receiver.
|
|
213
|
+
*/
|
|
214
|
+
getReceiver(e) {
|
|
215
|
+
return this.registry.get(e)?.receiver;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* @ru Возвращает имя текущего транспорта.
|
|
219
|
+
* @en Returns the name of the current transport.
|
|
220
|
+
* @returns Transport constructor name.
|
|
221
|
+
*/
|
|
222
|
+
async getTransportName() {
|
|
223
|
+
return this.assertRunning(), (await this.acquireTransport()).constructor.name;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* @ru Возвращает имя сендера протокола (по умолчанию — "rest").
|
|
227
|
+
* Протокол резолвится лениво, если ещё не зарегистрирован.
|
|
228
|
+
* @en Returns the sender constructor name for a protocol (default "rest").
|
|
229
|
+
* The protocol is resolved lazily if not registered yet.
|
|
230
|
+
* @param protocol - The protocol to inspect.
|
|
231
|
+
* @returns Sender constructor name.
|
|
232
|
+
*/
|
|
233
|
+
async getSenderName(e = "rest") {
|
|
234
|
+
const r = (await this.resolveRegisteredProtocol(e)).sender;
|
|
235
|
+
if (!r)
|
|
236
|
+
throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);
|
|
237
|
+
return r.constructor.name;
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* @ru Возвращает имя ресивера протокола (по умолчанию — "rest").
|
|
241
|
+
* Протокол резолвится лениво, если ещё не зарегистрирован.
|
|
242
|
+
* @en Returns the receiver constructor name for a protocol (default "rest").
|
|
243
|
+
* The protocol is resolved lazily if not registered yet.
|
|
244
|
+
* @param protocol - The protocol to inspect.
|
|
245
|
+
* @returns Receiver constructor name.
|
|
246
|
+
*/
|
|
247
|
+
async getReceiverName(e = "rest") {
|
|
248
|
+
const r = (await this.resolveRegisteredProtocol(e)).receiver;
|
|
249
|
+
if (!r)
|
|
250
|
+
throw new p(`[HyperCore] Protocol "${e}" has no receiver (server role).`);
|
|
251
|
+
return r.constructor.name;
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* @ru Возвращает имя модуля протокола (по умолчанию — "rest"): предпочитает
|
|
255
|
+
* `name`, затем `constructor.name`, затем идентификатор протокола.
|
|
256
|
+
* Протокол резолвится лениво, если ещё не зарегистрирован.
|
|
257
|
+
* @en Returns the protocol module name (default "rest"): prefers `name`, then
|
|
258
|
+
* `constructor.name`, then the protocol identifier.
|
|
259
|
+
* The protocol is resolved lazily if not registered yet.
|
|
260
|
+
* @param protocol - The protocol to inspect.
|
|
261
|
+
* @returns The protocol module display name.
|
|
262
|
+
*/
|
|
263
|
+
async getProtocolName(e = "rest") {
|
|
264
|
+
const t = await this.resolveRegisteredProtocol(e);
|
|
265
|
+
if (t.name)
|
|
266
|
+
return t.name;
|
|
267
|
+
const r = t.constructor;
|
|
268
|
+
return r && r.name && r.name !== "Object" ? r.name : String(t.protocol);
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* @ru Регистрирует единый модуль протокола и раскрывает методы его сендера
|
|
272
|
+
* на ядре (например, `core.rest` для REST).
|
|
273
|
+
* @en Registers a unified protocol module and exposes its sender methods on the
|
|
274
|
+
* core (e.g., `core.rest` for REST).
|
|
275
|
+
* @param protocol - The protocol module to register.
|
|
276
|
+
* @returns This instance for chaining.
|
|
277
|
+
*/
|
|
278
|
+
registerProtocol(e) {
|
|
279
|
+
this.assertActive();
|
|
280
|
+
const t = String(e.protocol), r = this;
|
|
281
|
+
if (t === "__proto__" || t === "prototype" || t === "constructor" || t in HyperCore.prototype || t in this && !this.protocolNamespaces.has(t))
|
|
282
|
+
throw new p(`[HyperCore] Protocol name "${t}" conflicts with the core API.`);
|
|
283
|
+
for (const [i, a] of this.flatMethodOwners)
|
|
284
|
+
a === t && (Object.getOwnPropertyDescriptor(this, i)?.value === this.flatMethodValues.get(i) && delete r[i], this.flatMethodValues.delete(i), this.flatMethodOwners.delete(i), this.generatedFlatMethods.delete(i));
|
|
285
|
+
this.protocolNamespaces.has(t) && (delete r[t], this.protocolNamespaces.delete(t)), this.registry.register(e);
|
|
286
|
+
const n = e.sender?.methods;
|
|
287
|
+
if (n && typeof n == "object") {
|
|
288
|
+
const i = /* @__PURE__ */ Object.create(null);
|
|
289
|
+
for (const a in n) {
|
|
290
|
+
if (!Object.hasOwn(n, a))
|
|
291
|
+
continue;
|
|
292
|
+
const c = n[a];
|
|
293
|
+
if (typeof c != "function")
|
|
294
|
+
continue;
|
|
295
|
+
const l = (...u) => c.apply(n, [this, ...u]);
|
|
296
|
+
i[a] = l, this.generatedFlatMethods.has(a) && Object.getOwnPropertyDescriptor(this, a)?.value === this.flatMethodValues.get(a) ? (r[a] = l, this.flatMethodOwners.set(a, t), this.flatMethodValues.set(a, l)) : !(a in HyperCore.prototype) && !(a in this) && (r[a] = l, this.generatedFlatMethods.add(a), this.flatMethodOwners.set(a, t), this.flatMethodValues.set(a, l));
|
|
297
|
+
}
|
|
298
|
+
r[t] = i, this.protocolNamespaces.add(t);
|
|
299
|
+
}
|
|
300
|
+
return this;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* @ru Регистрирует сендер протокола, оборачивая его в модуль протокола.
|
|
304
|
+
* Существующий ресивер того же протокола сохраняется.
|
|
305
|
+
* @en Registers a protocol sender, wrapping it into a protocol module.
|
|
306
|
+
* An existing receiver for the same protocol is preserved.
|
|
307
|
+
* @param sender - The protocol sender to register.
|
|
308
|
+
* @returns This instance for chaining.
|
|
309
|
+
*/
|
|
310
|
+
registerSender(e) {
|
|
311
|
+
const t = this.registry.get(e.protocol);
|
|
312
|
+
return this.registerProtocol({
|
|
313
|
+
protocol: e.protocol,
|
|
314
|
+
sender: e,
|
|
315
|
+
receiver: t?.receiver
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* @ru Регистрирует ресивер протокола, оборачивая его в модуль протокола.
|
|
320
|
+
* Существующий сендер того же протокола сохраняется.
|
|
321
|
+
* @en Registers a protocol receiver, wrapping it into a protocol module.
|
|
322
|
+
* An existing sender for the same protocol is preserved.
|
|
323
|
+
* @param receiver - The protocol receiver to register.
|
|
324
|
+
* @returns This instance for chaining.
|
|
325
|
+
*/
|
|
326
|
+
registerReceiver(e) {
|
|
327
|
+
const t = this.registry.get(e.protocol);
|
|
328
|
+
return this.registerProtocol({
|
|
329
|
+
protocol: e.protocol,
|
|
330
|
+
sender: t?.sender,
|
|
331
|
+
receiver: e
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* @ru Создаёт ленивый namespace методов протокола: методы доступны ещё до
|
|
336
|
+
* регистрации протокола и резолвятся по требованию при первом вызове.
|
|
337
|
+
* @en Creates a lazy protocol methods namespace: methods are reachable before
|
|
338
|
+
* the protocol is registered and are resolved on first call.
|
|
339
|
+
* @param protocol - The protocol to expose lazily.
|
|
340
|
+
* @returns A Proxy that dispatches method calls to the resolved protocol sender.
|
|
341
|
+
*/
|
|
342
|
+
createLazyNamespace(e) {
|
|
343
|
+
const t = {
|
|
344
|
+
get: (r, s) => {
|
|
345
|
+
if (!(typeof s != "string" || s === "then"))
|
|
346
|
+
return (...n) => this.dispatchLazyMethod(e, s, n);
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
return new Proxy({}, t);
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* @ru Разрешает протокол по требованию и вызывает метод `methods`-поверхности
|
|
353
|
+
* его сендера, биндя ядро первым аргументом.
|
|
354
|
+
* @en Resolves the protocol on demand and calls a method on its sender
|
|
355
|
+
* `methods` surface, binding the core as the first argument.
|
|
356
|
+
* @param protocol - The protocol identifier.
|
|
357
|
+
* @param name - The method name on the sender surface.
|
|
358
|
+
* @param args - Arguments forwarded after the core instance.
|
|
359
|
+
* @returns The result of the sender method call.
|
|
360
|
+
*/
|
|
361
|
+
async dispatchLazyMethod(e, t, r) {
|
|
362
|
+
const n = (await this.resolveRegisteredProtocol(e)).sender;
|
|
363
|
+
if (!n)
|
|
364
|
+
throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);
|
|
365
|
+
const i = n.methods, a = i && Object.hasOwn(i, t) ? i[t] : void 0;
|
|
366
|
+
if (typeof a != "function")
|
|
367
|
+
throw new TypeError(`[HyperCore] Protocol "${e}" has no method "${t}".`);
|
|
368
|
+
return a.apply(i, [this, ...r]);
|
|
369
|
+
}
|
|
370
|
+
async send(e) {
|
|
371
|
+
this.assertRunning();
|
|
372
|
+
let t;
|
|
373
|
+
const r = new Promise((n) => {
|
|
374
|
+
t = n;
|
|
375
|
+
});
|
|
376
|
+
this.activeRequests.add(r);
|
|
377
|
+
const s = U(e);
|
|
378
|
+
try {
|
|
379
|
+
const n = await this.executeRequest(e, s);
|
|
380
|
+
return await s.settle({ ok: !0, response: n }, (i) => this.log("error", "[HyperCore] Settlement callback failed", i)), n;
|
|
381
|
+
} catch (n) {
|
|
382
|
+
throw await s.settle({ ok: !1, error: n }, (i) => this.log("error", "[HyperCore] Settlement callback failed", i)), n;
|
|
383
|
+
} finally {
|
|
384
|
+
t(), this.activeRequests.delete(r);
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
async executeRequest(e, t) {
|
|
388
|
+
const r = this.plugins;
|
|
389
|
+
let s = e;
|
|
390
|
+
const n = /* @__PURE__ */ new Map();
|
|
391
|
+
let i = !1;
|
|
392
|
+
if (r.length === 0) {
|
|
393
|
+
const a = this.registry.get(e.protocol)?.sender;
|
|
394
|
+
if (a)
|
|
395
|
+
return this.runSender(a, e, t);
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
let a;
|
|
399
|
+
for (let c = 0; c < r.length; c++) {
|
|
400
|
+
const l = r[c];
|
|
401
|
+
if (typeof l.onRequest != "function")
|
|
402
|
+
continue;
|
|
403
|
+
n.set(l, s);
|
|
404
|
+
const o = await l.onRequest(s, this.pluginCtx, t);
|
|
405
|
+
if (o != null) {
|
|
406
|
+
if (q(o)) {
|
|
407
|
+
a = o;
|
|
408
|
+
break;
|
|
409
|
+
}
|
|
410
|
+
s = o, t.signal = s.signal;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (!a) {
|
|
414
|
+
const c = await this.resolveRequestSender(s.protocol);
|
|
415
|
+
a = await this.runSender(c, s, t);
|
|
416
|
+
}
|
|
417
|
+
return t.isFinalResponse(a) ? a : (i = !0, await this.runResponseHooks(a, s, t, r, n));
|
|
418
|
+
} catch (a) {
|
|
419
|
+
let c;
|
|
420
|
+
for (const l of r)
|
|
421
|
+
if (typeof l.onError == "function")
|
|
422
|
+
try {
|
|
423
|
+
const o = await l.onError(a, n.get(l) ?? s, this.pluginCtx, t);
|
|
424
|
+
!c && o != null && q(o) && (c = o);
|
|
425
|
+
} catch (o) {
|
|
426
|
+
this.log("error", "[HyperCore] Error hook failed", o);
|
|
427
|
+
}
|
|
428
|
+
if (c) {
|
|
429
|
+
if (i)
|
|
430
|
+
return c;
|
|
431
|
+
try {
|
|
432
|
+
return await this.runResponseHooks(c, s, t, r, n);
|
|
433
|
+
} catch (l) {
|
|
434
|
+
for (const o of r)
|
|
435
|
+
if (typeof o.onError == "function")
|
|
436
|
+
try {
|
|
437
|
+
await o.onError(l, n.get(o) ?? s, this.pluginCtx, t);
|
|
438
|
+
} catch (u) {
|
|
439
|
+
this.log("error", "[HyperCore] Error hook failed", u);
|
|
440
|
+
}
|
|
441
|
+
throw l;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
throw a;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
assertRunning() {
|
|
448
|
+
if (this.state === "initializing")
|
|
449
|
+
throw new p("[HyperCore] Operations cannot start during setup initialization.");
|
|
450
|
+
this.assertActive();
|
|
451
|
+
}
|
|
452
|
+
assertActive() {
|
|
453
|
+
if (this.isDestroyed)
|
|
454
|
+
throw new p("[HyperCore] Core instance has been destroyed.");
|
|
455
|
+
}
|
|
456
|
+
async resolveRegisteredProtocol(e) {
|
|
457
|
+
this.assertActive();
|
|
458
|
+
const t = this.registry.get(e);
|
|
459
|
+
if (t)
|
|
460
|
+
return t;
|
|
461
|
+
const r = await F(e);
|
|
462
|
+
this.assertActive();
|
|
463
|
+
const s = this.registry.get(e);
|
|
464
|
+
return s || (this.registerProtocol(r), r);
|
|
465
|
+
}
|
|
466
|
+
async resolveRequestSender(e) {
|
|
467
|
+
const r = (await this.resolveRegisteredProtocol(e)).sender;
|
|
468
|
+
if (!r)
|
|
469
|
+
throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);
|
|
470
|
+
return r;
|
|
471
|
+
}
|
|
472
|
+
async runResponseHooks(e, t, r, s, n) {
|
|
473
|
+
let i = e;
|
|
474
|
+
for (let a = 0; a < s.length; a++) {
|
|
475
|
+
const c = s[a];
|
|
476
|
+
if (typeof c.onResponse != "function")
|
|
477
|
+
continue;
|
|
478
|
+
const l = n.get(c) ?? t;
|
|
479
|
+
if (c.mode === "background") {
|
|
480
|
+
const u = { ...i, headers: { ...i.headers } };
|
|
481
|
+
Promise.resolve().then(() => c.onResponse(u, l, this.pluginCtx, r)).catch((y) => this.reportBackgroundPluginError(y));
|
|
482
|
+
continue;
|
|
483
|
+
}
|
|
484
|
+
const o = await c.onResponse(i, l, this.pluginCtx, r);
|
|
485
|
+
o != null && q(o) && (i = o);
|
|
486
|
+
}
|
|
487
|
+
return i;
|
|
488
|
+
}
|
|
489
|
+
reportBackgroundPluginError(e) {
|
|
490
|
+
const t = this.config.onError;
|
|
491
|
+
if (typeof t == "function")
|
|
492
|
+
try {
|
|
493
|
+
t(e);
|
|
494
|
+
return;
|
|
495
|
+
} catch (r) {
|
|
496
|
+
this.log("error", "[HyperCore] Background error handler failed", r);
|
|
497
|
+
}
|
|
498
|
+
this.log("error", "[HyperCore] Background plugin error", e);
|
|
499
|
+
}
|
|
500
|
+
log(e, t, r) {
|
|
501
|
+
try {
|
|
502
|
+
if (this.config.logger) {
|
|
503
|
+
this.config.logger(e, t, r);
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
if (!this.config.verbose && e !== "error")
|
|
507
|
+
return;
|
|
508
|
+
(e === "debug" ? console.debug : console[e])(t, r);
|
|
509
|
+
} catch {
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* @ru Атомарно получает транспорт для конкретного протокола и удерживает
|
|
514
|
+
* каждый физический экземпляр ровно один раз за время жизни ядра.
|
|
515
|
+
* @en Atomically acquires a transport for a protocol and retains each physical
|
|
516
|
+
* instance exactly once for the lifetime of this core.
|
|
517
|
+
*/
|
|
518
|
+
async acquireTransport(e = "rest", t = !1) {
|
|
519
|
+
if (this.isDestroyed)
|
|
520
|
+
throw new p("[HyperCore] Cannot acquire transport on a destroyed core instance.");
|
|
521
|
+
const r = t ? this.listenTransports : this.transports, s = t ? this.listenTransportPromises : this.transportPromises, n = r.get(e);
|
|
522
|
+
if (n)
|
|
523
|
+
return n;
|
|
524
|
+
let i = s.get(e);
|
|
525
|
+
if (!i) {
|
|
526
|
+
i = this.resolveAndRetainTransport(e, t);
|
|
527
|
+
let c;
|
|
528
|
+
c = i.catch((l) => {
|
|
529
|
+
throw s.get(e) === c && s.delete(e), l;
|
|
530
|
+
}), s.set(e, c), i = c;
|
|
531
|
+
}
|
|
532
|
+
const a = await i;
|
|
533
|
+
if (this.isDestroyed)
|
|
534
|
+
throw new p("[HyperCore] Core instance was destroyed while resolving transport.");
|
|
535
|
+
return a;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* @ru Получает один транспорт, поддерживающий все запрошенные протоколы.
|
|
539
|
+
* Это позволяет открыть один listener на порт для REST и gRPC.
|
|
540
|
+
* @en Acquires one transport supporting every requested protocol. This lets
|
|
541
|
+
* REST and gRPC share a single listener on one port.
|
|
542
|
+
*/
|
|
543
|
+
async acquireListenTransport(e) {
|
|
544
|
+
if (this.isDestroyed)
|
|
545
|
+
throw new p("[HyperCore] Cannot acquire transport on a destroyed core instance.");
|
|
546
|
+
for (const s of this.listenTransports.values())
|
|
547
|
+
if (this.transportSupportsAll(s, e))
|
|
548
|
+
return s;
|
|
549
|
+
const t = JSON.stringify([...e].sort());
|
|
550
|
+
let r = this.multiListenTransportPromises.get(t);
|
|
551
|
+
if (!r) {
|
|
552
|
+
let s;
|
|
553
|
+
s = this.resolveListenTransport(e).finally(() => {
|
|
554
|
+
this.multiListenTransportPromises.get(t) === s && this.multiListenTransportPromises.delete(t);
|
|
555
|
+
}), this.multiListenTransportPromises.set(t, s), r = s;
|
|
556
|
+
}
|
|
557
|
+
return r;
|
|
558
|
+
}
|
|
559
|
+
async resolveListenTransport(e) {
|
|
560
|
+
const { protocols: t, ...r } = this.config, s = this.fixedTransport && typeof this.fixedTransport.listen == "function" ? this.fixedTransport : await B(e, {
|
|
561
|
+
...r,
|
|
562
|
+
cacheKey: this.config,
|
|
563
|
+
customTransport: this.fixedTransport ?? this.config.customTransport,
|
|
564
|
+
requireListen: !0,
|
|
565
|
+
logger: this.config.logger,
|
|
566
|
+
verbose: this.config.verbose
|
|
567
|
+
});
|
|
568
|
+
if (!this.transportSupportsAll(s, e))
|
|
569
|
+
throw new p(`[HyperCore] Transport "${s.constructor.name}" does not support protocols ${e.map((n) => `"${n}"`).join(", ")}.`);
|
|
570
|
+
for (const n of e)
|
|
571
|
+
this.retainResolvedTransport(n, s, !0);
|
|
572
|
+
return s;
|
|
573
|
+
}
|
|
574
|
+
transportSupportsAll(e, t) {
|
|
575
|
+
return t.every((r) => typeof e.supports == "function" ? e.supports(r) : e.protocols?.includes(r) ?? !0);
|
|
576
|
+
}
|
|
577
|
+
routeServerRequest(e, t) {
|
|
578
|
+
if ((_(t.headers, "content-type") ?? "").startsWith("application/grpc") && e.includes("grpc"))
|
|
579
|
+
return "grpc";
|
|
580
|
+
if (t.protocol && e.includes(t.protocol))
|
|
581
|
+
return t.protocol;
|
|
582
|
+
if (e.length === 1)
|
|
583
|
+
return e[0];
|
|
584
|
+
if (e.includes("rest"))
|
|
585
|
+
return "rest";
|
|
586
|
+
}
|
|
587
|
+
async resolveAndRetainTransport(e, t = !1) {
|
|
588
|
+
const r = this.fixedTransport && (!t || typeof this.fixedTransport.listen == "function") ? this.fixedTransport : await V(e, {
|
|
589
|
+
...this.config,
|
|
590
|
+
cacheKey: this.config,
|
|
591
|
+
customTransport: this.fixedTransport ?? this.config.customTransport,
|
|
592
|
+
requireListen: t,
|
|
593
|
+
logger: this.config.logger,
|
|
594
|
+
verbose: this.config.verbose
|
|
595
|
+
});
|
|
596
|
+
if (!(typeof r.supports == "function" ? r.supports(e) : r.protocols?.includes(e) ?? !0))
|
|
597
|
+
throw new p(`[HyperCore] Transport "${r.constructor.name}" does not support protocol "${e}".`);
|
|
598
|
+
return this.retainResolvedTransport(e, r, t);
|
|
599
|
+
}
|
|
600
|
+
retainResolvedTransport(e, t, r = !1) {
|
|
601
|
+
return this.retainedTransports.has(t) || ($(t), this.retainedTransports.add(t)), (r ? this.listenTransports : this.transports).set(e, t), t;
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* @ru Выполняет ядро цикла запроса: prepare → send → parse через физический
|
|
605
|
+
* транспорт. Транспорт получается через `acquireTransport()`.
|
|
606
|
+
* @en Runs the core request cycle: prepare → send → parse through the physical
|
|
607
|
+
* transport. The transport is acquired via `acquireTransport()`.
|
|
608
|
+
* @param sender - The resolved protocol sender.
|
|
609
|
+
* @param req - The (possibly plugin-modified) universal request.
|
|
610
|
+
* @param ctx - The per-request execution context.
|
|
611
|
+
* @returns The normalized universal response.
|
|
612
|
+
*/
|
|
613
|
+
async runSender(e, t, r) {
|
|
614
|
+
this.assertActive();
|
|
615
|
+
const s = this.transports.get(t.protocol) ?? await this.acquireTransport(t.protocol), n = e.prepare(t, r), i = await e.send(n, s, r);
|
|
616
|
+
return e.parse(i, r);
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* @ru Запускает сервер для указанного протокола: связывает транспорт, ресивер и
|
|
620
|
+
* application handler в цепочку receive → handle → respond.
|
|
621
|
+
* @en Starts a server for the given protocol, wiring transport, receiver, and
|
|
622
|
+
* application handler into the receive → handle → respond pipeline.
|
|
623
|
+
* @template P - The protocol identifier.
|
|
624
|
+
* @param options - The server listen options.
|
|
625
|
+
* @returns A promise resolving to the transport server handle.
|
|
626
|
+
*/
|
|
627
|
+
async listen(e) {
|
|
628
|
+
this.assertRunning();
|
|
629
|
+
const t = this.startListening(e);
|
|
630
|
+
this.pendingListeners.add(t);
|
|
631
|
+
try {
|
|
632
|
+
return await t;
|
|
633
|
+
} finally {
|
|
634
|
+
this.pendingListeners.delete(t);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
async startListening(e) {
|
|
638
|
+
const t = e.protocols?.length ? e.protocols : e.protocol ? [e.protocol] : [];
|
|
639
|
+
if (t.length === 0)
|
|
640
|
+
throw new p("[HyperCore] listen() requires a protocol or a non-empty protocols array.");
|
|
641
|
+
const r = [...new Set(t)], s = await this.acquireListenTransport(r);
|
|
642
|
+
if (typeof s.listen != "function")
|
|
643
|
+
throw new p(`[HyperCore] Transport "${s.constructor.name}" does not support listen() (server role).`);
|
|
644
|
+
const n = await Promise.all(r.map((f) => this.resolveRegisteredProtocol(f))), i = /* @__PURE__ */ new Map();
|
|
645
|
+
for (let f = 0; f < r.length; f++) {
|
|
646
|
+
const P = n[f]?.receiver;
|
|
647
|
+
if (!P)
|
|
648
|
+
throw new p(`[HyperCore] Protocol "${r[f]}" has no receiver (server role).`);
|
|
649
|
+
i.set(r[f], P);
|
|
650
|
+
}
|
|
651
|
+
const a = e.handler, c = e.route, l = async (f) => {
|
|
652
|
+
const P = c?.(f) ?? this.routeServerRequest(r, f);
|
|
653
|
+
if (!P || !i.has(P))
|
|
654
|
+
return J(r);
|
|
655
|
+
const H = i.get(P), w = Object.assign(G(f), { protocol: P }), k = this.plugins;
|
|
656
|
+
let R = f, m, M = !1;
|
|
657
|
+
const x = async (g) => {
|
|
658
|
+
let d = g;
|
|
659
|
+
for (const T of k) {
|
|
660
|
+
const v = await T.onServerResponse?.(d, R, this.pluginCtx, w);
|
|
661
|
+
v !== void 0 && (d = v);
|
|
662
|
+
}
|
|
663
|
+
return d;
|
|
664
|
+
}, O = async (g) => {
|
|
665
|
+
let d;
|
|
666
|
+
for (const T of k)
|
|
667
|
+
try {
|
|
668
|
+
const v = await T.onServerError?.(g, R, this.pluginCtx, w);
|
|
669
|
+
d === void 0 && v !== void 0 && (d = v);
|
|
670
|
+
} catch (v) {
|
|
671
|
+
this.log("error", "[HyperCore] Server error hook failed", v);
|
|
672
|
+
}
|
|
673
|
+
return d;
|
|
674
|
+
};
|
|
675
|
+
try {
|
|
676
|
+
for (const v of k) {
|
|
677
|
+
const E = await v.onServerRequest?.(R, this.pluginCtx, w);
|
|
678
|
+
E !== void 0 && (R = E, w.signal = R.signal);
|
|
679
|
+
}
|
|
680
|
+
const g = await H.receive(R, w), d = a ? await a(g, w) : await H.handle(g, w), T = await H.respond(d, w);
|
|
681
|
+
M = !0, m = { ok: !0, response: await x(T) };
|
|
682
|
+
} catch (g) {
|
|
683
|
+
const d = await O(g);
|
|
684
|
+
if (d === void 0)
|
|
685
|
+
m = { ok: !1, error: g };
|
|
686
|
+
else if (M)
|
|
687
|
+
m = { ok: !0, response: d };
|
|
688
|
+
else
|
|
689
|
+
try {
|
|
690
|
+
m = { ok: !0, response: await x(d) };
|
|
691
|
+
} catch (T) {
|
|
692
|
+
await O(T), m = { ok: !1, error: T };
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
for (const g of k)
|
|
696
|
+
try {
|
|
697
|
+
await g.onServerSettled?.(m, R, this.pluginCtx, w);
|
|
698
|
+
} catch (d) {
|
|
699
|
+
this.log("error", "[HyperCore] Server settlement hook failed", d);
|
|
700
|
+
}
|
|
701
|
+
if (!m.ok)
|
|
702
|
+
throw m.error;
|
|
703
|
+
return m.response;
|
|
704
|
+
}, o = await s.listen({
|
|
705
|
+
host: e.host,
|
|
706
|
+
port: e.port,
|
|
707
|
+
signal: e.signal,
|
|
708
|
+
signaling: e.signaling,
|
|
709
|
+
onRequest: l
|
|
710
|
+
});
|
|
711
|
+
if (this.isDestroyed)
|
|
712
|
+
throw await o.close(), new p("[HyperCore] Core instance was destroyed while starting the server.");
|
|
713
|
+
let u;
|
|
714
|
+
const y = {
|
|
715
|
+
close: () => (u ??= Promise.resolve().then(() => o.close()).then(() => {
|
|
716
|
+
this.servers.delete(y);
|
|
717
|
+
}), u)
|
|
718
|
+
};
|
|
719
|
+
return this.servers.add(y), y;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* @ru Регистрирует плагин. Пропускает отключённые плагины.
|
|
723
|
+
* @en Registers a plugin. Skips disabled plugins.
|
|
724
|
+
* @param plugin - The plugin instance to register.
|
|
725
|
+
* @returns This instance for chaining.
|
|
726
|
+
*/
|
|
727
|
+
/**
|
|
728
|
+
* Creates a core asynchronously and resolves plugin module paths before construction.
|
|
729
|
+
*/
|
|
730
|
+
static async create(e = {}) {
|
|
731
|
+
const t = e.plugins;
|
|
732
|
+
if (!t?.some((s) => typeof s == "string"))
|
|
733
|
+
return new HyperCore(e);
|
|
734
|
+
const r = [];
|
|
735
|
+
for (const s of t) {
|
|
736
|
+
if (typeof s != "string") {
|
|
737
|
+
r.push(s);
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const n = await j(s), i = n.default ?? n.plugin;
|
|
741
|
+
if (!i || typeof i != "object")
|
|
742
|
+
throw new p(`[HyperCore] Plugin module "${s}" must export a plugin object as default or "plugin".`);
|
|
743
|
+
r.push(i);
|
|
744
|
+
}
|
|
745
|
+
return new HyperCore({ ...e, plugins: r });
|
|
746
|
+
}
|
|
747
|
+
use(e) {
|
|
748
|
+
if (this.assertActive(), this.plugins.includes(e))
|
|
749
|
+
return this;
|
|
750
|
+
if (this.plugins.some((s) => s.name === e.name))
|
|
751
|
+
throw new p(`[HyperCore] Plugin "${e.name}" is already registered.`);
|
|
752
|
+
const t = C.get(e);
|
|
753
|
+
if (!e.shared && t && t !== this)
|
|
754
|
+
throw new p("[HyperCore] Plugin instances cannot be shared across cores. Supply a fresh instance.");
|
|
755
|
+
if (e.shared && e.setup)
|
|
756
|
+
throw new p("[HyperCore] Shared stateless plugins cannot define setup().");
|
|
757
|
+
return (e.enabled ? e.enabled(this.config) : !0) ? (e.setup?.(this.pluginCtx), e.shared || C.set(e, this), this.plugins = [...this.plugins, e].sort((s, n) => (z[s.phase ?? ""] ?? 0) - (z[n.phase ?? ""] ?? 0)), this) : this;
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* @ru Создаёт новый экземпляр ядра с расширенной/переопределённой конфигурацией,
|
|
761
|
+
* переиспользуя текущий транспорт.
|
|
762
|
+
* @en Creates a new core instance with extended/overridden configuration,
|
|
763
|
+
* reusing the current transport.
|
|
764
|
+
* @param options - Partial configuration overrides.
|
|
765
|
+
* @returns A new IHyperCore instance.
|
|
766
|
+
*/
|
|
767
|
+
extend(e) {
|
|
768
|
+
this.assertActive();
|
|
769
|
+
const t = e.customTransport ?? this.fixedTransport ?? void 0, r = e.customTransport ? void 0 : this.transportPromises;
|
|
770
|
+
return new HyperCore({ ...this.config, ...e }, t, r);
|
|
771
|
+
}
|
|
772
|
+
/**
|
|
773
|
+
* @ru Создаёт полностью независимый экземпляр ядра на основе текущей
|
|
774
|
+
* конфигурации: не переиспользует текущий транспорт и по умолчанию не
|
|
775
|
+
* наследует `customTransport`.
|
|
776
|
+
* @en Creates a fully independent core instance based on the current config:
|
|
777
|
+
* it does not reuse the current transport and does not inherit
|
|
778
|
+
* `customTransport` by default.
|
|
779
|
+
* @param options - Partial configuration overrides.
|
|
780
|
+
* @returns A new IHyperCore instance.
|
|
781
|
+
*/
|
|
782
|
+
create(e) {
|
|
783
|
+
this.assertActive();
|
|
784
|
+
const t = { ...this.config };
|
|
785
|
+
return delete t.customTransport, new HyperCore({ ...t, ...e });
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* @ru Завершает работу ядра и освобождает ресурсы: закрывает активные серверы,
|
|
789
|
+
* затем освобождает удержание транспорта. Graceful-дренирование активных запросов
|
|
790
|
+
* определяется реализацией `TransportServer.close()`.
|
|
791
|
+
* @en Shuts down the core and releases resources: closes active servers, then
|
|
792
|
+
* releases the transport hold. Graceful draining of in-flight requests is defined
|
|
793
|
+
* by the `TransportServer.close()` implementation.
|
|
794
|
+
* @param graceful - If true, prefers `transport.close()`; otherwise prefers `transport.destroy()`.
|
|
795
|
+
* @returns Promise that resolves when shutdown is complete.
|
|
796
|
+
*/
|
|
797
|
+
destroy(e = !0) {
|
|
798
|
+
return this.state === "initializing" ? Promise.reject(new p("[HyperCore] Cannot destroy during setup initialization.")) : (this.destroyPromise || (this.destroyPromise = this.performDestroy(e)), this.destroyPromise);
|
|
799
|
+
}
|
|
800
|
+
async performDestroy(e) {
|
|
801
|
+
this.state = "destroying", e && await Promise.allSettled(this.activeRequests), await Promise.allSettled(this.pendingListeners);
|
|
802
|
+
for (const r of this.servers)
|
|
803
|
+
try {
|
|
804
|
+
await r.close();
|
|
805
|
+
} catch {
|
|
806
|
+
}
|
|
807
|
+
this.servers.clear(), await Promise.allSettled([
|
|
808
|
+
...this.transportPromises.values(),
|
|
809
|
+
...this.listenTransportPromises.values(),
|
|
810
|
+
...this.multiListenTransportPromises.values()
|
|
811
|
+
]), this.transportPromises.clear(), this.transports.clear(), this.listenTransportPromises.clear(), this.listenTransports.clear(), this.multiListenTransportPromises.clear();
|
|
812
|
+
const t = [...this.retainedTransports];
|
|
813
|
+
this.retainedTransports.clear();
|
|
814
|
+
for (const r of t)
|
|
815
|
+
if (!(K(r) > 0)) {
|
|
816
|
+
I(r);
|
|
817
|
+
try {
|
|
818
|
+
e && typeof r.close == "function" ? await r.close() : typeof r.destroy == "function" ? await r.destroy() : typeof r.close == "function" && await r.close();
|
|
819
|
+
} catch (s) {
|
|
820
|
+
this.log("error", "[HyperCore] Error closing transport during destroy", s);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
this.state = "destroyed";
|
|
824
|
+
}
|
|
825
|
+
}
|
|
2
826
|
//# sourceMappingURL=HyperCore.js.map
|