@hyperttp/core 3.0.9 → 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/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 transport selection with a browser-safe fetch fallback.
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
- The built-in `FetchTransport` supports REST by default; it is not a universal fallback for
80
- WebRTC, MQTT or WebSocket. Protocol packages and transport packages serve different roles.
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` | `core.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 | Preferred package | Fallback |
237
- | -------------- | ---------------------------- | ------------------------- |
238
- | Node.js | `@hyperttp/transport-undici` | built-in `FetchTransport` |
239
- | Bun | `@hyperttp/transport-bun` | built-in `FetchTransport` |
240
- | Deno | `@hyperttp/transport-deno` | built-in `FetchTransport` |
241
- | Browser / edge | custom transport | built-in `FetchTransport` |
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
- If the selected REST client transport has no `listen()`, the built-in server fallback is used
249
- without replacing the client transport. That fallback uses dynamically loaded `node:http`:
250
- browser-safe client imports do not imply browser server listening support.
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperttp/core",
3
- "version": "3.0.9",
3
+ "version": "3.1.0",
4
4
  "description": "Protocol-agnostic client/server execution core with pluggable protocols, transports and client policies",
5
5
  "keywords": [
6
6
  "browser",
@@ -1 +1 @@
1
- {"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/transports/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK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C"}
@@ -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 C = ["bun", "node", "deno", "browser"], x = [
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: C,
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
- { runtime: ["node"], pkg: "@hyperttp/transport-node", export: "FetchTransport" },
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: ["deno"], pkg: "@hyperttp/transport-deno", export: "DenoTransport" }
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 ? x.filter((o) => {
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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vBO,IAAM,KAAK,UAAU,CAAC,GAAGR,CAAS,EAAE,KAAI,CAAE,GAC1CqC,IAASpB,EAAM,MAAM,IAAIT,CAAG;AAClC,MAAI6B;AAAQ,WAAOA;AAEnB,QAAMC,IAAUrB,EAAM,iBAAiB,IAAIT,CAAG;AAC9C,MAAI8B;AAAS,WAAOA;AAEpB,QAAMC,IAAajB,EAAgBtB,GAAWC,CAAM,EACjD,KAAK,CAACH,MAAckC,EAAelC,GAAWmB,EAAM,OAAOT,CAAG,CAAC,EAC/D,QAAQ,MAAK;AACZ,IAAAS,EAAM,iBAAiB,OAAOT,CAAG;EACnC,CAAC;AAEH,SAAAS,EAAM,iBAAiB,IAAIT,GAAK+B,CAAU,GACnCA;AACT;AAQM,gBAAU,mBACd1C,IAA8B,QAC9BI,GAAgC;AAEhC,QAAMgB,IAAQF,EAASd,CAAM;AAC7B,UAAQA,GAAQ,gBAAgBgB,EAAM,SAASA,EAAM,QAAQ,IAAIpB,CAAQ;AAC3E;AAOM,gBAAU,qBAAqBC,GAAyB;AAC5D,aAAWmC,KAAWnB,EAAiB,IAAIhB,CAAS,KAAK,CAAA;AACvD,eAAW,CAACU,GAAK6B,CAAM,KAAKJ;AAC1B,MAAII,MAAWvC,KAAWmC,EAAQ,OAAOzB,CAAG;AAGhD,EAAAM,EAAiB,OAAOhB,CAAS;AACnC;AAQM,gBAAU,uBAAoB;AAClC,EAAAe,IAAkB,oBAAI,QAAO,GAC7BC,IAAmB,oBAAI,QAAO;AAChC;",
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,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;IACE,SAAS,CAAC,KAAK;IACf,KAAK;IACL,QAAQ;;EAEV,EAAE,SAAS,CAAC,MAAM,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T,CAAG;AAC9C,MAAI8B;AAAS,WAAOA;AAEpB,QAAMC,IAAajB,EAAgBtB,GAAWC,CAAM,EACjD,KAAK,CAACH,MAAckC,EAAelC,GAAWmB,EAAM,OAAOT,CAAG,CAAC,EAC/D,QAAQ,MAAK;AACZ,IAAAS,EAAM,iBAAiB,OAAOT,CAAG;EACnC,CAAC;AAEH,SAAAS,EAAM,iBAAiB,IAAIT,GAAK+B,CAAU,GACnCA;AACT;AAQM,gBAAU,mBACd1C,IAA8B,QAC9BI,GAAgC;AAEhC,QAAMgB,IAAQF,EAASd,CAAM;AAC7B,UAAQA,GAAQ,gBAAgBgB,EAAM,SAASA,EAAM,QAAQ,IAAIpB,CAAQ;AAC3E;AAOM,gBAAU,qBAAqBC,GAAyB;AAC5D,aAAWmC,KAAWnB,EAAiB,IAAIhB,CAAS,KAAK,CAAA;AACvD,eAAW,CAACU,GAAK6B,CAAM,KAAKJ;AAC1B,MAAII,MAAWvC,KAAWmC,EAAQ,OAAOzB,CAAG;AAGhD,EAAAM,EAAiB,OAAOhB,CAAS;AACnC;AAQM,gBAAU,uBAAoB;AAClC,EAAAe,IAAkB,oBAAI,QAAO,GAC7BC,IAAmB,oBAAI,QAAO;AAChC;",
6
6
  "names": ["dynamicImport", "isModuleNotFoundError", "ALL_RUNTIMES", "HTTP2_TRANSPORT_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
  }