@hyperttp/core 3.0.7 → 3.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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;AA+NL;;;;;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,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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"}
@@ -1,2 +1,183 @@
1
- "use strict";import{dynamicImport as g,isModuleNotFoundError as x}from"../utils/modules.js";export const CURRENT_RUNTIME=typeof Bun<"u"?"bun":typeof Deno<"u"?"deno":typeof process<"u"&&process.versions?.node?"node":"browser";const l=["bun","node","deno","browser"],C=[{protocols:["rest"],runtime:["bun"],pkg:"@hyperttp/transport-bun",export:"BunTransport"},{protocols:["rest"],runtime:["node"],pkg:"@hyperttp/transport-undici",export:"UndiciTransport"},{protocols:["rest"],runtime:["deno"],pkg:"@hyperttp/transport-deno",export:"DenoTransport"},{protocols:["rest","grpc"],runtime:["bun","node","deno"],pkg:"@hyperttp/transport-node",export:"Http2Transport"}],b=[{protocols:["webrtc"],runtime:l,pkg:"@hyperttp/transport-webrtc",export:"WebRtcTransport"},{protocols:["ws","websocket"],runtime:l,pkg:"@hyperttp/transport-websocket",export:"WebSocketTransport"},{protocols:["mqtt"],runtime:l,pkg:"@hyperttp/transport-mqtt",export:"MqttTransport"},{protocols:["grpc"],runtime:["bun","node","deno"],pkg:"@hyperttp/transport-node",export:"Http2Transport"},{runtime:["bun"],pkg:"@hyperttp/transport-bun",export:"BunTransport"},{runtime:["node"],pkg:"@hyperttp/transport-node",export:"FetchTransport"},{runtime:["node"],pkg:"@hyperttp/transport-undici",export:"UndiciTransport"},{runtime:["deno"],pkg:"@hyperttp/transport-deno",export:"DenoTransport"}];function R(t){return b.filter(e=>e.runtime.includes(CURRENT_RUNTIME)&&(!e.protocols||e.protocols.includes(t)))}function m(t,e){const r=e?.http2===!0?C.filter(o=>{const p=o.protocols;return o.runtime.includes(CURRENT_RUNTIME)&&(!p||t.some(u=>p.includes(u)))}):[],n=t.map(o=>R(o));n.sort((o,p)=>o.length-p.length);const s=new Map;for(const o of[...r,...n.flat()]){const p=`${o.pkg}:${o.export}`;s.has(p)||s.set(p,o)}return[...s.values()]}function M(t,e){const r=new Set(m(t,e).map(n=>n.pkg));return r.size===0?"":` Install ${[...r].map(n=>`"${n}"`).join(" or ")}.`}const E={};let d=new WeakMap,a=new WeakMap;function f(t){const e=t?.cacheKey??t??E;let r=d.get(e);return r||(r={client:new Map,listen:new Map,multi:new Map,clientResolutions:new Map,listenResolutions:new Map,multiResolutions:new Map},d.set(e,r)),r}function h(t){return typeof t.listen=="function"}function y(t,e){return typeof t.supports=="function"?t.supports(e):t.protocols?.includes(e)??!0}function w(t,e){return e.every(r=>y(t,r))}async function $(t){try{typeof t.destroy=="function"?await t.destroy():typeof t.close=="function"&&await t.close()}catch{}}async function T(t,e){const r=m(t,e);for(let s=0;s<r.length;s++){const o=r[s];let p;try{p=await g(o.pkg)}catch(c){if(!x(c))throw c;continue}const u=p[o.export]??p.default;if(typeof u!="function")continue;const i=new u(e??{});if(!w(i,t)||e?.requireListen&&!h(i)){await $(i);continue}return i}const n=t.length===1?"protocol":"protocols";throw new Error(`[HyperCore] No transport available for ${n} ${t.map(s=>`"${s}"`).join(", ")} in runtime "${CURRENT_RUNTIME}".${M(t,e)}`)}function k(t,e,r){e.set(r,t);let n=a.get(t);return n||(n=new Set,a.set(t,n)),n.add(e),t}export async function resolveTransport(t="rest",e){const r=e?.requireListen??!1;if(e?.customTransport){if(!y(e.customTransport,t))throw new Error(`[HyperCore] Custom transport does not support protocol "${t}".`);if(r&&!h(e.customTransport))throw new Error("[HyperCore] Custom transport does not support listen().");return e.customTransport}const n=f(e),s=r?n.listen:n.client,o=r?n.listenResolutions:n.clientResolutions,p=s.get(t);if(p)return p;const u=o.get(t);if(u)return u;const i=T([t],e).then(c=>k(c,s,t)).finally(()=>{o.delete(t)});return o.set(t,i),i}export async function resolveTransportForProtocols(t,e){if(t.length===0)throw new Error("[HyperCore] At least one protocol is required to resolve a transport.");if(t.length===1)return resolveTransport(t[0],e);const r=e?.requireListen??!1;if(e?.customTransport){if(!w(e.customTransport,t))throw new Error(`[HyperCore] Custom transport does not support protocols ${t.map(i=>`"${i}"`).join(", ")}.`);if(r&&!h(e.customTransport))throw new Error("[HyperCore] Custom transport does not support listen().");return e.customTransport}const n=f(e),s=JSON.stringify([...t].sort()),o=n.multi.get(s);if(o)return o;const p=n.multiResolutions.get(s);if(p)return p;const u=T(t,e).then(i=>k(i,n.multi,s)).finally(()=>{n.multiResolutions.delete(s)});return n.multiResolutions.set(s,u),u}export function getCachedTransport(t="rest",e){const r=f(e);return(e?.requireListen?r.listen:r.client).get(t)}export function evictCachedTransport(t){for(const e of a.get(t)??[])for(const[r,n]of e)n===t&&e.delete(r);a.delete(t)}export function resetCachedTransport(){d=new WeakMap,a=new WeakMap}
1
+ "use strict";
2
+ import { dynamicImport as k, isModuleNotFoundError as g } from "../utils/modules.js";
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 = [
5
+ {
6
+ protocols: ["rest"],
7
+ runtime: ["bun"],
8
+ pkg: "@hyperttp/transport-bun",
9
+ export: "BunTransport"
10
+ },
11
+ {
12
+ protocols: ["rest"],
13
+ runtime: ["node"],
14
+ pkg: "@hyperttp/transport-undici",
15
+ export: "UndiciTransport"
16
+ },
17
+ {
18
+ protocols: ["rest"],
19
+ runtime: ["deno"],
20
+ pkg: "@hyperttp/transport-deno",
21
+ export: "DenoTransport"
22
+ },
23
+ {
24
+ protocols: ["rest", "grpc"],
25
+ runtime: ["bun", "node", "deno"],
26
+ pkg: "@hyperttp/transport-node",
27
+ export: "Http2Transport"
28
+ }
29
+ ], R = [
30
+ {
31
+ protocols: ["webrtc"],
32
+ runtime: C,
33
+ pkg: "@hyperttp/transport-webrtc",
34
+ export: "WebRtcTransport"
35
+ },
36
+ {
37
+ protocols: ["grpc"],
38
+ runtime: ["bun", "node", "deno"],
39
+ pkg: "@hyperttp/transport-node",
40
+ export: "Http2Transport"
41
+ },
42
+ { runtime: ["bun"], pkg: "@hyperttp/transport-bun", export: "BunTransport" },
43
+ { runtime: ["node"], pkg: "@hyperttp/transport-node", export: "FetchTransport" },
44
+ { runtime: ["node"], pkg: "@hyperttp/transport-undici", export: "UndiciTransport" },
45
+ { runtime: ["deno"], pkg: "@hyperttp/transport-deno", export: "DenoTransport" }
46
+ ];
47
+ function b(t) {
48
+ return R.filter((e) => e.runtime.includes(CURRENT_RUNTIME) && (!e.protocols || e.protocols.includes(t)));
49
+ }
50
+ function h(t, e) {
51
+ const r = e?.http2 === !0 ? x.filter((o) => {
52
+ const p = o.protocols;
53
+ return o.runtime.includes(CURRENT_RUNTIME) && (!p || t.some((u) => p.includes(u)));
54
+ }) : [], n = t.map((o) => b(o));
55
+ n.sort((o, p) => o.length - p.length);
56
+ const s = /* @__PURE__ */ new Map();
57
+ for (const o of [...r, ...n.flat()]) {
58
+ const p = `${o.pkg}:${o.export}`;
59
+ s.has(p) || s.set(p, o);
60
+ }
61
+ return [...s.values()];
62
+ }
63
+ function M(t, e) {
64
+ const r = new Set(h(t, e).map((n) => n.pkg));
65
+ return r.size === 0 ? "" : ` Install ${[...r].map((n) => `"${n}"`).join(" or ")}.`;
66
+ }
67
+ const E = {};
68
+ let l = /* @__PURE__ */ new WeakMap(), a = /* @__PURE__ */ new WeakMap();
69
+ function d(t) {
70
+ const e = t?.cacheKey ?? t ?? E;
71
+ let r = l.get(e);
72
+ return r || (r = {
73
+ client: /* @__PURE__ */ new Map(),
74
+ listen: /* @__PURE__ */ new Map(),
75
+ multi: /* @__PURE__ */ new Map(),
76
+ clientResolutions: /* @__PURE__ */ new Map(),
77
+ listenResolutions: /* @__PURE__ */ new Map(),
78
+ multiResolutions: /* @__PURE__ */ new Map()
79
+ }, l.set(e, r)), r;
80
+ }
81
+ function f(t) {
82
+ return typeof t.listen == "function";
83
+ }
84
+ function m(t, e) {
85
+ return typeof t.supports == "function" ? t.supports(e) : t.protocols?.includes(e) ?? !0;
86
+ }
87
+ function y(t, e) {
88
+ return e.every((r) => m(t, r));
89
+ }
90
+ async function $(t) {
91
+ try {
92
+ typeof t.destroy == "function" ? await t.destroy() : typeof t.close == "function" && await t.close();
93
+ } catch {
94
+ }
95
+ }
96
+ async function T(t, e) {
97
+ const r = h(t, e);
98
+ for (let s = 0; s < r.length; s++) {
99
+ const o = r[s];
100
+ let p;
101
+ try {
102
+ p = await k(o.pkg);
103
+ } catch (c) {
104
+ if (!g(c))
105
+ throw c;
106
+ continue;
107
+ }
108
+ const u = p[o.export] ?? p.default;
109
+ if (typeof u != "function")
110
+ continue;
111
+ const i = new u(e ?? {});
112
+ if (!y(i, t) || e?.requireListen && !f(i)) {
113
+ await $(i);
114
+ continue;
115
+ }
116
+ return i;
117
+ }
118
+ const n = t.length === 1 ? "protocol" : "protocols";
119
+ throw new Error(`[HyperCore] No transport available for ${n} ${t.map((s) => `"${s}"`).join(", ")} in runtime "${CURRENT_RUNTIME}".${M(t, e)}`);
120
+ }
121
+ function w(t, e, r) {
122
+ e.set(r, t);
123
+ let n = a.get(t);
124
+ return n || (n = /* @__PURE__ */ new Set(), a.set(t, n)), n.add(e), t;
125
+ }
126
+ export async function resolveTransport(t = "rest", e) {
127
+ const r = e?.requireListen ?? !1;
128
+ if (e?.customTransport) {
129
+ if (!m(e.customTransport, t))
130
+ throw new Error(`[HyperCore] Custom transport does not support protocol "${t}".`);
131
+ if (r && !f(e.customTransport))
132
+ throw new Error("[HyperCore] Custom transport does not support listen().");
133
+ return e.customTransport;
134
+ }
135
+ const n = d(e), s = r ? n.listen : n.client, o = r ? n.listenResolutions : n.clientResolutions, p = s.get(t);
136
+ if (p)
137
+ return p;
138
+ const u = o.get(t);
139
+ if (u)
140
+ return u;
141
+ const i = T([t], e).then((c) => w(c, s, t)).finally(() => {
142
+ o.delete(t);
143
+ });
144
+ return o.set(t, i), i;
145
+ }
146
+ export async function resolveTransportForProtocols(t, e) {
147
+ if (t.length === 0)
148
+ throw new Error("[HyperCore] At least one protocol is required to resolve a transport.");
149
+ if (t.length === 1)
150
+ return resolveTransport(t[0], e);
151
+ const r = e?.requireListen ?? !1;
152
+ if (e?.customTransport) {
153
+ if (!y(e.customTransport, t))
154
+ throw new Error(`[HyperCore] Custom transport does not support protocols ${t.map((i) => `"${i}"`).join(", ")}.`);
155
+ if (r && !f(e.customTransport))
156
+ throw new Error("[HyperCore] Custom transport does not support listen().");
157
+ return e.customTransport;
158
+ }
159
+ const n = d(e), s = JSON.stringify([...t].sort()), o = n.multi.get(s);
160
+ if (o)
161
+ return o;
162
+ const p = n.multiResolutions.get(s);
163
+ if (p)
164
+ return p;
165
+ const u = T(t, e).then((i) => w(i, n.multi, s)).finally(() => {
166
+ n.multiResolutions.delete(s);
167
+ });
168
+ return n.multiResolutions.set(s, u), u;
169
+ }
170
+ export function getCachedTransport(t = "rest", e) {
171
+ const r = d(e);
172
+ return (e?.requireListen ? r.listen : r.client).get(t);
173
+ }
174
+ export function evictCachedTransport(t) {
175
+ for (const e of a.get(t) ?? [])
176
+ for (const [r, n] of e)
177
+ n === t && e.delete(r);
178
+ a.delete(t);
179
+ }
180
+ export function resetCachedTransport() {
181
+ l = /* @__PURE__ */ new WeakMap(), a = /* @__PURE__ */ new WeakMap();
182
+ }
2
183
  //# sourceMappingURL=manager.js.map
