@hyperttp/core 2.0.5 → 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Core/HyperCore.d.ts +16 -5
- package/Core/HyperCore.d.ts.map +1 -1
- package/Core/HyperCore.js +1 -1
- package/Core/HyperCore.js.map +3 -3
- package/README.md +141 -14
- package/index.d.ts +1 -0
- package/index.d.ts.map +1 -1
- package/index.js.map +1 -1
- package/package.json +3 -3
- package/protocols/manager.d.ts.map +1 -1
- package/protocols/manager.js +1 -1
- package/protocols/manager.js.map +3 -3
- package/protocols/rest/receiver.d.ts.map +1 -1
- package/protocols/rest/receiver.js +1 -1
- package/protocols/rest/receiver.js.map +3 -3
- package/protocols/rest/sender.d.ts.map +1 -1
- package/protocols/rest/sender.js +1 -1
- package/protocols/rest/sender.js.map +3 -3
- package/transports/fetch.d.ts.map +1 -1
- package/transports/fetch.js +1 -1
- package/transports/fetch.js.map +3 -3
- package/transports/manager.d.ts +3 -1
- package/transports/manager.d.ts.map +1 -1
- package/transports/manager.js +1 -1
- package/transports/manager.js.map +3 -3
- package/utils/errors.d.ts +2 -2
- package/utils/errors.d.ts.map +1 -1
- package/utils/errors.js +1 -1
- package/utils/errors.js.map +2 -2
package/README.md
CHANGED
|
@@ -20,7 +20,7 @@ batteries-included HTTP framework. It connects three independent extension point
|
|
|
20
20
|
receive through a `HyperReceiver`, or implement both roles as a `HyperProtocol`.
|
|
21
21
|
- **Transports** own physical I/O. The current transport contract executes outgoing requests and can
|
|
22
22
|
additionally listen for incoming requests.
|
|
23
|
-
- **Plugins** add client
|
|
23
|
+
- **Plugins** add client policy and explicit server lifecycle hooks without expanding the core.
|
|
24
24
|
|
|
25
25
|
The core owns dispatch, lifecycle, plugin execution and resource coordination. REST is included as
|
|
26
26
|
the baseline protocol; additional protocols, optimized transports and higher-level behavior live in
|
|
@@ -55,7 +55,8 @@ protocol packages. New I/O implementations should be transport packages.
|
|
|
55
55
|
- Client lifecycle: `prepare → send → parse`.
|
|
56
56
|
- Server lifecycle: `receive → handle → respond`.
|
|
57
57
|
- Per-protocol transport resolution and coordinated transport ownership.
|
|
58
|
-
- Blocking and background client plugin hooks.
|
|
58
|
+
- Blocking and background client plugin hooks, plus separate blocking server hooks.
|
|
59
|
+
- Stable request contexts and final settlement callbacks for resource cleanup.
|
|
59
60
|
- Runtime-aware transport selection with a browser-safe fetch fallback.
|
|
60
61
|
- Strict TypeScript contracts and module augmentation for typed protocol namespaces.
|
|
61
62
|
- No bundled runtime dependencies.
|
|
@@ -66,10 +67,14 @@ protocol packages. New I/O implementations should be transport packages.
|
|
|
66
67
|
npm install @hyperttp/core @hyperttp/types
|
|
67
68
|
```
|
|
68
69
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
70
|
+
Core requires `@hyperttp/types@^0.5.0`. Shared lifecycle and plugin contracts are exported
|
|
71
|
+
from that package, including `CorePluginFactory`, `RequestOutcome`, `ServerPluginContext`
|
|
72
|
+
and `ServerRequestOutcome`. Use `HyperProtocolName` for protocol identifiers;
|
|
73
|
+
`SenderProtocol` remains a deprecated compatibility alias.
|
|
74
|
+
|
|
75
|
+
Optimized transports are optional. Select releases compatible with the current contracts.
|
|
76
|
+
The built-in `FetchTransport` supports REST by default; it is not a universal fallback for
|
|
77
|
+
WebRTC, MQTT or WebSocket. Protocol packages and transport packages serve different roles.
|
|
73
78
|
|
|
74
79
|
## Client quick start
|
|
75
80
|
|
|
@@ -133,6 +138,10 @@ await core.destroy();
|
|
|
133
138
|
Protocols can be client-only, server-only or expose both roles. The current transport contract always
|
|
134
139
|
provides client `execute()` and can additionally provide server `listen()`.
|
|
135
140
|
|
|
141
|
+
Use `await server.close()` to close just this listener, or `await core.destroy()` to close
|
|
142
|
+
all listeners and release owned transports. Router methods such as `server.rest.get()`
|
|
143
|
+
and typed service injection belong to the high-level `hyperttp` package, not Core.
|
|
144
|
+
|
|
136
145
|
## Protocols
|
|
137
146
|
|
|
138
147
|
REST is the only protocol implemented inside the core. External protocol modules are loaded lazily:
|
|
@@ -146,10 +155,17 @@ REST is the only protocol implemented inside the core. External protocol modules
|
|
|
146
155
|
| WebSocket | `@hyperttp/protocol-websocket` | `core.ws` / `core.websocket` |
|
|
147
156
|
| SSE | `@hyperttp/protocol-sse` | `core.sse` |
|
|
148
157
|
| MQTT | `@hyperttp/protocol-mqtt` | `core.mqtt` |
|
|
158
|
+
| WebRTC | `@hyperttp/protocol-webrtc` | `core.webrtc` |
|
|
149
159
|
|
|
150
160
|
If an optional protocol package is missing, resolution fails with an installation hint instead of
|
|
151
161
|
silently selecting another protocol.
|
|
152
162
|
|
|
163
|
+
Explicitly registered senders expose their method namespace immediately, including registrations
|
|
164
|
+
after construction. Receiver-only modules can be used by `listen()` but do not provide client methods.
|
|
165
|
+
`registerProtocol()` replaces the whole module; use `registerSender()` or `registerReceiver()`
|
|
166
|
+
to replace one role while preserving the other. Generated flat methods are updated without deleting
|
|
167
|
+
user overrides. Names colliding with Core API or prototype-sensitive properties are rejected.
|
|
168
|
+
|
|
153
169
|
### Protocol roles
|
|
154
170
|
|
|
155
171
|
A unified protocol module can expose either or both roles:
|
|
@@ -180,6 +196,14 @@ declare module "@hyperttp/types" {
|
|
|
180
196
|
interface HyperProtocols {
|
|
181
197
|
"my-protocol": MyProtocolMethods;
|
|
182
198
|
}
|
|
199
|
+
|
|
200
|
+
interface ProtocolServerRequestMap {
|
|
201
|
+
"my-protocol": MyServerRequest;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
interface ProtocolServerResponseMap {
|
|
205
|
+
"my-protocol": MyServerResponse;
|
|
206
|
+
}
|
|
183
207
|
}
|
|
184
208
|
```
|
|
185
209
|
|
|
@@ -211,6 +235,16 @@ Runtime selection:
|
|
|
211
235
|
| Deno | `@hyperttp/transport-deno` | built-in `FetchTransport` |
|
|
212
236
|
| Browser / edge | custom transport | built-in `FetchTransport` |
|
|
213
237
|
|
|
238
|
+
WebRTC, WebSocket and MQTT first try their specialized `@hyperttp/transport-webrtc`,
|
|
239
|
+
`@hyperttp/transport-websocket` and `@hyperttp/transport-mqtt` packages respectively.
|
|
240
|
+
Every candidate is checked for protocol support; runtime selection does not imply universal support.
|
|
241
|
+
|
|
242
|
+
Client and listen transport caches are separate and automatic transports are scoped by
|
|
243
|
+
configuration identity. A custom transport does not populate the default cache of other cores.
|
|
244
|
+
If the selected REST client transport has no `listen()`, the built-in server fallback is used
|
|
245
|
+
without replacing the client transport. That fallback uses dynamically loaded `node:http`:
|
|
246
|
+
browser-safe client imports do not imply browser server listening support.
|
|
247
|
+
|
|
214
248
|
A transport can also be supplied explicitly:
|
|
215
249
|
|
|
216
250
|
```ts
|
|
@@ -252,6 +286,32 @@ Hooks:
|
|
|
252
286
|
- `enabled(config)` controls registration.
|
|
253
287
|
- `setup(context)` initializes a plugin.
|
|
254
288
|
|
|
289
|
+
Stateful plugin instances belong to one core. Registering the same instance twice on that
|
|
290
|
+
core is idempotent; duplicate names and implicit cross-core reuse are rejected. Prefer
|
|
291
|
+
`pluginFactories: [() => withQueue(options), () => withInflight()]`: factories run once for
|
|
292
|
+
each constructor, `extend()` and `create()`. Explicit `plugins` still work; when deriving a
|
|
293
|
+
core, replace inherited stateful instances with fresh `plugins` or `plugins: []`.
|
|
294
|
+
A stateless plugin may opt into cross-core reuse with `shared: true`, but cannot define
|
|
295
|
+
`setup()`. This is a promise by its author that no request/core state is shared in closures.
|
|
296
|
+
|
|
297
|
+
Phases run START, PREPARE, CONTROL, FORMAT, NETWORK, DATA; an omitted phase uses START.
|
|
298
|
+
`onResponse` and `onError` are transformation/recovery hooks, not exactly-once cleanup hooks.
|
|
299
|
+
They retain their existing forward phase order. Each receives the envelope seen by its own
|
|
300
|
+
`onRequest` and a stable `RequestContext`. All error hooks are attempted despite recovery
|
|
301
|
+
or diagnostic failures. Recovered responses enter response processing unless response
|
|
302
|
+
processing already failed; failure during recovery processing is reported without another
|
|
303
|
+
recovery cycle.
|
|
304
|
+
|
|
305
|
+
Register mandatory resource cleanup with `requestContext.onSettled(callback)`. It runs
|
|
306
|
+
exactly once after blocking response/recovery processing, with `{ ok: true, response }` or
|
|
307
|
+
`{ ok: false, error }`. All callbacks are attempted; their errors are diagnostic only.
|
|
308
|
+
Callbacks cannot register more callbacks once settlement starts. Updated queue/inflight
|
|
309
|
+
plugins use this path: queue releases once and inflight followers receive the final outcome.
|
|
310
|
+
A follower calls `acceptFinalResponse(response)` to reuse the finalized result without
|
|
311
|
+
applying response transformations twice. Background work is not awaited for settlement.
|
|
312
|
+
Background response/header snapshots are shallow: nested bodies, streams and context remain
|
|
313
|
+
shared and must not be mutated.
|
|
314
|
+
|
|
255
315
|
Examples of functionality that belongs in plugins:
|
|
256
316
|
|
|
257
317
|
- retries and circuit breakers;
|
|
@@ -261,40 +321,107 @@ Examples of functionality that belongs in plugins:
|
|
|
261
321
|
- rate limiting, concurrency control and scheduling;
|
|
262
322
|
- schema validation and application-specific policies.
|
|
263
323
|
|
|
324
|
+
## Server plugins
|
|
325
|
+
|
|
326
|
+
Client hooks do not run on incoming `listen()` requests. Register separate server hooks
|
|
327
|
+
with the same `core.use()` / `pluginFactories` API:
|
|
328
|
+
|
|
329
|
+
```ts
|
|
330
|
+
core.use({
|
|
331
|
+
name: "server-headers",
|
|
332
|
+
onServerResponse(response) {
|
|
333
|
+
return {
|
|
334
|
+
...response,
|
|
335
|
+
headers: { ...response.headers, "x-powered-by": "hyperttp" },
|
|
336
|
+
};
|
|
337
|
+
},
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
await core.listen({
|
|
341
|
+
protocol: "rest",
|
|
342
|
+
port: 3000,
|
|
343
|
+
handler: () => ({ body: { ok: true } }),
|
|
344
|
+
});
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
Server pipeline:
|
|
348
|
+
|
|
349
|
+
```text
|
|
350
|
+
onServerRequest → receiver.receive → handler/receiver.handle
|
|
351
|
+
→ receiver.respond → onServerResponse → transport
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
- `onServerRequest` can replace the raw `TransportRequest` before decoding.
|
|
355
|
+
- `onServerResponse` can replace serialized `TransportResponse`, including headers/body,
|
|
356
|
+
before transport transmission. Preserve the body/stream if only changing headers.
|
|
357
|
+
- `onServerError` observes failures; all error hooks run and the first returned raw response
|
|
358
|
+
recovers. Recovery enters outgoing hooks unless those hooks already failed. Another error
|
|
359
|
+
during recovered-response processing is propagated without another recovery cycle.
|
|
360
|
+
- `onServerSettled` runs once per incoming request with the final preparation outcome, even
|
|
361
|
+
if other diagnostic/cleanup hooks throw. Use it for server cleanup, not client onSettled.
|
|
362
|
+
|
|
363
|
+
All server hooks are awaited, even on plugins declaring client `mode: "background"`.
|
|
364
|
+
They follow forward phase order with one snapshot per incoming request, sharing a stable
|
|
365
|
+
context with the listen-bound `protocol`, signal, state and metadata. Settlement means the
|
|
366
|
+
response is ready to hand to the transport, **not** that streaming finished or bytes reached
|
|
367
|
+
the peer. Transport write failures happen outside this hook boundary.
|
|
368
|
+
|
|
369
|
+
Outbound auth/cache/retry are not automatically server authorization, server caching or
|
|
370
|
+
response retries. A plugin must explicitly implement the relevant server hooks.
|
|
371
|
+
|
|
264
372
|
## Built-in REST protocol
|
|
265
373
|
|
|
266
374
|
The REST package exposes client and server roles through `RestProtocol`.
|
|
267
375
|
|
|
268
376
|
```ts
|
|
269
|
-
const getResponse = await core.rest.get("/users", {
|
|
377
|
+
const getResponse = await core.rest.get("https://example.com/users", {
|
|
270
378
|
query: { page: 1, tag: ["a", "b"] },
|
|
271
379
|
headers: { accept: "application/json" },
|
|
272
380
|
timeout: 5_000,
|
|
273
381
|
});
|
|
274
382
|
|
|
275
|
-
const postResponse = await core.rest.post("/users", {
|
|
383
|
+
const postResponse = await core.rest.post("https://example.com/users", {
|
|
276
384
|
name: "Ada",
|
|
277
385
|
});
|
|
278
386
|
|
|
279
|
-
const streamResponse = await core.rest.stream("/events");
|
|
387
|
+
const streamResponse = await core.rest.stream("https://example.com/events");
|
|
280
388
|
```
|
|
281
389
|
|
|
282
390
|
REST behavior includes:
|
|
283
391
|
|
|
284
392
|
- query serialization with repeated array parameters;
|
|
285
|
-
- header normalization;
|
|
393
|
+
- header normalization accepting `Headers`, records and tuple arrays;
|
|
286
394
|
- JSON serialization for plain object and array request bodies;
|
|
287
395
|
- JSON, text and binary response handling;
|
|
288
|
-
-
|
|
396
|
+
- browser-safe UTF-8 request encoding with no required global `Buffer`;
|
|
397
|
+
- timeout and user abort propagation, retained through the response stream lifetime;
|
|
289
398
|
- unbuffered stream mode;
|
|
399
|
+
- binary request preservation and backpressure-aware server streaming;
|
|
400
|
+
- prototype-safe query dictionaries, including repeated keys;
|
|
290
401
|
- request decoding and response serialization for the server role.
|
|
291
402
|
|
|
403
|
+
The built-in server limits request bodies to 10 MiB by default. `maxBodyBytes` must be a
|
|
404
|
+
non-negative safe integer; zero allows only empty bodies. Custom transports enforce their
|
|
405
|
+
own limits. REST does not add application validation, authorization or a redirect credential
|
|
406
|
+
policy; redirect support and credential handling depend on the selected transport.
|
|
407
|
+
|
|
408
|
+
Core does not apply a client base URL; use absolute URLs with the built-in fetch transport.
|
|
409
|
+
|
|
292
410
|
REST-specific public types are available from `@hyperttp/core/rest`.
|
|
293
411
|
|
|
294
412
|
## Lifecycle
|
|
295
413
|
|
|
414
|
+
Core states are initializing, running, destroying and destroyed. `setup()` may register
|
|
415
|
+
protocols/plugins but cannot start sends/listens or acquire transports. `destroy()` rejects
|
|
416
|
+
new operations, awaits pending server startup/close and, in graceful mode, waits for accepted
|
|
417
|
+
client calls including settlement. Calls paused before dispatch may reject at the next state
|
|
418
|
+
check. Forced destroy delegates interruption to transport `destroy()` and does not await
|
|
419
|
+
client calls; a non-cooperative transport can leave them pending. Streams outlive the send
|
|
420
|
+
promise: their deadline/cancellation remain active until completion, cancellation or failure.
|
|
421
|
+
Do not await `destroy()` from an active request hook: graceful shutdown waits for that call.
|
|
422
|
+
|
|
296
423
|
```ts
|
|
297
|
-
const child = core.extend({ verbose: true }); // shares
|
|
424
|
+
const child = core.extend({ verbose: true }); // shares existing and pending client transport leases
|
|
298
425
|
const isolated = core.create({}); // independent transport lifecycle
|
|
299
426
|
|
|
300
427
|
await child.destroy();
|
|
@@ -313,7 +440,7 @@ await core.destroy();
|
|
|
313
440
|
import { HyperClientError, TimeoutError } from "@hyperttp/core";
|
|
314
441
|
|
|
315
442
|
try {
|
|
316
|
-
await core.rest.get("/slow", { timeout: 1_000 });
|
|
443
|
+
await core.rest.get("https://example.com/slow", { timeout: 1_000 });
|
|
317
444
|
} catch (error) {
|
|
318
445
|
if (TimeoutError.isTimeoutError(error)) {
|
|
319
446
|
console.error("Request timed out");
|
|
@@ -347,7 +474,7 @@ from the ecosystem around it.
|
|
|
347
474
|
## Development
|
|
348
475
|
|
|
349
476
|
```bash
|
|
350
|
-
|
|
477
|
+
bun install --frozen-lockfile
|
|
351
478
|
npm run format:check
|
|
352
479
|
npm run lint
|
|
353
480
|
npm run typecheck
|
package/index.d.ts
CHANGED
|
@@ -3,4 +3,5 @@ export { HyperClientError, TimeoutError } from "./utils/errors.js";
|
|
|
3
3
|
export { deepMerge } from "./utils/merge.js";
|
|
4
4
|
export { RestProtocol, RestReceiver, RestSender } from "./protocols/rest/index.js";
|
|
5
5
|
export { KNOWN_PROTOCOLS, resetCachedProtocols, resolveProtocol, resolveReceiver, resolveSender, } from "./protocols/manager.js";
|
|
6
|
+
export type { CorePluginFactory, ServerPluginContext, ServerRequestOutcome } from "@hyperttp/types";
|
|
6
7
|
//# sourceMappingURL=index.d.ts.map
|
package/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACnF,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,wBAAwB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AACnF,OAAO,EACL,eAAe,EACf,oBAAoB,EACpB,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,wBAAwB,CAAC;AAEhC,YAAY,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAC"}
|
package/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["export { HyperCore } from \"./Core/index.js\";\nexport { HyperClientError, TimeoutError } from \"./utils/errors.js\";\nexport { deepMerge } from \"./utils/merge.js\";\nexport { RestProtocol, RestReceiver, RestSender } from \"./protocols/rest/index.js\";\nexport {\n KNOWN_PROTOCOLS,\n resetCachedProtocols,\n resolveProtocol,\n resolveReceiver,\n resolveSender,\n} from \"./protocols/manager.js\";\n"],
|
|
4
|
+
"sourcesContent": ["export { HyperCore } from \"./Core/index.js\";\nexport { HyperClientError, TimeoutError } from \"./utils/errors.js\";\nexport { deepMerge } from \"./utils/merge.js\";\nexport { RestProtocol, RestReceiver, RestSender } from \"./protocols/rest/index.js\";\nexport {\n KNOWN_PROTOCOLS,\n resetCachedProtocols,\n resolveProtocol,\n resolveReceiver,\n resolveSender,\n} from \"./protocols/manager.js\";\n\nexport type { CorePluginFactory, ServerPluginContext, ServerRequestOutcome } from \"@hyperttp/types\";\n"],
|
|
5
5
|
"mappings": "aAAA,OAAS,cAAiB,kBAC1B,OAAS,iBAAkB,iBAAoB,oBAC/C,OAAS,cAAiB,mBAC1B,OAAS,aAAc,aAAc,eAAkB,4BACvD,OACE,gBACA,qBACA,gBACA,gBACA,kBACK",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hyperttp/core",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.2",
|
|
4
4
|
"description": "Protocol-agnostic client/server execution core with pluggable protocols, transports and client policies",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"browser",
|
|
@@ -46,11 +46,11 @@
|
|
|
46
46
|
}
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
|
-
"@hyperttp/types": "^0.
|
|
49
|
+
"@hyperttp/types": "^0.5.0"
|
|
50
50
|
},
|
|
51
51
|
"engines": {
|
|
52
52
|
"node": ">=20"
|
|
53
53
|
},
|
|
54
|
-
"packageManager": "bun@1.4.
|
|
54
|
+
"packageManager": "bun@1.4.4",
|
|
55
55
|
"private": false
|
|
56
56
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/protocols/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EACb,aAAa,EACb,WAAW,EACX,cAAc,EACf,MAAM,iBAAiB,CAAC;AAkCzB;;;GAGG;AACH,eAAO,MAAM,eAAe,EAAE,SAAS,cAAc,EAGnD,CAAC;
|
|
1
|
+
{"version":3,"file":"manager.d.ts","sourceRoot":"","sources":["../../src/protocols/manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,aAAa,EACb,aAAa,EACb,WAAW,EACX,cAAc,EACf,MAAM,iBAAiB,CAAC;AAkCzB;;;GAGG;AACH,eAAO,MAAM,eAAe,EAAE,SAAS,cAAc,EAGnD,CAAC;AAMH;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,CAAC,SAAS,cAAc,EAC5D,QAAQ,EAAE,CAAC,EACX,OAAO,CAAC,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,GACnC,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CA0B/D;AAiCD;;;GAGG;AACH,wBAAsB,aAAa,CAAC,CAAC,SAAS,cAAc,EAC1D,QAAQ,EAAE,CAAC,EACX,OAAO,CAAC,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,GACnC,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAM7D;AAED;;;GAGG;AACH,wBAAsB,eAAe,CAAC,CAAC,SAAS,cAAc,EAC5D,QAAQ,EAAE,CAAC,EACX,OAAO,CAAC,EAAE;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,GACnC,OAAO,CAAC,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAM/D;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,IAAI,IAAI,CAI3C"}
|
package/protocols/manager.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";import{HyperClientError as
|
|
1
|
+
"use strict";import{HyperClientError as h}from"../utils/errors.js";import{dynamicImport as y,isModuleNotFoundError as u}from"../utils/modules.js";import{RestProtocol as d}from"./rest/index.js";const l=[{protocol:"graphql",pkg:"@hyperttp/protocol-graphql",export:"GraphQLProtocol"},{protocol:"grpc",pkg:"@hyperttp/protocol-grpc",export:"GrpcProtocol"},{protocol:"trpc",pkg:"@hyperttp/protocol-trpc",export:"TrpcProtocol"},{protocol:"ws",pkg:"@hyperttp/protocol-websocket",export:"WebSocketProtocol"},{protocol:"websocket",pkg:"@hyperttp/protocol-websocket",export:"WebSocketProtocol"},{protocol:"sse",pkg:"@hyperttp/protocol-sse",export:"SseProtocol"},{protocol:"mqtt",pkg:"@hyperttp/protocol-mqtt",export:"MqttProtocol"},{protocol:"webrtc",pkg:"@hyperttp/protocol-webrtc",export:"WebRtcProtocol"}];export const KNOWN_PROTOCOLS=Object.freeze(["rest",...l.map(o=>o.protocol)]);const i=new Map,p=new Map;let g=0;export async function resolveProtocol(o,r){const t=i.get(o);if(t)return t;if(o==="rest")return i.set(o,d),d;const s=p.get(o);if(s)return await s;const c=g,n=w(o,r).then(e=>(c===g&&i.set(o,e),e)).finally(()=>{p.get(o)===n&&p.delete(o)});return p.set(o,n),await n}async function w(o,r){for(let c=0;c<l.length;c++){const n=l[c];if(n.protocol===o)try{const e=await y(n.pkg),a=e[n.export]??e.default,f=typeof a=="function"?new a(r):a;if(!f||typeof f.protocol!="string")continue;return f}catch(e){if(!u(e))throw e}}const t=l.find(c=>c.protocol===o),s=t?` Did you forget to install "${t.pkg}"?`:"";throw new h(`[HyperCore] No protocol available for "${o}".${s}`)}export async function resolveSender(o,r){const t=await resolveProtocol(o,r);if(!t.sender)throw new h(`[HyperCore] Protocol "${o}" has no sender (client role).`);return t.sender}export async function resolveReceiver(o,r){const t=await resolveProtocol(o,r);if(!t.receiver)throw new h(`[HyperCore] Protocol "${o}" has no receiver (server role).`);return t.receiver}export function resetCachedProtocols(){g++,i.clear(),p.clear()}
|
|
2
2
|
//# sourceMappingURL=manager.js.map
|
package/protocols/manager.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/protocols/manager.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n AnyHyperProtocol,\n HyperProtocol,\n HyperReceiver,\n HyperSender,\n SenderProtocol,\n} from \"@hyperttp/types\";\nimport { HyperClientError } from \"../utils/errors.js\";\nimport { dynamicImport, isModuleNotFoundError } from \"../utils/modules.js\";\nimport { RestProtocol } from \"./rest/index.js\";\n\ntype ProtocolDef = {\n readonly protocol: SenderProtocol;\n readonly pkg: string;\n readonly export: string;\n};\n\nconst PROTOCOL_DEFS: readonly ProtocolDef[] = [\n {\n protocol: \"graphql\",\n pkg: \"@hyperttp/protocol-graphql\",\n export: \"GraphQLProtocol\",\n },\n { protocol: \"grpc\", pkg: \"@hyperttp/protocol-grpc\", export: \"GrpcProtocol\" },\n { protocol: \"trpc\", pkg: \"@hyperttp/protocol-trpc\", export: \"TrpcProtocol\" },\n {\n protocol: \"ws\",\n pkg: \"@hyperttp/protocol-websocket\",\n export: \"WebSocketProtocol\",\n },\n {\n protocol: \"websocket\",\n pkg: \"@hyperttp/protocol-websocket\",\n export: \"WebSocketProtocol\",\n },\n { protocol: \"sse\", pkg: \"@hyperttp/protocol-sse\", export: \"SseProtocol\" },\n { protocol: \"mqtt\", pkg: \"@hyperttp/protocol-mqtt\", export: \"MqttProtocol\" },\n { protocol: \"webrtc\", pkg: \"@hyperttp/protocol-webrtc\", export: \"WebRtcProtocol\" },\n];\n\n/**\n * @ru Известные протоколы ядра: встроенный rest и пакетные модули.\n * @en Known core protocols: the built-in rest and packaged modules.\n */\nexport const KNOWN_PROTOCOLS: readonly SenderProtocol[] = Object.freeze([\n \"rest\",\n ...PROTOCOL_DEFS.map((d) => d.protocol),\n]);\n\nconst protocolCache = new Map<string, AnyHyperProtocol>();\n\n/**\n * @ru Разрешает модуль протокола. Встроенный rest возвращается статически,\n * остальные протоколы загружаются из пакетных модулей по требованию.\n * @en Resolves a protocol module. The built-in rest is returned statically,\n * other protocols are loaded from packaged modules on demand.\n */\nexport async function resolveProtocol<P extends SenderProtocol>(\n protocol: P,\n options?: { [key: string]: unknown },\n): Promise<HyperProtocol<unknown, unknown, unknown, unknown, P>> {\n const cached = protocolCache.get(protocol);\n if (cached) {\n return cached as AnyHyperProtocol<P>;\n }\n\n if (protocol === \"rest\") {\n protocolCache.set(protocol, RestProtocol);\n return RestProtocol as AnyHyperProtocol<P>;\n }\n\n for (let i = 0; i < PROTOCOL_DEFS.length; i++) {\n const def = PROTOCOL_DEFS[i]!;\n if (def.protocol !== protocol) continue;\n\n try {\n const mod = await dynamicImport(def.pkg);\n const candidate = (mod[def.export] ?? mod.default) as\n | { new (opts?: unknown): AnyHyperProtocol }\n | AnyHyperProtocol\n | undefined;\n const instance =\n typeof candidate === \"function\" ? new candidate(options) : (candidate as AnyHyperProtocol);\n\n if (!instance || typeof instance.protocol !== \"string\") continue;\n\n
|
|
5
|
-
"mappings": "aAOA,OAAS,oBAAAA,MAAwB,qBACjC,OAAS,iBAAAC,EAAe,yBAAAC,MAA6B,sBACrD,OAAS,gBAAAC,MAAoB,kBAQ7B,MAAMC,EAAwC,CAC5C,CACE,SAAU,UACV,IAAK,6BACL,OAAQ,mBAEV,CAAE,SAAU,OAAQ,IAAK,0BAA2B,OAAQ,cAAc,EAC1E,CAAE,SAAU,OAAQ,IAAK,0BAA2B,OAAQ,cAAc,EAC1E,CACE,SAAU,KACV,IAAK,+BACL,OAAQ,qBAEV,CACE,SAAU,YACV,IAAK,+BACL,OAAQ,qBAEV,CAAE,SAAU,MAAO,IAAK,yBAA0B,OAAQ,aAAa,EACvE,CAAE,SAAU,OAAQ,IAAK,0BAA2B,OAAQ,cAAc,EAC1E,CAAE,SAAU,SAAU,IAAK,4BAA6B,OAAQ,gBAAgB,GAO3E,aAAM,gBAA6C,OAAO,OAAO,CACtE,OACA,GAAGA,EAAc,IAAKC,GAAMA,EAAE,QAAQ,EACvC,EAED,MAAMC,EAAgB,IAAI,
|
|
6
|
-
"names": ["HyperClientError", "dynamicImport", "isModuleNotFoundError", "RestProtocol", "PROTOCOL_DEFS", "d", "protocolCache", "protocol", "options", "cached", "
|
|
4
|
+
"sourcesContent": ["import type {\n AnyHyperProtocol,\n HyperProtocol,\n HyperReceiver,\n HyperSender,\n SenderProtocol,\n} from \"@hyperttp/types\";\nimport { HyperClientError } from \"../utils/errors.js\";\nimport { dynamicImport, isModuleNotFoundError } from \"../utils/modules.js\";\nimport { RestProtocol } from \"./rest/index.js\";\n\ntype ProtocolDef = {\n readonly protocol: SenderProtocol;\n readonly pkg: string;\n readonly export: string;\n};\n\nconst PROTOCOL_DEFS: readonly ProtocolDef[] = [\n {\n protocol: \"graphql\",\n pkg: \"@hyperttp/protocol-graphql\",\n export: \"GraphQLProtocol\",\n },\n { protocol: \"grpc\", pkg: \"@hyperttp/protocol-grpc\", export: \"GrpcProtocol\" },\n { protocol: \"trpc\", pkg: \"@hyperttp/protocol-trpc\", export: \"TrpcProtocol\" },\n {\n protocol: \"ws\",\n pkg: \"@hyperttp/protocol-websocket\",\n export: \"WebSocketProtocol\",\n },\n {\n protocol: \"websocket\",\n pkg: \"@hyperttp/protocol-websocket\",\n export: \"WebSocketProtocol\",\n },\n { protocol: \"sse\", pkg: \"@hyperttp/protocol-sse\", export: \"SseProtocol\" },\n { protocol: \"mqtt\", pkg: \"@hyperttp/protocol-mqtt\", export: \"MqttProtocol\" },\n { protocol: \"webrtc\", pkg: \"@hyperttp/protocol-webrtc\", export: \"WebRtcProtocol\" },\n];\n\n/**\n * @ru Известные протоколы ядра: встроенный rest и пакетные модули.\n * @en Known core protocols: the built-in rest and packaged modules.\n */\nexport const KNOWN_PROTOCOLS: readonly SenderProtocol[] = Object.freeze([\n \"rest\",\n ...PROTOCOL_DEFS.map((d) => d.protocol),\n]);\n\nconst protocolCache = new Map<string, AnyHyperProtocol>();\nconst pendingProtocols = new Map<string, Promise<AnyHyperProtocol>>();\nlet cacheGeneration = 0;\n\n/**\n * @ru Разрешает модуль протокола. Встроенный rest возвращается статически,\n * остальные протоколы загружаются из пакетных модулей по требованию.\n * @en Resolves a protocol module. The built-in rest is returned statically,\n * other protocols are loaded from packaged modules on demand.\n */\nexport async function resolveProtocol<P extends SenderProtocol>(\n protocol: P,\n options?: { [key: string]: unknown },\n): Promise<HyperProtocol<unknown, unknown, unknown, unknown, P>> {\n const cached = protocolCache.get(protocol);\n if (cached) {\n return cached as AnyHyperProtocol<P>;\n }\n\n if (protocol === \"rest\") {\n protocolCache.set(protocol, RestProtocol);\n return RestProtocol as AnyHyperProtocol<P>;\n }\n\n const pending = pendingProtocols.get(protocol);\n if (pending) return (await pending) as AnyHyperProtocol<P>;\n\n const generation = cacheGeneration;\n const resolution = loadProtocol(protocol, options)\n .then((instance) => {\n if (generation === cacheGeneration) protocolCache.set(protocol, instance);\n return instance;\n })\n .finally(() => {\n // A pre-reset resolution must not remove a newer pending load.\n if (pendingProtocols.get(protocol) === resolution) pendingProtocols.delete(protocol);\n });\n pendingProtocols.set(protocol, resolution);\n return (await resolution) as AnyHyperProtocol<P>;\n}\n\nasync function loadProtocol(\n protocol: SenderProtocol,\n options?: { [key: string]: unknown },\n): Promise<AnyHyperProtocol> {\n for (let i = 0; i < PROTOCOL_DEFS.length; i++) {\n const def = PROTOCOL_DEFS[i]!;\n if (def.protocol !== protocol) continue;\n\n try {\n const mod = await dynamicImport(def.pkg);\n const candidate = (mod[def.export] ?? mod.default) as\n | { new (opts?: unknown): AnyHyperProtocol }\n | AnyHyperProtocol\n | undefined;\n const instance =\n typeof candidate === \"function\" ? new candidate(options) : (candidate as AnyHyperProtocol);\n\n if (!instance || typeof instance.protocol !== \"string\") continue;\n\n return instance;\n } catch (err) {\n if (!isModuleNotFoundError(err)) throw err;\n }\n }\n\n const pkgDef = PROTOCOL_DEFS.find((d) => d.protocol === protocol);\n const hint = pkgDef ? ` Did you forget to install \"${pkgDef.pkg}\"?` : \"\";\n\n throw new HyperClientError(`[HyperCore] No protocol available for \"${protocol}\".${hint}`);\n}\n\n/**\n * @ru Разрешает клиентский сендер протокола.\n * @en Resolves the client sender of a protocol.\n */\nexport async function resolveSender<P extends SenderProtocol>(\n protocol: P,\n options?: { [key: string]: unknown },\n): Promise<HyperSender<unknown, unknown, unknown, unknown, P>> {\n const resolved = await resolveProtocol(protocol, options);\n if (!resolved.sender) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no sender (client role).`);\n }\n return resolved.sender;\n}\n\n/**\n * @ru Разрешает серверный ресивер протокола.\n * @en Resolves the server receiver of a protocol.\n */\nexport async function resolveReceiver<P extends SenderProtocol>(\n protocol: P,\n options?: { [key: string]: unknown },\n): Promise<HyperReceiver<unknown, unknown, unknown, unknown, P>> {\n const resolved = await resolveProtocol(protocol, options);\n if (!resolved.receiver) {\n throw new HyperClientError(`[HyperCore] Protocol \"${protocol}\" has no receiver (server role).`);\n }\n return resolved.receiver;\n}\n\n/**\n * @ru Очищает кэш загруженных модулей протоколов. Не выгружает уже импортированные\n * JavaScript-модули из runtime.\n * @en Clears the loaded protocol-module cache. It does not unload JavaScript\n * modules already imported by the runtime.\n */\nexport function resetCachedProtocols(): void {\n cacheGeneration++;\n protocolCache.clear();\n pendingProtocols.clear();\n}\n"],
|
|
5
|
+
"mappings": "aAOA,OAAS,oBAAAA,MAAwB,qBACjC,OAAS,iBAAAC,EAAe,yBAAAC,MAA6B,sBACrD,OAAS,gBAAAC,MAAoB,kBAQ7B,MAAMC,EAAwC,CAC5C,CACE,SAAU,UACV,IAAK,6BACL,OAAQ,mBAEV,CAAE,SAAU,OAAQ,IAAK,0BAA2B,OAAQ,cAAc,EAC1E,CAAE,SAAU,OAAQ,IAAK,0BAA2B,OAAQ,cAAc,EAC1E,CACE,SAAU,KACV,IAAK,+BACL,OAAQ,qBAEV,CACE,SAAU,YACV,IAAK,+BACL,OAAQ,qBAEV,CAAE,SAAU,MAAO,IAAK,yBAA0B,OAAQ,aAAa,EACvE,CAAE,SAAU,OAAQ,IAAK,0BAA2B,OAAQ,cAAc,EAC1E,CAAE,SAAU,SAAU,IAAK,4BAA6B,OAAQ,gBAAgB,GAO3E,aAAM,gBAA6C,OAAO,OAAO,CACtE,OACA,GAAGA,EAAc,IAAKC,GAAMA,EAAE,QAAQ,EACvC,EAED,MAAMC,EAAgB,IAAI,IACpBC,EAAmB,IAAI,IAC7B,IAAIC,EAAkB,EAQtB,sBAAsB,gBACpBC,EACAC,EAAoC,CAEpC,MAAMC,EAASL,EAAc,IAAIG,CAAQ,EACzC,GAAIE,EACF,OAAOA,EAGT,GAAIF,IAAa,OACf,OAAAH,EAAc,IAAIG,EAAUN,CAAY,EACjCA,EAGT,MAAMS,EAAUL,EAAiB,IAAIE,CAAQ,EAC7C,GAAIG,EAAS,OAAQ,MAAMA,EAE3B,MAAMC,EAAaL,EACbM,EAAaC,EAAaN,EAAUC,CAAO,EAC9C,KAAMM,IACDH,IAAeL,GAAiBF,EAAc,IAAIG,EAAUO,CAAQ,EACjEA,EACR,EACA,QAAQ,IAAK,CAERT,EAAiB,IAAIE,CAAQ,IAAMK,GAAYP,EAAiB,OAAOE,CAAQ,CACrF,CAAC,EACH,OAAAF,EAAiB,IAAIE,EAAUK,CAAU,EACjC,MAAMA,CAChB,CAEA,eAAeC,EACbN,EACAC,EAAoC,CAEpC,QAASO,EAAI,EAAGA,EAAIb,EAAc,OAAQa,IAAK,CAC7C,MAAMC,EAAMd,EAAca,CAAC,EAC3B,GAAIC,EAAI,WAAaT,EAErB,GAAI,CACF,MAAMU,EAAM,MAAMlB,EAAciB,EAAI,GAAG,EACjCE,EAAaD,EAAID,EAAI,MAAM,GAAKC,EAAI,QAIpCH,EACJ,OAAOI,GAAc,WAAa,IAAIA,EAAUV,CAAO,EAAKU,EAE9D,GAAI,CAACJ,GAAY,OAAOA,EAAS,UAAa,SAAU,SAExD,OAAOA,CACT,OAASK,EAAK,CACZ,GAAI,CAACnB,EAAsBmB,CAAG,EAAG,MAAMA,CACzC,CACF,CAEA,MAAMC,EAASlB,EAAc,KAAMC,GAAMA,EAAE,WAAaI,CAAQ,EAC1Dc,EAAOD,EAAS,+BAA+BA,EAAO,GAAG,KAAO,GAEtE,MAAM,IAAItB,EAAiB,0CAA0CS,CAAQ,KAAKc,CAAI,EAAE,CAC1F,CAMA,sBAAsB,cACpBd,EACAC,EAAoC,CAEpC,MAAMc,EAAW,MAAM,gBAAgBf,EAAUC,CAAO,EACxD,GAAI,CAACc,EAAS,OACZ,MAAM,IAAIxB,EAAiB,yBAAyBS,CAAQ,gCAAgC,EAE9F,OAAOe,EAAS,MAClB,CAMA,sBAAsB,gBACpBf,EACAC,EAAoC,CAEpC,MAAMc,EAAW,MAAM,gBAAgBf,EAAUC,CAAO,EACxD,GAAI,CAACc,EAAS,SACZ,MAAM,IAAIxB,EAAiB,yBAAyBS,CAAQ,kCAAkC,EAEhG,OAAOe,EAAS,QAClB,CAQM,gBAAU,sBAAoB,CAClChB,IACAF,EAAc,MAAK,EACnBC,EAAiB,MAAK,CACxB",
|
|
6
|
+
"names": ["HyperClientError", "dynamicImport", "isModuleNotFoundError", "RestProtocol", "PROTOCOL_DEFS", "d", "protocolCache", "pendingProtocols", "cacheGeneration", "protocol", "options", "cached", "pending", "generation", "resolution", "loadProtocol", "instance", "i", "def", "mod", "candidate", "err", "pkgDef", "hint", "resolved"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"receiver.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/receiver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,oBAAoB,EACpB,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"receiver.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/receiver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,oBAAoB,EACpB,gBAAgB,EAChB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AA6FxF;;;;;GAKG;AACH,qBAAa,YAAa,YAAW,aAAa,CAChD,eAAe,EACf,kBAAkB,EAClB,gBAAgB,EAChB,iBAAiB,CAClB;IACC,QAAQ,CAAC,QAAQ,UAAU;IAC3B,SAAS,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,iBAAiB,CAAC;IAE/C;;;;OAIG;IACH,YAAY,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,iBAAiB,CAAA;KAAO,EAExD;IAED;;;OAGG;IACH,OAAO,CAAC,GAAG,EAAE,gBAAgB,EAAE,IAAI,EAAE,oBAAoB,GAAG,eAAe,CAU1E;IAED;;;OAGG;IACH,MAAM,CACJ,OAAO,EAAE,eAAe,EACxB,GAAG,EAAE,oBAAoB,GACxB,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAYlD;IAED;;;OAGG;IACH,OAAO,CAAC,QAAQ,EAAE,kBAAkB,EAAE,IAAI,EAAE,oBAAoB,GAAG,iBAAiB,CA6BnF;CACF"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";import{HyperClientError as
|
|
1
|
+
"use strict";import{HyperClientError as h}from"../../utils/errors.js";import{DEFAULT_STATUS_TEXTS as c,getHeaderValue as u}from"./utils.js";const s="application/json",d=new TextDecoder,p=new TextEncoder,a=typeof Buffer<"u";function l(n){return a?Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString("utf8"):d.decode(n)}function b(n){return a?Buffer.from(n).toString("utf8"):d.decode(n)}function T(n){return a?Buffer.from(n):p.encode(n)}function m(n){const e=Object.create(null);for(const[r,o]of new URLSearchParams(n)){const i=e[r];i===void 0?e[r]=o:Array.isArray(i)?i.push(o):e[r]=[i,o]}return e}function f(n,e){if((u(n,"content-type")??"").includes(s))try{return JSON.parse(e)}catch{return e}return e}function A(n){const e=n.body;if(e==null)return;const r=u(n.headers,"content-type")??"",o=r.includes(s)||r.includes("text/")||r.includes("application/xml")||r.includes("application/x-www-form-urlencoded");if(e instanceof Uint8Array)return o?f(n.headers,l(e)):e;if(e instanceof ArrayBuffer)return o?f(n.headers,b(e)):new Uint8Array(e);if(ArrayBuffer.isView(e)){const i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return o?f(n.headers,l(i)):i}return typeof e=="string"?f(n.headers,e):e}export class RestReceiver{protocol="rest";handler;constructor(e={}){this.handler=e.handler}receive(e,r){const o=new URL(e.url,"http://hyperttp.local");return{method:e.method,path:o.pathname,headers:e.headers,query:m(o.search.slice(1)),body:A(e)}}handle(e,r){if(r.signal?.aborted)throw r.signal.reason??new Error("Request aborted");if(!this.handler)throw new h('[RestReceiver] No application handler registered for protocol "rest".');return this.handler(e,r)}respond(e,r){const o={...e.headers},i=e.status??200;let t=e.body;return t!=null&&typeof t=="object"&&(typeof ReadableStream<"u"&&t instanceof ReadableStream||Symbol.asyncIterator in t)?{status:i,statusText:c[i]??"",headers:o,body:t}:(t instanceof ArrayBuffer?t=new Uint8Array(t):ArrayBuffer.isView(t)&&!(t instanceof Uint8Array)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength).slice():t!=null&&typeof t=="object"&&!(t instanceof Uint8Array)&&(t=JSON.stringify(t),Object.keys(o).some(y=>y.toLowerCase()==="content-type")||(o["content-type"]=s)),{status:i,statusText:c[i]??"",headers:o,body:t==null?void 0:t instanceof Uint8Array?t:T(String(t))})}}
|
|
2
2
|
//# sourceMappingURL=receiver.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/protocols/rest/receiver.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n HyperReceiver,\n ServerRequestContext,\n TransportRequest,\n TransportResponse,\n} from \"@hyperttp/types\";\nimport type { RestServerHandler, RestServerInput, RestServerResponse } from \"./type.js\";\nimport { HyperClientError } from \"../../utils/errors.js\";\nimport { DEFAULT_STATUS_TEXTS, getHeaderValue } from \"./utils.js\";\n\nconst JSON_TYPE = \"application/json\";\nconst TEXT_DECODER = new TextDecoder();\nconst TEXT_ENCODER = new TextEncoder();\nconst HAS_BUFFER = typeof Buffer !== \"undefined\";\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n if (HAS_BUFFER) {\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(\"utf8\");\n }\n return TEXT_DECODER.decode(bytes);\n}\n\nfunction decodeArrayBuffer(ab: ArrayBuffer): string {\n if (HAS_BUFFER) {\n return Buffer.from(ab).toString(\"utf8\");\n }\n return TEXT_DECODER.decode(ab);\n}\n\nfunction encodeUtf8(str: string): Uint8Array {\n if (HAS_BUFFER) {\n return Buffer.from(str);\n }\n return TEXT_ENCODER.encode(str);\n}\n\n/**\n * @ru Разбирает query-строку URL в словарь (поддерживает повторные ключи как массивы).\n * @en Parses a URL query string into a dictionary (supports repeated keys as arrays).\n */\nfunction parseQuery(queryString: string): Record<string, string | string[]> {\n
|
|
5
|
-
"mappings": "aAOA,OAAS,oBAAAA,MAAwB,wBACjC,OAAS,wBAAAC,EAAsB,kBAAAC,MAAsB,aAErD,MAAMC,EAAY,mBACZC,EAAe,IAAI,YACnBC,EAAe,IAAI,YACnBC,EAAa,OAAO,OAAW,IAErC,SAASC,EAAWC,EAAiB,CACnC,OAAIF,EACK,OAAO,KAAKE,EAAM,OAAQA,EAAM,WAAYA,EAAM,UAAU,EAAE,SAAS,MAAM,EAE/EJ,EAAa,OAAOI,CAAK,CAClC,CAEA,SAASC,EAAkBC,EAAe,CACxC,OAAIJ,EACK,OAAO,KAAKI,CAAE,EAAE,SAAS,MAAM,EAEjCN,EAAa,OAAOM,CAAE,CAC/B,CAEA,SAASC,EAAWC,EAAW,CAC7B,OAAIN,EACK,OAAO,KAAKM,CAAG,EAEjBP,EAAa,OAAOO,CAAG,CAChC,CAMA,SAASC,EAAWC,EAAmB,CACrC,
|
|
6
|
-
"names": ["HyperClientError", "DEFAULT_STATUS_TEXTS", "getHeaderValue", "JSON_TYPE", "TEXT_DECODER", "TEXT_ENCODER", "HAS_BUFFER", "decodeUtf8", "bytes", "decodeArrayBuffer", "ab", "encodeUtf8", "str", "parseQuery", "queryString", "out", "key", "value", "existing", "parseTextBody", "headers", "text", "decodeBody", "raw", "body", "options", "_ctx", "url", "request", "ctx", "response", "status", "k"]
|
|
4
|
+
"sourcesContent": ["import type {\n HyperReceiver,\n ServerRequestContext,\n TransportRequest,\n TransportResponse,\n} from \"@hyperttp/types\";\nimport type { RestServerHandler, RestServerInput, RestServerResponse } from \"./type.js\";\nimport { HyperClientError } from \"../../utils/errors.js\";\nimport { DEFAULT_STATUS_TEXTS, getHeaderValue } from \"./utils.js\";\n\nconst JSON_TYPE = \"application/json\";\nconst TEXT_DECODER = new TextDecoder();\nconst TEXT_ENCODER = new TextEncoder();\nconst HAS_BUFFER = typeof Buffer !== \"undefined\";\n\nfunction decodeUtf8(bytes: Uint8Array): string {\n if (HAS_BUFFER) {\n return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString(\"utf8\");\n }\n return TEXT_DECODER.decode(bytes);\n}\n\nfunction decodeArrayBuffer(ab: ArrayBuffer): string {\n if (HAS_BUFFER) {\n return Buffer.from(ab).toString(\"utf8\");\n }\n return TEXT_DECODER.decode(ab);\n}\n\nfunction encodeUtf8(str: string): Uint8Array {\n if (HAS_BUFFER) {\n return Buffer.from(str);\n }\n return TEXT_ENCODER.encode(str);\n}\n\n/**\n * @ru Разбирает query-строку URL в словарь (поддерживает повторные ключи как массивы).\n * @en Parses a URL query string into a dictionary (supports repeated keys as arrays).\n */\nfunction parseQuery(queryString: string): Record<string, string | string[]> {\n const out: Record<string, string | string[]> = Object.create(null);\n\n for (const [key, value] of new URLSearchParams(queryString)) {\n const existing = out[key];\n if (existing === undefined) {\n out[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n out[key] = [existing, value];\n }\n }\n\n return out;\n}\n\n/**\n * @ru Декодирует тело запроса по content-type.\n * @en Decodes the request body based on content-type.\n */\nfunction parseTextBody(\n headers: Readonly<Record<string, string | string[]>>,\n text: string,\n): unknown {\n const contentType = getHeaderValue(headers, \"content-type\") ?? \"\";\n if (contentType.includes(JSON_TYPE)) {\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n return text;\n}\n\nfunction decodeBody(raw: TransportRequest): unknown {\n const body = raw.body;\n if (body == null) return undefined;\n const contentType = getHeaderValue(raw.headers, \"content-type\") ?? \"\";\n const textual =\n contentType.includes(JSON_TYPE) ||\n contentType.includes(\"text/\") ||\n contentType.includes(\"application/xml\") ||\n contentType.includes(\"application/x-www-form-urlencoded\");\n if (body instanceof Uint8Array) {\n return textual ? parseTextBody(raw.headers, decodeUtf8(body)) : body;\n }\n if (body instanceof ArrayBuffer) {\n return textual ? parseTextBody(raw.headers, decodeArrayBuffer(body)) : new Uint8Array(body);\n }\n if (ArrayBuffer.isView(body)) {\n const bytes = new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n return textual ? parseTextBody(raw.headers, decodeUtf8(bytes)) : bytes;\n }\n if (typeof body === \"string\") return parseTextBody(raw.headers, body);\n return body;\n}\n\n/**\n * @ru REST/HTTP серверный адаптер. Зеркальная к `RestSender` реализация\n * трёхфазного цикла receive → handle → respond.\n * @en REST/HTTP server adapter. Mirror implementation of `RestSender` for the\n * three-phase receive → handle → respond cycle.\n */\nexport class RestReceiver implements HyperReceiver<\n RestServerInput,\n RestServerResponse,\n TransportRequest,\n TransportResponse\n> {\n readonly protocol = \"rest\";\n protected readonly handler?: RestServerHandler;\n\n /**\n * @ru Создаёт REST-ресивер с необязательным application handler.\n * @en Creates a REST receiver with an optional application handler.\n * @param options - Настройки ресивера и его обработчик. @en Receiver settings and its handler.\n */\n constructor(options: { handler?: RestServerHandler } = {}) {\n this.handler = options.handler;\n }\n\n /**\n * @ru Фаза приёма: разбирает сырой запрос транспорта в REST-структуру.\n * @en Receive phase: parses raw transport request into REST input structure.\n */\n receive(raw: TransportRequest, _ctx: ServerRequestContext): RestServerInput {\n const url = new URL(raw.url, \"http://hyperttp.local\");\n\n return {\n method: raw.method,\n path: url.pathname,\n headers: raw.headers,\n query: parseQuery(url.search.slice(1)),\n body: decodeBody(raw),\n };\n }\n\n /**\n * @ru Фаза обработки: вызывает зарегистрированный handler.\n * @en Handle phase: executes the registered application handler.\n */\n handle(\n request: RestServerInput,\n ctx: ServerRequestContext,\n ): RestServerResponse | Promise<RestServerResponse> {\n if (ctx.signal?.aborted) {\n throw ctx.signal.reason ?? new Error(\"Request aborted\");\n }\n\n if (!this.handler) {\n throw new HyperClientError(\n '[RestReceiver] No application handler registered for protocol \"rest\".',\n );\n }\n\n return this.handler(request, ctx);\n }\n\n /**\n * @ru Фаза ответа: сериализует протокольный ответ в транспортный формат.\n * @en Respond phase: serializes protocol response to raw transport format.\n */\n respond(response: RestServerResponse, _ctx: ServerRequestContext): TransportResponse {\n const headers: Record<string, string> = { ...response.headers };\n const status = response.status ?? 200;\n\n let body: unknown = response.body;\n const streaming =\n body != null &&\n typeof body === \"object\" &&\n ((typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream) ||\n Symbol.asyncIterator in body);\n if (streaming) {\n return { status, statusText: DEFAULT_STATUS_TEXTS[status] ?? \"\", headers, body };\n }\n if (body instanceof ArrayBuffer) {\n body = new Uint8Array(body);\n } else if (ArrayBuffer.isView(body) && !(body instanceof Uint8Array)) {\n body = new Uint8Array(body.buffer, body.byteOffset, body.byteLength).slice();\n } else if (body != null && typeof body === \"object\" && !(body instanceof Uint8Array)) {\n body = JSON.stringify(body);\n const hasContentType = Object.keys(headers).some((k) => k.toLowerCase() === \"content-type\");\n if (!hasContentType) headers[\"content-type\"] = JSON_TYPE;\n }\n\n return {\n status,\n statusText: DEFAULT_STATUS_TEXTS[status] ?? \"\",\n headers,\n body: body == null ? undefined : body instanceof Uint8Array ? body : encodeUtf8(String(body)),\n };\n }\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["HyperClientError", "DEFAULT_STATUS_TEXTS", "getHeaderValue", "JSON_TYPE", "TEXT_DECODER", "TEXT_ENCODER", "HAS_BUFFER", "decodeUtf8", "bytes", "decodeArrayBuffer", "ab", "encodeUtf8", "str", "parseQuery", "queryString", "out", "key", "value", "existing", "parseTextBody", "headers", "text", "decodeBody", "raw", "body", "contentType", "textual", "options", "_ctx", "url", "request", "ctx", "response", "status", "k"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sender.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/sender.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EAEd,cAAc,EACd,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,SAAS,EAAkC,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"sender.d.ts","sourceRoot":"","sources":["../../../src/protocols/rest/sender.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,cAAc,EAEd,cAAc,EACd,WAAW,EACX,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,SAAS,EAAkC,MAAM,WAAW,CAAC;AAiM3E,qBAAa,UAAW,YAAW,WAAW,CAC5C,SAAS,EACT,OAAO,EACP,gBAAgB,EAChB,iBAAiB,CAClB;IACC,QAAQ,CAAC,QAAQ,UAAU;IAE3B,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC,CAAC,CAyGjE;IAEF,OAAO,CAAC,OAAO,EAAE,WAAW,CAAC,SAAS,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,cAAc,GAAG,gBAAgB,CAqEtF;IAEK,IAAI,CACR,QAAQ,EAAE,gBAAgB,EAC1B,SAAS,EAAE,cAAc,EACzB,IAAI,EAAE,cAAc,GACnB,OAAO,CAAC,iBAAiB,CAAC,CAqC5B;IAED,KAAK,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,cAAc,GAAG,iBAAiB,CAAC,OAAO,CAAC,CA6B9E;IAED,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,QAAQ;CAsCjB"}
|
package/protocols/rest/sender.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";import{TimeoutError as
|
|
1
|
+
"use strict";import{TimeoutError as m}from"../../utils/errors.js";import{applyTimeout as g}from"../../utils/abort.js";import{DEFAULT_STATUS_TEXTS as b,getHeaderValue as E}from"./utils.js";const h="rest:stream",p=new TextEncoder,S=new TextDecoder,y=new WeakMap;function T(l){if(l===null||typeof l!="object")return!1;const e=Object.getPrototypeOf(l);return e===null||e===Object.prototype}async function w(l){if(l instanceof Uint8Array)return l;if(l instanceof ArrayBuffer)return new Uint8Array(l);if(ArrayBuffer.isView(l))return new Uint8Array(l.buffer,l.byteOffset,l.byteLength).slice();if(l&&typeof l=="object"&&"arrayBuffer"in l){const e=l.arrayBuffer;if(typeof e=="function")return new Uint8Array(await e.call(l))}if(typeof ReadableStream<"u"&&l instanceof ReadableStream){const e=l.getReader(),o=[];let t=0;try{for(;;){const{done:i,value:a}=await e.read();if(i)break;const s=a instanceof Uint8Array?a:new Uint8Array(a);o.push(s),t+=s.byteLength}}finally{e.releaseLock()}const r=new Uint8Array(t);let n=0;for(const i of o)r.set(i,n),n+=i.byteLength;return r}return l}function A(l,e,o){const t=l.getReader();let r=!1,n;const i=()=>{r||(r=!0,e?.removeEventListener("abort",s),t.releaseLock(),o())},a=async c=>{try{await t.cancel(c)}finally{i()}},s=()=>{n.error(e?.reason),a(e?.reason).catch(()=>{})};return new ReadableStream({start(c){n=c,e?.addEventListener("abort",s,{once:!0}),e?.aborted&&s()},async pull(){try{const c=await t.read();if(r)return;c.done?(n.close(),i()):n.enqueue(c.value)}catch(c){r||(n.error(c),i())}},cancel:a})}function R(l,e,o){const t=l[Symbol.asyncIterator]();let r=!1,n=!1;const i=()=>{r||(r=!0,e?.removeEventListener("abort",a),o())},a=()=>{n=!0,i(),(async()=>{try{l.destroy?.()}finally{await t.return?.()}})().catch(()=>{})};return e?.addEventListener("abort",a,{once:!0}),e?.aborted&&a(),{[Symbol.asyncIterator](){return this},async next(){if(n)throw e?.reason;if(r)return{done:!0,value:void 0};let s;const c=new Promise((u,f)=>{s=()=>f(e?.reason),e?.addEventListener("abort",s,{once:!0})});try{const u=await Promise.race([t.next(),c]);if(n)throw e?.reason;return u.done&&i(),u}catch(u){throw i(),u}finally{e?.removeEventListener("abort",s)}},async return(s){try{return await t.return?.(s)??{done:!0,value:s}}finally{i()}},async throw(s){try{if(t.throw)return await t.throw(s);throw await t.return?.(),s}finally{i()}}}}export class RestSender{protocol="rest";methods={get:(e,o,t,r)=>this.dispatch(e,{method:"GET",url:o,...t,signal:r??t?.signal}),post:(e,o,t,r,n)=>this.dispatch(e,{method:"POST",url:o,...r,body:t,signal:n??r?.signal}),put:(e,o,t,r,n)=>this.dispatch(e,{method:"PUT",url:o,...r,body:t,signal:n??r?.signal}),patch:(e,o,t,r,n)=>this.dispatch(e,{method:"PATCH",url:o,...r,body:t,signal:n??r?.signal}),delete:(e,o,t,r)=>this.dispatch(e,{method:"DELETE",url:o,...t,signal:r??t?.signal}),head:(e,o,t,r)=>this.dispatch(e,{method:"HEAD",url:o,...t,signal:r??t?.signal}),options:(e,o,t,r)=>this.dispatch(e,{method:"OPTIONS",url:o,...t,signal:r??t?.signal}),query:(e,o,t,r,n)=>this.dispatch(e,{method:"QUERY",url:o,...r,body:t,signal:n??r?.signal}),request:(e,o,t,r,n)=>this.dispatch(e,{method:o,url:t,...r,signal:n??r?.signal}),stream:(e,o,t,r)=>this.dispatch(e,{method:"GET",url:o,...t,stream:!0,signal:r??t?.signal})};prepare(e,o){const{input:t}=e,r=e.signal??t.signal??o.signal,n=t.timeout;let i,a=r;if(n!=null&&n>0){const s={};a=g(r,n,s,()=>new m(t.url,n)),i=s.cleanupSignal}try{const s={};if(t.headers)if(t.headers instanceof Headers)t.headers.forEach((f,d)=>{s[d.toLowerCase()]=f});else if(Array.isArray(t.headers))for(const[f,d]of t.headers)s[f.toLowerCase()]=d;else for(const[f,d]of Object.entries(t.headers))d!=null&&(s[f.toLowerCase()]=String(d));let c=t.body;c!=null&&(T(c)||Array.isArray(c))?(c=p.encode(JSON.stringify(c)),s["content-type"]||(s["content-type"]="application/json; charset=utf-8")):typeof c=="string"&&(c=p.encode(c));const u={method:t.method.toUpperCase(),url:this.buildUrl(t.url,t.query),headers:s,body:c,signal:a,protocol:this.protocol,stream:t.stream,stealth:t.stealth,followRedirects:t.followRedirects,maxRedirects:t.maxRedirects};return i&&y.set(u,i),u}catch(s){throw i?.(),s}}async send(e,o,t){const r=e,n=()=>{const a=y.get(e);y.delete(e),a?.()};let i=!1;try{const a=await o.execute(e);if(r.stream){if(typeof ReadableStream<"u"&&a.body instanceof ReadableStream){const c=A(a.body,e.signal,n);return i=!0,{...a,body:c,[h]:!0}}if(a.body!=null&&typeof a.body=="object"&&typeof a.body[Symbol.asyncIterator]=="function"){const c=R(a.body,e.signal,n);return i=!0,{...a,body:c,[h]:!0}}return{...a,[h]:!0}}const s=await w(a.body);return s===a.body?a:{...a,body:s}}finally{i||n()}}parse(e,o){const t=e.status>=200&&e.status<300;let r=e.body;if(!e[h]&&e.body instanceof Uint8Array){const n=E(e.headers,"content-type")??"",i=S.decode(e.body);if(n.includes("application/json"))try{r=JSON.parse(i)}catch{r=i}else(n.includes("text/")||n.includes("application/xml"))&&(r=i)}return{protocol:this.protocol,ok:t,status:e.status,statusText:e.statusText||b[e.status]||"",headers:e.headers,url:e.url,data:r,raw:e}}dispatch(e,o){return e.send({protocol:"rest",input:o,signal:o.signal})}buildUrl(e,o){if(!o)return e;const t=[];for(const[a,s]of Object.entries(o)){if(s==null)continue;const c=Array.isArray(s)?s:[s];for(const u of c)t.push(`${encodeURIComponent(a)}=${encodeURIComponent(String(u))}`)}if(t.length===0)return e;const r=t.join("&"),n=e.indexOf("#");if(n!==-1){const a=e.slice(0,n),s=e.slice(n),c=a.includes("?")?"&":"?";return`${a}${c}${r}${s}`}const i=e.includes("?")?"&":"?";return`${e}${i}${r}`}}
|
|
2
2
|
//# sourceMappingURL=sender.js.map
|