snapreq 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +144 -0
- package/package.json +39 -0
- package/src/capabilities.js +31 -0
- package/src/errors.js +69 -0
- package/src/headers.js +92 -0
- package/src/index.js +22 -0
- package/src/request.js +104 -0
- package/src/response.js +156 -0
- package/src/retry.js +105 -0
- package/src/snap-req.js +248 -0
- package/src/transports/fetch-transport.js +128 -0
- package/src/transports/node-transport.js +323 -0
- package/src/transports/select.js +73 -0
- package/src/transports/xhr-transport.js +112 -0
- package/src/websocket/websocket-channel.js +176 -0
- package/src/websocket/websocket-client.js +1029 -0
- package/src/websocket/websocket-connection.js +154 -0
package/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# snapreq
|
|
2
|
+
|
|
3
|
+
A cross-platform HTTP and WebSocket client with **one API** across Node, the web, Expo and React Native.
|
|
4
|
+
|
|
5
|
+
The same code runs everywhere. Where a platform cannot provide a feature (Unix sockets in a browser, request-body compression over `fetch`, …) snapreq raises a clear `SnapReqUnsupportedFeatureError` instead of silently changing behaviour — so the API is identical and the gaps are explicit.
|
|
6
|
+
|
|
7
|
+
- Zero runtime dependencies.
|
|
8
|
+
- Picks the right transport at runtime: Node `http`/`https`, `fetch`, or `XMLHttpRequest`.
|
|
9
|
+
- `node:*` modules are loaded with a dynamic `import()` from the Node transport only, so web/Expo bundlers (Metro, webpack, …) never try to bundle them.
|
|
10
|
+
- ESM + JSDoc types, checked with `tsc`.
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm install snapreq
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## HTTP
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
import SnapReq from "snapreq"
|
|
22
|
+
|
|
23
|
+
const client = new SnapReq({baseUrl: "https://api.example.com"})
|
|
24
|
+
|
|
25
|
+
const response = await client.get("/users", {query: {page: 1}})
|
|
26
|
+
const users = await response.json()
|
|
27
|
+
|
|
28
|
+
await client.post("/users", {name: "Ada"})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Every call returns a `SnapReqResponse`:
|
|
32
|
+
|
|
33
|
+
```js
|
|
34
|
+
response.status // 200
|
|
35
|
+
response.ok // status in 200..299
|
|
36
|
+
response.headers.get("content-type")
|
|
37
|
+
await response.json() // parsed JSON (null for an empty body)
|
|
38
|
+
await response.text() // UTF-8 string
|
|
39
|
+
await response.bytes() // Uint8Array
|
|
40
|
+
await response.buffer() // Node Buffer (Node only)
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`request()` does **not** throw on a non-2xx status by default (like `fetch`). Pass `throwOnError: true` (per request or on the client) to get a `SnapReqHttpError` carrying `status`, `responseText` and the `response`.
|
|
44
|
+
|
|
45
|
+
### Client options
|
|
46
|
+
|
|
47
|
+
```js
|
|
48
|
+
new SnapReq({
|
|
49
|
+
baseUrl, // origin (and optional base path) prefixed onto relative paths
|
|
50
|
+
headers, // default headers — object or a factory `() => ({...})` for dynamic auth
|
|
51
|
+
retry, // default retry policy (see below)
|
|
52
|
+
throwOnError, // throw SnapReqHttpError on non-2xx (default false)
|
|
53
|
+
credentials, // fetch credentials mode: "omit" | "same-origin" | "include"
|
|
54
|
+
transport, // "auto" (default) | "node" | "fetch" | "xhr" | a transport instance
|
|
55
|
+
|
|
56
|
+
// Node transport only:
|
|
57
|
+
socketPath, // connect over a Unix domain socket
|
|
58
|
+
tls, // {ca, cert, key, rejectUnauthorized}
|
|
59
|
+
keepAlive // reuse connections (default true)
|
|
60
|
+
})
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Retry
|
|
64
|
+
|
|
65
|
+
Retries transient network errors and retryable HTTP statuses (502/503/504 by default). Only applies to buffered requests — never to streamed bodies.
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
await client.get("/flaky", {retry: true})
|
|
69
|
+
await client.get("/flaky", {retry: {tries: 5, waitMs: 200, retryableStatuses: [503]}})
|
|
70
|
+
|
|
71
|
+
// Compose extra rules on top of the default network classifier:
|
|
72
|
+
import {defaultRetryableError} from "snapreq"
|
|
73
|
+
|
|
74
|
+
await client.get("/x", {retry: {shouldRetry: (error) => defaultRetryableError(error) || isMyCase(error)}})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Streaming
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
const response = await client.requestStream({method: "GET", path: "/logs"})
|
|
81
|
+
|
|
82
|
+
for await (const chunk of response.stream()) {
|
|
83
|
+
process.stdout.write(chunk) // chunk is a Uint8Array
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`requestStream()` requires a transport that supports response streaming and never retries. On Node the raw stream is also available as `response.nodeStream`.
|
|
88
|
+
|
|
89
|
+
### Request-body compression (Node)
|
|
90
|
+
|
|
91
|
+
```js
|
|
92
|
+
await client.post("/upload", largePayload, {bodyCompression: "gzip"}) // gzip | deflate | br | zstd
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Over `fetch`/`xhr` this raises `SnapReqUnsupportedFeatureError`.
|
|
96
|
+
|
|
97
|
+
### Capabilities
|
|
98
|
+
|
|
99
|
+
Each transport advertises what it can do. Inspect them when you need to branch on platform support:
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
const caps = await client.capabilities()
|
|
103
|
+
// {unixSocket, tlsClientCert, requestCompression, responseStreaming, requestStreaming, keepAlive, abort}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
| Capability | Node | fetch | xhr |
|
|
107
|
+
| ------------------- | :--: | :---: | :-: |
|
|
108
|
+
| unixSocket | ✅ | — | — |
|
|
109
|
+
| tlsClientCert | ✅ | — | — |
|
|
110
|
+
| requestCompression | ✅ | — | — |
|
|
111
|
+
| responseStreaming | ✅ | ✅ | — |
|
|
112
|
+
| requestStreaming | ✅ | — | — |
|
|
113
|
+
| keepAlive | ✅ | — | — |
|
|
114
|
+
| abort | ✅ | ✅ | ✅ |
|
|
115
|
+
|
|
116
|
+
## WebSocket
|
|
117
|
+
|
|
118
|
+
A WebSocket client over `globalThis.WebSocket` with auto-reconnect, session resumption, request/response calls, channel subscriptions and 1:1 connections.
|
|
119
|
+
|
|
120
|
+
```js
|
|
121
|
+
import {SnapReqWebSocketClient} from "snapreq"
|
|
122
|
+
|
|
123
|
+
const client = new SnapReqWebSocketClient({url: "wss://example.com/websocket"})
|
|
124
|
+
|
|
125
|
+
await client.connect()
|
|
126
|
+
|
|
127
|
+
// Request/response over the socket
|
|
128
|
+
const response = await client.post("/things", {name: "thing"})
|
|
129
|
+
response.json()
|
|
130
|
+
|
|
131
|
+
// Channel subscription
|
|
132
|
+
const unsubscribe = await client.subscribeAndWait("updates", {}, (payload) => console.log(payload))
|
|
133
|
+
|
|
134
|
+
// 1:1 connection
|
|
135
|
+
const connection = client.openConnection("ChatConnection", {onMessage: (body) => console.log(body)})
|
|
136
|
+
await connection.ready
|
|
137
|
+
connection.sendMessage({text: "hi"})
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Optional adapters: `networkMonitor` (gate reconnects on online state) and `sessionStore` (persist the session id across reloads).
|
|
141
|
+
|
|
142
|
+
## License
|
|
143
|
+
|
|
144
|
+
ISC
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "snapreq",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Cross-platform HTTP and WebSocket client with one API across Node, web, Expo and React Native",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src/**"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"lint": "eslint src spec",
|
|
15
|
+
"test": "node --test \"spec/**/*-spec.js\"",
|
|
16
|
+
"typecheck": "tsc --noEmit"
|
|
17
|
+
},
|
|
18
|
+
"keywords": [
|
|
19
|
+
"http",
|
|
20
|
+
"fetch",
|
|
21
|
+
"websocket",
|
|
22
|
+
"client",
|
|
23
|
+
"expo",
|
|
24
|
+
"react-native",
|
|
25
|
+
"cross-platform"
|
|
26
|
+
],
|
|
27
|
+
"author": "kasper@diestoeckels.de",
|
|
28
|
+
"license": "ISC",
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@eslint/js": "^9.0.0",
|
|
31
|
+
"@types/node": "^22.0.0",
|
|
32
|
+
"@types/ws": "^8.18.1",
|
|
33
|
+
"eslint": "^10.3.0",
|
|
34
|
+
"eslint-plugin-jsdoc": "^62.9.0",
|
|
35
|
+
"globals": "^16.0.0",
|
|
36
|
+
"typescript": "^6.0.3",
|
|
37
|
+
"ws": "^8.21.0"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @typedef {object} TransportCapabilities
|
|
5
|
+
* @property {boolean} unixSocket - Connect over a Unix domain socket.
|
|
6
|
+
* @property {boolean} tlsClientCert - Present a client certificate / custom CA for TLS.
|
|
7
|
+
* @property {boolean} requestCompression - Compress the request body (gzip/deflate/br/zstd).
|
|
8
|
+
* @property {boolean} responseStreaming - Expose the response body as a stream before it is fully read.
|
|
9
|
+
* @property {boolean} requestStreaming - Send a streamed (async-iterable) request body.
|
|
10
|
+
* @property {boolean} keepAlive - Reuse connections across requests (HTTP keep-alive).
|
|
11
|
+
* @property {boolean} abort - Cancel an in-flight request via an `AbortSignal`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Builds a fully-populated capability object so callers can read every flag
|
|
16
|
+
* without undefined checks.
|
|
17
|
+
* @param {Partial<TransportCapabilities>} overrides - Capabilities the transport supports.
|
|
18
|
+
* @returns {TransportCapabilities} - Complete capability flags.
|
|
19
|
+
*/
|
|
20
|
+
export function buildCapabilities(overrides) {
|
|
21
|
+
return {
|
|
22
|
+
unixSocket: false,
|
|
23
|
+
tlsClientCert: false,
|
|
24
|
+
requestCompression: false,
|
|
25
|
+
responseStreaming: false,
|
|
26
|
+
requestStreaming: false,
|
|
27
|
+
keepAlive: false,
|
|
28
|
+
abort: false,
|
|
29
|
+
...overrides
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/** Base class for every error thrown by snapreq. */
|
|
4
|
+
export class SnapReqError extends Error {
|
|
5
|
+
/** @param {string} message - Human readable description. */
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message)
|
|
8
|
+
this.name = "SnapReqError"
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Thrown when a request completes with a non-2xx status and the caller asked
|
|
14
|
+
* snapreq to treat error statuses as failures (`throwOnError`, the default for
|
|
15
|
+
* the high-level helpers). Carries enough metadata to build a friendly message
|
|
16
|
+
* without re-reading the response.
|
|
17
|
+
*/
|
|
18
|
+
export class SnapReqHttpError extends SnapReqError {
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} options - Error metadata.
|
|
21
|
+
* @param {string} options.message - Human readable description.
|
|
22
|
+
* @param {string} options.method - HTTP method used for the request.
|
|
23
|
+
* @param {string} options.url - Fully resolved request URL.
|
|
24
|
+
* @param {number} options.status - HTTP status code returned by the server.
|
|
25
|
+
* @param {string} [options.statusText] - HTTP status text returned by the server.
|
|
26
|
+
* @param {string} [options.responseText] - Decoded response body, when available.
|
|
27
|
+
* @param {import("./response.js").default} [options.response] - The response that failed.
|
|
28
|
+
*/
|
|
29
|
+
constructor({message, method, url, status, statusText, responseText, response}) {
|
|
30
|
+
super(message)
|
|
31
|
+
this.name = "SnapReqHttpError"
|
|
32
|
+
this.method = method
|
|
33
|
+
this.url = url
|
|
34
|
+
this.status = status
|
|
35
|
+
this.statusText = statusText
|
|
36
|
+
this.responseText = responseText
|
|
37
|
+
this.response = response
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Thrown when a request asks for a capability the active transport cannot
|
|
43
|
+
* provide on the current platform (for example a Unix socket or request-body
|
|
44
|
+
* compression in a browser). The API stays identical across platforms; this
|
|
45
|
+
* error is how snapreq tells you a specific feature had to be left out.
|
|
46
|
+
*/
|
|
47
|
+
export class SnapReqUnsupportedFeatureError extends SnapReqError {
|
|
48
|
+
/**
|
|
49
|
+
* @param {object} options - Error metadata.
|
|
50
|
+
* @param {string} options.feature - The capability that is not supported.
|
|
51
|
+
* @param {string} options.transport - Name of the active transport.
|
|
52
|
+
* @param {string} [options.detail] - Optional extra context.
|
|
53
|
+
*/
|
|
54
|
+
constructor({feature, transport, detail}) {
|
|
55
|
+
super(`The "${transport}" transport does not support ${feature}${detail ? `: ${detail}` : ""}.`)
|
|
56
|
+
this.name = "SnapReqUnsupportedFeatureError"
|
|
57
|
+
this.feature = feature
|
|
58
|
+
this.transport = transport
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Thrown when a request is aborted via an `AbortSignal`. */
|
|
63
|
+
export class SnapReqAbortError extends SnapReqError {
|
|
64
|
+
/** @param {string} [message] - Human readable description. */
|
|
65
|
+
constructor(message = "Request aborted.") {
|
|
66
|
+
super(message)
|
|
67
|
+
this.name = "SnapReqAbortError"
|
|
68
|
+
}
|
|
69
|
+
}
|
package/src/headers.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A tiny case-insensitive header bag. Works the same on every platform and
|
|
5
|
+
* avoids depending on the DOM `Headers` global (absent in some runtimes) or on
|
|
6
|
+
* Node's header handling. Header values are always stored as strings.
|
|
7
|
+
*/
|
|
8
|
+
export default class SnapReqHeaders {
|
|
9
|
+
/**
|
|
10
|
+
* @param {Record<string, string | number | string[]> | SnapReqHeaders | Iterable<[string, string]>} [init] - Initial headers.
|
|
11
|
+
*/
|
|
12
|
+
constructor(init) {
|
|
13
|
+
/** @type {Map<string, {name: string, value: string}>} - Keyed by lower-cased name. */
|
|
14
|
+
this._map = new Map()
|
|
15
|
+
|
|
16
|
+
if (!init) return
|
|
17
|
+
|
|
18
|
+
if (init instanceof SnapReqHeaders) {
|
|
19
|
+
for (const [name, value] of init.entries()) this.set(name, value)
|
|
20
|
+
} else if (typeof (/** @type {any} */ (init)[Symbol.iterator]) === "function") {
|
|
21
|
+
for (const [name, value] of /** @type {Iterable<[string, string]>} */ (init)) this.set(name, value)
|
|
22
|
+
} else {
|
|
23
|
+
for (const [name, value] of Object.entries(init)) {
|
|
24
|
+
if (Array.isArray(value)) {
|
|
25
|
+
this.set(name, value.join(", "))
|
|
26
|
+
} else if (value !== undefined && value !== null) {
|
|
27
|
+
this.set(name, String(value))
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {string} name - Header name (case-insensitive).
|
|
35
|
+
* @param {string | number} value - Header value.
|
|
36
|
+
* @returns {void}
|
|
37
|
+
*/
|
|
38
|
+
set(name, value) {
|
|
39
|
+
this._map.set(name.toLowerCase(), {name, value: String(value)})
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {string} name - Header name (case-insensitive).
|
|
44
|
+
* @returns {string | null} - The header value or null when absent.
|
|
45
|
+
*/
|
|
46
|
+
get(name) {
|
|
47
|
+
return this._map.get(name.toLowerCase())?.value ?? null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @param {string} name - Header name (case-insensitive).
|
|
52
|
+
* @returns {boolean} - Whether the header is present.
|
|
53
|
+
*/
|
|
54
|
+
has(name) {
|
|
55
|
+
return this._map.has(name.toLowerCase())
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {string} name - Header name (case-insensitive).
|
|
60
|
+
* @returns {void}
|
|
61
|
+
*/
|
|
62
|
+
delete(name) {
|
|
63
|
+
this._map.delete(name.toLowerCase())
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* @yields {[string, string]} - Name/value pair preserving original casing.
|
|
68
|
+
* @returns {IterableIterator<[string, string]>} - Name/value pairs preserving original casing.
|
|
69
|
+
*/
|
|
70
|
+
*entries() {
|
|
71
|
+
for (const {name, value} of this._map.values()) yield [name, value]
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @returns {[string, string][]} - Name/value pairs preserving original casing. */
|
|
75
|
+
toArray() {
|
|
76
|
+
return [...this.entries()]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Plain object form keyed by the original header casing. Suitable for
|
|
81
|
+
* passing straight to `http.request` or `fetch`.
|
|
82
|
+
* @returns {Record<string, string>} - Header object.
|
|
83
|
+
*/
|
|
84
|
+
toObject() {
|
|
85
|
+
/** @type {Record<string, string>} */
|
|
86
|
+
const object = {}
|
|
87
|
+
|
|
88
|
+
for (const {name, value} of this._map.values()) object[name] = value
|
|
89
|
+
|
|
90
|
+
return object
|
|
91
|
+
}
|
|
92
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import SnapReq from "./snap-req.js"
|
|
4
|
+
|
|
5
|
+
export default SnapReq
|
|
6
|
+
export {default as SnapReq} from "./snap-req.js"
|
|
7
|
+
export {default as SnapReqResponse} from "./response.js"
|
|
8
|
+
export {default as SnapReqHeaders} from "./headers.js"
|
|
9
|
+
export {
|
|
10
|
+
SnapReqError,
|
|
11
|
+
SnapReqHttpError,
|
|
12
|
+
SnapReqUnsupportedFeatureError,
|
|
13
|
+
SnapReqAbortError
|
|
14
|
+
} from "./errors.js"
|
|
15
|
+
export {defaultRetryableError} from "./retry.js"
|
|
16
|
+
export {detectRuntime, selectTransport} from "./transports/select.js"
|
|
17
|
+
export {default as FetchTransport} from "./transports/fetch-transport.js"
|
|
18
|
+
export {default as XhrTransport} from "./transports/xhr-transport.js"
|
|
19
|
+
|
|
20
|
+
// The WebSocket client is exported from its own module so importing the HTTP
|
|
21
|
+
// client never pulls WebSocket code into a bundle that does not need it.
|
|
22
|
+
export {default as SnapReqWebSocketClient} from "./websocket/websocket-client.js"
|
package/src/request.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import SnapReqHeaders from "./headers.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {"identity" | "gzip" | "deflate" | "br" | "zstd"} CompressionEncoding
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* @typedef {object} NormalizedBody
|
|
11
|
+
* @property {"none" | "text" | "bytes" | "stream"} kind - Shape of the body payload.
|
|
12
|
+
* @property {string | Uint8Array | AsyncIterable<Uint8Array> | null} value - The payload itself.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const ABSOLUTE_URL_REGEX = /^[a-z][a-z0-9+.-]*:\/\//i
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Joins a base URL and a path and appends query parameters. `path` may be a
|
|
19
|
+
* fully-qualified URL, in which case the base is ignored.
|
|
20
|
+
* @param {string | undefined} baseUrl - Origin (and optional base path).
|
|
21
|
+
* @param {string} path - Path or absolute URL.
|
|
22
|
+
* @param {Record<string, string | number | boolean | null | undefined> | undefined} query - Query parameters.
|
|
23
|
+
* @returns {string} - Resolved absolute URL.
|
|
24
|
+
*/
|
|
25
|
+
export function buildUrl(baseUrl, path, query) {
|
|
26
|
+
/** @type {string} */
|
|
27
|
+
let resolved
|
|
28
|
+
|
|
29
|
+
if (ABSOLUTE_URL_REGEX.test(path)) {
|
|
30
|
+
resolved = path
|
|
31
|
+
} else if (baseUrl) {
|
|
32
|
+
resolved = `${baseUrl.replace(/\/$/, "")}/${path.replace(/^\//, "")}`
|
|
33
|
+
} else {
|
|
34
|
+
resolved = path
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (!query) return resolved
|
|
38
|
+
|
|
39
|
+
const params = new URLSearchParams()
|
|
40
|
+
|
|
41
|
+
for (const [key, value] of Object.entries(query)) {
|
|
42
|
+
if (value !== undefined && value !== null) params.append(key, String(value))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const queryString = params.toString()
|
|
46
|
+
|
|
47
|
+
if (!queryString) return resolved
|
|
48
|
+
|
|
49
|
+
return resolved.includes("?") ? `${resolved}&${queryString}` : `${resolved}?${queryString}`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Determines whether a value should be sent as a streamed request body.
|
|
54
|
+
* @param {unknown} body - Candidate body value.
|
|
55
|
+
* @returns {boolean} - Whether the body is a stream.
|
|
56
|
+
*/
|
|
57
|
+
export function isStreamBody(body) {
|
|
58
|
+
return Boolean(
|
|
59
|
+
body &&
|
|
60
|
+
typeof body === "object" &&
|
|
61
|
+
!(body instanceof Uint8Array) &&
|
|
62
|
+
!(body instanceof ArrayBuffer) &&
|
|
63
|
+
(typeof (/** @type {any} */ (body).pipe) === "function" || typeof (/** @type {any} */ (body)[Symbol.asyncIterator]) === "function")
|
|
64
|
+
)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Normalizes a user-supplied body into one of a small set of shapes and applies
|
|
69
|
+
* a default `Content-Type` header when the caller did not set one.
|
|
70
|
+
* @param {unknown} body - Raw body value.
|
|
71
|
+
* @param {SnapReqHeaders} headers - Headers to receive a default `Content-Type`.
|
|
72
|
+
* @returns {NormalizedBody} - Normalized body descriptor.
|
|
73
|
+
*/
|
|
74
|
+
export function normalizeBody(body, headers) {
|
|
75
|
+
if (body === undefined || body === null) {
|
|
76
|
+
return {kind: "none", value: null}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (body instanceof Uint8Array) {
|
|
80
|
+
if (!headers.has("content-type")) headers.set("Content-Type", "application/octet-stream")
|
|
81
|
+
|
|
82
|
+
return {kind: "bytes", value: body}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (body instanceof ArrayBuffer) {
|
|
86
|
+
if (!headers.has("content-type")) headers.set("Content-Type", "application/octet-stream")
|
|
87
|
+
|
|
88
|
+
return {kind: "bytes", value: new Uint8Array(body)}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (isStreamBody(body)) {
|
|
92
|
+
if (!headers.has("content-type")) headers.set("Content-Type", "application/octet-stream")
|
|
93
|
+
|
|
94
|
+
return {kind: "stream", value: /** @type {AsyncIterable<Uint8Array>} */ (body)}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (typeof body === "string") {
|
|
98
|
+
return {kind: "text", value: body}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (!headers.has("content-type")) headers.set("Content-Type", "application/json")
|
|
102
|
+
|
|
103
|
+
return {kind: "text", value: JSON.stringify(body)}
|
|
104
|
+
}
|
package/src/response.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import SnapReqHeaders from "./headers.js"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Concatenates a list of byte chunks into a single `Uint8Array`.
|
|
7
|
+
* @param {Uint8Array[]} chunks - Byte chunks in order.
|
|
8
|
+
* @returns {Uint8Array} - The concatenated bytes.
|
|
9
|
+
*/
|
|
10
|
+
function concatChunks(chunks) {
|
|
11
|
+
let total = 0
|
|
12
|
+
|
|
13
|
+
for (const chunk of chunks) total += chunk.byteLength
|
|
14
|
+
|
|
15
|
+
const result = new Uint8Array(total)
|
|
16
|
+
let offset = 0
|
|
17
|
+
|
|
18
|
+
for (const chunk of chunks) {
|
|
19
|
+
result.set(chunk, offset)
|
|
20
|
+
offset += chunk.byteLength
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
return result
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A platform-agnostic response. Transports build it with either a fully-read
|
|
28
|
+
* body (`bytes`) or a `stream` (an async iterable of `Uint8Array`) that the
|
|
29
|
+
* read helpers buffer on first use. The body can be read exactly once as a
|
|
30
|
+
* stream; the buffering helpers may be called repeatedly because they cache.
|
|
31
|
+
*/
|
|
32
|
+
export default class SnapReqResponse {
|
|
33
|
+
/**
|
|
34
|
+
* @param {object} options - Response data.
|
|
35
|
+
* @param {string} options.url - Fully resolved request URL.
|
|
36
|
+
* @param {string} options.method - HTTP method used for the request.
|
|
37
|
+
* @param {number} options.status - HTTP status code.
|
|
38
|
+
* @param {string} [options.statusText] - HTTP status text.
|
|
39
|
+
* @param {SnapReqHeaders} [options.headers] - Response headers.
|
|
40
|
+
* @param {Uint8Array} [options.bytes] - Fully-read body, when the transport already buffered it.
|
|
41
|
+
* @param {AsyncIterable<Uint8Array>} [options.stream] - Streamed body, when the transport supports streaming.
|
|
42
|
+
* @param {import("node:stream").Readable} [options.nodeStream] - Raw Node stream, when available, for advanced consumers.
|
|
43
|
+
*/
|
|
44
|
+
constructor({url, method, status, statusText = "", headers, bytes, stream, nodeStream}) {
|
|
45
|
+
this.url = url
|
|
46
|
+
this.method = method
|
|
47
|
+
this.status = status
|
|
48
|
+
this.statusText = statusText
|
|
49
|
+
this.headers = headers || new SnapReqHeaders()
|
|
50
|
+
/** @type {Uint8Array | null} */
|
|
51
|
+
this._bytes = bytes ?? null
|
|
52
|
+
/** @type {AsyncIterable<Uint8Array> | null} */
|
|
53
|
+
this._stream = stream ?? null
|
|
54
|
+
/** @type {import("node:stream").Readable | undefined} */
|
|
55
|
+
this.nodeStream = nodeStream
|
|
56
|
+
this._streamConsumed = false
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** @returns {boolean} - Whether the status is in the 2xx range. */
|
|
60
|
+
get ok() {
|
|
61
|
+
return this.status >= 200 && this.status < 300
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Returns the response body as an async iterable of byte chunks. Can only be
|
|
66
|
+
* called once and only when the transport provided a stream.
|
|
67
|
+
* @returns {AsyncIterable<Uint8Array>} - The streamed body.
|
|
68
|
+
*/
|
|
69
|
+
stream() {
|
|
70
|
+
if (!this._stream) {
|
|
71
|
+
throw new Error("This response has no readable stream (the body was already buffered by the transport).")
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (this._streamConsumed) {
|
|
75
|
+
throw new Error("This response stream has already been consumed.")
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
this._streamConsumed = true
|
|
79
|
+
|
|
80
|
+
return this._stream
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @returns {boolean} - Whether the body is available as a stream that has not been read yet. */
|
|
84
|
+
get streamable() {
|
|
85
|
+
return Boolean(this._stream) && !this._streamConsumed
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Reads the whole body into a `Uint8Array`, buffering the stream if needed.
|
|
90
|
+
* @returns {Promise<Uint8Array>} - The full response body.
|
|
91
|
+
*/
|
|
92
|
+
async bytes() {
|
|
93
|
+
if (this._bytes) return this._bytes
|
|
94
|
+
|
|
95
|
+
if (!this._stream) {
|
|
96
|
+
this._bytes = new Uint8Array(0)
|
|
97
|
+
|
|
98
|
+
return this._bytes
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (this._streamConsumed) {
|
|
102
|
+
throw new Error("Cannot buffer this response: its stream was already consumed via stream().")
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
this._streamConsumed = true
|
|
106
|
+
|
|
107
|
+
/** @type {Uint8Array[]} */
|
|
108
|
+
const chunks = []
|
|
109
|
+
|
|
110
|
+
for await (const chunk of this._stream) {
|
|
111
|
+
chunks.push(chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk))
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
this._bytes = concatChunks(chunks)
|
|
115
|
+
|
|
116
|
+
return this._bytes
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Reads the whole body as a Node `Buffer`. Node-only convenience; throws when
|
|
121
|
+
* the `Buffer` global is unavailable.
|
|
122
|
+
* @returns {Promise<Buffer>} - The full response body as a Buffer.
|
|
123
|
+
*/
|
|
124
|
+
async buffer() {
|
|
125
|
+
if (typeof Buffer === "undefined") {
|
|
126
|
+
throw new Error("Buffer is not available on this platform; use bytes() instead.")
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const bytes = await this.bytes()
|
|
130
|
+
|
|
131
|
+
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Reads the whole body and decodes it as a UTF-8 string.
|
|
136
|
+
* @returns {Promise<string>} - The decoded response body.
|
|
137
|
+
*/
|
|
138
|
+
async text() {
|
|
139
|
+
const bytes = await this.bytes()
|
|
140
|
+
|
|
141
|
+
return new TextDecoder("utf-8").decode(bytes)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Reads the whole body and parses it as JSON. Returns `null` for an empty
|
|
146
|
+
* body.
|
|
147
|
+
* @returns {Promise<any>} - The parsed JSON body.
|
|
148
|
+
*/
|
|
149
|
+
async json() {
|
|
150
|
+
const text = await this.text()
|
|
151
|
+
|
|
152
|
+
if (!text) return null
|
|
153
|
+
|
|
154
|
+
return JSON.parse(text)
|
|
155
|
+
}
|
|
156
|
+
}
|