@@ -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: [\"ws\", \"websocket\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-websocket\",\n export: \"WebSocketTransport\",\n },\n {\n protocols: [\"mqtt\"],\n runtime: ALL_RUNTIMES,\n pkg: \"@hyperttp/transport-mqtt\",\n export: \"MqttTransport\",\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,OAAS,iBAAAA,EAAe,yBAAAC,MAA6B,sBAwB9C,aAAM,gBACP,OAAO,IAAQ,IAAoB,MACnC,OAAO,KAAS,IAAoB,OACpC,OAAO,QAAY,KAAe,QAAQ,UAAU,KAAa,OAC9D,UAWT,MAAMC,EAAmC,CAAC,MAAO,OAAQ,OAAQ,SAAS,EAEpEC,EAAgD,CACpD,CACE,UAAW,CAAC,MAAM,EAClB,QAAS,CAAC,KAAK,EACf,IAAK,0BACL,OAAQ,gBAEV,CACE,UAAW,CAAC,MAAM,EAClB,QAAS,CAAC,MAAM,EAChB,IAAK,6BACL,OAAQ,mBAEV,CACE,UAAW,CAAC,MAAM,EAClB,QAAS,CAAC,MAAM,EAChB,IAAK,2BACL,OAAQ,iBAEV,CACE,UAAW,CAAC,OAAQ,MAAM,EAC1B,QAAS,CAAC,MAAO,OAAQ,MAAM,EAC/B,IAAK,2BACL,OAAQ,mBAINC,EAA0C,CAC9C,CACE,UAAW,CAAC,QAAQ,EACpB,QAASF,EACT,IAAK,6BACL,OAAQ,mBAEV,CACE,UAAW,CAAC,KAAM,WAAW,EAC7B,QAASA,EACT,IAAK,gCACL,OAAQ,sBAEV,CACE,UAAW,CAAC,MAAM,EAClB,QAASA,EACT,IAAK,2BACL,OAAQ,iBAEV,CACE,UAAW,CAAC,MAAM,EAClB,QAAS,CAAC,MAAO,O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,EAC/D,QAAQ,IAAK,CACZS,EAAM,iBAAiB,OAAOT,CAAG,CACnC,CAAC,EAEH,OAAAS,EAAM,iBAAiB,IAAIT,EAAK+B,CAAU,EACnCA,CACT,CAQM,gBAAU,mBACd1C,EAA8B,OAC9BI,EAAgC,CAEhC,MAAMgB,EAAQF,EAASd,CAAM,EAC7B,OAAQA,GAAQ,cAAgBgB,EAAM,OAASA,EAAM,QAAQ,IAAIpB,CAAQ,CAC3E,CAOM,gBAAU,qBAAqBC,EAAyB,CAC5D,UAAWmC,KAAWnB,EAAiB,IAAIhB,CAAS,GAAK,CAAA,EACvD,SAAW,CAACU,EAAK6B,CAAM,IAAKJ,EACtBI,IAAWvC,GAAWmC,EAAQ,OAAOzB,CAAG,EAGhDM,EAAiB,OAAOhB,CAAS,CACnC,CAQM,gBAAU,sBAAoB,CAClCe,EAAkB,IAAI,QACtBC,EAAmB,IAAI,OACzB",
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,GAEpE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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
  }
