@hyperttp/core 3.0.8 → 3.1.0
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 +89 -89
- package/Core/HyperCore.js.map +3 -3
- package/README.md +16 -13
- package/package.json +1 -1
- package/transports/manager.d.ts.map +1 -1
- package/transports/manager.js +20 -5
- package/transports/manager.js.map +2 -2
- package/utils/modules.d.ts.map +1 -1
- package/utils/modules.js +16 -9
- package/utils/modules.js.map +3 -3
package/Core/HyperCore.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HyperCore.d.ts","sourceRoot":"","sources":["../../src/Core/HyperCore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,kBAAkB,EAClB,WAAW,EACX,aAAa,EACb,cAAc,EACd,aAAa,EACb,WAAW,EACX,wBAAwB,EACxB,cAAc,EACd,UAAU,EAMV,iBAAiB,EACjB,WAAW,EAIX,eAAe,EACf,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AAsNzB,MAAM,WAAW,SAAU,SAAQ,cAAc;CAAG;AAEpD;;;;;;;;;GASG;AACH,qBAAa,SAAU,YAAW,UAAU;IAC1C,SAAgB,MAAM,EAAE,kBAAkB,CAAC;IAE3C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAiC;IAC1D,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAgB;IAC1C,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8B;IACtD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAuC;IACxE,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA6B;IAC9D,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAA8B;IAC/D,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CA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;OAKG;YACW,sBAAsB;YA6BtB,sBAAsB;IA4BpC,OAAO,CAAC,oBAAoB;IAW5B,OAAO,CAAC,kBAAkB;YAcZ,yBAAyB;IA6BvC,OAAO,CAAC,uBAAuB;IAc/B;;;;;;;;;OASG;YACW,SAAS;IAavB;;;;;;;;OAQG;IACU,MAAM,CAAC,CAAC,SAAS,iBAAiB,GAAG,iBAAiB,EACjE,OAAO,EAAE,wBAAwB,CAAC,CAAC,CAAC,GACnC,OAAO,CAAC,eAAe,CAAC,CAS1B;YAEa,cAAc;IAmJ5B;;;;;OAKG;IACH;;OAEG;IACH,OAAoB,MAAM,CAAC,MAAM,GAAE,OAAO,CAAC,kBAAkB,CAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAuBvF;IAEM,GAAG,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAwBpC;IAED;;;;;;;OAOG;IACI,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,UAAU,CAK9D;IAED;;;;;;;;;OASG;IACI,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,UAAU,CAK9D;IAED;;;;;;;;;OASG;IACI,OAAO,CAAC,QAAQ,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAU7C;YAEa,cAAc;CAgD7B"}
|
package/Core/HyperCore.js
CHANGED
|
@@ -55,8 +55,8 @@ class D {
|
|
|
55
55
|
for (const s of r)
|
|
56
56
|
try {
|
|
57
57
|
await s(e);
|
|
58
|
-
} catch (
|
|
59
|
-
t(
|
|
58
|
+
} catch (n) {
|
|
59
|
+
t(n);
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
constructor(e) {
|
|
@@ -151,16 +151,16 @@ export class HyperCore {
|
|
|
151
151
|
if (s)
|
|
152
152
|
for (let o = 0; o < s.length; o++)
|
|
153
153
|
this.registerProtocol(s[o]);
|
|
154
|
-
const
|
|
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;
|
|
155
161
|
if (a)
|
|
156
162
|
for (let o = 0; o < a.length; o++)
|
|
157
|
-
this.
|
|
158
|
-
const n = this.config.customSender;
|
|
159
|
-
n && this.registerSender(n);
|
|
160
|
-
const i = this.config.receivers;
|
|
161
|
-
if (i)
|
|
162
|
-
for (let o = 0; o < i.length; o++)
|
|
163
|
-
this.registerReceiver(i[o]);
|
|
163
|
+
this.registerReceiver(a[o]);
|
|
164
164
|
const c = this.config.plugins;
|
|
165
165
|
if (c)
|
|
166
166
|
for (let o = 0; o < c.length; o++) {
|
|
@@ -280,22 +280,22 @@ export class HyperCore {
|
|
|
280
280
|
const t = String(e.protocol), r = this;
|
|
281
281
|
if (t === "__proto__" || t === "prototype" || t === "constructor" || t in HyperCore.prototype || t in this && !this.protocolNamespaces.has(t))
|
|
282
282
|
throw new p(`[HyperCore] Protocol name "${t}" conflicts with the core API.`);
|
|
283
|
-
for (const [
|
|
284
|
-
|
|
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
285
|
this.protocolNamespaces.has(t) && (delete r[t], this.protocolNamespaces.delete(t)), this.registry.register(e);
|
|
286
|
-
const
|
|
287
|
-
if (
|
|
288
|
-
const
|
|
289
|
-
for (const
|
|
290
|
-
if (!Object.hasOwn(
|
|
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
291
|
continue;
|
|
292
|
-
const c = a
|
|
292
|
+
const c = n[a];
|
|
293
293
|
if (typeof c != "function")
|
|
294
294
|
continue;
|
|
295
|
-
const l = (...u) => c.apply(
|
|
296
|
-
|
|
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
297
|
}
|
|
298
|
-
r[t] =
|
|
298
|
+
r[t] = i, this.protocolNamespaces.add(t);
|
|
299
299
|
}
|
|
300
300
|
return this;
|
|
301
301
|
}
|
|
@@ -343,7 +343,7 @@ export class HyperCore {
|
|
|
343
343
|
const t = {
|
|
344
344
|
get: (r, s) => {
|
|
345
345
|
if (!(typeof s != "string" || s === "then"))
|
|
346
|
-
return (...
|
|
346
|
+
return (...n) => this.dispatchLazyMethod(e, s, n);
|
|
347
347
|
}
|
|
348
348
|
};
|
|
349
349
|
return new Proxy({}, t);
|
|
@@ -359,27 +359,27 @@ export class HyperCore {
|
|
|
359
359
|
* @returns The result of the sender method call.
|
|
360
360
|
*/
|
|
361
361
|
async dispatchLazyMethod(e, t, r) {
|
|
362
|
-
const
|
|
363
|
-
if (!
|
|
362
|
+
const n = (await this.resolveRegisteredProtocol(e)).sender;
|
|
363
|
+
if (!n)
|
|
364
364
|
throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);
|
|
365
|
-
const
|
|
366
|
-
if (typeof
|
|
365
|
+
const i = n.methods, a = i && Object.hasOwn(i, t) ? i[t] : void 0;
|
|
366
|
+
if (typeof a != "function")
|
|
367
367
|
throw new TypeError(`[HyperCore] Protocol "${e}" has no method "${t}".`);
|
|
368
|
-
return
|
|
368
|
+
return a.apply(i, [this, ...r]);
|
|
369
369
|
}
|
|
370
370
|
async send(e) {
|
|
371
371
|
this.assertRunning();
|
|
372
372
|
let t;
|
|
373
|
-
const r = new Promise((
|
|
374
|
-
t =
|
|
373
|
+
const r = new Promise((n) => {
|
|
374
|
+
t = n;
|
|
375
375
|
});
|
|
376
376
|
this.activeRequests.add(r);
|
|
377
377
|
const s = U(e);
|
|
378
378
|
try {
|
|
379
|
-
const
|
|
380
|
-
return await s.settle({ ok: !0, response:
|
|
381
|
-
} catch (
|
|
382
|
-
throw await s.settle({ ok: !1, error:
|
|
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
383
|
} finally {
|
|
384
384
|
t(), this.activeRequests.delete(r);
|
|
385
385
|
}
|
|
@@ -387,61 +387,61 @@ export class HyperCore {
|
|
|
387
387
|
async executeRequest(e, t) {
|
|
388
388
|
const r = this.plugins;
|
|
389
389
|
let s = e;
|
|
390
|
-
const
|
|
391
|
-
let
|
|
390
|
+
const n = /* @__PURE__ */ new Map();
|
|
391
|
+
let i = !1;
|
|
392
392
|
if (r.length === 0) {
|
|
393
|
-
const
|
|
394
|
-
if (
|
|
395
|
-
return this.runSender(
|
|
393
|
+
const a = this.registry.get(e.protocol)?.sender;
|
|
394
|
+
if (a)
|
|
395
|
+
return this.runSender(a, e, t);
|
|
396
396
|
}
|
|
397
397
|
try {
|
|
398
|
-
let
|
|
398
|
+
let a;
|
|
399
399
|
for (let c = 0; c < r.length; c++) {
|
|
400
400
|
const l = r[c];
|
|
401
401
|
if (typeof l.onRequest != "function")
|
|
402
402
|
continue;
|
|
403
|
-
|
|
403
|
+
n.set(l, s);
|
|
404
404
|
const o = await l.onRequest(s, this.pluginCtx, t);
|
|
405
405
|
if (o != null) {
|
|
406
406
|
if (q(o)) {
|
|
407
|
-
|
|
407
|
+
a = o;
|
|
408
408
|
break;
|
|
409
409
|
}
|
|
410
410
|
s = o, t.signal = s.signal;
|
|
411
411
|
}
|
|
412
412
|
}
|
|
413
|
-
if (!
|
|
413
|
+
if (!a) {
|
|
414
414
|
const c = await this.resolveRequestSender(s.protocol);
|
|
415
|
-
|
|
415
|
+
a = await this.runSender(c, s, t);
|
|
416
416
|
}
|
|
417
|
-
return t.isFinalResponse(
|
|
418
|
-
} catch (
|
|
417
|
+
return t.isFinalResponse(a) ? a : (i = !0, await this.runResponseHooks(a, s, t, r, n));
|
|
418
|
+
} catch (a) {
|
|
419
419
|
let c;
|
|
420
420
|
for (const l of r)
|
|
421
421
|
if (typeof l.onError == "function")
|
|
422
422
|
try {
|
|
423
|
-
const o = await l.onError(
|
|
423
|
+
const o = await l.onError(a, n.get(l) ?? s, this.pluginCtx, t);
|
|
424
424
|
!c && o != null && q(o) && (c = o);
|
|
425
425
|
} catch (o) {
|
|
426
426
|
this.log("error", "[HyperCore] Error hook failed", o);
|
|
427
427
|
}
|
|
428
428
|
if (c) {
|
|
429
|
-
if (
|
|
429
|
+
if (i)
|
|
430
430
|
return c;
|
|
431
431
|
try {
|
|
432
|
-
return await this.runResponseHooks(c, s, t, r,
|
|
432
|
+
return await this.runResponseHooks(c, s, t, r, n);
|
|
433
433
|
} catch (l) {
|
|
434
434
|
for (const o of r)
|
|
435
435
|
if (typeof o.onError == "function")
|
|
436
436
|
try {
|
|
437
|
-
await o.onError(l,
|
|
437
|
+
await o.onError(l, n.get(o) ?? s, this.pluginCtx, t);
|
|
438
438
|
} catch (u) {
|
|
439
439
|
this.log("error", "[HyperCore] Error hook failed", u);
|
|
440
440
|
}
|
|
441
441
|
throw l;
|
|
442
442
|
}
|
|
443
443
|
}
|
|
444
|
-
throw
|
|
444
|
+
throw a;
|
|
445
445
|
}
|
|
446
446
|
}
|
|
447
447
|
assertRunning() {
|
|
@@ -469,22 +469,22 @@ export class HyperCore {
|
|
|
469
469
|
throw new p(`[HyperCore] Protocol "${e}" has no sender (client role).`);
|
|
470
470
|
return r;
|
|
471
471
|
}
|
|
472
|
-
async runResponseHooks(e, t, r, s,
|
|
473
|
-
let
|
|
474
|
-
for (let
|
|
475
|
-
const c = s[
|
|
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
476
|
if (typeof c.onResponse != "function")
|
|
477
477
|
continue;
|
|
478
|
-
const l =
|
|
478
|
+
const l = n.get(c) ?? t;
|
|
479
479
|
if (c.mode === "background") {
|
|
480
|
-
const u = { ...
|
|
480
|
+
const u = { ...i, headers: { ...i.headers } };
|
|
481
481
|
Promise.resolve().then(() => c.onResponse(u, l, this.pluginCtx, r)).catch((y) => this.reportBackgroundPluginError(y));
|
|
482
482
|
continue;
|
|
483
483
|
}
|
|
484
|
-
const o = await c.onResponse(
|
|
485
|
-
o != null && q(o) && (
|
|
484
|
+
const o = await c.onResponse(i, l, this.pluginCtx, r);
|
|
485
|
+
o != null && q(o) && (i = o);
|
|
486
486
|
}
|
|
487
|
-
return
|
|
487
|
+
return i;
|
|
488
488
|
}
|
|
489
489
|
reportBackgroundPluginError(e) {
|
|
490
490
|
const t = this.config.onError;
|
|
@@ -518,21 +518,21 @@ export class HyperCore {
|
|
|
518
518
|
async acquireTransport(e = "rest", t = !1) {
|
|
519
519
|
if (this.isDestroyed)
|
|
520
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,
|
|
522
|
-
if (
|
|
523
|
-
return
|
|
524
|
-
let
|
|
525
|
-
if (!
|
|
526
|
-
|
|
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
527
|
let c;
|
|
528
|
-
c =
|
|
528
|
+
c = i.catch((l) => {
|
|
529
529
|
throw s.get(e) === c && s.delete(e), l;
|
|
530
|
-
}), s.set(e, c),
|
|
530
|
+
}), s.set(e, c), i = c;
|
|
531
531
|
}
|
|
532
|
-
const
|
|
532
|
+
const a = await i;
|
|
533
533
|
if (this.isDestroyed)
|
|
534
534
|
throw new p("[HyperCore] Core instance was destroyed while resolving transport.");
|
|
535
|
-
return
|
|
535
|
+
return a;
|
|
536
536
|
}
|
|
537
537
|
/**
|
|
538
538
|
* @ru Получает один транспорт, поддерживающий все запрошенные протоколы.
|
|
@@ -557,19 +557,19 @@ export class HyperCore {
|
|
|
557
557
|
return r;
|
|
558
558
|
}
|
|
559
559
|
async resolveListenTransport(e) {
|
|
560
|
-
const t = this.fixedTransport && typeof this.fixedTransport.listen == "function" ? this.fixedTransport : await B(e, {
|
|
561
|
-
...
|
|
560
|
+
const { protocols: t, ...r } = this.config, s = this.fixedTransport && typeof this.fixedTransport.listen == "function" ? this.fixedTransport : await B(e, {
|
|
561
|
+
...r,
|
|
562
562
|
cacheKey: this.config,
|
|
563
563
|
customTransport: this.fixedTransport ?? this.config.customTransport,
|
|
564
564
|
requireListen: !0,
|
|
565
565
|
logger: this.config.logger,
|
|
566
566
|
verbose: this.config.verbose
|
|
567
567
|
});
|
|
568
|
-
if (!this.transportSupportsAll(
|
|
569
|
-
throw new p(`[HyperCore] Transport "${
|
|
570
|
-
for (const
|
|
571
|
-
this.retainResolvedTransport(
|
|
572
|
-
return
|
|
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
573
|
}
|
|
574
574
|
transportSupportsAll(e, t) {
|
|
575
575
|
return t.every((r) => typeof e.supports == "function" ? e.supports(r) : e.protocols?.includes(r) ?? !0);
|
|
@@ -612,8 +612,8 @@ export class HyperCore {
|
|
|
612
612
|
*/
|
|
613
613
|
async runSender(e, t, r) {
|
|
614
614
|
this.assertActive();
|
|
615
|
-
const s = this.transports.get(t.protocol) ?? await this.acquireTransport(t.protocol),
|
|
616
|
-
return e.parse(
|
|
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
617
|
}
|
|
618
618
|
/**
|
|
619
619
|
* @ru Запускает сервер для указанного протокола: связывает транспорт, ресивер и
|
|
@@ -641,18 +641,18 @@ export class HyperCore {
|
|
|
641
641
|
const r = [...new Set(t)], s = await this.acquireListenTransport(r);
|
|
642
642
|
if (typeof s.listen != "function")
|
|
643
643
|
throw new p(`[HyperCore] Transport "${s.constructor.name}" does not support listen() (server role).`);
|
|
644
|
-
const
|
|
644
|
+
const n = await Promise.all(r.map((f) => this.resolveRegisteredProtocol(f))), i = /* @__PURE__ */ new Map();
|
|
645
645
|
for (let f = 0; f < r.length; f++) {
|
|
646
|
-
const P =
|
|
646
|
+
const P = n[f]?.receiver;
|
|
647
647
|
if (!P)
|
|
648
648
|
throw new p(`[HyperCore] Protocol "${r[f]}" has no receiver (server role).`);
|
|
649
|
-
|
|
649
|
+
i.set(r[f], P);
|
|
650
650
|
}
|
|
651
|
-
const
|
|
651
|
+
const a = e.handler, c = e.route, l = async (f) => {
|
|
652
652
|
const P = c?.(f) ?? this.routeServerRequest(r, f);
|
|
653
|
-
if (!P || !
|
|
653
|
+
if (!P || !i.has(P))
|
|
654
654
|
return J(r);
|
|
655
|
-
const H =
|
|
655
|
+
const H = i.get(P), w = Object.assign(G(f), { protocol: P }), k = this.plugins;
|
|
656
656
|
let R = f, m, M = !1;
|
|
657
657
|
const x = async (g) => {
|
|
658
658
|
let d = g;
|
|
@@ -677,7 +677,7 @@ export class HyperCore {
|
|
|
677
677
|
const E = await v.onServerRequest?.(R, this.pluginCtx, w);
|
|
678
678
|
E !== void 0 && (R = E, w.signal = R.signal);
|
|
679
679
|
}
|
|
680
|
-
const g = await H.receive(R, w), d =
|
|
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
681
|
M = !0, m = { ok: !0, response: await x(T) };
|
|
682
682
|
} catch (g) {
|
|
683
683
|
const d = await O(g);
|
|
@@ -737,10 +737,10 @@ export class HyperCore {
|
|
|
737
737
|
r.push(s);
|
|
738
738
|
continue;
|
|
739
739
|
}
|
|
740
|
-
const
|
|
741
|
-
if (!
|
|
740
|
+
const n = await j(s), i = n.default ?? n.plugin;
|
|
741
|
+
if (!i || typeof i != "object")
|
|
742
742
|
throw new p(`[HyperCore] Plugin module "${s}" must export a plugin object as default or "plugin".`);
|
|
743
|
-
r.push(
|
|
743
|
+
r.push(i);
|
|
744
744
|
}
|
|
745
745
|
return new HyperCore({ ...e, plugins: r });
|
|
746
746
|
}
|
|
@@ -754,7 +754,7 @@ export class HyperCore {
|
|
|
754
754
|
throw new p("[HyperCore] Plugin instances cannot be shared across cores. Supply a fresh instance.");
|
|
755
755
|
if (e.shared && e.setup)
|
|
756
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,
|
|
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
758
|
}
|
|
759
759
|
/**
|
|
760
760
|
* @ru Создаёт новый экземпляр ядра с расширенной/переопределённой конфигурацией,
|
package/Core/HyperCore.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/Core/HyperCore.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n AnyHyperSender,\n AnyHyperProtocol,\n AnyHyperReceiver,\n InferProtocolInput,\n HyperClientOptions,\n HyperPlugin,\n HyperProtocol,\n HyperProtocols,\n HyperReceiver,\n HyperSender,\n HyperServerListenOptions,\n HyperTransport,\n IHyperCore,\n PluginContext,\n ProtocolRegistry,\n RequestContext,\n RequestOutcome,\n ServerRequestOutcome,\n HyperProtocolName,\n SendRequest,\n ServerRequestContext,\n TransportRequest,\n TransportResponse,\n TransportServer,\n UniversalResponse,\n} from \"@hyperttp/types\";\nimport { dynamicImport } from \"../utils/modules.js\";\nimport { defaultCoreConfig } from \"../defaultConfig.js\";\nimport { KNOWN_PROTOCOLS, resolveProtocol } from \"../protocols/manager.js\";\nimport {\n evictCachedTransport,\n resolveTransport,\n resolveTransportForProtocols,\n} from \"../transports/manager.js\";\nimport { HyperClientError } from \"../utils/errors.js\";\n\nlet requestCounter = 0;\nlet requestIdBase = Date.now().toString(36) + \"-\";\n\nconst PLUGIN_PHASE_ORDER: Readonly<Record<string, number>> = Object.freeze({\n START: 0,\n PREPARE: 1,\n CONTROL: 2,\n FORMAT: 3,\n NETWORK: 4,\n DATA: 5,\n});\n\n/**\n * @ru Генерирует уникальный идентификатор запроса без аллокаций на каждый вызов:\n * базовый таймстемп пересчитывается при переполнении счётчика, а уникальность\n * обеспечивает инкрементальный битовый счётчик (общий для всех ядер).\n * @en Generates a unique request identifier without per-call allocations:\n * the base timestamp is recalculated when the counter wraps around, and uniqueness\n * is ensured by an incremental bitwise counter (shared across all cores).\n * @returns A compact unique string identifier.\n */\nfunction createRequestId(): string {\n requestCounter = (requestCounter + 1) >>> 0;\n if (requestCounter === 0) {\n requestIdBase = Date.now().toString(36) + \"-\";\n }\n return requestIdBase + (requestCounter >>> 0).toString(36);\n}\n\n/**\n * @ru Счётчик активных удержаний транспорта. Позволяет нескольким ядрам\n * (например, через `extend()`) разделять один транспорт, закрывая его только\n * после освобождения последней ссылки.\n * @en Active transport hold count. Lets multiple cores (e.g. via `extend()`)\n * share one transport, closing it only after the last reference is released.\n */\nconst transportRefs = new WeakMap<HyperTransport, number>();\nconst pluginOwners = new WeakMap<HyperPlugin, HyperCore>();\n\nfunction retainTransport(transport: HyperTransport): void {\n transportRefs.set(transport, (transportRefs.get(transport) ?? 0) + 1);\n}\n\nfunction releaseTransport(transport: HyperTransport): number {\n const next = (transportRefs.get(transport) ?? 1) - 1;\n if (next <= 0) {\n transportRefs.delete(transport);\n } else {\n transportRefs.set(transport, next);\n }\n return next;\n}\n\n/**\n * @ru Создаёт RequestContext на один цикл выполнения (prepare → send → parse).\n * `meta` и `state` инициализируются лениво при первом обращении, чтобы не\n * аллоцировать объекты для запросов, которые их не используют.\n * @en Creates a RequestContext for a single execution cycle (prepare → send → parse).\n * `meta` and `state` are initialized lazily on first access to avoid allocating\n * objects for requests that never use them.\n * @param req - The universal request being dispatched.\n * @returns A new RequestContext.\n */\nclass DefaultRequestContext implements RequestContext {\n public readonly requestId = createRequestId();\n public readonly startTime = performance.now();\n public readonly signal?: AbortSignal;\n private requestMeta?: Record<string, unknown>;\n private requestState?: Record<string, unknown>;\n private settlementCallbacks: ((outcome: RequestOutcome) => void | Promise<void>)[] = [];\n private finalized = false;\n private acceptedResponse?: UniversalResponse;\n\n public onSettled(callback: (outcome: RequestOutcome) => void | Promise<void>): void {\n if (this.finalized) throw new Error(\"[HyperCore] Request settlement has already started.\");\n this.settlementCallbacks.push(callback);\n }\n\n public acceptFinalResponse<T>(response: UniversalResponse<T>): UniversalResponse<T> {\n if (this.finalized) throw new Error(\"[HyperCore] Request has already settled.\");\n this.acceptedResponse = response;\n return response;\n }\n\n public isFinalResponse(response: UniversalResponse): boolean {\n return this.acceptedResponse === response;\n }\n\n public async settle(outcome: RequestOutcome, report: (error: unknown) => void): Promise<void> {\n if (this.finalized) return;\n this.finalized = true;\n const callbacks = this.settlementCallbacks;\n this.settlementCallbacks = [];\n for (const callback of callbacks) {\n try {\n await callback(outcome);\n } catch (error) {\n report(error);\n }\n }\n }\n\n constructor(signal?: AbortSignal) {\n this.signal = signal;\n }\n\n public get meta(): Record<string, unknown> {\n return (this.requestMeta ??= {});\n }\n\n public set meta(value: Record<string, unknown>) {\n this.requestMeta = value;\n }\n\n public get state(): Record<string, unknown> {\n return (this.requestState ??= {});\n }\n\n public set state(value: Record<string, unknown>) {\n this.requestState = value;\n }\n}\n\nfunction createRequestContext(req: SendRequest<unknown, string>): DefaultRequestContext {\n return new DefaultRequestContext(req.signal);\n}\n\n/**\n * @ru Создаёт ServerRequestContext на один серверный цикл (receive → handle → respond).\n * `meta` и `state` инициализируются лениво, как и в клиентском контексте.\n * @en Creates a ServerRequestContext for a single server cycle (receive → handle → respond).\n * `meta` and `state` are initialized lazily, like in the client context.\n * @param raw - The raw transport request being received.\n * @returns A new ServerRequestContext.\n */\nfunction createServerRequestContext(raw: TransportRequest): ServerRequestContext {\n return new DefaultRequestContext(raw.signal) as ServerRequestContext;\n}\n\nfunction getRequestHeader(\n headers: Readonly<Record<string, string | string[]>>,\n name: string,\n): string | undefined {\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction unsupportedProtocolResponse(protocols: readonly HyperProtocolName[]): TransportResponse {\n return {\n status: 415,\n statusText: \"Unsupported Media Type\",\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n body: new TextEncoder().encode(\n `Unsupported protocol. Expected one of: ${protocols.join(\", \")}.`,\n ),\n };\n}\n\n/**\n * @ru Проверяет, является ли значение UniversalResponse (а не SendRequest).\n * @en Checks whether the value is a UniversalResponse (rather than a SendRequest).\n * @param value - The value to inspect.\n * @returns True if the value carries response shape (data + status).\n */\nfunction isUniversalResponse(value: unknown): value is UniversalResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"data\" in value &&\n \"status\" in value &&\n !(\"input\" in value)\n );\n}\n\n/**\n * @ru Внутренний реестр протоколов: хранит единые модули (Sender + Receiver).\n * @en Internal protocol registry: stores unified modules (Sender + Receiver).\n */\nclass DefaultProtocolRegistry implements ProtocolRegistry {\n private readonly protocols = new Map<HyperProtocolName, AnyHyperProtocol>();\n\n public register<P extends HyperProtocolName>(protocol: AnyHyperProtocol<P>): void {\n this.protocols.set(protocol.protocol, protocol);\n }\n\n public get<P extends HyperProtocolName>(\n protocol: P,\n ): HyperProtocol<unknown, unknown, unknown, unknown, P> | undefined {\n return this.protocols.get(protocol) as\n | HyperProtocol<unknown, unknown, unknown, unknown, P>\n | undefined;\n }\n\n public has(protocol: HyperProtocolName): boolean {\n return this.protocols.has(protocol);\n }\n\n public get size(): number {\n return this.protocols.size;\n }\n}\n\n// oxlint-disable-next-line no-unsafe-declaration-merging\nexport interface HyperCore extends HyperProtocols {}\n\n/**\n * @ru Универсальное ядро v2.0.0. Протокол-независимый диспетчер: регистрирует\n * единые модули протоколов (Sender + Receiver), выполняет клиентский цикл\n * prepare → send → parse и серверный цикл receive → handle → respond через\n * физический транспорт, а также прогоняет хуки плагинов.\n * @en Universal core v2.0.0. Protocol-agnostic dispatcher: registers unified\n * protocol modules (Sender + Receiver), runs the client cycle prepare → send → parse\n * and the server cycle receive → handle → respond through the physical transport,\n * and executes plugin hooks.\n */\nexport class HyperCore implements IHyperCore {\n public readonly config: HyperClientOptions;\n\n private readonly registry = new DefaultProtocolRegistry();\n private readonly pluginCtx: PluginContext;\n private plugins: HyperPlugin[] = [];\n private readonly servers = new Set<TransportServer>();\n private readonly pendingListeners = new Set<Promise<TransportServer>>();\n private readonly flatMethodOwners = new Map<string, string>();\n private readonly flatMethodValues = new Map<string, unknown>();\n private readonly protocolNamespaces = new Set<string>();\n private readonly generatedFlatMethods = new Set<string>();\n private readonly transportPromises = new Map<HyperProtocolName, Promise<HyperTransport>>();\n private readonly transports = new Map<HyperProtocolName, HyperTransport>();\n private readonly listenTransportPromises = new Map<HyperProtocolName, Promise<HyperTransport>>();\n private readonly listenTransports = new Map<HyperProtocolName, HyperTransport>();\n private readonly multiListenTransportPromises = new Map<string, Promise<HyperTransport>>();\n private readonly retainedTransports = new Set<HyperTransport>();\n private readonly fixedTransport: HyperTransport | null;\n private destroyPromise: Promise<void> | null = null;\n private state: \"initializing\" | \"running\" | \"destroying\" | \"destroyed\" = \"initializing\";\n private readonly activeRequests = new Set<Promise<void>>();\n\n private get isDestroyed(): boolean {\n return this.state === \"destroying\" || this.state === \"destroyed\";\n }\n\n constructor(\n config: Partial<HyperClientOptions> = {},\n transport?: HyperTransport,\n sharedTransportPromises?: ReadonlyMap<HyperProtocolName, Promise<HyperTransport>>,\n ) {\n this.config = {\n ...defaultCoreConfig,\n ...config,\n retry: {\n ...defaultCoreConfig.retry,\n ...config.retry,\n },\n };\n this.fixedTransport = transport ?? null;\n this.pluginCtx = { config: this.config, core: this };\n\n for (const plugin of this.config.plugins ?? []) {\n if (typeof plugin !== \"string\" && !plugin.shared && pluginOwners.has(plugin)) {\n throw new HyperClientError(\n \"[HyperCore] Plugin instances cannot be shared across cores. Supply fresh plugins when extending or creating a core.\",\n );\n }\n }\n\n const protocols = this.config.protocols;\n if (protocols) {\n for (let i = 0; i < protocols.length; i++) {\n this.registerProtocol(protocols[i]!);\n }\n }\n\n const senders = this.config.senders;\n if (senders) {\n for (let i = 0; i < senders.length; i++) {\n this.registerSender(senders[i]!);\n }\n }\n\n const customSender = this.config.customSender;\n if (customSender) {\n this.registerSender(customSender);\n }\n\n const receivers = this.config.receivers;\n if (receivers) {\n for (let i = 0; i < receivers.length; i++) {\n this.registerReceiver(receivers[i]!);\n }\n }\n\n const plugins = this.config.plugins;\n if (plugins) {\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i]!;\n if (typeof plugin === \"string\") {\n throw new HyperClientError(\n `[HyperCore] Plugin module \"${plugin}\" cannot be loaded by the synchronous constructor. Import it and pass the plugin instance instead.`,\n );\n }\n try {\n this.use(plugin);\n } catch (error) {\n for (const registered of this.plugins) pluginOwners.delete(registered);\n throw error;\n }\n }\n }\n\n try {\n for (const factory of this.config.pluginFactories ?? []) this.use(factory());\n } catch (error) {\n for (const registered of this.plugins) {\n if (pluginOwners.get(registered) === this) pluginOwners.delete(registered);\n }\n throw error;\n }\n\n const namespaces = this as unknown as Record<string, unknown>;\n for (let i = 0; i < KNOWN_PROTOCOLS.length; i++) {\n const protocol = KNOWN_PROTOCOLS[i]!;\n if (!this.registry.has(protocol) && namespaces[protocol] === undefined) {\n namespaces[protocol] = this.createLazyNamespace(protocol);\n this.protocolNamespaces.add(protocol);\n }\n }\n if (transport && !this.retainedTransports.has(transport)) {\n retainTransport(transport);\n this.retainedTransports.add(transport);\n }\n if (sharedTransportPromises) {\n for (const [protocol, sharedPromise] of sharedTransportPromises) {\n this.transportPromises.set(\n protocol,\n sharedPromise.then((sharedTransport) =>\n this.retainResolvedTransport(protocol, sharedTransport),\n ),\n );\n }\n }\n this.state = \"running\";\n }\n\n /**\n * @ru Получает зарегистрированный модуль протокола (Sender + Receiver).\n * @en Gets a registered protocol module (Sender + Receiver).\n */\n public getProtocol<P extends HyperProtocolName>(\n protocol: P,\n ): HyperProtocol<unknown, unknown, unknown, unknown, P> | undefined {\n return this.registry.get(protocol);\n }\n\n /**\n * @ru Получает зарегистрированный сендер протокола.\n * @en Gets a registered protocol sender.\n */\n public getSender<P extends HyperProtocolName>(\n protocol: P,\n ): HyperSender<unknown, unknown, unknown, unknown, P> | undefined {\n return this.registry.get(protocol)?.sender;\n }\n\n /**\n * @ru Получает зарегистрированный ресивер протокола.\n * @en Gets a registered protocol receiver.\n */\n public getReceiver<P extends HyperProtocolName>(\n protocol: P,\n ): HyperReceiver<unknown, unknown, unknown, unknown, P> | undefined {\n return this.registry.get(protocol)?.receiver;\n }\n\n /**\n * @ru Возвращает имя текущего транспорта.\n * @en Returns the name of the current transport.\n * @returns Transport constructor name.\n */\n public async getTransportName(): Promise<string> {\n this.assertRunning();\n const t = await this.acquireTransport();\n return t.constructor.name;\n }\n\n /**\n * @ru Возвращает имя сендера протокола (по умолчанию — \"rest\").\n * Протокол резолвится лениво, если ещё не зарегистрирован.\n * @en Returns the sender constructor name for a protocol (default \"rest\").\n * The protocol is resolved lazily if not registered yet.\n * @param protocol - The protocol to inspect.\n * @returns Sender constructor name.\n */\n public async getSenderName(protocol: HyperProtocolName = \"rest\"): Promise<string> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n const sender = resolved.sender;\n if (!sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n return sender.constructor.name;\n }\n\n /**\n * @ru Возвращает имя ресивера протокола (по умолчанию — \"rest\").\n * Протокол резолвится лениво, если ещё не зарегистрирован.\n * @en Returns the receiver constructor name for a protocol (default \"rest\").\n * The protocol is resolved lazily if not registered yet.\n * @param protocol - The protocol to inspect.\n * @returns Receiver constructor name.\n */\n public async getReceiverName(protocol: HyperProtocolName = \"rest\"): Promise<string> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n const receiver = resolved.receiver;\n if (!receiver) {\n throw new HyperClientError(\n `[HyperCore] Protocol \"${protocol}\" has no receiver (server role).`,\n );\n }\n return receiver.constructor.name;\n }\n\n /**\n * @ru Возвращает имя модуля протокола (по умолчанию — \"rest\"): предпочитает\n * `name`, затем `constructor.name`, затем идентификатор протокола.\n * Протокол резолвится лениво, если ещё не зарегистрирован.\n * @en Returns the protocol module name (default \"rest\"): prefers `name`, then\n * `constructor.name`, then the protocol identifier.\n * The protocol is resolved lazily if not registered yet.\n * @param protocol - The protocol to inspect.\n * @returns The protocol module display name.\n */\n public async getProtocolName(protocol: HyperProtocolName = \"rest\"): Promise<string> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n if (resolved.name) return resolved.name;\n const ctor = resolved.constructor;\n return ctor && ctor.name && ctor.name !== \"Object\" ? ctor.name : String(resolved.protocol);\n }\n\n /**\n * @ru Регистрирует единый модуль протокола и раскрывает методы его сендера\n * на ядре (например, `core.rest` для REST).\n * @en Registers a unified protocol module and exposes its sender methods on the\n * core (e.g., `core.rest` for REST).\n * @param protocol - The protocol module to register.\n * @returns This instance for chaining.\n */\n public registerProtocol<P extends HyperProtocolName>(protocol: AnyHyperProtocol<P>): this {\n this.assertActive();\n const protocolName = String(protocol.protocol);\n const namespaces = this as unknown as Record<string, unknown>;\n const isReserved =\n protocolName === \"__proto__\" ||\n protocolName === \"prototype\" ||\n protocolName === \"constructor\" ||\n protocolName in HyperCore.prototype ||\n (protocolName in this && !this.protocolNamespaces.has(protocolName));\n\n if (isReserved) {\n throw new HyperClientError(\n `[HyperCore] Protocol name \"${protocolName}\" conflicts with the core API.`,\n );\n }\n\n for (const [name, owner] of this.flatMethodOwners) {\n if (owner === protocolName) {\n if (\n Object.getOwnPropertyDescriptor(this, name)?.value === this.flatMethodValues.get(name)\n ) {\n delete namespaces[name];\n }\n this.flatMethodValues.delete(name);\n this.flatMethodOwners.delete(name);\n this.generatedFlatMethods.delete(name);\n }\n }\n if (this.protocolNamespaces.has(protocolName)) {\n delete namespaces[protocolName];\n this.protocolNamespaces.delete(protocolName);\n }\n this.registry.register(protocol);\n\n const methods = protocol.sender?.methods;\n if (methods && typeof methods === \"object\") {\n const namespace: Record<string, unknown> = Object.create(null);\n\n for (const name in methods) {\n if (!Object.hasOwn(methods, name)) continue;\n\n const method = methods[name] as ((...args: unknown[]) => unknown) | undefined;\n if (typeof method !== \"function\") continue;\n\n const boundMethod = (...args: unknown[]) => method.apply(methods, [this, ...args]);\n namespace[name] = boundMethod;\n\n const stillGenerated =\n this.generatedFlatMethods.has(name) &&\n Object.getOwnPropertyDescriptor(this, name)?.value === this.flatMethodValues.get(name);\n if (stillGenerated) {\n namespaces[name] = boundMethod;\n this.flatMethodOwners.set(name, protocolName);\n this.flatMethodValues.set(name, boundMethod);\n } else if (!(name in HyperCore.prototype) && !(name in this)) {\n namespaces[name] = boundMethod;\n this.generatedFlatMethods.add(name);\n this.flatMethodOwners.set(name, protocolName);\n this.flatMethodValues.set(name, boundMethod);\n }\n }\n\n namespaces[protocolName] = namespace;\n this.protocolNamespaces.add(protocolName);\n }\n\n return this;\n }\n\n /**\n * @ru Регистрирует сендер протокола, оборачивая его в модуль протокола.\n * Существующий ресивер того же протокола сохраняется.\n * @en Registers a protocol sender, wrapping it into a protocol module.\n * An existing receiver for the same protocol is preserved.\n * @param sender - The protocol sender to register.\n * @returns This instance for chaining.\n */\n public registerSender<P extends HyperProtocolName>(sender: AnyHyperSender<P>): this {\n const existing = this.registry.get(sender.protocol);\n return this.registerProtocol({\n protocol: sender.protocol,\n sender,\n receiver: existing?.receiver,\n });\n }\n\n /**\n * @ru Регистрирует ресивер протокола, оборачивая его в модуль протокола.\n * Существующий сендер того же протокола сохраняется.\n * @en Registers a protocol receiver, wrapping it into a protocol module.\n * An existing sender for the same protocol is preserved.\n * @param receiver - The protocol receiver to register.\n * @returns This instance for chaining.\n */\n public registerReceiver<P extends HyperProtocolName>(receiver: AnyHyperReceiver<P>): this {\n const existing = this.registry.get(receiver.protocol);\n return this.registerProtocol({\n protocol: receiver.protocol,\n sender: existing?.sender,\n receiver,\n });\n }\n\n /**\n * @ru Создаёт ленивый namespace методов протокола: методы доступны ещё до\n * регистрации протокола и резолвятся по требованию при первом вызове.\n * @en Creates a lazy protocol methods namespace: methods are reachable before\n * the protocol is registered and are resolved on first call.\n * @param protocol - The protocol to expose lazily.\n * @returns A Proxy that dispatches method calls to the resolved protocol sender.\n */\n private createLazyNamespace(protocol: HyperProtocolName): Record<string, unknown> {\n const handler: ProxyHandler<Record<string, unknown>> = {\n get: (_target, name) => {\n if (typeof name !== \"string\" || name === \"then\") return undefined;\n return (...args: unknown[]) => this.dispatchLazyMethod(protocol, name, args);\n },\n };\n return new Proxy({}, handler);\n }\n\n /**\n * @ru Разрешает протокол по требованию и вызывает метод `methods`-поверхности\n * его сендера, биндя ядро первым аргументом.\n * @en Resolves the protocol on demand and calls a method on its sender\n * `methods` surface, binding the core as the first argument.\n * @param protocol - The protocol identifier.\n * @param name - The method name on the sender surface.\n * @param args - Arguments forwarded after the core instance.\n * @returns The result of the sender method call.\n */\n private async dispatchLazyMethod(\n protocol: HyperProtocolName,\n name: string,\n args: unknown[],\n ): Promise<unknown> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n\n const sender = resolved.sender;\n if (!sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n\n const methods = sender.methods as\n | Record<string, (...callArgs: unknown[]) => unknown>\n | undefined;\n const method = methods && Object.hasOwn(methods, name) ? methods[name] : undefined;\n if (typeof method !== \"function\") {\n throw new TypeError(`[HyperCore] Protocol \"${protocol}\" has no method \"${name}\".`);\n }\n return method.apply(methods, [this, ...args]);\n }\n\n /**\n * @ru Основной метод диспетчеризации: выбирает сендер по протоколу и выполняет\n * трёхфазный цикл с поддержкой плагинов.\n * @en Main dispatch method: resolves the sender by protocol and runs the three-phase\n * cycle with plugin support.\n * @param req - The universal request envelope.\n * @returns A promise resolving to the normalized universal response.\n */\n public send<TOutput = unknown, P extends HyperProtocolName = HyperProtocolName>(\n req: SendRequest<InferProtocolInput<P>, P>,\n ): Promise<UniversalResponse<TOutput>>;\n public send<TInput = unknown, TOutput = unknown, P extends HyperProtocolName = HyperProtocolName>(\n req: SendRequest<TInput, P>,\n ): Promise<UniversalResponse<TOutput>>;\n public async send<TInput = unknown, TOutput = unknown, P extends string = string>(\n req: SendRequest<TInput, P>,\n ): Promise<UniversalResponse<TOutput>> {\n this.assertRunning();\n let complete!: () => void;\n const completion = new Promise<void>((resolve) => {\n complete = resolve;\n });\n this.activeRequests.add(completion);\n const ctx = createRequestContext(req as SendRequest<unknown, string>);\n try {\n const response = await this.executeRequest<TInput, TOutput, P>(req, ctx);\n await ctx.settle({ ok: true, response }, (error) =>\n this.log(\"error\", \"[HyperCore] Settlement callback failed\", error),\n );\n return response;\n } catch (error) {\n await ctx.settle({ ok: false, error }, (diagnostic) =>\n this.log(\"error\", \"[HyperCore] Settlement callback failed\", diagnostic),\n );\n throw error;\n } finally {\n complete();\n this.activeRequests.delete(completion);\n }\n }\n\n private async executeRequest<TInput, TOutput, P extends string>(\n req: SendRequest<TInput, P>,\n ctx: DefaultRequestContext,\n ): Promise<UniversalResponse<TOutput>> {\n const plugins = this.plugins;\n let currentReq = req as SendRequest<any, any>;\n const hookRequests = new Map<HyperPlugin, SendRequest<any, any>>();\n let responseHooksStarted = false;\n\n if (plugins.length === 0) {\n const sender = this.registry.get(req.protocol)?.sender;\n if (sender) {\n return this.runSender<TInput, TOutput>(sender, req as SendRequest<TInput, string>, ctx);\n }\n }\n\n try {\n let response: UniversalResponse<TOutput> | undefined;\n\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i]!;\n if (typeof plugin.onRequest !== \"function\") continue;\n\n hookRequests.set(plugin, currentReq);\n const result = await plugin.onRequest(currentReq, this.pluginCtx, ctx);\n if (result == null) continue;\n\n if (isUniversalResponse(result)) {\n response = result as UniversalResponse<TOutput>;\n break;\n }\n\n currentReq = result as SendRequest<any, any>;\n (ctx as { signal?: AbortSignal }).signal = currentReq.signal;\n }\n\n if (!response) {\n const sender = await this.resolveRequestSender(currentReq.protocol);\n response = await this.runSender<unknown, TOutput>(sender, currentReq, ctx);\n }\n\n if (ctx.isFinalResponse(response)) return response;\n responseHooksStarted = true;\n return await this.runResponseHooks(response, currentReq, ctx, plugins, hookRequests);\n } catch (err) {\n let recovery: UniversalResponse<TOutput> | undefined;\n for (const plugin of plugins) {\n if (typeof plugin.onError !== \"function\") continue;\n try {\n const recovered = await plugin.onError(\n err,\n hookRequests.get(plugin) ?? currentReq,\n this.pluginCtx,\n ctx,\n );\n if (!recovery && recovered != null && isUniversalResponse(recovered)) {\n recovery = recovered as UniversalResponse<TOutput>;\n }\n } catch (hookError) {\n this.log(\"error\", \"[HyperCore] Error hook failed\", hookError);\n }\n }\n if (recovery) {\n // A response-hook failure already triggered cleanup; do not repeat those hooks.\n if (responseHooksStarted) return recovery;\n try {\n return await this.runResponseHooks(recovery, currentReq, ctx, plugins, hookRequests);\n } catch (responseError) {\n // Report the new failure and finish cleanup without starting another recovery cycle.\n for (const plugin of plugins) {\n if (typeof plugin.onError !== \"function\") continue;\n try {\n await plugin.onError(\n responseError,\n hookRequests.get(plugin) ?? currentReq,\n this.pluginCtx,\n ctx,\n );\n } catch (hookError) {\n this.log(\"error\", \"[HyperCore] Error hook failed\", hookError);\n }\n }\n throw responseError;\n }\n }\n throw err;\n }\n }\n\n private assertRunning(): void {\n if (this.state === \"initializing\") {\n throw new HyperClientError(\n \"[HyperCore] Operations cannot start during setup initialization.\",\n );\n }\n this.assertActive();\n }\n\n private assertActive(): void {\n if (this.isDestroyed) {\n throw new HyperClientError(\"[HyperCore] Core instance has been destroyed.\");\n }\n }\n\n private async resolveRegisteredProtocol<P extends HyperProtocolName>(\n protocol: P,\n ): Promise<AnyHyperProtocol<P>> {\n this.assertActive();\n const existing = this.registry.get(protocol);\n if (existing) return existing;\n const loaded = await resolveProtocol(protocol);\n this.assertActive();\n // Explicit registration during the import has priority over its late result.\n const registered = this.registry.get(protocol);\n if (registered) return registered;\n this.registerProtocol(loaded);\n return loaded;\n }\n\n private async resolveRequestSender(\n protocol: HyperProtocolName,\n ): Promise<HyperSender<any, any, any, any>> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n\n const sender = resolved.sender;\n if (!sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n return sender;\n }\n\n private async runResponseHooks<TOutput>(\n initialResponse: UniversalResponse<TOutput>,\n req: SendRequest<any, any>,\n ctx: RequestContext,\n plugins: readonly HyperPlugin[],\n hookRequests: ReadonlyMap<HyperPlugin, SendRequest<any, any>>,\n ): Promise<UniversalResponse<TOutput>> {\n let response = initialResponse;\n\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i]!;\n if (typeof plugin.onResponse !== \"function\") continue;\n\n const hookRequest = hookRequests.get(plugin) ?? req;\n if (plugin.mode === \"background\") {\n const snapshot = { ...response, headers: { ...response.headers } };\n void Promise.resolve()\n .then(() => plugin.onResponse!(snapshot, hookRequest, this.pluginCtx, ctx))\n .catch((err: unknown) => this.reportBackgroundPluginError(err));\n continue;\n }\n\n const result = await plugin.onResponse(response, hookRequest, this.pluginCtx, ctx);\n if (result != null && isUniversalResponse(result)) {\n response = result as UniversalResponse<TOutput>;\n }\n }\n\n return response;\n }\n\n private reportBackgroundPluginError(err: unknown): void {\n const customOnError = (this.config as Record<string, unknown>).onError;\n if (typeof customOnError === \"function\") {\n try {\n (customOnError as (error: unknown) => void)(err);\n return;\n } catch (handlerError) {\n this.log(\"error\", \"[HyperCore] Background error handler failed\", handlerError);\n }\n }\n this.log(\"error\", \"[HyperCore] Background plugin error\", err);\n }\n\n private log(level: \"debug\" | \"info\" | \"warn\" | \"error\", message: string, meta?: unknown): void {\n try {\n if (this.config.logger) {\n this.config.logger(level, message, meta);\n return;\n }\n if (!this.config.verbose && level !== \"error\") return;\n const output = level === \"debug\" ? console.debug : console[level];\n output(message, meta);\n } catch {\n // Diagnostics must never interrupt lifecycle cleanup.\n }\n }\n\n /**\n * @ru Атомарно получает транспорт для конкретного протокола и удерживает\n * каждый физический экземпляр ровно один раз за время жизни ядра.\n * @en Atomically acquires a transport for a protocol and retains each physical\n * instance exactly once for the lifetime of this core.\n */\n private async acquireTransport(\n protocol: HyperProtocolName = \"rest\",\n requireListen = false,\n ): Promise<HyperTransport> {\n if (this.isDestroyed) {\n throw new HyperClientError(\n \"[HyperCore] Cannot acquire transport on a destroyed core instance.\",\n );\n }\n\n const transports = requireListen ? this.listenTransports : this.transports;\n const transportPromises = requireListen ? this.listenTransportPromises : this.transportPromises;\n const existing = transports.get(protocol);\n if (existing) return existing;\n\n let pending = transportPromises.get(protocol);\n if (!pending) {\n pending = this.resolveAndRetainTransport(protocol, requireListen);\n let tracked!: Promise<HyperTransport>;\n tracked = pending.catch((err: unknown) => {\n if (transportPromises.get(protocol) === tracked) {\n transportPromises.delete(protocol);\n }\n throw err;\n });\n transportPromises.set(protocol, tracked);\n pending = tracked;\n }\n\n const transport = await pending;\n if (this.isDestroyed) {\n throw new HyperClientError(\n \"[HyperCore] Core instance was destroyed while resolving transport.\",\n );\n }\n\n return transport;\n }\n\n /**\n * @ru Получает один транспорт, поддерживающий все запрошенные протоколы.\n * Это позволяет открыть один listener на порт для REST и gRPC.\n * @en Acquires one transport supporting every requested protocol. This lets\n * REST and gRPC share a single listener on one port.\n */\n private async acquireListenTransport(\n protocols: readonly HyperProtocolName[],\n ): Promise<HyperTransport> {\n if (this.isDestroyed) {\n throw new HyperClientError(\n \"[HyperCore] Cannot acquire transport on a destroyed core instance.\",\n );\n }\n\n for (const transport of this.listenTransports.values()) {\n if (this.transportSupportsAll(transport, protocols)) return transport;\n }\n\n const key = JSON.stringify([...protocols].sort());\n let pending = this.multiListenTransportPromises.get(key);\n if (!pending) {\n let tracked!: Promise<HyperTransport>;\n tracked = this.resolveListenTransport(protocols).finally(() => {\n if (this.multiListenTransportPromises.get(key) === tracked) {\n this.multiListenTransportPromises.delete(key);\n }\n });\n this.multiListenTransportPromises.set(key, tracked);\n pending = tracked;\n }\n\n return pending;\n }\n\n private async resolveListenTransport(\n protocols: readonly HyperProtocolName[],\n ): Promise<HyperTransport> {\n const transport =\n this.fixedTransport && typeof this.fixedTransport.listen === \"function\"\n ? this.fixedTransport\n : await resolveTransportForProtocols(protocols, {\n ...this.config,\n cacheKey: this.config,\n customTransport: this.fixedTransport ?? this.config.customTransport,\n requireListen: true,\n logger: this.config.logger,\n verbose: this.config.verbose,\n });\n\n if (!this.transportSupportsAll(transport, protocols)) {\n throw new HyperClientError(\n `[HyperCore] Transport \"${transport.constructor.name}\" does not support protocols ${protocols.map((protocol) => `\"${protocol}\"`).join(\", \")}.`,\n );\n }\n\n for (const protocol of protocols) {\n this.retainResolvedTransport(protocol, transport, true);\n }\n return transport;\n }\n\n private transportSupportsAll(\n transport: HyperTransport,\n protocols: readonly HyperProtocolName[],\n ): boolean {\n return protocols.every((protocol) =>\n typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true),\n );\n }\n\n private routeServerRequest(\n protocols: readonly HyperProtocolName[],\n raw: TransportRequest,\n ): HyperProtocolName | undefined {\n const contentType = getRequestHeader(raw.headers, \"content-type\") ?? \"\";\n if (contentType.startsWith(\"application/grpc\") && protocols.includes(\"grpc\")) {\n return \"grpc\";\n }\n if (raw.protocol && protocols.includes(raw.protocol)) return raw.protocol;\n if (protocols.length === 1) return protocols[0];\n if (protocols.includes(\"rest\")) return \"rest\";\n return undefined;\n }\n\n private async resolveAndRetainTransport(\n protocol: HyperProtocolName,\n requireListen = false,\n ): Promise<HyperTransport> {\n const transport =\n this.fixedTransport && (!requireListen || typeof this.fixedTransport.listen === \"function\")\n ? this.fixedTransport\n : await resolveTransport(protocol, {\n ...this.config,\n cacheKey: this.config,\n customTransport: this.fixedTransport ?? this.config.customTransport,\n requireListen,\n logger: this.config.logger,\n verbose: this.config.verbose,\n });\n const supportsProtocol =\n typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true);\n\n if (!supportsProtocol) {\n throw new HyperClientError(\n `[HyperCore] Transport \"${transport.constructor.name}\" does not support protocol \"${protocol}\".`,\n );\n }\n\n return this.retainResolvedTransport(protocol, transport, requireListen);\n }\n\n private retainResolvedTransport(\n protocol: HyperProtocolName,\n transport: HyperTransport,\n requireListen = false,\n ): HyperTransport {\n if (!this.retainedTransports.has(transport)) {\n retainTransport(transport);\n this.retainedTransports.add(transport);\n }\n\n (requireListen ? this.listenTransports : this.transports).set(protocol, transport);\n return transport;\n }\n\n /**\n * @ru Выполняет ядро цикла запроса: prepare → send → parse через физический\n * транспорт. Транспорт получается через `acquireTransport()`.\n * @en Runs the core request cycle: prepare → send → parse through the physical\n * transport. The transport is acquired via `acquireTransport()`.\n * @param sender - The resolved protocol sender.\n * @param req - The (possibly plugin-modified) universal request.\n * @param ctx - The per-request execution context.\n * @returns The normalized universal response.\n */\n private async runSender<TInput, TOutput>(\n sender: HyperSender<any, any, any, any>,\n req: SendRequest<TInput, string>,\n ctx: RequestContext,\n ): Promise<UniversalResponse<TOutput>> {\n this.assertActive();\n const transport =\n this.transports.get(req.protocol) ?? (await this.acquireTransport(req.protocol));\n const prepared = sender.prepare(req, ctx);\n const raw = await sender.send(prepared, transport, ctx);\n return sender.parse(raw, ctx) as UniversalResponse<TOutput>;\n }\n\n /**\n * @ru Запускает сервер для указанного протокола: связывает транспорт, ресивер и\n * application handler в цепочку receive → handle → respond.\n * @en Starts a server for the given protocol, wiring transport, receiver, and\n * application handler into the receive → handle → respond pipeline.\n * @template P - The protocol identifier.\n * @param options - The server listen options.\n * @returns A promise resolving to the transport server handle.\n */\n public async listen<P extends HyperProtocolName = HyperProtocolName>(\n options: HyperServerListenOptions<P>,\n ): Promise<TransportServer> {\n this.assertRunning();\n const pending = this.startListening(options);\n this.pendingListeners.add(pending);\n try {\n return await pending;\n } finally {\n this.pendingListeners.delete(pending);\n }\n }\n\n private async startListening<P extends HyperProtocolName>(\n options: HyperServerListenOptions<P>,\n ): Promise<TransportServer> {\n const requested = options.protocols?.length\n ? options.protocols\n : options.protocol\n ? [options.protocol]\n : [];\n if (requested.length === 0) {\n throw new HyperClientError(\n \"[HyperCore] listen() requires a protocol or a non-empty protocols array.\",\n );\n }\n const protocols = [...new Set(requested)];\n\n const transport = await this.acquireListenTransport(protocols);\n\n if (typeof transport.listen !== \"function\") {\n throw new HyperClientError(\n `[HyperCore] Transport \"${transport.constructor.name}\" does not support listen() (server role).`,\n );\n }\n\n const resolvedProtocols = await Promise.all(\n protocols.map((protocol) => this.resolveRegisteredProtocol(protocol)),\n );\n const receivers = new Map<HyperProtocolName, AnyHyperReceiver>();\n for (let i = 0; i < protocols.length; i++) {\n const receiver = resolvedProtocols[i]?.receiver;\n if (!receiver) {\n throw new HyperClientError(\n `[HyperCore] Protocol \"${protocols[i]}\" has no receiver (server role).`,\n );\n }\n receivers.set(protocols[i]!, receiver);\n }\n\n const handler = options.handler as\n | ((request: unknown, ctx: ServerRequestContext) => unknown)\n | undefined;\n const route = options.route;\n\n const onRequest = async (raw: TransportRequest): Promise<TransportResponse> => {\n const protocol = route?.(raw) ?? this.routeServerRequest(protocols, raw);\n if (!protocol || !receivers.has(protocol)) {\n return unsupportedProtocolResponse(protocols);\n }\n const receiver = receivers.get(protocol)!;\n const ctx = Object.assign(createServerRequestContext(raw), { protocol });\n const plugins = this.plugins;\n let currentRequest = raw;\n let outcome: ServerRequestOutcome;\n let responseHooksStarted = false;\n const responseHooks = async (initial: TransportResponse): Promise<TransportResponse> => {\n let response = initial;\n for (const plugin of plugins) {\n const result = await plugin.onServerResponse?.(\n response,\n currentRequest,\n this.pluginCtx,\n ctx,\n );\n if (result !== undefined) response = result;\n }\n return response;\n };\n const errorHooks = async (error: unknown): Promise<TransportResponse | undefined> => {\n let recovery: TransportResponse | undefined;\n for (const plugin of plugins) {\n try {\n const result = await plugin.onServerError?.(error, currentRequest, this.pluginCtx, ctx);\n if (recovery === undefined && result !== undefined) recovery = result;\n } catch (diagnostic) {\n this.log(\"error\", \"[HyperCore] Server error hook failed\", diagnostic);\n }\n }\n return recovery;\n };\n try {\n for (const plugin of plugins) {\n const result = await plugin.onServerRequest?.(currentRequest, this.pluginCtx, ctx);\n if (result !== undefined) {\n currentRequest = result;\n (ctx as { signal?: AbortSignal }).signal = currentRequest.signal;\n }\n }\n const request = await receiver.receive(currentRequest, ctx);\n const response = handler\n ? await handler(request, ctx)\n : await receiver.handle(request, ctx);\n const serialized = await receiver.respond(response, ctx);\n responseHooksStarted = true;\n outcome = { ok: true, response: await responseHooks(serialized) };\n } catch (error) {\n const recovery = await errorHooks(error);\n if (recovery === undefined) outcome = { ok: false, error };\n else if (responseHooksStarted) outcome = { ok: true, response: recovery };\n else {\n try {\n outcome = { ok: true, response: await responseHooks(recovery) };\n } catch (responseError) {\n await errorHooks(responseError);\n outcome = { ok: false, error: responseError };\n }\n }\n }\n for (const plugin of plugins) {\n try {\n await plugin.onServerSettled?.(outcome, currentRequest, this.pluginCtx, ctx);\n } catch (diagnostic) {\n this.log(\"error\", \"[HyperCore] Server settlement hook failed\", diagnostic);\n }\n }\n if (!outcome.ok) throw outcome.error;\n return outcome.response;\n };\n\n const server = await transport.listen!({\n host: options.host,\n port: options.port,\n signal: options.signal,\n signaling: options.signaling,\n onRequest,\n });\n\n if (this.isDestroyed) {\n await server.close();\n throw new HyperClientError(\n \"[HyperCore] Core instance was destroyed while starting the server.\",\n );\n }\n\n let closing: Promise<void> | undefined;\n const tracked: TransportServer = {\n close: () => {\n closing ??= Promise.resolve()\n .then(() => server.close())\n .then(() => {\n this.servers.delete(tracked);\n });\n return closing;\n },\n };\n this.servers.add(tracked);\n return tracked;\n }\n\n /**\n * @ru Регистрирует плагин. Пропускает отключённые плагины.\n * @en Registers a plugin. Skips disabled plugins.\n * @param plugin - The plugin instance to register.\n * @returns This instance for chaining.\n */\n /**\n * Creates a core asynchronously and resolves plugin module paths before construction.\n */\n public static async create(config: Partial<HyperClientOptions> = {}): Promise<HyperCore> {\n const plugins = config.plugins;\n if (!plugins?.some((plugin) => typeof plugin === \"string\")) {\n return new HyperCore(config);\n }\n\n const resolvedPlugins: HyperPlugin[] = [];\n for (const plugin of plugins) {\n if (typeof plugin !== \"string\") {\n resolvedPlugins.push(plugin);\n continue;\n }\n const module = await dynamicImport(plugin);\n const candidate = module.default ?? module.plugin;\n if (!candidate || typeof candidate !== \"object\") {\n throw new HyperClientError(\n `[HyperCore] Plugin module \"${plugin}\" must export a plugin object as default or \"plugin\".`,\n );\n }\n resolvedPlugins.push(candidate as HyperPlugin);\n }\n\n return new HyperCore({ ...config, plugins: resolvedPlugins });\n }\n\n public use(plugin: HyperPlugin): this {\n this.assertActive();\n if (this.plugins.includes(plugin)) return this;\n if (this.plugins.some((existing) => existing.name === plugin.name)) {\n throw new HyperClientError(`[HyperCore] Plugin \"${plugin.name}\" is already registered.`);\n }\n const owner = pluginOwners.get(plugin);\n if (!plugin.shared && owner && owner !== this) {\n throw new HyperClientError(\n \"[HyperCore] Plugin instances cannot be shared across cores. Supply a fresh instance.\",\n );\n }\n if (plugin.shared && plugin.setup) {\n throw new HyperClientError(\"[HyperCore] Shared stateless plugins cannot define setup().\");\n }\n const enabled = plugin.enabled ? plugin.enabled(this.config) : true;\n if (!enabled) return this;\n\n plugin.setup?.(this.pluginCtx);\n if (!plugin.shared) pluginOwners.set(plugin, this);\n this.plugins = [...this.plugins, plugin].sort(\n (a, b) => (PLUGIN_PHASE_ORDER[a.phase ?? \"\"] ?? 0) - (PLUGIN_PHASE_ORDER[b.phase ?? \"\"] ?? 0),\n );\n return this;\n }\n\n /**\n * @ru Создаёт новый экземпляр ядра с расширенной/переопределённой конфигурацией,\n * переиспользуя текущий транспорт.\n * @en Creates a new core instance with extended/overridden configuration,\n * reusing the current transport.\n * @param options - Partial configuration overrides.\n * @returns A new IHyperCore instance.\n */\n public extend(options: Partial<HyperClientOptions>): IHyperCore {\n this.assertActive();\n const transport = options.customTransport ?? this.fixedTransport ?? undefined;\n const sharedTransports = options.customTransport ? undefined : this.transportPromises;\n return new HyperCore({ ...this.config, ...options }, transport, sharedTransports);\n }\n\n /**\n * @ru Создаёт полностью независимый экземпляр ядра на основе текущей\n * конфигурации: не переиспользует текущий транспорт и по умолчанию не\n * наследует `customTransport`.\n * @en Creates a fully independent core instance based on the current config:\n * it does not reuse the current transport and does not inherit\n * `customTransport` by default.\n * @param options - Partial configuration overrides.\n * @returns A new IHyperCore instance.\n */\n public create(options: Partial<HyperClientOptions>): IHyperCore {\n this.assertActive();\n const base: Partial<HyperClientOptions> = { ...this.config };\n delete base.customTransport;\n return new HyperCore({ ...base, ...options });\n }\n\n /**\n * @ru Завершает работу ядра и освобождает ресурсы: закрывает активные серверы,\n * затем освобождает удержание транспорта. Graceful-дренирование активных запросов\n * определяется реализацией `TransportServer.close()`.\n * @en Shuts down the core and releases resources: closes active servers, then\n * releases the transport hold. Graceful draining of in-flight requests is defined\n * by the `TransportServer.close()` implementation.\n * @param graceful - If true, prefers `transport.close()`; otherwise prefers `transport.destroy()`.\n * @returns Promise that resolves when shutdown is complete.\n */\n public destroy(graceful = true): Promise<void> {\n if (this.state === \"initializing\") {\n return Promise.reject(\n new HyperClientError(\"[HyperCore] Cannot destroy during setup initialization.\"),\n );\n }\n if (!this.destroyPromise) {\n this.destroyPromise = this.performDestroy(graceful);\n }\n return this.destroyPromise;\n }\n\n private async performDestroy(graceful: boolean): Promise<void> {\n this.state = \"destroying\";\n // Accepted calls finish or reject at the next admission check before resources close.\n if (graceful) await Promise.allSettled(this.activeRequests);\n\n await Promise.allSettled(this.pendingListeners);\n for (const server of this.servers) {\n try {\n await server.close();\n } catch {\n // Continue releasing the remaining resources.\n }\n }\n this.servers.clear();\n\n await Promise.allSettled([\n ...this.transportPromises.values(),\n ...this.listenTransportPromises.values(),\n ...this.multiListenTransportPromises.values(),\n ]);\n this.transportPromises.clear();\n this.transports.clear();\n this.listenTransportPromises.clear();\n this.listenTransports.clear();\n this.multiListenTransportPromises.clear();\n\n const transports = [...this.retainedTransports];\n this.retainedTransports.clear();\n\n for (const transport of transports) {\n if (releaseTransport(transport) > 0) continue;\n\n evictCachedTransport(transport);\n\n try {\n if (graceful && typeof transport.close === \"function\") {\n await transport.close();\n } else if (typeof transport.destroy === \"function\") {\n await transport.destroy();\n } else if (typeof transport.close === \"function\") {\n await transport.close();\n }\n } catch (err) {\n this.log(\"error\", \"[HyperCore] Error closing transport during destroy\", err);\n }\n }\n this.state = \"destroyed\";\n }\n}\n"],
|
|
5
|
-
"mappings": ";AA2BA,SAAS,iBAAAA,SAAqB;AAC9B,SAAS,qBAAAC,SAAyB;AAClC,SAAS,mBAAAC,GAAiB,mBAAAC,SAAuB;AACjD,SACE,wBAAAC,GACA,oBAAAC,GACA,gCAAAC,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GAC3B,KAAK,6BAA6B,MAAK;AAEvC,UAAMjB,IAAa,CAAC,GAAG,KAAK,kBAAkB;AAC9C,SAAK,mBAAmB,MAAK;AAE7B,eAAW3E,KAAa2E;AACtB,UAAI,EAAA1E,EAAiBD,CAAS,IAAI,IAElC;QAAAX,EAAqBW,CAAS;AAE9B,YAAI;AACF,UAAIqG,KAAY,OAAOrG,EAAU,SAAU,aACzC,MAAMA,EAAU,MAAK,IACZ,OAAOA,EAAU,WAAY,aACtC,MAAMA,EAAU,QAAO,IACd,OAAOA,EAAU,SAAU,cACpC,MAAMA,EAAU,MAAK;QAEzB,SAAS4D,GAAK;AACZ,eAAK,IAAI,SAAS,sDAAsDA,CAAG;QAC7E;;AAEF,SAAK,QAAQ;EACf;;",
|
|
6
|
-
"names": ["dynamicImport", "defaultCoreConfig", "KNOWN_PROTOCOLS", "resolveProtocol", "evictCachedTransport", "resolveTransport", "resolveTransportForProtocols", "HyperClientError", "requestCounter", "requestIdBase", "PLUGIN_PHASE_ORDER", "createRequestId", "transportRefs", "pluginOwners", "retainTransport", "transport", "releaseTransport", "next", "DefaultRequestContext", "callback", "response", "outcome", "report", "callbacks", "error", "signal", "value", "createRequestContext", "req", "createServerRequestContext", "raw", "getRequestHeader", "headers", "name", "unsupportedProtocolResponse", "protocols", "isUniversalResponse", "DefaultProtocolRegistry", "protocol", "config", "sharedTransportPromises", "plugin", "i", "senders", "customSender", "receivers", "plugins", "registered", "factory", "namespaces", "sharedPromise", "sharedTransport", "sender", "receiver", "resolved", "ctor", "protocolName", "owner", "methods", "namespace", "method", "boundMethod", "args", "existing", "handler", "_target", "complete", "completion", "resolve", "ctx", "diagnostic", "currentReq", "hookRequests", "responseHooksStarted", "result", "err", "recovery", "recovered", "hookError", "responseError", "loaded", "initialResponse", "hookRequest", "snapshot", "customOnError", "handlerError", "level", "message", "meta", "requireListen", "transports", "transportPromises", "pending", "tracked", "key", "prepared", "options", "requested", "resolvedProtocols", "route", "onRequest", "currentRequest", "responseHooks", "initial", "errorHooks", "request", "serialized", "server", "closing", "resolvedPlugins", "module", "candidate", "a", "b", "sharedTransports", "base", "graceful"]
|
|
4
|
+
"sourcesContent": ["import type {\n AnyHyperSender,\n AnyHyperProtocol,\n AnyHyperReceiver,\n InferProtocolInput,\n HyperClientOptions,\n HyperPlugin,\n HyperProtocol,\n HyperProtocols,\n HyperReceiver,\n HyperSender,\n HyperServerListenOptions,\n HyperTransport,\n IHyperCore,\n PluginContext,\n ProtocolRegistry,\n RequestContext,\n RequestOutcome,\n ServerRequestOutcome,\n HyperProtocolName,\n SendRequest,\n ServerRequestContext,\n TransportRequest,\n TransportResponse,\n TransportServer,\n UniversalResponse,\n} from \"@hyperttp/types\";\nimport { dynamicImport } from \"../utils/modules.js\";\nimport { defaultCoreConfig } from \"../defaultConfig.js\";\nimport { KNOWN_PROTOCOLS, resolveProtocol } from \"../protocols/manager.js\";\nimport {\n evictCachedTransport,\n resolveTransport,\n resolveTransportForProtocols,\n} from \"../transports/manager.js\";\nimport { HyperClientError } from \"../utils/errors.js\";\n\nlet requestCounter = 0;\nlet requestIdBase = Date.now().toString(36) + \"-\";\n\nconst PLUGIN_PHASE_ORDER: Readonly<Record<string, number>> = Object.freeze({\n START: 0,\n PREPARE: 1,\n CONTROL: 2,\n FORMAT: 3,\n NETWORK: 4,\n DATA: 5,\n});\n\n/**\n * @ru Генерирует уникальный идентификатор запроса без аллокаций на каждый вызов:\n * базовый таймстемп пересчитывается при переполнении счётчика, а уникальность\n * обеспечивает инкрементальный битовый счётчик (общий для всех ядер).\n * @en Generates a unique request identifier without per-call allocations:\n * the base timestamp is recalculated when the counter wraps around, and uniqueness\n * is ensured by an incremental bitwise counter (shared across all cores).\n * @returns A compact unique string identifier.\n */\nfunction createRequestId(): string {\n requestCounter = (requestCounter + 1) >>> 0;\n if (requestCounter === 0) {\n requestIdBase = Date.now().toString(36) + \"-\";\n }\n return requestIdBase + (requestCounter >>> 0).toString(36);\n}\n\n/**\n * @ru Счётчик активных удержаний транспорта. Позволяет нескольким ядрам\n * (например, через `extend()`) разделять один транспорт, закрывая его только\n * после освобождения последней ссылки.\n * @en Active transport hold count. Lets multiple cores (e.g. via `extend()`)\n * share one transport, closing it only after the last reference is released.\n */\nconst transportRefs = new WeakMap<HyperTransport, number>();\nconst pluginOwners = new WeakMap<HyperPlugin, HyperCore>();\n\nfunction retainTransport(transport: HyperTransport): void {\n transportRefs.set(transport, (transportRefs.get(transport) ?? 0) + 1);\n}\n\nfunction releaseTransport(transport: HyperTransport): number {\n const next = (transportRefs.get(transport) ?? 1) - 1;\n if (next <= 0) {\n transportRefs.delete(transport);\n } else {\n transportRefs.set(transport, next);\n }\n return next;\n}\n\n/**\n * @ru Создаёт RequestContext на один цикл выполнения (prepare → send → parse).\n * `meta` и `state` инициализируются лениво при первом обращении, чтобы не\n * аллоцировать объекты для запросов, которые их не используют.\n * @en Creates a RequestContext for a single execution cycle (prepare → send → parse).\n * `meta` and `state` are initialized lazily on first access to avoid allocating\n * objects for requests that never use them.\n * @param req - The universal request being dispatched.\n * @returns A new RequestContext.\n */\nclass DefaultRequestContext implements RequestContext {\n public readonly requestId = createRequestId();\n public readonly startTime = performance.now();\n public readonly signal?: AbortSignal;\n private requestMeta?: Record<string, unknown>;\n private requestState?: Record<string, unknown>;\n private settlementCallbacks: ((outcome: RequestOutcome) => void | Promise<void>)[] = [];\n private finalized = false;\n private acceptedResponse?: UniversalResponse;\n\n public onSettled(callback: (outcome: RequestOutcome) => void | Promise<void>): void {\n if (this.finalized) throw new Error(\"[HyperCore] Request settlement has already started.\");\n this.settlementCallbacks.push(callback);\n }\n\n public acceptFinalResponse<T>(response: UniversalResponse<T>): UniversalResponse<T> {\n if (this.finalized) throw new Error(\"[HyperCore] Request has already settled.\");\n this.acceptedResponse = response;\n return response;\n }\n\n public isFinalResponse(response: UniversalResponse): boolean {\n return this.acceptedResponse === response;\n }\n\n public async settle(outcome: RequestOutcome, report: (error: unknown) => void): Promise<void> {\n if (this.finalized) return;\n this.finalized = true;\n const callbacks = this.settlementCallbacks;\n this.settlementCallbacks = [];\n for (const callback of callbacks) {\n try {\n await callback(outcome);\n } catch (error) {\n report(error);\n }\n }\n }\n\n constructor(signal?: AbortSignal) {\n this.signal = signal;\n }\n\n public get meta(): Record<string, unknown> {\n return (this.requestMeta ??= {});\n }\n\n public set meta(value: Record<string, unknown>) {\n this.requestMeta = value;\n }\n\n public get state(): Record<string, unknown> {\n return (this.requestState ??= {});\n }\n\n public set state(value: Record<string, unknown>) {\n this.requestState = value;\n }\n}\n\nfunction createRequestContext(req: SendRequest<unknown, string>): DefaultRequestContext {\n return new DefaultRequestContext(req.signal);\n}\n\n/**\n * @ru Создаёт ServerRequestContext на один серверный цикл (receive → handle → respond).\n * `meta` и `state` инициализируются лениво, как и в клиентском контексте.\n * @en Creates a ServerRequestContext for a single server cycle (receive → handle → respond).\n * `meta` and `state` are initialized lazily, like in the client context.\n * @param raw - The raw transport request being received.\n * @returns A new ServerRequestContext.\n */\nfunction createServerRequestContext(raw: TransportRequest): ServerRequestContext {\n return new DefaultRequestContext(raw.signal) as ServerRequestContext;\n}\n\nfunction getRequestHeader(\n headers: Readonly<Record<string, string | string[]>>,\n name: string,\n): string | undefined {\n const value = headers[name] ?? headers[name.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n}\n\nfunction unsupportedProtocolResponse(protocols: readonly HyperProtocolName[]): TransportResponse {\n return {\n status: 415,\n statusText: \"Unsupported Media Type\",\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n body: new TextEncoder().encode(\n `Unsupported protocol. Expected one of: ${protocols.join(\", \")}.`,\n ),\n };\n}\n\n/**\n * @ru Проверяет, является ли значение UniversalResponse (а не SendRequest).\n * @en Checks whether the value is a UniversalResponse (rather than a SendRequest).\n * @param value - The value to inspect.\n * @returns True if the value carries response shape (data + status).\n */\nfunction isUniversalResponse(value: unknown): value is UniversalResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"data\" in value &&\n \"status\" in value &&\n !(\"input\" in value)\n );\n}\n\n/**\n * @ru Внутренний реестр протоколов: хранит единые модули (Sender + Receiver).\n * @en Internal protocol registry: stores unified modules (Sender + Receiver).\n */\nclass DefaultProtocolRegistry implements ProtocolRegistry {\n private readonly protocols = new Map<HyperProtocolName, AnyHyperProtocol>();\n\n public register<P extends HyperProtocolName>(protocol: AnyHyperProtocol<P>): void {\n this.protocols.set(protocol.protocol, protocol);\n }\n\n public get<P extends HyperProtocolName>(\n protocol: P,\n ): HyperProtocol<unknown, unknown, unknown, unknown, P> | undefined {\n return this.protocols.get(protocol) as\n | HyperProtocol<unknown, unknown, unknown, unknown, P>\n | undefined;\n }\n\n public has(protocol: HyperProtocolName): boolean {\n return this.protocols.has(protocol);\n }\n\n public get size(): number {\n return this.protocols.size;\n }\n}\n\n// oxlint-disable-next-line no-unsafe-declaration-merging\nexport interface HyperCore extends HyperProtocols {}\n\n/**\n * @ru Универсальное ядро v2.0.0. Протокол-независимый диспетчер: регистрирует\n * единые модули протоколов (Sender + Receiver), выполняет клиентский цикл\n * prepare → send → parse и серверный цикл receive → handle → respond через\n * физический транспорт, а также прогоняет хуки плагинов.\n * @en Universal core v2.0.0. Protocol-agnostic dispatcher: registers unified\n * protocol modules (Sender + Receiver), runs the client cycle prepare → send → parse\n * and the server cycle receive → handle → respond through the physical transport,\n * and executes plugin hooks.\n */\nexport class HyperCore implements IHyperCore {\n public readonly config: HyperClientOptions;\n\n private readonly registry = new DefaultProtocolRegistry();\n private readonly pluginCtx: PluginContext;\n private plugins: HyperPlugin[] = [];\n private readonly servers = new Set<TransportServer>();\n private readonly pendingListeners = new Set<Promise<TransportServer>>();\n private readonly flatMethodOwners = new Map<string, string>();\n private readonly flatMethodValues = new Map<string, unknown>();\n private readonly protocolNamespaces = new Set<string>();\n private readonly generatedFlatMethods = new Set<string>();\n private readonly transportPromises = new Map<HyperProtocolName, Promise<HyperTransport>>();\n private readonly transports = new Map<HyperProtocolName, HyperTransport>();\n private readonly listenTransportPromises = new Map<HyperProtocolName, Promise<HyperTransport>>();\n private readonly listenTransports = new Map<HyperProtocolName, HyperTransport>();\n private readonly multiListenTransportPromises = new Map<string, Promise<HyperTransport>>();\n private readonly retainedTransports = new Set<HyperTransport>();\n private readonly fixedTransport: HyperTransport | null;\n private destroyPromise: Promise<void> | null = null;\n private state: \"initializing\" | \"running\" | \"destroying\" | \"destroyed\" = \"initializing\";\n private readonly activeRequests = new Set<Promise<void>>();\n\n private get isDestroyed(): boolean {\n return this.state === \"destroying\" || this.state === \"destroyed\";\n }\n\n constructor(\n config: Partial<HyperClientOptions> = {},\n transport?: HyperTransport,\n sharedTransportPromises?: ReadonlyMap<HyperProtocolName, Promise<HyperTransport>>,\n ) {\n this.config = {\n ...defaultCoreConfig,\n ...config,\n retry: {\n ...defaultCoreConfig.retry,\n ...config.retry,\n },\n };\n this.fixedTransport = transport ?? null;\n this.pluginCtx = { config: this.config, core: this };\n\n for (const plugin of this.config.plugins ?? []) {\n if (typeof plugin !== \"string\" && !plugin.shared && pluginOwners.has(plugin)) {\n throw new HyperClientError(\n \"[HyperCore] Plugin instances cannot be shared across cores. Supply fresh plugins when extending or creating a core.\",\n );\n }\n }\n\n const protocols = this.config.protocols;\n if (protocols) {\n for (let i = 0; i < protocols.length; i++) {\n this.registerProtocol(protocols[i]!);\n }\n }\n\n const senders = this.config.senders;\n if (senders) {\n for (let i = 0; i < senders.length; i++) {\n this.registerSender(senders[i]!);\n }\n }\n\n const customSender = this.config.customSender;\n if (customSender) {\n this.registerSender(customSender);\n }\n\n const receivers = this.config.receivers;\n if (receivers) {\n for (let i = 0; i < receivers.length; i++) {\n this.registerReceiver(receivers[i]!);\n }\n }\n\n const plugins = this.config.plugins;\n if (plugins) {\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i]!;\n if (typeof plugin === \"string\") {\n throw new HyperClientError(\n `[HyperCore] Plugin module \"${plugin}\" cannot be loaded by the synchronous constructor. Import it and pass the plugin instance instead.`,\n );\n }\n try {\n this.use(plugin);\n } catch (error) {\n for (const registered of this.plugins) pluginOwners.delete(registered);\n throw error;\n }\n }\n }\n\n try {\n for (const factory of this.config.pluginFactories ?? []) this.use(factory());\n } catch (error) {\n for (const registered of this.plugins) {\n if (pluginOwners.get(registered) === this) pluginOwners.delete(registered);\n }\n throw error;\n }\n\n const namespaces = this as unknown as Record<string, unknown>;\n for (let i = 0; i < KNOWN_PROTOCOLS.length; i++) {\n const protocol = KNOWN_PROTOCOLS[i]!;\n if (!this.registry.has(protocol) && namespaces[protocol] === undefined) {\n namespaces[protocol] = this.createLazyNamespace(protocol);\n this.protocolNamespaces.add(protocol);\n }\n }\n if (transport && !this.retainedTransports.has(transport)) {\n retainTransport(transport);\n this.retainedTransports.add(transport);\n }\n if (sharedTransportPromises) {\n for (const [protocol, sharedPromise] of sharedTransportPromises) {\n this.transportPromises.set(\n protocol,\n sharedPromise.then((sharedTransport) =>\n this.retainResolvedTransport(protocol, sharedTransport),\n ),\n );\n }\n }\n this.state = \"running\";\n }\n\n /**\n * @ru Получает зарегистрированный модуль протокола (Sender + Receiver).\n * @en Gets a registered protocol module (Sender + Receiver).\n */\n public getProtocol<P extends HyperProtocolName>(\n protocol: P,\n ): HyperProtocol<unknown, unknown, unknown, unknown, P> | undefined {\n return this.registry.get(protocol);\n }\n\n /**\n * @ru Получает зарегистрированный сендер протокола.\n * @en Gets a registered protocol sender.\n */\n public getSender<P extends HyperProtocolName>(\n protocol: P,\n ): HyperSender<unknown, unknown, unknown, unknown, P> | undefined {\n return this.registry.get(protocol)?.sender;\n }\n\n /**\n * @ru Получает зарегистрированный ресивер протокола.\n * @en Gets a registered protocol receiver.\n */\n public getReceiver<P extends HyperProtocolName>(\n protocol: P,\n ): HyperReceiver<unknown, unknown, unknown, unknown, P> | undefined {\n return this.registry.get(protocol)?.receiver;\n }\n\n /**\n * @ru Возвращает имя текущего транспорта.\n * @en Returns the name of the current transport.\n * @returns Transport constructor name.\n */\n public async getTransportName(): Promise<string> {\n this.assertRunning();\n const t = await this.acquireTransport();\n return t.constructor.name;\n }\n\n /**\n * @ru Возвращает имя сендера протокола (по умолчанию — \"rest\").\n * Протокол резолвится лениво, если ещё не зарегистрирован.\n * @en Returns the sender constructor name for a protocol (default \"rest\").\n * The protocol is resolved lazily if not registered yet.\n * @param protocol - The protocol to inspect.\n * @returns Sender constructor name.\n */\n public async getSenderName(protocol: HyperProtocolName = \"rest\"): Promise<string> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n const sender = resolved.sender;\n if (!sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n return sender.constructor.name;\n }\n\n /**\n * @ru Возвращает имя ресивера протокола (по умолчанию — \"rest\").\n * Протокол резолвится лениво, если ещё не зарегистрирован.\n * @en Returns the receiver constructor name for a protocol (default \"rest\").\n * The protocol is resolved lazily if not registered yet.\n * @param protocol - The protocol to inspect.\n * @returns Receiver constructor name.\n */\n public async getReceiverName(protocol: HyperProtocolName = \"rest\"): Promise<string> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n const receiver = resolved.receiver;\n if (!receiver) {\n throw new HyperClientError(\n `[HyperCore] Protocol \"${protocol}\" has no receiver (server role).`,\n );\n }\n return receiver.constructor.name;\n }\n\n /**\n * @ru Возвращает имя модуля протокола (по умолчанию — \"rest\"): предпочитает\n * `name`, затем `constructor.name`, затем идентификатор протокола.\n * Протокол резолвится лениво, если ещё не зарегистрирован.\n * @en Returns the protocol module name (default \"rest\"): prefers `name`, then\n * `constructor.name`, then the protocol identifier.\n * The protocol is resolved lazily if not registered yet.\n * @param protocol - The protocol to inspect.\n * @returns The protocol module display name.\n */\n public async getProtocolName(protocol: HyperProtocolName = \"rest\"): Promise<string> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n if (resolved.name) return resolved.name;\n const ctor = resolved.constructor;\n return ctor && ctor.name && ctor.name !== \"Object\" ? ctor.name : String(resolved.protocol);\n }\n\n /**\n * @ru Регистрирует единый модуль протокола и раскрывает методы его сендера\n * на ядре (например, `core.rest` для REST).\n * @en Registers a unified protocol module and exposes its sender methods on the\n * core (e.g., `core.rest` for REST).\n * @param protocol - The protocol module to register.\n * @returns This instance for chaining.\n */\n public registerProtocol<P extends HyperProtocolName>(protocol: AnyHyperProtocol<P>): this {\n this.assertActive();\n const protocolName = String(protocol.protocol);\n const namespaces = this as unknown as Record<string, unknown>;\n const isReserved =\n protocolName === \"__proto__\" ||\n protocolName === \"prototype\" ||\n protocolName === \"constructor\" ||\n protocolName in HyperCore.prototype ||\n (protocolName in this && !this.protocolNamespaces.has(protocolName));\n\n if (isReserved) {\n throw new HyperClientError(\n `[HyperCore] Protocol name \"${protocolName}\" conflicts with the core API.`,\n );\n }\n\n for (const [name, owner] of this.flatMethodOwners) {\n if (owner === protocolName) {\n if (\n Object.getOwnPropertyDescriptor(this, name)?.value === this.flatMethodValues.get(name)\n ) {\n delete namespaces[name];\n }\n this.flatMethodValues.delete(name);\n this.flatMethodOwners.delete(name);\n this.generatedFlatMethods.delete(name);\n }\n }\n if (this.protocolNamespaces.has(protocolName)) {\n delete namespaces[protocolName];\n this.protocolNamespaces.delete(protocolName);\n }\n this.registry.register(protocol);\n\n const methods = protocol.sender?.methods;\n if (methods && typeof methods === \"object\") {\n const namespace: Record<string, unknown> = Object.create(null);\n\n for (const name in methods) {\n if (!Object.hasOwn(methods, name)) continue;\n\n const method = methods[name] as ((...args: unknown[]) => unknown) | undefined;\n if (typeof method !== \"function\") continue;\n\n const boundMethod = (...args: unknown[]) => method.apply(methods, [this, ...args]);\n namespace[name] = boundMethod;\n\n const stillGenerated =\n this.generatedFlatMethods.has(name) &&\n Object.getOwnPropertyDescriptor(this, name)?.value === this.flatMethodValues.get(name);\n if (stillGenerated) {\n namespaces[name] = boundMethod;\n this.flatMethodOwners.set(name, protocolName);\n this.flatMethodValues.set(name, boundMethod);\n } else if (!(name in HyperCore.prototype) && !(name in this)) {\n namespaces[name] = boundMethod;\n this.generatedFlatMethods.add(name);\n this.flatMethodOwners.set(name, protocolName);\n this.flatMethodValues.set(name, boundMethod);\n }\n }\n\n namespaces[protocolName] = namespace;\n this.protocolNamespaces.add(protocolName);\n }\n\n return this;\n }\n\n /**\n * @ru Регистрирует сендер протокола, оборачивая его в модуль протокола.\n * Существующий ресивер того же протокола сохраняется.\n * @en Registers a protocol sender, wrapping it into a protocol module.\n * An existing receiver for the same protocol is preserved.\n * @param sender - The protocol sender to register.\n * @returns This instance for chaining.\n */\n public registerSender<P extends HyperProtocolName>(sender: AnyHyperSender<P>): this {\n const existing = this.registry.get(sender.protocol);\n return this.registerProtocol({\n protocol: sender.protocol,\n sender,\n receiver: existing?.receiver,\n });\n }\n\n /**\n * @ru Регистрирует ресивер протокола, оборачивая его в модуль протокола.\n * Существующий сендер того же протокола сохраняется.\n * @en Registers a protocol receiver, wrapping it into a protocol module.\n * An existing sender for the same protocol is preserved.\n * @param receiver - The protocol receiver to register.\n * @returns This instance for chaining.\n */\n public registerReceiver<P extends HyperProtocolName>(receiver: AnyHyperReceiver<P>): this {\n const existing = this.registry.get(receiver.protocol);\n return this.registerProtocol({\n protocol: receiver.protocol,\n sender: existing?.sender,\n receiver,\n });\n }\n\n /**\n * @ru Создаёт ленивый namespace методов протокола: методы доступны ещё до\n * регистрации протокола и резолвятся по требованию при первом вызове.\n * @en Creates a lazy protocol methods namespace: methods are reachable before\n * the protocol is registered and are resolved on first call.\n * @param protocol - The protocol to expose lazily.\n * @returns A Proxy that dispatches method calls to the resolved protocol sender.\n */\n private createLazyNamespace(protocol: HyperProtocolName): Record<string, unknown> {\n const handler: ProxyHandler<Record<string, unknown>> = {\n get: (_target, name) => {\n if (typeof name !== \"string\" || name === \"then\") return undefined;\n return (...args: unknown[]) => this.dispatchLazyMethod(protocol, name, args);\n },\n };\n return new Proxy({}, handler);\n }\n\n /**\n * @ru Разрешает протокол по требованию и вызывает метод `methods`-поверхности\n * его сендера, биндя ядро первым аргументом.\n * @en Resolves the protocol on demand and calls a method on its sender\n * `methods` surface, binding the core as the first argument.\n * @param protocol - The protocol identifier.\n * @param name - The method name on the sender surface.\n * @param args - Arguments forwarded after the core instance.\n * @returns The result of the sender method call.\n */\n private async dispatchLazyMethod(\n protocol: HyperProtocolName,\n name: string,\n args: unknown[],\n ): Promise<unknown> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n\n const sender = resolved.sender;\n if (!sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n\n const methods = sender.methods as\n | Record<string, (...callArgs: unknown[]) => unknown>\n | undefined;\n const method = methods && Object.hasOwn(methods, name) ? methods[name] : undefined;\n if (typeof method !== \"function\") {\n throw new TypeError(`[HyperCore] Protocol \"${protocol}\" has no method \"${name}\".`);\n }\n return method.apply(methods, [this, ...args]);\n }\n\n /**\n * @ru Основной метод диспетчеризации: выбирает сендер по протоколу и выполняет\n * трёхфазный цикл с поддержкой плагинов.\n * @en Main dispatch method: resolves the sender by protocol and runs the three-phase\n * cycle with plugin support.\n * @param req - The universal request envelope.\n * @returns A promise resolving to the normalized universal response.\n */\n public send<TOutput = unknown, P extends HyperProtocolName = HyperProtocolName>(\n req: SendRequest<InferProtocolInput<P>, P>,\n ): Promise<UniversalResponse<TOutput>>;\n public send<TInput = unknown, TOutput = unknown, P extends HyperProtocolName = HyperProtocolName>(\n req: SendRequest<TInput, P>,\n ): Promise<UniversalResponse<TOutput>>;\n public async send<TInput = unknown, TOutput = unknown, P extends string = string>(\n req: SendRequest<TInput, P>,\n ): Promise<UniversalResponse<TOutput>> {\n this.assertRunning();\n let complete!: () => void;\n const completion = new Promise<void>((resolve) => {\n complete = resolve;\n });\n this.activeRequests.add(completion);\n const ctx = createRequestContext(req as SendRequest<unknown, string>);\n try {\n const response = await this.executeRequest<TInput, TOutput, P>(req, ctx);\n await ctx.settle({ ok: true, response }, (error) =>\n this.log(\"error\", \"[HyperCore] Settlement callback failed\", error),\n );\n return response;\n } catch (error) {\n await ctx.settle({ ok: false, error }, (diagnostic) =>\n this.log(\"error\", \"[HyperCore] Settlement callback failed\", diagnostic),\n );\n throw error;\n } finally {\n complete();\n this.activeRequests.delete(completion);\n }\n }\n\n private async executeRequest<TInput, TOutput, P extends string>(\n req: SendRequest<TInput, P>,\n ctx: DefaultRequestContext,\n ): Promise<UniversalResponse<TOutput>> {\n const plugins = this.plugins;\n let currentReq = req as SendRequest<any, any>;\n const hookRequests = new Map<HyperPlugin, SendRequest<any, any>>();\n let responseHooksStarted = false;\n\n if (plugins.length === 0) {\n const sender = this.registry.get(req.protocol)?.sender;\n if (sender) {\n return this.runSender<TInput, TOutput>(sender, req as SendRequest<TInput, string>, ctx);\n }\n }\n\n try {\n let response: UniversalResponse<TOutput> | undefined;\n\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i]!;\n if (typeof plugin.onRequest !== \"function\") continue;\n\n hookRequests.set(plugin, currentReq);\n const result = await plugin.onRequest(currentReq, this.pluginCtx, ctx);\n if (result == null) continue;\n\n if (isUniversalResponse(result)) {\n response = result as UniversalResponse<TOutput>;\n break;\n }\n\n currentReq = result as SendRequest<any, any>;\n (ctx as { signal?: AbortSignal }).signal = currentReq.signal;\n }\n\n if (!response) {\n const sender = await this.resolveRequestSender(currentReq.protocol);\n response = await this.runSender<unknown, TOutput>(sender, currentReq, ctx);\n }\n\n if (ctx.isFinalResponse(response)) return response;\n responseHooksStarted = true;\n return await this.runResponseHooks(response, currentReq, ctx, plugins, hookRequests);\n } catch (err) {\n let recovery: UniversalResponse<TOutput> | undefined;\n for (const plugin of plugins) {\n if (typeof plugin.onError !== \"function\") continue;\n try {\n const recovered = await plugin.onError(\n err,\n hookRequests.get(plugin) ?? currentReq,\n this.pluginCtx,\n ctx,\n );\n if (!recovery && recovered != null && isUniversalResponse(recovered)) {\n recovery = recovered as UniversalResponse<TOutput>;\n }\n } catch (hookError) {\n this.log(\"error\", \"[HyperCore] Error hook failed\", hookError);\n }\n }\n if (recovery) {\n // A response-hook failure already triggered cleanup; do not repeat those hooks.\n if (responseHooksStarted) return recovery;\n try {\n return await this.runResponseHooks(recovery, currentReq, ctx, plugins, hookRequests);\n } catch (responseError) {\n // Report the new failure and finish cleanup without starting another recovery cycle.\n for (const plugin of plugins) {\n if (typeof plugin.onError !== \"function\") continue;\n try {\n await plugin.onError(\n responseError,\n hookRequests.get(plugin) ?? currentReq,\n this.pluginCtx,\n ctx,\n );\n } catch (hookError) {\n this.log(\"error\", \"[HyperCore] Error hook failed\", hookError);\n }\n }\n throw responseError;\n }\n }\n throw err;\n }\n }\n\n private assertRunning(): void {\n if (this.state === \"initializing\") {\n throw new HyperClientError(\n \"[HyperCore] Operations cannot start during setup initialization.\",\n );\n }\n this.assertActive();\n }\n\n private assertActive(): void {\n if (this.isDestroyed) {\n throw new HyperClientError(\"[HyperCore] Core instance has been destroyed.\");\n }\n }\n\n private async resolveRegisteredProtocol<P extends HyperProtocolName>(\n protocol: P,\n ): Promise<AnyHyperProtocol<P>> {\n this.assertActive();\n const existing = this.registry.get(protocol);\n if (existing) return existing;\n const loaded = await resolveProtocol(protocol);\n this.assertActive();\n // Explicit registration during the import has priority over its late result.\n const registered = this.registry.get(protocol);\n if (registered) return registered;\n this.registerProtocol(loaded);\n return loaded;\n }\n\n private async resolveRequestSender(\n protocol: HyperProtocolName,\n ): Promise<HyperSender<any, any, any, any>> {\n const resolved = await this.resolveRegisteredProtocol(protocol);\n\n const sender = resolved.sender;\n if (!sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n return sender;\n }\n\n private async runResponseHooks<TOutput>(\n initialResponse: UniversalResponse<TOutput>,\n req: SendRequest<any, any>,\n ctx: RequestContext,\n plugins: readonly HyperPlugin[],\n hookRequests: ReadonlyMap<HyperPlugin, SendRequest<any, any>>,\n ): Promise<UniversalResponse<TOutput>> {\n let response = initialResponse;\n\n for (let i = 0; i < plugins.length; i++) {\n const plugin = plugins[i]!;\n if (typeof plugin.onResponse !== \"function\") continue;\n\n const hookRequest = hookRequests.get(plugin) ?? req;\n if (plugin.mode === \"background\") {\n const snapshot = { ...response, headers: { ...response.headers } };\n void Promise.resolve()\n .then(() => plugin.onResponse!(snapshot, hookRequest, this.pluginCtx, ctx))\n .catch((err: unknown) => this.reportBackgroundPluginError(err));\n continue;\n }\n\n const result = await plugin.onResponse(response, hookRequest, this.pluginCtx, ctx);\n if (result != null && isUniversalResponse(result)) {\n response = result as UniversalResponse<TOutput>;\n }\n }\n\n return response;\n }\n\n private reportBackgroundPluginError(err: unknown): void {\n const customOnError = (this.config as Record<string, unknown>).onError;\n if (typeof customOnError === \"function\") {\n try {\n (customOnError as (error: unknown) => void)(err);\n return;\n } catch (handlerError) {\n this.log(\"error\", \"[HyperCore] Background error handler failed\", handlerError);\n }\n }\n this.log(\"error\", \"[HyperCore] Background plugin error\", err);\n }\n\n private log(level: \"debug\" | \"info\" | \"warn\" | \"error\", message: string, meta?: unknown): void {\n try {\n if (this.config.logger) {\n this.config.logger(level, message, meta);\n return;\n }\n if (!this.config.verbose && level !== \"error\") return;\n const output = level === \"debug\" ? console.debug : console[level];\n output(message, meta);\n } catch {\n // Diagnostics must never interrupt lifecycle cleanup.\n }\n }\n\n /**\n * @ru Атомарно получает транспорт для конкретного протокола и удерживает\n * каждый физический экземпляр ровно один раз за время жизни ядра.\n * @en Atomically acquires a transport for a protocol and retains each physical\n * instance exactly once for the lifetime of this core.\n */\n private async acquireTransport(\n protocol: HyperProtocolName = \"rest\",\n requireListen = false,\n ): Promise<HyperTransport> {\n if (this.isDestroyed) {\n throw new HyperClientError(\n \"[HyperCore] Cannot acquire transport on a destroyed core instance.\",\n );\n }\n\n const transports = requireListen ? this.listenTransports : this.transports;\n const transportPromises = requireListen ? this.listenTransportPromises : this.transportPromises;\n const existing = transports.get(protocol);\n if (existing) return existing;\n\n let pending = transportPromises.get(protocol);\n if (!pending) {\n pending = this.resolveAndRetainTransport(protocol, requireListen);\n let tracked!: Promise<HyperTransport>;\n tracked = pending.catch((err: unknown) => {\n if (transportPromises.get(protocol) === tracked) {\n transportPromises.delete(protocol);\n }\n throw err;\n });\n transportPromises.set(protocol, tracked);\n pending = tracked;\n }\n\n const transport = await pending;\n if (this.isDestroyed) {\n throw new HyperClientError(\n \"[HyperCore] Core instance was destroyed while resolving transport.\",\n );\n }\n\n return transport;\n }\n\n /**\n * @ru Получает один транспорт, поддерживающий все запрошенные протоколы.\n * Это позволяет открыть один listener на порт для REST и gRPC.\n * @en Acquires one transport supporting every requested protocol. This lets\n * REST and gRPC share a single listener on one port.\n */\n private async acquireListenTransport(\n protocols: readonly HyperProtocolName[],\n ): Promise<HyperTransport> {\n if (this.isDestroyed) {\n throw new HyperClientError(\n \"[HyperCore] Cannot acquire transport on a destroyed core instance.\",\n );\n }\n\n for (const transport of this.listenTransports.values()) {\n if (this.transportSupportsAll(transport, protocols)) return transport;\n }\n\n const key = JSON.stringify([...protocols].sort());\n let pending = this.multiListenTransportPromises.get(key);\n if (!pending) {\n let tracked!: Promise<HyperTransport>;\n tracked = this.resolveListenTransport(protocols).finally(() => {\n if (this.multiListenTransportPromises.get(key) === tracked) {\n this.multiListenTransportPromises.delete(key);\n }\n });\n this.multiListenTransportPromises.set(key, tracked);\n pending = tracked;\n }\n\n return pending;\n }\n\n private async resolveListenTransport(\n protocols: readonly HyperProtocolName[],\n ): Promise<HyperTransport> {\n const { protocols: _, ...transportConfig } = this.config;\n const transport =\n this.fixedTransport && typeof this.fixedTransport.listen === \"function\"\n ? this.fixedTransport\n : await resolveTransportForProtocols(protocols, {\n ...transportConfig,\n cacheKey: this.config,\n customTransport: this.fixedTransport ?? this.config.customTransport,\n requireListen: true,\n logger: this.config.logger,\n verbose: this.config.verbose,\n });\n\n if (!this.transportSupportsAll(transport, protocols)) {\n throw new HyperClientError(\n `[HyperCore] Transport \"${transport.constructor.name}\" does not support protocols ${protocols.map((protocol) => `\"${protocol}\"`).join(\", \")}.`,\n );\n }\n\n for (const protocol of protocols) {\n this.retainResolvedTransport(protocol, transport, true);\n }\n return transport;\n }\n\n private transportSupportsAll(\n transport: HyperTransport,\n protocols: readonly HyperProtocolName[],\n ): boolean {\n return protocols.every((protocol) =>\n typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true),\n );\n }\n\n private routeServerRequest(\n protocols: readonly HyperProtocolName[],\n raw: TransportRequest,\n ): HyperProtocolName | undefined {\n const contentType = getRequestHeader(raw.headers, \"content-type\") ?? \"\";\n if (contentType.startsWith(\"application/grpc\") && protocols.includes(\"grpc\")) {\n return \"grpc\";\n }\n if (raw.protocol && protocols.includes(raw.protocol)) return raw.protocol;\n if (protocols.length === 1) return protocols[0];\n if (protocols.includes(\"rest\")) return \"rest\";\n return undefined;\n }\n\n private async resolveAndRetainTransport(\n protocol: HyperProtocolName,\n requireListen = false,\n ): Promise<HyperTransport> {\n const transport =\n this.fixedTransport && (!requireListen || typeof this.fixedTransport.listen === \"function\")\n ? this.fixedTransport\n : await resolveTransport(protocol, {\n ...this.config,\n cacheKey: this.config,\n customTransport: this.fixedTransport ?? this.config.customTransport,\n requireListen,\n logger: this.config.logger,\n verbose: this.config.verbose,\n });\n const supportsProtocol =\n typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true);\n\n if (!supportsProtocol) {\n throw new HyperClientError(\n `[HyperCore] Transport \"${transport.constructor.name}\" does not support protocol \"${protocol}\".`,\n );\n }\n\n return this.retainResolvedTransport(protocol, transport, requireListen);\n }\n\n private retainResolvedTransport(\n protocol: HyperProtocolName,\n transport: HyperTransport,\n requireListen = false,\n ): HyperTransport {\n if (!this.retainedTransports.has(transport)) {\n retainTransport(transport);\n this.retainedTransports.add(transport);\n }\n\n (requireListen ? this.listenTransports : this.transports).set(protocol, transport);\n return transport;\n }\n\n /**\n * @ru Выполняет ядро цикла запроса: prepare → send → parse через физический\n * транспорт. Транспорт получается через `acquireTransport()`.\n * @en Runs the core request cycle: prepare → send → parse through the physical\n * transport. The transport is acquired via `acquireTransport()`.\n * @param sender - The resolved protocol sender.\n * @param req - The (possibly plugin-modified) universal request.\n * @param ctx - The per-request execution context.\n * @returns The normalized universal response.\n */\n private async runSender<TInput, TOutput>(\n sender: HyperSender<any, any, any, any>,\n req: SendRequest<TInput, string>,\n ctx: RequestContext,\n ): Promise<UniversalResponse<TOutput>> {\n this.assertActive();\n const transport =\n this.transports.get(req.protocol) ?? (await this.acquireTransport(req.protocol));\n const prepared = sender.prepare(req, ctx);\n const raw = await sender.send(prepared, transport, ctx);\n return sender.parse(raw, ctx) as UniversalResponse<TOutput>;\n }\n\n /**\n * @ru Запускает сервер для указанного протокола: связывает транспорт, ресивер и\n * application handler в цепочку receive → handle → respond.\n * @en Starts a server for the given protocol, wiring transport, receiver, and\n * application handler into the receive → handle → respond pipeline.\n * @template P - The protocol identifier.\n * @param options - The server listen options.\n * @returns A promise resolving to the transport server handle.\n */\n public async listen<P extends HyperProtocolName = HyperProtocolName>(\n options: HyperServerListenOptions<P>,\n ): Promise<TransportServer> {\n this.assertRunning();\n const pending = this.startListening(options);\n this.pendingListeners.add(pending);\n try {\n return await pending;\n } finally {\n this.pendingListeners.delete(pending);\n }\n }\n\n private async startListening<P extends HyperProtocolName>(\n options: HyperServerListenOptions<P>,\n ): Promise<TransportServer> {\n const requested = options.protocols?.length\n ? options.protocols\n : options.protocol\n ? [options.protocol]\n : [];\n if (requested.length === 0) {\n throw new HyperClientError(\n \"[HyperCore] listen() requires a protocol or a non-empty protocols array.\",\n );\n }\n const protocols = [...new Set(requested)];\n\n const transport = await this.acquireListenTransport(protocols);\n\n if (typeof transport.listen !== \"function\") {\n throw new HyperClientError(\n `[HyperCore] Transport \"${transport.constructor.name}\" does not support listen() (server role).`,\n );\n }\n\n const resolvedProtocols = await Promise.all(\n protocols.map((protocol) => this.resolveRegisteredProtocol(protocol)),\n );\n const receivers = new Map<HyperProtocolName, AnyHyperReceiver>();\n for (let i = 0; i < protocols.length; i++) {\n const receiver = resolvedProtocols[i]?.receiver;\n if (!receiver) {\n throw new HyperClientError(\n `[HyperCore] Protocol \"${protocols[i]}\" has no receiver (server role).`,\n );\n }\n receivers.set(protocols[i]!, receiver);\n }\n\n const handler = options.handler as\n | ((request: unknown, ctx: ServerRequestContext) => unknown)\n | undefined;\n const route = options.route;\n\n const onRequest = async (raw: TransportRequest): Promise<TransportResponse> => {\n const protocol = route?.(raw) ?? this.routeServerRequest(protocols, raw);\n if (!protocol || !receivers.has(protocol)) {\n return unsupportedProtocolResponse(protocols);\n }\n const receiver = receivers.get(protocol)!;\n const ctx = Object.assign(createServerRequestContext(raw), { protocol });\n const plugins = this.plugins;\n let currentRequest = raw;\n let outcome: ServerRequestOutcome;\n let responseHooksStarted = false;\n const responseHooks = async (initial: TransportResponse): Promise<TransportResponse> => {\n let response = initial;\n for (const plugin of plugins) {\n const result = await plugin.onServerResponse?.(\n response,\n currentRequest,\n this.pluginCtx,\n ctx,\n );\n if (result !== undefined) response = result;\n }\n return response;\n };\n const errorHooks = async (error: unknown): Promise<TransportResponse | undefined> => {\n let recovery: TransportResponse | undefined;\n for (const plugin of plugins) {\n try {\n const result = await plugin.onServerError?.(error, currentRequest, this.pluginCtx, ctx);\n if (recovery === undefined && result !== undefined) recovery = result;\n } catch (diagnostic) {\n this.log(\"error\", \"[HyperCore] Server error hook failed\", diagnostic);\n }\n }\n return recovery;\n };\n try {\n for (const plugin of plugins) {\n const result = await plugin.onServerRequest?.(currentRequest, this.pluginCtx, ctx);\n if (result !== undefined) {\n currentRequest = result;\n (ctx as { signal?: AbortSignal }).signal = currentRequest.signal;\n }\n }\n const request = await receiver.receive(currentRequest, ctx);\n const response = handler\n ? await handler(request, ctx)\n : await receiver.handle(request, ctx);\n const serialized = await receiver.respond(response, ctx);\n responseHooksStarted = true;\n outcome = { ok: true, response: await responseHooks(serialized) };\n } catch (error) {\n const recovery = await errorHooks(error);\n if (recovery === undefined) outcome = { ok: false, error };\n else if (responseHooksStarted) outcome = { ok: true, response: recovery };\n else {\n try {\n outcome = { ok: true, response: await responseHooks(recovery) };\n } catch (responseError) {\n await errorHooks(responseError);\n outcome = { ok: false, error: responseError };\n }\n }\n }\n for (const plugin of plugins) {\n try {\n await plugin.onServerSettled?.(outcome, currentRequest, this.pluginCtx, ctx);\n } catch (diagnostic) {\n this.log(\"error\", \"[HyperCore] Server settlement hook failed\", diagnostic);\n }\n }\n if (!outcome.ok) throw outcome.error;\n return outcome.response;\n };\n\n const server = await transport.listen!({\n host: options.host,\n port: options.port,\n signal: options.signal,\n signaling: options.signaling,\n onRequest,\n });\n\n if (this.isDestroyed) {\n await server.close();\n throw new HyperClientError(\n \"[HyperCore] Core instance was destroyed while starting the server.\",\n );\n }\n\n let closing: Promise<void> | undefined;\n const tracked: TransportServer = {\n close: () => {\n closing ??= Promise.resolve()\n .then(() => server.close())\n .then(() => {\n this.servers.delete(tracked);\n });\n return closing;\n },\n };\n this.servers.add(tracked);\n return tracked;\n }\n\n /**\n * @ru Регистрирует плагин. Пропускает отключённые плагины.\n * @en Registers a plugin. Skips disabled plugins.\n * @param plugin - The plugin instance to register.\n * @returns This instance for chaining.\n */\n /**\n * Creates a core asynchronously and resolves plugin module paths before construction.\n */\n public static async create(config: Partial<HyperClientOptions> = {}): Promise<HyperCore> {\n const plugins = config.plugins;\n if (!plugins?.some((plugin) => typeof plugin === \"string\")) {\n return new HyperCore(config);\n }\n\n const resolvedPlugins: HyperPlugin[] = [];\n for (const plugin of plugins) {\n if (typeof plugin !== \"string\") {\n resolvedPlugins.push(plugin);\n continue;\n }\n const module = await dynamicImport(plugin);\n const candidate = module.default ?? module.plugin;\n if (!candidate || typeof candidate !== \"object\") {\n throw new HyperClientError(\n `[HyperCore] Plugin module \"${plugin}\" must export a plugin object as default or \"plugin\".`,\n );\n }\n resolvedPlugins.push(candidate as HyperPlugin);\n }\n\n return new HyperCore({ ...config, plugins: resolvedPlugins });\n }\n\n public use(plugin: HyperPlugin): this {\n this.assertActive();\n if (this.plugins.includes(plugin)) return this;\n if (this.plugins.some((existing) => existing.name === plugin.name)) {\n throw new HyperClientError(`[HyperCore] Plugin \"${plugin.name}\" is already registered.`);\n }\n const owner = pluginOwners.get(plugin);\n if (!plugin.shared && owner && owner !== this) {\n throw new HyperClientError(\n \"[HyperCore] Plugin instances cannot be shared across cores. Supply a fresh instance.\",\n );\n }\n if (plugin.shared && plugin.setup) {\n throw new HyperClientError(\"[HyperCore] Shared stateless plugins cannot define setup().\");\n }\n const enabled = plugin.enabled ? plugin.enabled(this.config) : true;\n if (!enabled) return this;\n\n plugin.setup?.(this.pluginCtx);\n if (!plugin.shared) pluginOwners.set(plugin, this);\n this.plugins = [...this.plugins, plugin].sort(\n (a, b) => (PLUGIN_PHASE_ORDER[a.phase ?? \"\"] ?? 0) - (PLUGIN_PHASE_ORDER[b.phase ?? \"\"] ?? 0),\n );\n return this;\n }\n\n /**\n * @ru Создаёт новый экземпляр ядра с расширенной/переопределённой конфигурацией,\n * переиспользуя текущий транспорт.\n * @en Creates a new core instance with extended/overridden configuration,\n * reusing the current transport.\n * @param options - Partial configuration overrides.\n * @returns A new IHyperCore instance.\n */\n public extend(options: Partial<HyperClientOptions>): IHyperCore {\n this.assertActive();\n const transport = options.customTransport ?? this.fixedTransport ?? undefined;\n const sharedTransports = options.customTransport ? undefined : this.transportPromises;\n return new HyperCore({ ...this.config, ...options }, transport, sharedTransports);\n }\n\n /**\n * @ru Создаёт полностью независимый экземпляр ядра на основе текущей\n * конфигурации: не переиспользует текущий транспорт и по умолчанию не\n * наследует `customTransport`.\n * @en Creates a fully independent core instance based on the current config:\n * it does not reuse the current transport and does not inherit\n * `customTransport` by default.\n * @param options - Partial configuration overrides.\n * @returns A new IHyperCore instance.\n */\n public create(options: Partial<HyperClientOptions>): IHyperCore {\n this.assertActive();\n const base: Partial<HyperClientOptions> = { ...this.config };\n delete base.customTransport;\n return new HyperCore({ ...base, ...options });\n }\n\n /**\n * @ru Завершает работу ядра и освобождает ресурсы: закрывает активные серверы,\n * затем освобождает удержание транспорта. Graceful-дренирование активных запросов\n * определяется реализацией `TransportServer.close()`.\n * @en Shuts down the core and releases resources: closes active servers, then\n * releases the transport hold. Graceful draining of in-flight requests is defined\n * by the `TransportServer.close()` implementation.\n * @param graceful - If true, prefers `transport.close()`; otherwise prefers `transport.destroy()`.\n * @returns Promise that resolves when shutdown is complete.\n */\n public destroy(graceful = true): Promise<void> {\n if (this.state === \"initializing\") {\n return Promise.reject(\n new HyperClientError(\"[HyperCore] Cannot destroy during setup initialization.\"),\n );\n }\n if (!this.destroyPromise) {\n this.destroyPromise = this.performDestroy(graceful);\n }\n return this.destroyPromise;\n }\n\n private async performDestroy(graceful: boolean): Promise<void> {\n this.state = \"destroying\";\n // Accepted calls finish or reject at the next admission check before resources close.\n if (graceful) await Promise.allSettled(this.activeRequests);\n\n await Promise.allSettled(this.pendingListeners);\n for (const server of this.servers) {\n try {\n await server.close();\n } catch {\n // Continue releasing the remaining resources.\n }\n }\n this.servers.clear();\n\n await Promise.allSettled([\n ...this.transportPromises.values(),\n ...this.listenTransportPromises.values(),\n ...this.multiListenTransportPromises.values(),\n ]);\n this.transportPromises.clear();\n this.transports.clear();\n this.listenTransportPromises.clear();\n this.listenTransports.clear();\n this.multiListenTransportPromises.clear();\n\n const transports = [...this.retainedTransports];\n this.retainedTransports.clear();\n\n for (const transport of transports) {\n if (releaseTransport(transport) > 0) continue;\n\n evictCachedTransport(transport);\n\n try {\n if (graceful && typeof transport.close === \"function\") {\n await transport.close();\n } else if (typeof transport.destroy === \"function\") {\n await transport.destroy();\n } else if (typeof transport.close === \"function\") {\n await transport.close();\n }\n } catch (err) {\n this.log(\"error\", \"[HyperCore] Error closing transport during destroy\", err);\n }\n }\n this.state = \"destroyed\";\n }\n}\n"],
|
|
5
|
+
"mappings": ";AA2BA,SAAS,iBAAAA,SAAqB;AAC9B,SAAS,qBAAAC,SAAyB;AAClC,SAAS,mBAAAC,GAAiB,mBAAAC,SAAuB;AACjD,SACE,wBAAAC,GACA,oBAAAC,GACA,gCAAAC,SACK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GACrB,KAAK,wBAAwB,MAAK,GAClC,KAAK,iBAAiB,MAAK,GAC3B,KAAK,6BAA6B,MAAK;AAEvC,UAAMnB,IAAa,CAAC,GAAG,KAAK,kBAAkB;AAC9C,SAAK,mBAAmB,MAAK;AAE7B,eAAW3E,KAAa2E;AACtB,UAAI,EAAA1E,EAAiBD,CAAS,IAAI,IAElC;QAAAX,EAAqBW,CAAS;AAE9B,YAAI;AACF,UAAIuG,KAAY,OAAOvG,EAAU,SAAU,aACzC,MAAMA,EAAU,MAAK,IACZ,OAAOA,EAAU,WAAY,aACtC,MAAMA,EAAU,QAAO,IACd,OAAOA,EAAU,SAAU,cACpC,MAAMA,EAAU,MAAK;QAEzB,SAAS4D,GAAK;AACZ,eAAK,IAAI,SAAS,sDAAsDA,CAAG;QAC7E;;AAEF,SAAK,QAAQ;EACf;;",
|
|
6
|
+
"names": ["dynamicImport", "defaultCoreConfig", "KNOWN_PROTOCOLS", "resolveProtocol", "evictCachedTransport", "resolveTransport", "resolveTransportForProtocols", "HyperClientError", "requestCounter", "requestIdBase", "PLUGIN_PHASE_ORDER", "createRequestId", "transportRefs", "pluginOwners", "retainTransport", "transport", "releaseTransport", "next", "DefaultRequestContext", "callback", "response", "outcome", "report", "callbacks", "error", "signal", "value", "createRequestContext", "req", "createServerRequestContext", "raw", "getRequestHeader", "headers", "name", "unsupportedProtocolResponse", "protocols", "isUniversalResponse", "DefaultProtocolRegistry", "protocol", "config", "sharedTransportPromises", "plugin", "i", "senders", "customSender", "receivers", "plugins", "registered", "factory", "namespaces", "sharedPromise", "sharedTransport", "sender", "receiver", "resolved", "ctor", "protocolName", "owner", "methods", "namespace", "method", "boundMethod", "args", "existing", "handler", "_target", "complete", "completion", "resolve", "ctx", "diagnostic", "currentReq", "hookRequests", "responseHooksStarted", "result", "err", "recovery", "recovered", "hookError", "responseError", "loaded", "initialResponse", "hookRequest", "snapshot", "customOnError", "handlerError", "level", "message", "meta", "requireListen", "transports", "transportPromises", "pending", "tracked", "key", "_", "transportConfig", "prepared", "options", "requested", "resolvedProtocols", "route", "onRequest", "currentRequest", "responseHooks", "initial", "errorHooks", "request", "serialized", "server", "closing", "resolvedPlugins", "module", "candidate", "a", "b", "sharedTransports", "base", "graceful"]
|
|
7
7
|
}
|
package/README.md
CHANGED
|
@@ -60,7 +60,7 @@ protocol packages. New I/O implementations should be transport packages.
|
|
|
60
60
|
- Per-protocol transport resolution and coordinated transport ownership.
|
|
61
61
|
- Blocking and background client plugin hooks, plus separate blocking server hooks.
|
|
62
62
|
- Stable request contexts and final settlement callbacks for resource cleanup.
|
|
63
|
-
- Runtime-aware
|
|
63
|
+
- Runtime-aware selection of optional transport packages.
|
|
64
64
|
- Strict TypeScript contracts and module augmentation for typed protocol namespaces.
|
|
65
65
|
- No bundled runtime dependencies.
|
|
66
66
|
|
|
@@ -76,8 +76,10 @@ and `ServerRequestOutcome`. Use `HyperProtocolName` for protocol identifiers;
|
|
|
76
76
|
`SenderProtocol` remains a deprecated compatibility alias.
|
|
77
77
|
|
|
78
78
|
Optimized transports are optional. Select releases compatible with the current contracts.
|
|
79
|
-
|
|
80
|
-
|
|
79
|
+
For REST clients, Bun tries `@hyperttp/transport-bun` first and then the native-fetch
|
|
80
|
+
`FetchTransport` from `@hyperttp/transport-node`; Node.js and Deno use their runtime-specific
|
|
81
|
+
transport packages. Browser and edge applications use the browser-safe
|
|
82
|
+
`@hyperttp/transport-node/fetch` fallback. Protocol packages and transport packages serve different roles.
|
|
81
83
|
|
|
82
84
|
## Client quick start
|
|
83
85
|
|
|
@@ -153,7 +155,7 @@ REST is explicitly registered from its package. Other known optional modules can
|
|
|
153
155
|
|
|
154
156
|
| Protocol | Package | Namespace |
|
|
155
157
|
| --------- | ------------------------------ | ---------------------------- |
|
|
156
|
-
| REST | `@hyperttp/protocol-rest`
|
|
158
|
+
| REST | `@hyperttp/protocol-rest` | `core.rest` |
|
|
157
159
|
| GraphQL | `@hyperttp/protocol-graphql` | `core.graphql` |
|
|
158
160
|
| gRPC | `@hyperttp/protocol-grpc` | `core.grpc` |
|
|
159
161
|
| tRPC | `@hyperttp/protocol-trpc` | `core.trpc` |
|
|
@@ -233,21 +235,22 @@ interface HyperTransport {
|
|
|
233
235
|
|
|
234
236
|
Runtime selection:
|
|
235
237
|
|
|
236
|
-
| Runtime |
|
|
237
|
-
| -------------- | ---------------------------- |
|
|
238
|
-
| Node.js | `@hyperttp/transport-undici` |
|
|
239
|
-
| Bun | `@hyperttp/transport-bun` |
|
|
240
|
-
| Deno | `@hyperttp/transport-deno` |
|
|
241
|
-
| Browser / edge | custom transport |
|
|
238
|
+
| Runtime | First candidate | REST fallback |
|
|
239
|
+
| -------------- | ---------------------------- | -------------------------- |
|
|
240
|
+
| Node.js | `@hyperttp/transport-undici` | `@hyperttp/transport-node` |
|
|
241
|
+
| Bun | `@hyperttp/transport-bun` | `@hyperttp/transport-node` |
|
|
242
|
+
| Deno | `@hyperttp/transport-deno` | `@hyperttp/transport-node` |
|
|
243
|
+
| Browser / edge | custom transport | `@hyperttp/transport-node/fetch` |
|
|
242
244
|
|
|
243
245
|
WebRTC first tries the specialized `@hyperttp/transport-webrtc` package.
|
|
244
246
|
Every candidate is checked for protocol support; runtime selection does not imply universal support.
|
|
245
247
|
|
|
246
248
|
Client and listen transport caches are separate and automatic transports are scoped by
|
|
247
249
|
configuration identity. A custom transport does not populate the default cache of other cores.
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
250
|
+
The `@hyperttp/transport-node` `FetchTransport` supports REST client requests and Node.js
|
|
251
|
+
`listen()`; Bun and Deno use it only after their runtime-specific transports are unavailable.
|
|
252
|
+
Browser and edge runtimes use the `@hyperttp/transport-node/fetch` subpath, which keeps the
|
|
253
|
+
Node.js server and HTTP/2 modules out of browser bundles.
|
|
251
254
|
|
|
252
255
|
A transport can also be supplied explicitly:
|
|
253
256
|
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/transports/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAMnF,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAE1D;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,eAAe,CAAC,EAAE,cAAc,CAAC;IACjC,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACpE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,eAAO,MAAM,eAAe,EAAE,OAK1B,CAAC;
|
|
1
|
+
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/transports/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAMnF,MAAM,MAAM,OAAO,GAAG,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;AAE1D;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,eAAe,CAAC,EAAE,cAAc,CAAC;IACjC,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0CAA0C;IAC1C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,0EAA0E;IAC1E,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;IACpE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,eAAO,MAAM,eAAe,EAAE,OAK1B,CAAC;AAkOL;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,QAAQ,GAAE,iBAA0B,EACpC,MAAM,CAAC,EAAE,uBAAuB,GAC/B,OAAO,CAAC,cAAc,CAAC,CA+BzB;AAED;;;;;;GAMG;AACH,wBAAsB,4BAA4B,CAChD,SAAS,EAAE,SAAS,iBAAiB,EAAE,EACvC,MAAM,CAAC,EAAE,uBAAuB,GAC/B,OAAO,CAAC,cAAc,CAAC,CAoCzB;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,GAAE,iBAA0B,EACpC,MAAM,CAAC,EAAE,uBAAuB,GAC/B,cAAc,GAAG,SAAS,CAG5B;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,SAAS,EAAE,cAAc,GAAG,IAAI,CAOpE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAG3C"}
|
package/transports/manager.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
import { dynamicImport as k, isModuleNotFoundError as g } from "../utils/modules.js";
|
|
3
3
|
export const CURRENT_RUNTIME = typeof Bun < "u" ? "bun" : typeof Deno < "u" ? "deno" : typeof process < "u" && process.versions?.node ? "node" : "browser";
|
|
4
|
-
const
|
|
4
|
+
const x = ["bun", "node", "deno", "browser"], C = [
|
|
5
5
|
{
|
|
6
6
|
protocols: ["rest"],
|
|
7
7
|
runtime: ["bun"],
|
|
@@ -29,7 +29,7 @@ const C = ["bun", "node", "deno", "browser"], x = [
|
|
|
29
29
|
], R = [
|
|
30
30
|
{
|
|
31
31
|
protocols: ["webrtc"],
|
|
32
|
-
runtime:
|
|
32
|
+
runtime: x,
|
|
33
33
|
pkg: "@hyperttp/transport-webrtc",
|
|
34
34
|
export: "WebRtcTransport"
|
|
35
35
|
},
|
|
@@ -40,15 +40,30 @@ const C = ["bun", "node", "deno", "browser"], x = [
|
|
|
40
40
|
export: "Http2Transport"
|
|
41
41
|
},
|
|
42
42
|
{ runtime: ["bun"], pkg: "@hyperttp/transport-bun", export: "BunTransport" },
|
|
43
|
-
{
|
|
43
|
+
{
|
|
44
|
+
runtime: ["bun"],
|
|
45
|
+
pkg: "@hyperttp/transport-node",
|
|
46
|
+
export: "FetchTransport"
|
|
47
|
+
},
|
|
44
48
|
{ runtime: ["node"], pkg: "@hyperttp/transport-undici", export: "UndiciTransport" },
|
|
45
|
-
{ runtime: ["
|
|
49
|
+
{ runtime: ["node"], pkg: "@hyperttp/transport-node", export: "FetchTransport" },
|
|
50
|
+
{ runtime: ["deno"], pkg: "@hyperttp/transport-deno", export: "DenoTransport" },
|
|
51
|
+
{
|
|
52
|
+
runtime: ["deno"],
|
|
53
|
+
pkg: "@hyperttp/transport-node",
|
|
54
|
+
export: "FetchTransport"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
runtime: ["browser"],
|
|
58
|
+
pkg: "@hyperttp/transport-node/fetch",
|
|
59
|
+
export: "FetchTransport"
|
|
60
|
+
}
|
|
46
61
|
];
|
|
47
62
|
function b(t) {
|
|
48
63
|
return R.filter((e) => e.runtime.includes(CURRENT_RUNTIME) && (!e.protocols || e.protocols.includes(t)));
|
|
49
64
|
}
|
|
50
65
|
function h(t, e) {
|
|
51
|
-
const r = e?.http2 === !0 ?
|
|
66
|
+
const r = e?.http2 === !0 ? C.filter((o) => {
|
|
52
67
|
const p = o.protocols;
|
|
53
68
|
return o.runtime.includes(CURRENT_RUNTIME) && (!p || t.some((u) => p.includes(u)));
|
|
54
69
|
}) : [], n = t.map((o) => b(o));
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/transports/manager.ts"],
|
|
4
|
-
"sourcesContent": ["import type { HyperTransport, LogLevel, HyperProtocolName } from \"@hyperttp/types\";\nimport { dynamicImport, isModuleNotFoundError } from \"../utils/modules.js\";\n\ndeclare const Bun: unknown;\ndeclare const Deno: unknown;\n\nexport type Runtime = \"bun\" | \"node\" | \"deno\" | \"browser\";\n\n/**\n * @ru Опции разрешения транспорта. `customTransport` имеет приоритет над автовыбором.\n * @en Transport resolution options. `customTransport` takes priority over auto-selection.\n */\nexport interface ResolveTransportOptions {\n customTransport?: HyperTransport;\n /** Stable configuration identity for sharing automatic transports across calls. */\n cacheKey?: object;\n /** Requires the transport server role. */\n requireListen?: boolean;\n /** Prefer an HTTP/2 transport for REST and gRPC when one is available. */\n http2?: boolean;\n logger?: (level: LogLevel, message: string, meta?: unknown) => void;\n verbose?: boolean;\n [key: string]: unknown;\n}\n\nexport const CURRENT_RUNTIME: Runtime = (() => {\n if (typeof Bun !== \"undefined\") return \"bun\";\n if (typeof Deno !== \"undefined\") return \"deno\";\n if (typeof process !== \"undefined\" && process.versions?.node) return \"node\";\n return \"browser\";\n})();\n\ntype TransportDef = {\n readonly runtime: readonly Runtime[];\n readonly pkg: string;\n readonly export: string;\n /** Protocols that require this transport family. Omitted for generic transports. */\n readonly protocols?: readonly HyperProtocolName[];\n};\n\nconst ALL_RUNTIMES: readonly Runtime[] = [\"bun\", \"node\", \"deno\", \"browser\"];\n\nconst HTTP2_TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"rest\"],\n runtime: [\"bun\"],\n pkg: \"@hyperttp/transport-bun\",\n export: \"BunTransport\",\n },\n {\n protocols: [\"rest\"],\n runtime: [\"node\"],\n pkg: \"@hyperttp/transport-undici\",\n export: \"UndiciTransport\",\n },\n {\n protocols: [\"rest\"],\n runtime: [\"deno\"],\n pkg: \"@hyperttp/transport-deno\",\n export: \"DenoTransport\",\n },\n {\n protocols: [\"rest\", \"grpc\"],\n runtime: [\"bun\", \"node\", \"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"Http2Transport\",\n },\n];\n\nconst TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"webrtc\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-webrtc\",\n export: \"WebRtcTransport\",\n },\n {\n protocols: [\"grpc\"],\n runtime: [\"bun\", \"node\", \"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"Http2Transport\",\n },\n { runtime: [\"bun\"], pkg: \"@hyperttp/transport-bun\", export: \"BunTransport\" },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-node\", export: \"FetchTransport\" },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-undici\", export: \"UndiciTransport\" },\n { runtime: [\"deno\"], pkg: \"@hyperttp/transport-deno\", export: \"DenoTransport\" },\n];\n\nfunction getCandidates(protocol: HyperProtocolName): readonly TransportDef[] {\n return TRANSPORT_DEFS.filter(\n (transport) =>\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!transport.protocols || transport.protocols.includes(protocol)),\n );\n}\n\nfunction getCandidatesForProtocols(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): readonly TransportDef[] {\n const preferred =\n config?.http2 === true\n ? HTTP2_TRANSPORT_DEFS.filter((transport) => {\n const supportedProtocols = transport.protocols;\n return (\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!supportedProtocols ||\n protocols.some((protocol) => supportedProtocols.includes(protocol)))\n );\n })\n : [];\n const lists = protocols.map((protocol) => getCandidates(protocol));\n // Start with the most constrained protocol so a dedicated transport such as\n // GrpcTransport is tried before a generic REST transport.\n lists.sort((a, b) => a.length - b.length);\n\n const defs = new Map<string, TransportDef>();\n for (const transport of [...preferred, ...lists.flat()]) {\n const key = `${transport.pkg}:${transport.export}`;\n if (!defs.has(key)) defs.set(key, transport);\n }\n return [...defs.values()];\n}\n\nfunction getTransportInstallHint(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): string {\n const packages = new Set(\n getCandidatesForProtocols(protocols, config).map((transport) => transport.pkg),\n );\n if (packages.size === 0) return \"\";\n\n return ` Install ${[...packages].map((pkg) => `\"${pkg}\"`).join(\" or \")}.`;\n}\n\ntype TransportCache = {\n client: Map<string, HyperTransport>;\n listen: Map<string, HyperTransport>;\n multi: Map<string, HyperTransport>;\n clientResolutions: Map<string, Promise<HyperTransport>>;\n listenResolutions: Map<string, Promise<HyperTransport>>;\n multiResolutions: Map<string, Promise<HyperTransport>>;\n};\n\nconst defaultCacheKey = {};\nlet transportCaches = new WeakMap<object, TransportCache>();\nlet transportEntries = new WeakMap<HyperTransport, Set<Map<string, HyperTransport>>>();\n\nfunction getCache(config?: ResolveTransportOptions): TransportCache {\n const identity = config?.cacheKey ?? config ?? defaultCacheKey;\n let cache = transportCaches.get(identity);\n if (!cache) {\n cache = {\n client: new Map(),\n listen: new Map(),\n multi: new Map(),\n clientResolutions: new Map(),\n listenResolutions: new Map(),\n multiResolutions: new Map(),\n };\n transportCaches.set(identity, cache);\n }\n return cache;\n}\n\nfunction supportsListen(transport: HyperTransport): boolean {\n return typeof transport.listen === \"function\";\n}\n\nfunction supportsProtocol(transport: HyperTransport, protocol: HyperProtocolName): boolean {\n return typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true);\n}\n\nfunction supportsAll(transport: HyperTransport, protocols: readonly HyperProtocolName[]): boolean {\n return protocols.every((protocol) => supportsProtocol(transport, protocol));\n}\n\nasync function disposeUnusedTransport(transport: HyperTransport): Promise<void> {\n try {\n if (typeof transport.destroy === \"function\") {\n await transport.destroy();\n } else if (typeof transport.close === \"function\") {\n await transport.close();\n }\n } catch {\n //\n }\n}\n\nasync function createTransport(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const candidates = getCandidatesForProtocols(protocols, config);\n for (let i = 0; i < candidates.length; i++) {\n const t = candidates[i]!;\n let mod: Record<string, unknown>;\n try {\n mod = await dynamicImport(t.pkg);\n } catch (err) {\n if (!isModuleNotFoundError(err)) throw err;\n continue;\n }\n const candidate = (mod[t.export] ?? mod.default) as\n | { new (opts?: unknown): HyperTransport }\n | undefined;\n if (typeof candidate !== \"function\") continue;\n\n const instance = new candidate(config ?? {});\n if (!supportsAll(instance, protocols) || (config?.requireListen && !supportsListen(instance))) {\n await disposeUnusedTransport(instance);\n continue;\n }\n\n return instance;\n }\n\n const label = protocols.length === 1 ? \"protocol\" : \"protocols\";\n throw new Error(\n `[HyperCore] No transport available for ${label} ${protocols.map((p) => `\"${p}\"`).join(\", \")} in runtime \"${CURRENT_RUNTIME}\".${getTransportInstallHint(protocols, config)}`,\n );\n}\n\nfunction cacheTransport(\n transport: HyperTransport,\n cache: Map<string, HyperTransport>,\n key: string,\n): HyperTransport {\n cache.set(key, transport);\n let entries = transportEntries.get(transport);\n if (!entries) {\n entries = new Set();\n transportEntries.set(transport, entries);\n }\n entries.add(cache);\n return transport;\n}\n\n/**\n * @ru Разрешает оптимальный транспорт для указанного протокола и текущей среды.\n * Кастомный транспорт из конфигурации имеет приоритет над автовыбором.\n * @en Resolves optimal transport for the given protocol and current runtime.\n * A custom transport from the config takes priority over auto-selection.\n */\nexport async function resolveTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsProtocol(config.customTransport, protocol)) {\n throw new Error(`[HyperCore] Custom transport does not support protocol \"${protocol}\".`);\n }\n\n if (requireListen && !supportsListen(config.customTransport)) {\n throw new Error(\"[HyperCore] Custom transport does not support listen().\");\n }\n return config.customTransport;\n }\n\n const cache = getCache(config);\n const transportCache = requireListen ? cache.listen : cache.client;\n const transportResolutions = requireListen ? cache.listenResolutions : cache.clientResolutions;\n const cached = transportCache.get(protocol);\n if (cached) return cached;\n\n const pending = transportResolutions.get(protocol);\n if (pending) return pending;\n\n const resolution = createTransport([protocol], config)\n .then((transport) => cacheTransport(transport, transportCache, protocol))\n .finally(() => {\n transportResolutions.delete(protocol);\n });\n\n transportResolutions.set(protocol, resolution);\n return resolution;\n}\n\n/**\n * @ru Разрешает один транспорт, поддерживающий сразу все указанные протоколы.\n * Используется мультипротокольным `listen({ protocols })`, чтобы не открывать\n * несколько слушателей на одном порту.\n * @en Resolves one transport supporting every requested protocol. Used by the\n * multi-protocol `listen({ protocols })` so one port is not opened multiple times.\n */\nexport async function resolveTransportForProtocols(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n if (protocols.length === 0) {\n throw new Error(\"[HyperCore] At least one protocol is required to resolve a transport.\");\n }\n if (protocols.length === 1) return resolveTransport(protocols[0], config);\n\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsAll(config.customTransport, protocols)) {\n throw new Error(\n `[HyperCore] Custom transport does not support protocols ${protocols.map((p) => `\"${p}\"`).join(\", \")}.`,\n );\n }\n if (requireListen && !supportsListen(config.customTransport)) {\n throw new Error(\"[HyperCore] Custom transport does not support listen().\");\n }\n return config.customTransport;\n }\n\n const cache = getCache(config);\n const key = JSON.stringify([...protocols].sort());\n const cached = cache.multi.get(key);\n if (cached) return cached;\n\n const pending = cache.multiResolutions.get(key);\n if (pending) return pending;\n\n const resolution = createTransport(protocols, config)\n .then((transport) => cacheTransport(transport, cache.multi, key))\n .finally(() => {\n cache.multiResolutions.delete(key);\n });\n\n cache.multiResolutions.set(key, resolution);\n return resolution;\n}\n\n/**\n * @ru Синхронно возвращает транспорт из кэша без создания Promise.\n * @en Synchronously returns a cached transport without creating a Promise.\n * @param protocol - Протокол, для которого запрашивается транспорт. @en Protocol whose transport is requested.\n * @returns Кэшированный транспорт или `undefined`. @en Cached transport or `undefined`.\n */\nexport function getCachedTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): HyperTransport | undefined {\n const cache = getCache(config);\n return (config?.requireListen ? cache.listen : cache.client).get(protocol);\n}\n\n/**\n * @ru Удаляет все записи кэша, ссылающиеся на указанный транспорт.\n * @en Removes every cache entry that references the given transport.\n * @param transport - Экземпляр транспорта для удаления из кэша. @en Transport instance to evict from the cache.\n */\nexport function evictCachedTransport(transport: HyperTransport): void {\n for (const entries of transportEntries.get(transport) ?? []) {\n for (const [key, cached] of entries) {\n if (cached === transport) entries.delete(key);\n }\n }\n transportEntries.delete(transport);\n}\n\n/**\n * @ru Очищает кэш транспортов и ожидающих их разрешений. Не закрывает уже\n * созданные экземпляры транспорта.\n * @en Clears cached transports and pending resolutions. It does not close\n * already-created transport instances.\n */\nexport function resetCachedTransport(): void {\n transportCaches = new WeakMap();\n transportEntries = new WeakMap();\n}\n"],
|
|
5
|
-
"mappings": ";AACA,SAAS,iBAAAA,GAAe,yBAAAC,SAA6B;AAwB9C,aAAM,kBACP,OAAO,MAAQ,MAAoB,QACnC,OAAO,OAAS,MAAoB,SACpC,OAAO,UAAY,OAAe,QAAQ,UAAU,OAAa,SAC9D;AAWT,MAAMC,IAAmC,CAAC,OAAO,QAAQ,QAAQ,SAAS,GAEpEC,IAAgD;EACpD;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,KAAK;IACf,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,MAAM;IAChB,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,MAAM;IAChB,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,CAAC,QAAQ,MAAM;IAC1B,SAAS,CAAC,OAAO,QAAQ,MAAM;IAC/B,KAAK;IACL,QAAQ;;GAINC,IAA0C;EAC9C;IACE,WAAW,CAAC,QAAQ;IACpB,SAASF;IACT,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,OAAO,QAAQ,MAAM;IAC/B,KAAK;IACL,QAAQ;;EAEV,EAAE,SAAS,CAAC,KAAK,GAAG,KAAK,2BAA2B,QAAQ,eAAc;EAC1E,EAAE,SAAS,CAAC,MAAM,GAAG,KAAK,
|
|
4
|
+
"sourcesContent": ["import type { HyperTransport, LogLevel, HyperProtocolName } from \"@hyperttp/types\";\nimport { dynamicImport, isModuleNotFoundError } from \"../utils/modules.js\";\n\ndeclare const Bun: unknown;\ndeclare const Deno: unknown;\n\nexport type Runtime = \"bun\" | \"node\" | \"deno\" | \"browser\";\n\n/**\n * @ru Опции разрешения транспорта. `customTransport` имеет приоритет над автовыбором.\n * @en Transport resolution options. `customTransport` takes priority over auto-selection.\n */\nexport interface ResolveTransportOptions {\n customTransport?: HyperTransport;\n /** Stable configuration identity for sharing automatic transports across calls. */\n cacheKey?: object;\n /** Requires the transport server role. */\n requireListen?: boolean;\n /** Prefer an HTTP/2 transport for REST and gRPC when one is available. */\n http2?: boolean;\n logger?: (level: LogLevel, message: string, meta?: unknown) => void;\n verbose?: boolean;\n [key: string]: unknown;\n}\n\nexport const CURRENT_RUNTIME: Runtime = (() => {\n if (typeof Bun !== \"undefined\") return \"bun\";\n if (typeof Deno !== \"undefined\") return \"deno\";\n if (typeof process !== \"undefined\" && process.versions?.node) return \"node\";\n return \"browser\";\n})();\n\ntype TransportDef = {\n readonly runtime: readonly Runtime[];\n readonly pkg: string;\n readonly export: string;\n /** Protocols that require this transport family. Omitted for generic transports. */\n readonly protocols?: readonly HyperProtocolName[];\n};\n\nconst ALL_RUNTIMES: readonly Runtime[] = [\"bun\", \"node\", \"deno\", \"browser\"];\n\nconst HTTP2_TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"rest\"],\n runtime: [\"bun\"],\n pkg: \"@hyperttp/transport-bun\",\n export: \"BunTransport\",\n },\n {\n protocols: [\"rest\"],\n runtime: [\"node\"],\n pkg: \"@hyperttp/transport-undici\",\n export: \"UndiciTransport\",\n },\n {\n protocols: [\"rest\"],\n runtime: [\"deno\"],\n pkg: \"@hyperttp/transport-deno\",\n export: \"DenoTransport\",\n },\n {\n protocols: [\"rest\", \"grpc\"],\n runtime: [\"bun\", \"node\", \"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"Http2Transport\",\n },\n];\n\nconst TRANSPORT_DEFS: readonly TransportDef[] = [\n {\n protocols: [\"webrtc\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-webrtc\",\n export: \"WebRtcTransport\",\n },\n {\n protocols: [\"grpc\"],\n runtime: [\"bun\", \"node\", \"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"Http2Transport\",\n },\n { runtime: [\"bun\"], pkg: \"@hyperttp/transport-bun\", export: \"BunTransport\" },\n {\n runtime: [\"bun\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"FetchTransport\",\n },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-undici\", export: \"UndiciTransport\" },\n { runtime: [\"node\"], pkg: \"@hyperttp/transport-node\", export: \"FetchTransport\" },\n { runtime: [\"deno\"], pkg: \"@hyperttp/transport-deno\", export: \"DenoTransport\" },\n {\n runtime: [\"deno\"],\n pkg: \"@hyperttp/transport-node\",\n export: \"FetchTransport\",\n },\n {\n runtime: [\"browser\"],\n pkg: \"@hyperttp/transport-node/fetch\",\n export: \"FetchTransport\",\n },\n];\n\nfunction getCandidates(protocol: HyperProtocolName): readonly TransportDef[] {\n return TRANSPORT_DEFS.filter(\n (transport) =>\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!transport.protocols || transport.protocols.includes(protocol)),\n );\n}\n\nfunction getCandidatesForProtocols(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): readonly TransportDef[] {\n const preferred =\n config?.http2 === true\n ? HTTP2_TRANSPORT_DEFS.filter((transport) => {\n const supportedProtocols = transport.protocols;\n return (\n transport.runtime.includes(CURRENT_RUNTIME) &&\n (!supportedProtocols ||\n protocols.some((protocol) => supportedProtocols.includes(protocol)))\n );\n })\n : [];\n const lists = protocols.map((protocol) => getCandidates(protocol));\n // Start with the most constrained protocol so a dedicated transport such as\n // GrpcTransport is tried before a generic REST transport.\n lists.sort((a, b) => a.length - b.length);\n\n const defs = new Map<string, TransportDef>();\n for (const transport of [...preferred, ...lists.flat()]) {\n const key = `${transport.pkg}:${transport.export}`;\n if (!defs.has(key)) defs.set(key, transport);\n }\n return [...defs.values()];\n}\n\nfunction getTransportInstallHint(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): string {\n const packages = new Set(\n getCandidatesForProtocols(protocols, config).map((transport) => transport.pkg),\n );\n if (packages.size === 0) return \"\";\n\n return ` Install ${[...packages].map((pkg) => `\"${pkg}\"`).join(\" or \")}.`;\n}\n\ntype TransportCache = {\n client: Map<string, HyperTransport>;\n listen: Map<string, HyperTransport>;\n multi: Map<string, HyperTransport>;\n clientResolutions: Map<string, Promise<HyperTransport>>;\n listenResolutions: Map<string, Promise<HyperTransport>>;\n multiResolutions: Map<string, Promise<HyperTransport>>;\n};\n\nconst defaultCacheKey = {};\nlet transportCaches = new WeakMap<object, TransportCache>();\nlet transportEntries = new WeakMap<HyperTransport, Set<Map<string, HyperTransport>>>();\n\nfunction getCache(config?: ResolveTransportOptions): TransportCache {\n const identity = config?.cacheKey ?? config ?? defaultCacheKey;\n let cache = transportCaches.get(identity);\n if (!cache) {\n cache = {\n client: new Map(),\n listen: new Map(),\n multi: new Map(),\n clientResolutions: new Map(),\n listenResolutions: new Map(),\n multiResolutions: new Map(),\n };\n transportCaches.set(identity, cache);\n }\n return cache;\n}\n\nfunction supportsListen(transport: HyperTransport): boolean {\n return typeof transport.listen === \"function\";\n}\n\nfunction supportsProtocol(transport: HyperTransport, protocol: HyperProtocolName): boolean {\n return typeof transport.supports === \"function\"\n ? transport.supports(protocol)\n : (transport.protocols?.includes(protocol) ?? true);\n}\n\nfunction supportsAll(transport: HyperTransport, protocols: readonly HyperProtocolName[]): boolean {\n return protocols.every((protocol) => supportsProtocol(transport, protocol));\n}\n\nasync function disposeUnusedTransport(transport: HyperTransport): Promise<void> {\n try {\n if (typeof transport.destroy === \"function\") {\n await transport.destroy();\n } else if (typeof transport.close === \"function\") {\n await transport.close();\n }\n } catch {\n //\n }\n}\n\nasync function createTransport(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const candidates = getCandidatesForProtocols(protocols, config);\n for (let i = 0; i < candidates.length; i++) {\n const t = candidates[i]!;\n let mod: Record<string, unknown>;\n try {\n mod = await dynamicImport(t.pkg);\n } catch (err) {\n if (!isModuleNotFoundError(err)) throw err;\n continue;\n }\n const candidate = (mod[t.export] ?? mod.default) as\n | { new (opts?: unknown): HyperTransport }\n | undefined;\n if (typeof candidate !== \"function\") continue;\n\n const instance = new candidate(config ?? {});\n if (!supportsAll(instance, protocols) || (config?.requireListen && !supportsListen(instance))) {\n await disposeUnusedTransport(instance);\n continue;\n }\n\n return instance;\n }\n\n const label = protocols.length === 1 ? \"protocol\" : \"protocols\";\n throw new Error(\n `[HyperCore] No transport available for ${label} ${protocols.map((p) => `\"${p}\"`).join(\", \")} in runtime \"${CURRENT_RUNTIME}\".${getTransportInstallHint(protocols, config)}`,\n );\n}\n\nfunction cacheTransport(\n transport: HyperTransport,\n cache: Map<string, HyperTransport>,\n key: string,\n): HyperTransport {\n cache.set(key, transport);\n let entries = transportEntries.get(transport);\n if (!entries) {\n entries = new Set();\n transportEntries.set(transport, entries);\n }\n entries.add(cache);\n return transport;\n}\n\n/**\n * @ru Разрешает оптимальный транспорт для указанного протокола и текущей среды.\n * Кастомный транспорт из конфигурации имеет приоритет над автовыбором.\n * @en Resolves optimal transport for the given protocol and current runtime.\n * A custom transport from the config takes priority over auto-selection.\n */\nexport async function resolveTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsProtocol(config.customTransport, protocol)) {\n throw new Error(`[HyperCore] Custom transport does not support protocol \"${protocol}\".`);\n }\n\n if (requireListen && !supportsListen(config.customTransport)) {\n throw new Error(\"[HyperCore] Custom transport does not support listen().\");\n }\n return config.customTransport;\n }\n\n const cache = getCache(config);\n const transportCache = requireListen ? cache.listen : cache.client;\n const transportResolutions = requireListen ? cache.listenResolutions : cache.clientResolutions;\n const cached = transportCache.get(protocol);\n if (cached) return cached;\n\n const pending = transportResolutions.get(protocol);\n if (pending) return pending;\n\n const resolution = createTransport([protocol], config)\n .then((transport) => cacheTransport(transport, transportCache, protocol))\n .finally(() => {\n transportResolutions.delete(protocol);\n });\n\n transportResolutions.set(protocol, resolution);\n return resolution;\n}\n\n/**\n * @ru Разрешает один транспорт, поддерживающий сразу все указанные протоколы.\n * Используется мультипротокольным `listen({ protocols })`, чтобы не открывать\n * несколько слушателей на одном порту.\n * @en Resolves one transport supporting every requested protocol. Used by the\n * multi-protocol `listen({ protocols })` so one port is not opened multiple times.\n */\nexport async function resolveTransportForProtocols(\n protocols: readonly HyperProtocolName[],\n config?: ResolveTransportOptions,\n): Promise<HyperTransport> {\n if (protocols.length === 0) {\n throw new Error(\"[HyperCore] At least one protocol is required to resolve a transport.\");\n }\n if (protocols.length === 1) return resolveTransport(protocols[0], config);\n\n const requireListen = config?.requireListen ?? false;\n\n if (config?.customTransport) {\n if (!supportsAll(config.customTransport, protocols)) {\n throw new Error(\n `[HyperCore] Custom transport does not support protocols ${protocols.map((p) => `\"${p}\"`).join(\", \")}.`,\n );\n }\n if (requireListen && !supportsListen(config.customTransport)) {\n throw new Error(\"[HyperCore] Custom transport does not support listen().\");\n }\n return config.customTransport;\n }\n\n const cache = getCache(config);\n const key = JSON.stringify([...protocols].sort());\n const cached = cache.multi.get(key);\n if (cached) return cached;\n\n const pending = cache.multiResolutions.get(key);\n if (pending) return pending;\n\n const resolution = createTransport(protocols, config)\n .then((transport) => cacheTransport(transport, cache.multi, key))\n .finally(() => {\n cache.multiResolutions.delete(key);\n });\n\n cache.multiResolutions.set(key, resolution);\n return resolution;\n}\n\n/**\n * @ru Синхронно возвращает транспорт из кэша без создания Promise.\n * @en Synchronously returns a cached transport without creating a Promise.\n * @param protocol - Протокол, для которого запрашивается транспорт. @en Protocol whose transport is requested.\n * @returns Кэшированный транспорт или `undefined`. @en Cached transport or `undefined`.\n */\nexport function getCachedTransport(\n protocol: HyperProtocolName = \"rest\",\n config?: ResolveTransportOptions,\n): HyperTransport | undefined {\n const cache = getCache(config);\n return (config?.requireListen ? cache.listen : cache.client).get(protocol);\n}\n\n/**\n * @ru Удаляет все записи кэша, ссылающиеся на указанный транспорт.\n * @en Removes every cache entry that references the given transport.\n * @param transport - Экземпляр транспорта для удаления из кэша. @en Transport instance to evict from the cache.\n */\nexport function evictCachedTransport(transport: HyperTransport): void {\n for (const entries of transportEntries.get(transport) ?? []) {\n for (const [key, cached] of entries) {\n if (cached === transport) entries.delete(key);\n }\n }\n transportEntries.delete(transport);\n}\n\n/**\n * @ru Очищает кэш транспортов и ожидающих их разрешений. Не закрывает уже\n * созданные экземпляры транспорта.\n * @en Clears cached transports and pending resolutions. It does not close\n * already-created transport instances.\n */\nexport function resetCachedTransport(): void {\n transportCaches = new WeakMap();\n transportEntries = new WeakMap();\n}\n"],
|
|
5
|
+
"mappings": ";AACA,SAAS,iBAAAA,GAAe,yBAAAC,SAA6B;AAwB9C,aAAM,kBACP,OAAO,MAAQ,MAAoB,QACnC,OAAO,OAAS,MAAoB,SACpC,OAAO,UAAY,OAAe,QAAQ,UAAU,OAAa,SAC9D;AAWT,MAAMC,IAAmC,CAAC,OAAO,QAAQ,QAAQ,SAAS,GAEpEC,IAAgD;EACpD;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,KAAK;IACf,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,MAAM;IAChB,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,CAAC,MAAM;IAClB,SAAS,CAAC,MAAM;IAChB,KAAK;IACL,QAAQ;;EAEV;IACE,WAAW,C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PORT_DEFS", "TRANSPORT_DEFS", "getCandidates", "protocol", "transport", "getCandidatesForProtocols", "protocols", "config", "preferred", "supportedProtocols", "lists", "a", "b", "defs", "key", "getTransportInstallHint", "packages", "pkg", "defaultCacheKey", "transportCaches", "transportEntries", "getCache", "identity", "cache", "supportsListen", "supportsProtocol", "supportsAll", "disposeUnusedTransport", "createTransport", "candidates", "i", "t", "mod", "err", "candidate", "instance", "label", "p", "cacheTransport", "entries", "requireListen", "transportCache", "transportResolutions", "cached", "pending", "resolution"]
|
|
7
7
|
}
|
package/utils/modules.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"modules.d.ts","sourceRoot":"","sources":["../../src/utils/modules.ts"],"names":[],"mappings":"AAAA,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAW3D;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"modules.d.ts","sourceRoot":"","sources":["../../src/utils/modules.ts"],"names":[],"mappings":"AAAA,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAW3D;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAYjF"}
|
package/utils/modules.js
CHANGED
|
@@ -2,16 +2,23 @@
|
|
|
2
2
|
export function isModuleNotFoundError(e) {
|
|
3
3
|
if (!e || typeof e != "object")
|
|
4
4
|
return !1;
|
|
5
|
-
const
|
|
6
|
-
if (
|
|
5
|
+
const t = e;
|
|
6
|
+
if (t.code === "ERR_MODULE_NOT_FOUND" || t.code === "MODULE_NOT_FOUND")
|
|
7
7
|
return !0;
|
|
8
|
-
const
|
|
9
|
-
return
|
|
8
|
+
const o = e instanceof Error ? e.message : String(t.message ?? "");
|
|
9
|
+
return o.includes("Cannot find module") || o.includes("Failed to resolve") || o.includes("Failed to load");
|
|
10
10
|
}
|
|
11
|
-
export async function dynamicImport(
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
11
|
+
export async function dynamicImport(pkg) {
|
|
12
|
+
try {
|
|
13
|
+
return await import(
|
|
14
|
+
/* @vite-ignore */
|
|
15
|
+
pkg
|
|
16
|
+
);
|
|
17
|
+
} catch (err) {
|
|
18
|
+
const message = err && typeof err == "object" ? String(err.message ?? "") : "";
|
|
19
|
+
if (!message.includes("Failed to load url"))
|
|
20
|
+
throw err;
|
|
21
|
+
return eval("import(/* @vite-ignore */ pkg)");
|
|
22
|
+
}
|
|
16
23
|
}
|
|
17
24
|
//# sourceMappingURL=modules.js.map
|
package/utils/modules.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/utils/modules.ts"],
|
|
4
|
-
"sourcesContent": ["export function isModuleNotFoundError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as Record<string, unknown>;\n if (e.code === \"ERR_MODULE_NOT_FOUND\" || e.code === \"MODULE_NOT_FOUND\") return true;\n\n const message = err instanceof Error ? err.message : String(e.message ?? \"\");\n return (\n message.includes(\"Cannot find module\") ||\n message.includes(\"Failed to resolve\") ||\n message.includes(\"Failed to load\")\n );\n}\n\nexport async function dynamicImport(pkg: string): Promise<Record<string, unknown>> {\n return import(/* @vite-ignore */ pkg);\n}\n"],
|
|
5
|
-
"mappings": ";AAAM,gBAAU,sBAAsBA,GAAY;AAChD,MAAI,CAACA,KAAO,OAAOA,KAAQ;AAAU,WAAO;AAC5C,QAAMC,IAAID;AACV,MAAIC,EAAE,SAAS,0BAA0BA,EAAE,SAAS;AAAoB,WAAO;AAE/E,QAAMC,IAAUF,aAAe,QAAQA,EAAI,UAAU,OAAOC,EAAE,WAAW,EAAE;AAC3E,SACEC,EAAQ,SAAS,oBAAoB,KACrCA,EAAQ,SAAS,mBAAmB,KACpCA,EAAQ,SAAS,gBAAgB;AAErC;AAEA,sBAAsB,
|
|
6
|
-
"names": ["err", "e", "message"
|
|
4
|
+
"sourcesContent": ["export function isModuleNotFoundError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const e = err as Record<string, unknown>;\n if (e.code === \"ERR_MODULE_NOT_FOUND\" || e.code === \"MODULE_NOT_FOUND\") return true;\n\n const message = err instanceof Error ? err.message : String(e.message ?? \"\");\n return (\n message.includes(\"Cannot find module\") ||\n message.includes(\"Failed to resolve\") ||\n message.includes(\"Failed to load\")\n );\n}\n\nexport async function dynamicImport(pkg: string): Promise<Record<string, unknown>> {\n try {\n return await import(/* @vite-ignore */ pkg);\n } catch (err) {\n const message =\n err && typeof err === \"object\" ? String((err as { message?: unknown }).message ?? \"\") : \"\";\n if (!message.includes(\"Failed to load url\")) throw err;\n\n // Vite's SSR resolver cannot load arbitrary bare package specifiers.\n // oxlint-disable-next-line no-eval -- The code is static; pkg stays lexical.\n return eval(\"import(/* @vite-ignore */ pkg)\");\n }\n}\n"],
|
|
5
|
+
"mappings": ";AAAM,gBAAU,sBAAsBA,GAAY;AAChD,MAAI,CAACA,KAAO,OAAOA,KAAQ;AAAU,WAAO;AAC5C,QAAMC,IAAID;AACV,MAAIC,EAAE,SAAS,0BAA0BA,EAAE,SAAS;AAAoB,WAAO;AAE/E,QAAMC,IAAUF,aAAe,QAAQA,EAAI,UAAU,OAAOC,EAAE,WAAW,EAAE;AAC3E,SACEC,EAAQ,SAAS,oBAAoB,KACrCA,EAAQ,SAAS,mBAAmB,KACpCA,EAAQ,SAAS,gBAAgB;AAErC;AAEA,sBAAsB,cAAc,KAAW;AAC7C,MAAI;AACF,WAAO,MAAM;;MAA0B;;EACzC,SAAS,KAAK;AACZ,UAAM,UACJ,OAAO,OAAO,OAAQ,WAAW,OAAQ,IAA8B,WAAW,EAAE,IAAI;AAC1F,QAAI,CAAC,QAAQ,SAAS,oBAAoB;AAAG,YAAM;AAInD,WAAO,KAAK,gCAAgC;EAC9C;AACF;",
|
|
6
|
+
"names": ["err", "e", "message"]
|
|
7
7
|
}
|