package/utils/abort.js CHANGED
@@ -1,2 +1,19 @@
1
- "use strict";export function createTimeoutSignal(e,t,n,o){const r=new AbortController;let l=!1;const c=()=>{l||(l=!0,e&&e.removeEventListener("abort",i),clearTimeout(a))},a=setTimeout(()=>{r.signal.isTimeout=!0;const u=typeof o=="function"?o():o;r.abort(u??new DOMException("Timeout","TimeoutError")),c()},t),i=()=>{r.abort(e?.reason),c()};return e&&(e.aborted?i():e.addEventListener("abort",i)),n.cleanupSignal=c,r.signal}export function applyTimeout(e,t,n,o){return t==null||t<=0?e:createTimeoutSignal(e,t,n,o)}
1
+ "use strict";
2
+ export function createTimeoutSignal(e, t, n, o) {
3
+ const r = new AbortController();
4
+ let l = !1;
5
+ const c = () => {
6
+ l || (l = !0, e && e.removeEventListener("abort", i), clearTimeout(a));
7
+ }, a = setTimeout(() => {
8
+ r.signal.isTimeout = !0;
9
+ const u = typeof o == "function" ? o() : o;
10
+ r.abort(u ?? new DOMException("Timeout", "TimeoutError")), c();
11
+ }, t), i = () => {
12
+ r.abort(e?.reason), c();
13
+ };
14
+ return e && (e.aborted ? i() : e.addEventListener("abort", i)), n.cleanupSignal = c, r.signal;
15
+ }
16
+ export function applyTimeout(e, t, n, o) {
17
+ return t == null || t <= 0 ? e : createTimeoutSignal(e, t, n, o);
18
+ }
2
19
  //# sourceMappingURL=abort.js.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/abort.ts"],
4
4
  "sourcesContent": ["/**\n * @ru Создаёт AbortSignal с тайм-аутом и привязкой к пользовательскому сигналу отмены.\n * @en Creates an AbortSignal with timeout and user abort signal binding.\n * @param userSignal - Optional external abort signal.\n * @param timeoutMs - Timeout in milliseconds.\n * @param meta - Metadata object receiving the cleanup function.\n * @returns AbortSignal bound to the timeout and user signal.\n */\nexport function createTimeoutSignal(\n userSignal: AbortSignal | undefined,\n timeoutMs: number,\n meta: { cleanupSignal?: () => void },\n timeoutReason?: unknown | (() => unknown),\n): AbortSignal {\n const controller = new AbortController();\n\n let cleaned = false;\n const cleanup = () => {\n if (cleaned) return;\n cleaned = true;\n\n if (userSignal) {\n userSignal.removeEventListener(\"abort\", onUserAbort);\n }\n clearTimeout(timeoutId);\n };\n\n const timeoutId = setTimeout(() => {\n (controller.signal as { isTimeout?: boolean }).isTimeout = true;\n const reason =\n typeof timeoutReason === \"function\" ? (timeoutReason as () => unknown)() : timeoutReason;\n controller.abort(reason ?? new DOMException(\"Timeout\", \"TimeoutError\"));\n cleanup();\n }, timeoutMs);\n\n const onUserAbort = () => {\n controller.abort(userSignal?.reason);\n cleanup();\n };\n\n if (userSignal) {\n if (userSignal.aborted) {\n onUserAbort();\n } else {\n userSignal.addEventListener(\"abort\", onUserAbort);\n }\n }\n\n meta.cleanupSignal = cleanup;\n\n return controller.signal;\n}\n\n/**\n * @ru Применяет тайм-аут к сигналу отмены.\n * @en Applies a timeout to the abort signal.\n * @param signal - Optional external abort signal.\n * @param timeout - Timeout in milliseconds (skip if null/<=0).\n * @param meta - Metadata object receiving the cleanup function.\n * @returns New abort signal with timeout, or the original signal.\n */\nexport function applyTimeout(\n signal: AbortSignal | undefined,\n timeout: number | undefined,\n meta: { cleanupSignal?: () => void },\n timeoutReason?: unknown | (() => unknown),\n): AbortSignal | undefined {\n if (timeout == null || timeout <= 0) return signal;\n return createTimeoutSignal(signal, timeout, meta, timeoutReason);\n}\n"],
5
- "mappings": "aAQM,gBAAU,oBACdA,EACAC,EACAC,EACAC,EAAyC,CAEzC,MAAMC,EAAa,IAAI,gBAEvB,IAAIC,EAAU,GACd,MAAMC,EAAU,IAAK,CACfD,IACJA,EAAU,GAENL,GACFA,EAAW,oBAAoB,QAASO,CAAW,EAErD,aAAaC,CAAS,EACxB,EAEMA,EAAY,WAAW,IAAK,CAC/BJ,EAAW,OAAmC,UAAY,GAC3D,MAAMK,EACJ,OAAON,GAAkB,WAAcA,EAA+B,EAAKA,EAC7EC,EAAW,MAAMK,GAAU,IAAI,aAAa,UAAW,cAAc,CAAC,EACtEH,EAAO,CACT,EAAGL,CAAS,EAENM,EAAc,IAAK,CACvBH,EAAW,MAAMJ,GAAY,MAAM,EACnCM,EAAO,CACT,EAEA,OAAIN,IACEA,EAAW,QACbO,EAAW,EAEXP,EAAW,iBAAiB,QAASO,CAAW,GAIpDL,EAAK,cAAgBI,EAEdF,EAAW,MACpB,CAUM,gBAAU,aACdM,EACAC,EACAT,EACAC,EAAyC,CAEzC,OAAIQ,GAAW,MAAQA,GAAW,EAAUD,EACrC,oBAAoBA,EAAQC,EAAST,EAAMC,CAAa,CACjE",
5
+ "mappings": ";AAQM,gBAAU,oBACdA,GACAC,GACAC,GACAC,GAAyC;AAEzC,QAAMC,IAAa,IAAI,gBAAe;AAEtC,MAAIC,IAAU;AACd,QAAMC,IAAU,MAAK;AACnB,IAAID,MACJA,IAAU,IAENL,KACFA,EAAW,oBAAoB,SAASO,CAAW,GAErD,aAAaC,CAAS;EACxB,GAEMA,IAAY,WAAW,MAAK;AAC/B,IAAAJ,EAAW,OAAmC,YAAY;AAC3D,UAAMK,IACJ,OAAON,KAAkB,aAAcA,EAA+B,IAAKA;AAC7E,IAAAC,EAAW,MAAMK,KAAU,IAAI,aAAa,WAAW,cAAc,CAAC,GACtEH,EAAO;EACT,GAAGL,CAAS,GAENM,IAAc,MAAK;AACvB,IAAAH,EAAW,MAAMJ,GAAY,MAAM,GACnCM,EAAO;EACT;AAEA,SAAIN,MACEA,EAAW,UACbO,EAAW,IAEXP,EAAW,iBAAiB,SAASO,CAAW,IAIpDL,EAAK,gBAAgBI,GAEdF,EAAW;AACpB;AAUM,gBAAU,aACdM,GACAC,GACAT,GACAC,GAAyC;AAEzC,SAAIQ,KAAW,QAAQA,KAAW,IAAUD,IACrC,oBAAoBA,GAAQC,GAAST,GAAMC,CAAa;AACjE;",
6
6
  "names": ["userSignal", "timeoutMs", "meta", "timeoutReason", "controller", "cleaned", "cleanup", "onUserAbort", "timeoutId", "reason", "signal", "timeout"]
7
7
  }
package/utils/errors.js CHANGED
@@ -1,2 +1,47 @@
1
- "use strict";export class HyperClientError extends Error{code;statusCode;originalError;url;method;constructor(t,e="HYPER_ERROR",s,o,r,i){super(t,o?{cause:o}:void 0),this.code=e,this.statusCode=s,this.originalError=o,this.url=r,this.method=i,this.name="HyperClientError",Object.setPrototypeOf(this,new.target.prototype)}static isHyperClientError(t){return t instanceof HyperClientError||t instanceof Error&&"code"in t&&t.code==="HYPER_ERROR"}}export class TimeoutError extends HyperClientError{constructor(t,e){super(`Timeout after ${e}ms`,"TIMEOUT",408,void 0,t),this.name="TimeoutError",Object.setPrototypeOf(this,new.target.prototype)}static isTimeoutError(t){return t instanceof TimeoutError||t instanceof Error&&"code"in t&&t.code==="TIMEOUT"}}
1
+ "use strict";
2
+ export class HyperClientError extends Error {
3
+ code;
4
+ statusCode;
5
+ originalError;
6
+ url;
7
+ method;
8
+ /**
9
+ * @ru Создает ошибку Hyperttp с дополнительным сетевым контекстом.
10
+ * @en Creates a Hyperttp error with optional network context.
11
+ * @param message - Человекочитаемое описание ошибки. @en Human-readable error description.
12
+ * @param code - Машиночитаемый код ошибки. @en Machine-readable error code.
13
+ * @param statusCode - Связанный HTTP-статус, если есть. @en Associated HTTP status, when available.
14
+ * @param originalError - Исходная ошибка как `cause`. @en Original error exposed as `cause`.
15
+ * @param url - URL, связанный с ошибкой. @en URL associated with the error.
16
+ * @param method - HTTP-метод, связанный с ошибкой. @en HTTP method associated with the error.
17
+ */
18
+ constructor(t, e = "HYPER_ERROR", s, o, r, i) {
19
+ super(t, o ? { cause: o } : void 0), this.code = e, this.statusCode = s, this.originalError = o, this.url = r, this.method = i, this.name = "HyperClientError", Object.setPrototypeOf(this, new.target.prototype);
20
+ }
21
+ /**
22
+ * @ru Проверяет, является ли ошибка экземпляром HyperClientError (безопасно для разрозненных бандлов).
23
+ * @en Checks if an error is a HyperClientError instance (bundle boundary safe).
24
+ */
25
+ static isHyperClientError(t) {
26
+ return t instanceof HyperClientError || t instanceof Error && "code" in t && t.code === "HYPER_ERROR";
27
+ }
28
+ }
29
+ export class TimeoutError extends HyperClientError {
30
+ /**
31
+ * @ru Создает ошибку таймаута для указанного URL.
32
+ * @en Creates a timeout error for the given URL.
33
+ * @param url - URL запроса с истекшим таймаутом. @en URL of the timed-out request.
34
+ * @param timeout - Лимит времени в миллисекундах. @en Time limit in milliseconds.
35
+ */
36
+ constructor(t, e) {
37
+ super(`Timeout after ${e}ms`, "TIMEOUT", 408, void 0, t), this.name = "TimeoutError", Object.setPrototypeOf(this, new.target.prototype);
38
+ }
39
+ /**
40
+ * @ru Проверяет, является ли ошибка экземпляром TimeoutError.
41
+ * @en Checks if an error is a TimeoutError instance.
42
+ */
43
+ static isTimeoutError(t) {
44
+ return t instanceof TimeoutError || t instanceof Error && "code" in t && t.code === "TIMEOUT";
45
+ }
46
+ }
2
47
  //# sourceMappingURL=errors.js.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/errors.ts"],
4
4
  "sourcesContent": ["/**\n * @ru Базовый класс ошибок клиента Hyperttp, агрегирующий контекст неудачного сетевого запроса.\n * @en Base error class for the Hyperttp client, providing explicit layout context for failed requests.\n */\nexport class HyperClientError extends Error {\n /**\n * @ru Создает ошибку Hyperttp с дополнительным сетевым контекстом.\n * @en Creates a Hyperttp error with optional network context.\n * @param message - Человекочитаемое описание ошибки. @en Human-readable error description.\n * @param code - Машиночитаемый код ошибки. @en Machine-readable error code.\n * @param statusCode - Связанный HTTP-статус, если есть. @en Associated HTTP status, when available.\n * @param originalError - Исходная ошибка как `cause`. @en Original error exposed as `cause`.\n * @param url - URL, связанный с ошибкой. @en URL associated with the error.\n * @param method - HTTP-метод, связанный с ошибкой. @en HTTP method associated with the error.\n */\n constructor(\n message: string,\n public code: string = \"HYPER_ERROR\",\n public statusCode?: number,\n public originalError?: Error,\n public url?: string,\n public method?: string,\n ) {\n super(message, originalError ? { cause: originalError } : undefined);\n this.name = \"HyperClientError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * @ru Проверяет, является ли ошибка экземпляром HyperClientError (безопасно для разрозненных бандлов).\n * @en Checks if an error is a HyperClientError instance (bundle boundary safe).\n */\n public static isHyperClientError(err: unknown): err is HyperClientError {\n return (\n err instanceof HyperClientError ||\n (err instanceof Error && \"code\" in err && err.code === \"HYPER_ERROR\")\n );\n }\n}\n\n/**\n * @ru Ошибка, возникающая при превышении лимита времени ожидания ответа от сервера.\n * @en Error thrown when a network request exceeds its allocated execution timeout threshold.\n */\nexport class TimeoutError extends HyperClientError {\n /**\n * @ru Создает ошибку таймаута для указанного URL.\n * @en Creates a timeout error for the given URL.\n * @param url - URL запроса с истекшим таймаутом. @en URL of the timed-out request.\n * @param timeout - Лимит времени в миллисекундах. @en Time limit in milliseconds.\n */\n constructor(url: string, timeout: number) {\n super(`Timeout after ${timeout}ms`, \"TIMEOUT\", 408, undefined, url);\n this.name = \"TimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * @ru Проверяет, является ли ошибка экземпляром TimeoutError.\n * @en Checks if an error is a TimeoutError instance.\n */\n public static isTimeoutError(err: unknown): err is TimeoutError {\n return (\n err instanceof TimeoutError ||\n (err instanceof Error && \"code\" in err && err.code === \"TIMEOUT\")\n );\n }\n}\n"],
5
- "mappings": "aAI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AACvC,WACEA,aAAe,gBACdA,aAAe,SAAS,UAAUA,KAAOA,EAAI,SAAS;EAE3D;;",
6
6
  "names": ["message", "code", "statusCode", "originalError", "url", "method", "err", "timeout"]
7
7
  }
package/utils/merge.js CHANGED
@@ -1,2 +1,19 @@
1
- "use strict";export function deepMerge(n,c){const e={...n};for(const t in c){if(!Object.prototype.hasOwnProperty.call(c,t)||t==="__proto__"||t==="constructor"||t==="prototype")continue;const o=c[t],u=e[t];if(r(o)&&r(u)){e[t]=deepMerge(u,o);continue}o!==void 0&&(e[t]=r(o)?deepMerge({},o):o)}return e}function r(n){return typeof n=="object"&&n!==null&&(n.constructor===Object||n.constructor===void 0)}
1
+ "use strict";
2
+ export function deepMerge(n, c) {
3
+ const e = { ...n };
4
+ for (const t in c) {
5
+ if (!Object.prototype.hasOwnProperty.call(c, t) || t === "__proto__" || t === "constructor" || t === "prototype")
6
+ continue;
7
+ const o = c[t], u = e[t];
8
+ if (r(o) && r(u)) {
9
+ e[t] = deepMerge(u, o);
10
+ continue;
11
+ }
12
+ o !== void 0 && (e[t] = r(o) ? deepMerge({}, o) : o);
13
+ }
14
+ return e;
15
+ }
16
+ function r(n) {
17
+ return typeof n == "object" && n !== null && (n.constructor === Object || n.constructor === void 0);
18
+ }
2
19
  //# sourceMappingURL=merge.js.map
@@ -2,6 +2,6 @@
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/merge.ts"],
4
4
  "sourcesContent": ["/**\n * @ru Рекурсивно объединяет два объекта. Избегает лишних аллокаций памяти и защищает от разделения ссылок nested-структур.\n * @en Recursively merges two objects. Avoids redundant memory allocations and prevents shared reference leakage for nested structures.\n */\nexport function deepMerge<T extends Record<string, unknown>, S extends Record<string, unknown>>(\n target: T,\n source: S,\n): T & S {\n const output: Record<string, unknown> = { ...target };\n\n for (const key in source) {\n if (!Object.prototype.hasOwnProperty.call(source, key)) continue;\n\n if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") {\n continue;\n }\n\n const sourceValue = source[key];\n const targetValue = output[key];\n\n if (isObject(sourceValue) && isObject(targetValue)) {\n output[key] = deepMerge(\n targetValue as Record<string, unknown>,\n sourceValue as Record<string, unknown>,\n );\n continue;\n }\n\n if (sourceValue !== undefined) {\n output[key] = isObject(sourceValue)\n ? deepMerge({}, sourceValue as Record<string, unknown>)\n : sourceValue;\n }\n }\n\n return output as T & S;\n}\n\n/**\n * @ru Быстрая проверка, является ли переданный элемент чистым объектом (исключая массивы и null).\n * @en Fast check verifying if the provided item is a plain object layout (excluding arrays and null).\n */\nfunction isObject(item: unknown): item is Record<string, unknown> {\n return (\n typeof item === \"object\" &&\n item !== null &&\n (item.constructor === Object || item.constructor === undefined)\n );\n}\n"],
5
- "mappings": "aAIM,gBAAU,UACdA,EACAC,EAAS,CAET,MAAMC,EAAkC,CAAE,GAAGF,CAAM,EAEnD,UAAWG,KAAOF,EAAQ,CAGxB,GAFI,CAAC,OAAO,UAAU,eAAe,KAAKA,EAAQE,CAAG,GAEjDA,IAAQ,aAAeA,IAAQ,eAAiBA,IAAQ,YAC1D,SAGF,MAAMC,EAAcH,EAAOE,CAAG,EACxBE,EAAcH,EAAOC,CAAG,EAE9B,GAAIG,EAASF,CAAW,GAAKE,EAASD,CAAW,EAAG,CAClDH,EAAOC,CAAG,EAAI,UACZE,EACAD,CAAsC,EAExC,QACF,CAEIA,IAAgB,SAClBF,EAAOC,CAAG,EAAIG,EAASF,CAAW,EAC9B,UAAU,CAAA,EAAIA,CAAsC,EACpDA,EAER,CAEA,OAAOF,CACT,CAMA,SAASI,EAASC,EAAa,CAC7B,OACE,OAAOA,GAAS,UAChBA,IAAS,OACRA,EAAK,cAAgB,QAAUA,EAAK,cAAgB,OAEzD",
5
+ "mappings": ";AAIM,gBAAU,UACdA,GACAC,GAAS;AAET,QAAMC,IAAkC,EAAE,GAAGF,EAAM;AAEnD,aAAWG,KAAOF,GAAQ;AAGxB,QAFI,CAAC,OAAO,UAAU,eAAe,KAAKA,GAAQE,CAAG,KAEjDA,MAAQ,eAAeA,MAAQ,iBAAiBA,MAAQ;AAC1D;AAGF,UAAMC,IAAcH,EAAOE,CAAG,GACxBE,IAAcH,EAAOC,CAAG;AAE9B,QAAIG,EAASF,CAAW,KAAKE,EAASD,CAAW,GAAG;AAClD,MAAAH,EAAOC,CAAG,IAAI,UACZE,GACAD,CAAsC;AAExC;IACF;AAEA,IAAIA,MAAgB,WAClBF,EAAOC,CAAG,IAAIG,EAASF,CAAW,IAC9B,UAAU,CAAA,GAAIA,CAAsC,IACpDA;EAER;AAEA,SAAOF;AACT;AAMA,SAASI,EAASC,GAAa;AAC7B,SACE,OAAOA,KAAS,YAChBA,MAAS,SACRA,EAAK,gBAAgB,UAAUA,EAAK,gBAAgB;AAEzD;",
6
6
  "names": ["target", "source", "output", "key", "sourceValue", "targetValue", "isObject", "item"]
7
7
  }
@@ -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,CAGjF"}
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
@@ -1,2 +1,24 @@
1
- "use strict";export function isModuleNotFoundError(e){if(!e||typeof e!="object")return!1;const o=e;if(o.code==="ERR_MODULE_NOT_FOUND"||o.code==="MODULE_NOT_FOUND")return!0;const n=e instanceof Error?e.message:String(o.message??"");return n.includes("Cannot find module")||n.includes("Failed to resolve")||n.includes("Failed to load")}export async function dynamicImport(e){return import(e)}
1
+ "use strict";
2
+ export function isModuleNotFoundError(e) {
3
+ if (!e || typeof e != "object")
4
+ return !1;
5
+ const t = e;
6
+ if (t.code === "ERR_MODULE_NOT_FOUND" || t.code === "MODULE_NOT_FOUND")
7
+ return !0;
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
+ }
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
+ }
23
+ }
2
24
  //# sourceMappingURL=modules.js.map
@@ -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 /* @vite-ignore */\n return import(/* webpackIgnore: true */ pkg);\n}\n"],
5
- "mappings": "aAAM,gBAAU,sBAAsBA,EAAY,CAChD,GAAI,CAACA,GAAO,OAAOA,GAAQ,SAAU,MAAO,GAC5C,MAAMC,EAAID,EACV,GAAIC,EAAE,OAAS,wBAA0BA,EAAE,OAAS,mBAAoB,MAAO,GAE/E,MAAMC,EAAUF,aAAe,MAAQA,EAAI,QAAU,OAAOC,EAAE,SAAW,EAAE,EAC3E,OACEC,EAAQ,SAAS,oBAAoB,GACrCA,EAAQ,SAAS,mBAAmB,GACpCA,EAAQ,SAAS,gBAAgB,CAErC,CAEA,sBAAsB,cAAcC,EAAW,CAE7C,OAAO,OAAiCA,EAC1C",
6
- "names": ["err", "e", "message", "pkg"]
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
  }