@npy/fetch 0.1.0 → 0.1.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.
Files changed (102) hide show
  1. package/_internal/consts.cjs +4 -0
  2. package/_internal/consts.d.cts +3 -0
  3. package/_internal/consts.d.ts +3 -0
  4. package/_internal/consts.js +4 -0
  5. package/_internal/decode-stream-error.cjs +18 -0
  6. package/_internal/decode-stream-error.d.cts +11 -0
  7. package/_internal/decode-stream-error.d.ts +11 -0
  8. package/_internal/decode-stream-error.js +18 -0
  9. package/_internal/error-mapping.cjs +44 -0
  10. package/_internal/error-mapping.d.cts +15 -0
  11. package/_internal/error-mapping.d.ts +15 -0
  12. package/_internal/error-mapping.js +41 -0
  13. package/_internal/guards.cjs +23 -0
  14. package/_internal/guards.d.cts +15 -0
  15. package/_internal/guards.d.ts +15 -0
  16. package/_internal/guards.js +15 -0
  17. package/_internal/net.cjs +95 -0
  18. package/_internal/net.d.cts +11 -0
  19. package/_internal/net.d.ts +11 -0
  20. package/_internal/net.js +92 -0
  21. package/_internal/promises.cjs +18 -0
  22. package/_internal/promises.d.cts +1 -0
  23. package/_internal/promises.d.ts +1 -0
  24. package/_internal/promises.js +18 -0
  25. package/_internal/streams.cjs +37 -0
  26. package/_internal/streams.d.cts +21 -0
  27. package/_internal/streams.d.ts +21 -0
  28. package/_internal/streams.js +36 -0
  29. package/_internal/symbols.cjs +4 -0
  30. package/_internal/symbols.d.cts +1 -0
  31. package/_internal/symbols.d.ts +1 -0
  32. package/_internal/symbols.js +4 -0
  33. package/_virtual/_rolldown/runtime.cjs +23 -0
  34. package/agent-pool.cjs +96 -0
  35. package/agent-pool.d.cts +2 -0
  36. package/agent-pool.d.ts +2 -0
  37. package/agent-pool.js +95 -0
  38. package/agent.cjs +260 -0
  39. package/agent.d.cts +3 -0
  40. package/agent.d.ts +3 -0
  41. package/agent.js +259 -0
  42. package/body.cjs +105 -0
  43. package/body.d.cts +12 -0
  44. package/body.d.ts +12 -0
  45. package/body.js +102 -0
  46. package/dialers/index.d.cts +3 -0
  47. package/dialers/index.d.ts +3 -0
  48. package/dialers/proxy.cjs +56 -0
  49. package/dialers/proxy.d.cts +27 -0
  50. package/dialers/proxy.d.ts +27 -0
  51. package/dialers/proxy.js +55 -0
  52. package/dialers/tcp.cjs +92 -0
  53. package/dialers/tcp.d.cts +57 -0
  54. package/dialers/tcp.d.ts +57 -0
  55. package/dialers/tcp.js +89 -0
  56. package/encoding.cjs +114 -0
  57. package/encoding.d.cts +35 -0
  58. package/encoding.d.ts +35 -0
  59. package/encoding.js +110 -0
  60. package/errors.cjs +275 -0
  61. package/errors.d.cts +110 -0
  62. package/errors.d.ts +110 -0
  63. package/errors.js +259 -0
  64. package/fetch.cjs +353 -0
  65. package/fetch.d.cts +58 -0
  66. package/fetch.d.ts +58 -0
  67. package/fetch.js +350 -0
  68. package/http-client.cjs +75 -0
  69. package/http-client.d.cts +39 -0
  70. package/http-client.d.ts +39 -0
  71. package/http-client.js +75 -0
  72. package/index.cjs +49 -0
  73. package/index.d.cts +14 -0
  74. package/index.d.ts +14 -0
  75. package/index.js +11 -0
  76. package/io/_utils.cjs +56 -0
  77. package/io/_utils.d.cts +10 -0
  78. package/io/_utils.d.ts +10 -0
  79. package/io/_utils.js +51 -0
  80. package/io/buf-writer.cjs +149 -0
  81. package/io/buf-writer.d.cts +13 -0
  82. package/io/buf-writer.d.ts +13 -0
  83. package/io/buf-writer.js +148 -0
  84. package/io/io.cjs +199 -0
  85. package/io/io.d.cts +5 -0
  86. package/io/io.d.ts +5 -0
  87. package/io/io.js +198 -0
  88. package/io/readers.cjs +337 -0
  89. package/io/readers.d.cts +69 -0
  90. package/io/readers.d.ts +69 -0
  91. package/io/readers.js +333 -0
  92. package/io/writers.cjs +196 -0
  93. package/io/writers.d.cts +22 -0
  94. package/io/writers.d.ts +22 -0
  95. package/io/writers.js +195 -0
  96. package/package.json +23 -10
  97. package/types/agent.d.cts +72 -0
  98. package/types/agent.d.ts +72 -0
  99. package/types/dialer.d.cts +30 -0
  100. package/types/dialer.d.ts +30 -0
  101. package/types/index.d.cts +2 -0
  102. package/types/index.d.ts +2 -0
package/errors.js ADDED
@@ -0,0 +1,259 @@
1
+ //#region src/errors.ts
2
+ var ErrorType = {
3
+ ABORTED: "ABORTED",
4
+ NETWORK: "NETWORK",
5
+ TIMEOUT: "TIMEOUT",
6
+ HTTP_CLIENT_ERROR: "HTTP_CLIENT_ERROR",
7
+ HTTP_SERVER_ERROR: "HTTP_SERVER_ERROR"
8
+ };
9
+ var FetchErrorCode = {
10
+ ABORTED: "ERR_FETCH_ABORTED",
11
+ TIMEOUT: "ERR_FETCH_TIMEOUT",
12
+ CONNECTION: "ERR_FETCH_CONNECTION",
13
+ AGENT_CLOSED: "ERR_FETCH_AGENT_CLOSED",
14
+ AGENT_BUSY: "ERR_FETCH_AGENT_BUSY",
15
+ ORIGIN_MISMATCH: "ERR_FETCH_ORIGIN_MISMATCH",
16
+ UNSUPPORTED_PROTOCOL: "ERR_FETCH_UNSUPPORTED_PROTOCOL",
17
+ UNSUPPORTED_METHOD: "ERR_FETCH_UNSUPPORTED_METHOD",
18
+ TLS_ALPN: "ERR_FETCH_TLS_ALPN",
19
+ REQUEST_WRITE: "ERR_FETCH_REQUEST_WRITE",
20
+ RESPONSE_HEADERS: "ERR_FETCH_RESPONSE_HEADERS",
21
+ RESPONSE_BODY: "ERR_FETCH_RESPONSE_BODY",
22
+ RESPONSE_DECODE: "ERR_FETCH_RESPONSE_DECODE",
23
+ HTTP_STATUS: "ERR_FETCH_HTTP_STATUS"
24
+ };
25
+ var FetchError = class extends Error {
26
+ code;
27
+ phase;
28
+ context;
29
+ retryable;
30
+ type;
31
+ cause;
32
+ constructor(options) {
33
+ super(options.message, { cause: options.cause });
34
+ this.code = options.code;
35
+ this.phase = options.phase;
36
+ this.context = options.context;
37
+ this.retryable = options.retryable ?? false;
38
+ this.type = options.type;
39
+ this.cause = options.cause;
40
+ Object.setPrototypeOf(this, new.target.prototype);
41
+ }
42
+ get name() {
43
+ return this.constructor.name;
44
+ }
45
+ get [Symbol.toStringTag]() {
46
+ return this.name;
47
+ }
48
+ toJSON() {
49
+ return {
50
+ name: this.name,
51
+ message: this.message,
52
+ code: this.code,
53
+ phase: this.phase,
54
+ retryable: this.retryable,
55
+ type: this.type,
56
+ context: this.context,
57
+ cause: this.cause instanceof Error ? {
58
+ name: this.cause.name,
59
+ message: this.cause.message
60
+ } : this.cause
61
+ };
62
+ }
63
+ };
64
+ var RequestAbortedError = class extends FetchError {
65
+ constructor(cause, context, message) {
66
+ super({
67
+ message: message ?? "The request was aborted",
68
+ code: FetchErrorCode.ABORTED,
69
+ phase: "request",
70
+ cause,
71
+ context,
72
+ retryable: false,
73
+ type: ErrorType.ABORTED
74
+ });
75
+ }
76
+ };
77
+ var ConnectTimeoutError = class extends FetchError {
78
+ constructor(cause, context, message) {
79
+ super({
80
+ message: message ?? "Connection timed out",
81
+ code: FetchErrorCode.TIMEOUT,
82
+ phase: "connect",
83
+ cause,
84
+ context,
85
+ retryable: true,
86
+ type: ErrorType.TIMEOUT
87
+ });
88
+ }
89
+ };
90
+ var ConnectionError = class extends FetchError {
91
+ constructor(cause, context, message) {
92
+ super({
93
+ message: message ?? "Network connection failed",
94
+ code: FetchErrorCode.CONNECTION,
95
+ phase: "connect",
96
+ cause,
97
+ context,
98
+ retryable: true,
99
+ type: ErrorType.NETWORK
100
+ });
101
+ }
102
+ };
103
+ var AgentClosedError = class extends FetchError {
104
+ constructor(context, cause) {
105
+ super({
106
+ message: "Agent is closed",
107
+ code: FetchErrorCode.AGENT_CLOSED,
108
+ phase: "agent",
109
+ cause,
110
+ context,
111
+ retryable: false,
112
+ type: ErrorType.NETWORK
113
+ });
114
+ }
115
+ };
116
+ var AgentBusyError = class extends FetchError {
117
+ constructor(context, cause) {
118
+ super({
119
+ message: "Agent is busy",
120
+ code: FetchErrorCode.AGENT_BUSY,
121
+ phase: "agent",
122
+ cause,
123
+ context,
124
+ retryable: true,
125
+ type: ErrorType.NETWORK
126
+ });
127
+ }
128
+ };
129
+ var OriginMismatchError = class extends FetchError {
130
+ constructor(expectedOrigin, actualOrigin, context) {
131
+ super({
132
+ message: `Agent origin mismatch: expected ${expectedOrigin}, got ${actualOrigin}`,
133
+ code: FetchErrorCode.ORIGIN_MISMATCH,
134
+ phase: "policy",
135
+ context: {
136
+ ...context,
137
+ details: {
138
+ ...context?.details ?? {},
139
+ expectedOrigin,
140
+ actualOrigin
141
+ }
142
+ },
143
+ retryable: false,
144
+ type: ErrorType.NETWORK
145
+ });
146
+ }
147
+ };
148
+ var UnsupportedProtocolError = class extends FetchError {
149
+ constructor(protocol, context) {
150
+ super({
151
+ message: `Unsupported protocol: ${protocol}`,
152
+ code: FetchErrorCode.UNSUPPORTED_PROTOCOL,
153
+ phase: "policy",
154
+ context,
155
+ retryable: false,
156
+ type: ErrorType.NETWORK
157
+ });
158
+ }
159
+ };
160
+ var UnsupportedMethodError = class extends FetchError {
161
+ constructor(method, context) {
162
+ super({
163
+ message: `Unsupported method: ${method}`,
164
+ code: FetchErrorCode.UNSUPPORTED_METHOD,
165
+ phase: "policy",
166
+ context,
167
+ retryable: false,
168
+ type: ErrorType.NETWORK
169
+ });
170
+ }
171
+ };
172
+ var UnsupportedAlpnProtocolError = class extends FetchError {
173
+ constructor(alpn, context, cause) {
174
+ super({
175
+ message: `Unsupported ALPN protocol negotiated: ${alpn}`,
176
+ code: FetchErrorCode.TLS_ALPN,
177
+ phase: "connect",
178
+ cause,
179
+ context: {
180
+ ...context,
181
+ alpn
182
+ },
183
+ retryable: false,
184
+ type: ErrorType.NETWORK
185
+ });
186
+ }
187
+ };
188
+ var RequestWriteError = class extends FetchError {
189
+ constructor(cause, context, message) {
190
+ super({
191
+ message: message ?? "Failed to write HTTP request",
192
+ code: FetchErrorCode.REQUEST_WRITE,
193
+ phase: "request",
194
+ cause,
195
+ context,
196
+ retryable: true,
197
+ type: ErrorType.NETWORK
198
+ });
199
+ }
200
+ };
201
+ var ResponseHeaderError = class extends FetchError {
202
+ constructor(cause, context, message) {
203
+ super({
204
+ message: message ?? "Failed while reading response headers",
205
+ code: FetchErrorCode.RESPONSE_HEADERS,
206
+ phase: "response",
207
+ cause,
208
+ context,
209
+ retryable: true,
210
+ type: ErrorType.NETWORK
211
+ });
212
+ }
213
+ };
214
+ var ResponseBodyError = class extends FetchError {
215
+ constructor(cause, context, message) {
216
+ super({
217
+ message: message ?? "Failed while reading response body",
218
+ code: FetchErrorCode.RESPONSE_BODY,
219
+ phase: "body",
220
+ cause,
221
+ context,
222
+ retryable: true,
223
+ type: ErrorType.NETWORK
224
+ });
225
+ }
226
+ };
227
+ var ResponseDecodeError = class extends FetchError {
228
+ constructor(cause, context, message) {
229
+ super({
230
+ message: message ?? "Failed while decoding response body",
231
+ code: FetchErrorCode.RESPONSE_DECODE,
232
+ phase: "decode",
233
+ cause,
234
+ context,
235
+ retryable: false,
236
+ type: ErrorType.NETWORK
237
+ });
238
+ }
239
+ };
240
+ var HttpStatusError = class extends FetchError {
241
+ statusCode;
242
+ constructor(statusCode, context, cause, message) {
243
+ super({
244
+ message: message ?? `HTTP ${statusCode}`,
245
+ code: FetchErrorCode.HTTP_STATUS,
246
+ phase: "response",
247
+ cause,
248
+ context: {
249
+ ...context,
250
+ status: statusCode
251
+ },
252
+ retryable: statusCode >= 500,
253
+ type: statusCode < 500 ? ErrorType.HTTP_CLIENT_ERROR : ErrorType.HTTP_SERVER_ERROR
254
+ });
255
+ this.statusCode = statusCode;
256
+ }
257
+ };
258
+ //#endregion
259
+ export { AgentBusyError, AgentClosedError, ConnectTimeoutError, ConnectionError, ErrorType, FetchError, FetchErrorCode, HttpStatusError, OriginMismatchError, RequestAbortedError, RequestWriteError, ResponseBodyError, ResponseDecodeError, ResponseHeaderError, UnsupportedAlpnProtocolError, UnsupportedMethodError, UnsupportedProtocolError };
package/fetch.cjs ADDED
@@ -0,0 +1,353 @@
1
+ require("./_virtual/_rolldown/runtime.cjs");
2
+ const require_error_mapping = require("./_internal/error-mapping.cjs");
3
+ const require_symbols = require("./_internal/symbols.cjs");
4
+ const require_guards = require("./_internal/guards.cjs");
5
+ const require_body = require("./body.cjs");
6
+ const require_proxy = require("./dialers/proxy.cjs");
7
+ const require_tcp = require("./dialers/tcp.cjs");
8
+ const require_http_client = require("./http-client.cjs");
9
+ let _npy_proxy_kit = require("@npy/proxy-kit");
10
+ //#region src/fetch.ts
11
+ var MAX_REDIRECTS = 20;
12
+ var REDIRECT_STATUSES = new Set([
13
+ 301,
14
+ 302,
15
+ 303,
16
+ 307,
17
+ 308
18
+ ]);
19
+ var SENSITIVE_REDIRECT_HEADERS = [
20
+ "authorization",
21
+ "cookie",
22
+ "proxy-authorization"
23
+ ];
24
+ var BODY_HEADERS = [
25
+ "content-encoding",
26
+ "content-language",
27
+ "content-length",
28
+ "content-location",
29
+ "content-type",
30
+ "transfer-encoding"
31
+ ];
32
+ function createDefaultHttpClient(options = {}) {
33
+ return new require_http_client.HttpClient({
34
+ ...options,
35
+ dialer: options.dialer ?? new require_tcp.AutoDialer()
36
+ });
37
+ }
38
+ /**
39
+ * Normalizes any supported header input into a {@link Headers} instance.
40
+ *
41
+ * @remarks
42
+ * If the input is already a {@link Headers} object, the same instance is returned.
43
+ * Tuple arrays and plain records are copied into a new {@link Headers}.
44
+ */
45
+ function normalizeHeaders(headers) {
46
+ if (headers instanceof Headers) return headers;
47
+ const result = new Headers();
48
+ if (!headers) return result;
49
+ if (Array.isArray(headers)) {
50
+ for (const [key, value] of headers) result.append(key, value);
51
+ return result;
52
+ }
53
+ for (const [key, value] of Object.entries(headers)) if (Array.isArray(value)) for (const entry of value) result.append(key, entry);
54
+ else if (value !== void 0) result.append(key, value);
55
+ return result;
56
+ }
57
+ function resolveUrl(input) {
58
+ if (input instanceof URL) return input;
59
+ return new URL(input instanceof Request ? input.url : String(input));
60
+ }
61
+ function resolveMethod(input, init) {
62
+ return (init.method ?? (input instanceof Request ? input.method : void 0))?.toUpperCase().trim() ?? "GET";
63
+ }
64
+ function resolveHeaders(input, init) {
65
+ return normalizeHeaders(init.headers !== void 0 ? init.headers : input instanceof Request ? input.headers : void 0);
66
+ }
67
+ function resolveSignal(input, init) {
68
+ return init.signal ?? (input instanceof Request ? input.signal : void 0);
69
+ }
70
+ function resolveBody(input, init) {
71
+ if (init.body !== void 0) return init.body;
72
+ return input instanceof Request ? require_body.fromRequestBody(input) : void 0;
73
+ }
74
+ function resolveRedirectMode(input, init) {
75
+ return init.redirect ?? (input instanceof Request ? input.redirect : "follow");
76
+ }
77
+ function getBodyReplaySource(input, init, method, body, redirect) {
78
+ if (redirect !== "follow" || init.body !== void 0 || body == null || method === "GET" || method === "HEAD" || !(input instanceof Request)) return;
79
+ return input.clone();
80
+ }
81
+ function assertValidFetchUrl(url) {
82
+ if (url.username || url.password) throw new TypeError("Request URL must not include embedded credentials");
83
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new TypeError(`fetch failed: unsupported scheme ${url.protocol}`);
84
+ }
85
+ function assertValidFetchBody(method, body) {
86
+ if (body == null) return;
87
+ if (method === "GET" || method === "HEAD") throw new TypeError(`Request with ${method} method cannot have a body`);
88
+ }
89
+ function lookupEnvProxy(...names) {
90
+ for (const name of names) {
91
+ const normalized = (process.env[name] ?? process.env[name.toLowerCase()])?.trim();
92
+ if (normalized) return normalized;
93
+ }
94
+ }
95
+ function resolveProxyFromEnv(url) {
96
+ const socksProxy = lookupEnvProxy("SOCKS5_PROXY", "SOCKS_PROXY");
97
+ if (socksProxy) return socksProxy;
98
+ if (url.protocol === "https:") return lookupEnvProxy("HTTPS_PROXY", "HTTP_PROXY");
99
+ return lookupEnvProxy("HTTP_PROXY");
100
+ }
101
+ function normalizeProxyConfig(proxy) {
102
+ const parsed = typeof proxy === "string" ? (0, _npy_proxy_kit.parse)(proxy, { strict: true }) : proxy;
103
+ if (parsed == null) throw new TypeError(`Invalid proxy string: ${String(proxy)}`);
104
+ const key = (0, _npy_proxy_kit.stringify)(parsed, {
105
+ strict: true,
106
+ format: "user:pass@ip:port"
107
+ });
108
+ if (!key) throw new TypeError("Failed to normalize proxy configuration");
109
+ return {
110
+ key,
111
+ proxy: parsed
112
+ };
113
+ }
114
+ function resolveNormalizedProxy(url, proxy) {
115
+ if (proxy === null) return null;
116
+ if (proxy !== void 0) return normalizeProxyConfig(proxy);
117
+ const envProxy = resolveProxyFromEnv(url);
118
+ return envProxy ? normalizeProxyConfig(envProxy) : null;
119
+ }
120
+ function annotateResponse(response, url, redirected) {
121
+ try {
122
+ if (redirected) Object.defineProperties(response, {
123
+ redirected: {
124
+ configurable: true,
125
+ enumerable: true,
126
+ value: true,
127
+ writable: false
128
+ },
129
+ url: {
130
+ configurable: true,
131
+ enumerable: true,
132
+ value: url,
133
+ writable: false
134
+ }
135
+ });
136
+ else Object.defineProperty(response, "url", {
137
+ configurable: true,
138
+ enumerable: true,
139
+ value: url,
140
+ writable: false
141
+ });
142
+ } catch {}
143
+ return response;
144
+ }
145
+ async function discardResponse(response) {
146
+ try {
147
+ await response.body?.cancel();
148
+ } catch {}
149
+ }
150
+ function isRedirectResponse(response) {
151
+ return REDIRECT_STATUSES.has(response.status) && response.headers.get("location") != null;
152
+ }
153
+ function isReplayableBody(body) {
154
+ if (body == null || typeof body === "string" || body instanceof Uint8Array || require_guards.isBlob(body) || require_guards.isFormData(body) || require_guards.isURLSearchParameters(body)) return true;
155
+ if (require_guards.isReadableStream(body) || require_guards.isReadable(body) || require_guards.isMultipartFormDataStream(body) || require_guards.isIterable(body)) return false;
156
+ return true;
157
+ }
158
+ async function resolveReplayableBody(current) {
159
+ if (isReplayableBody(current.body)) return current.body;
160
+ if (current.replayBodyRequest) {
161
+ const buffer = await current.replayBodyRequest.arrayBuffer();
162
+ return buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
163
+ }
164
+ throw new TypeError("Cannot follow redirect with a non-replayable request body");
165
+ }
166
+ function shouldDropBodyOnRedirect(status, method) {
167
+ if (status === 303) return method !== "HEAD";
168
+ return (status === 301 || status === 302) && method === "POST";
169
+ }
170
+ function resolveRedirectMethod(status, method) {
171
+ if (status === 303 && method !== "HEAD" || (status === 301 || status === 302) && method === "POST") return "GET";
172
+ return method;
173
+ }
174
+ function createRedirectHeaders(current, nextUrl, dropBody) {
175
+ const headers = new Headers(current.headers);
176
+ const isCrossOrigin = current.url.origin !== nextUrl.origin;
177
+ const isDowngrade = current.url.protocol === "https:" && nextUrl.protocol === "http:";
178
+ headers.delete("host");
179
+ if (isCrossOrigin) for (const name of SENSITIVE_REDIRECT_HEADERS) headers.delete(name);
180
+ if (dropBody) for (const name of BODY_HEADERS) headers.delete(name);
181
+ if (!headers.has("referer") && !isDowngrade) headers.set("referer", current.url.toString());
182
+ return headers;
183
+ }
184
+ async function buildRedirectRequest(current, response) {
185
+ const location = response.headers.get("location");
186
+ if (!location) return current;
187
+ const nextUrl = new URL(location, current.url);
188
+ const nextMethod = resolveRedirectMethod(response.status, current.method);
189
+ const dropBody = shouldDropBodyOnRedirect(response.status, current.method);
190
+ const nextHeaders = createRedirectHeaders(current, nextUrl, dropBody);
191
+ const nextBody = dropBody ? void 0 : await resolveReplayableBody(current);
192
+ return {
193
+ ...current,
194
+ url: nextUrl,
195
+ method: nextMethod,
196
+ headers: nextHeaders,
197
+ body: nextBody,
198
+ replayBodyRequest: void 0
199
+ };
200
+ }
201
+ async function sendPreparedRequest(prepared, getProxyClient) {
202
+ assertValidFetchUrl(prepared.url);
203
+ assertValidFetchBody(prepared.method, prepared.body);
204
+ const normalizedProxy = resolveNormalizedProxy(prepared.url, prepared.proxy);
205
+ const client = normalizedProxy ? getProxyClient(prepared.baseClient, normalizedProxy) : prepared.baseClient;
206
+ try {
207
+ const sendOptions = Object.defineProperty({
208
+ url: prepared.url,
209
+ method: prepared.method,
210
+ headers: prepared.headers,
211
+ body: prepared.body ?? null,
212
+ signal: prepared.signal
213
+ }, require_symbols.bodyErrorMapperSymbol, {
214
+ configurable: false,
215
+ enumerable: false,
216
+ writable: false,
217
+ value: (error) => require_error_mapping.toWebBodyReadError(error, prepared.signal)
218
+ });
219
+ return await client.send(sendOptions);
220
+ } catch (error) {
221
+ throw require_error_mapping.toWebFetchError(error, prepared.signal);
222
+ }
223
+ }
224
+ function prepareRequest(input, init, defaultHttpClient) {
225
+ const url = resolveUrl(input);
226
+ const method = resolveMethod(input, init);
227
+ const headers = resolveHeaders(input, init);
228
+ const body = resolveBody(input, init);
229
+ const signal = resolveSignal(input, init);
230
+ const redirect = resolveRedirectMode(input, init);
231
+ return {
232
+ url,
233
+ method,
234
+ headers,
235
+ body,
236
+ signal,
237
+ redirect,
238
+ baseClient: init.client ?? defaultHttpClient,
239
+ proxy: init.proxy,
240
+ replayBodyRequest: getBodyReplaySource(input, init, method, body, redirect)
241
+ };
242
+ }
243
+ /**
244
+ * Creates a fetch-compatible client backed by {@link HttpClient}.
245
+ *
246
+ * @remarks
247
+ * The returned function follows the standard fetch shape, but uses this library's
248
+ * connection pooling, proxy support and body/error mapping rules.
249
+ *
250
+ * When no client is provided, an internal {@link HttpClient} is created and owned
251
+ * by the returned fetch-like function. Calling {@link FetchLike.close} closes that
252
+ * internal client and any proxy-specific clients created on demand.
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * const fetchLike = createFetch();
257
+ * const response = await fetchLike("https://httpbin.org/anything");
258
+ * const data = await response.json();
259
+ * await fetchLike.close();
260
+ * ```
261
+ */
262
+ function createFetch(client) {
263
+ const defaultHttpClient = client ?? createDefaultHttpClient();
264
+ const proxyClientsByBase = /* @__PURE__ */ new WeakMap();
265
+ const ownedProxyClients = /* @__PURE__ */ new Set();
266
+ let closePromise;
267
+ const getProxyClient = (baseClient, proxy) => {
268
+ let clients = proxyClientsByBase.get(baseClient);
269
+ if (!clients) {
270
+ clients = /* @__PURE__ */ new Map();
271
+ proxyClientsByBase.set(baseClient, clients);
272
+ }
273
+ const existing = clients.get(proxy.key);
274
+ if (existing) return existing;
275
+ const proxyClient = new require_http_client.HttpClient({
276
+ ...baseClient.options,
277
+ dialer: new require_proxy.ProxyDialer(proxy.proxy)
278
+ });
279
+ clients.set(proxy.key, proxyClient);
280
+ ownedProxyClients.add(proxyClient);
281
+ return proxyClient;
282
+ };
283
+ const fetchLike = (async (input, init = {}) => {
284
+ let prepared = prepareRequest(input, init, defaultHttpClient);
285
+ let redirected = false;
286
+ let redirects = 0;
287
+ for (;;) {
288
+ const response = await sendPreparedRequest(prepared, getProxyClient);
289
+ if (!isRedirectResponse(response) || prepared.redirect === "manual") return annotateResponse(response, prepared.url.toString(), redirected);
290
+ if (prepared.redirect === "error") {
291
+ await discardResponse(response);
292
+ throw new TypeError(`fetch failed: redirect mode is set to "error"`);
293
+ }
294
+ if (redirects >= MAX_REDIRECTS) {
295
+ await discardResponse(response);
296
+ throw new TypeError(`fetch failed: maximum redirect count exceeded`);
297
+ }
298
+ prepared = await buildRedirectRequest(prepared, response);
299
+ await discardResponse(response);
300
+ redirected = true;
301
+ redirects += 1;
302
+ }
303
+ });
304
+ const close = async () => {
305
+ if (closePromise) return closePromise;
306
+ const promise = (async () => {
307
+ const proxyClients = Array.from(ownedProxyClients);
308
+ ownedProxyClients.clear();
309
+ const errors = (await Promise.allSettled([...proxyClients.map((c) => c.close()), ...client == null ? [defaultHttpClient.close()] : []])).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
310
+ if (errors.length === 1) throw errors[0];
311
+ if (errors.length > 1) throw new AggregateError(errors, "Failed to close one or more fetch clients");
312
+ })();
313
+ closePromise = promise;
314
+ try {
315
+ await promise;
316
+ } finally {
317
+ if (closePromise === promise) closePromise = void 0;
318
+ }
319
+ };
320
+ Object.defineProperties(fetchLike, {
321
+ client: {
322
+ configurable: false,
323
+ enumerable: false,
324
+ value: defaultHttpClient,
325
+ writable: false
326
+ },
327
+ close: {
328
+ configurable: false,
329
+ enumerable: false,
330
+ value: close,
331
+ writable: false
332
+ },
333
+ [Symbol.asyncDispose]: {
334
+ configurable: false,
335
+ enumerable: false,
336
+ value: close,
337
+ writable: false
338
+ }
339
+ });
340
+ return fetchLike;
341
+ }
342
+ /**
343
+ * Default fetch-compatible client created with {@link createFetch}.
344
+ *
345
+ * @remarks
346
+ * This singleton owns its internal {@link HttpClient}. Call {@link FetchLike.close}
347
+ * when you want to release pooled connections explicitly.
348
+ */
349
+ var fetch = createFetch();
350
+ //#endregion
351
+ exports.createFetch = createFetch;
352
+ exports.default = fetch;
353
+ exports.normalizeHeaders = normalizeHeaders;
package/fetch.d.cts ADDED
@@ -0,0 +1,58 @@
1
+ import { ProxyInfo } from '@npy/proxy-kit';
2
+ import { BodyInit as FetchBodyInit } from './body';
3
+ import { HttpClientOptions, HttpClient } from './http-client';
4
+ export type FetchProxyInput = string | ProxyInfo | null;
5
+ export interface RequestInit extends Omit<globalThis.RequestInit, "body" | "headers"> {
6
+ body?: FetchBodyInit | null;
7
+ headers?: HeadersInit;
8
+ client?: HttpClient;
9
+ proxy?: FetchProxyInput;
10
+ }
11
+ export type FetchRequestInit = RequestInit;
12
+ export interface FetchOptions extends HttpClientOptions {
13
+ }
14
+ export interface FetchLike {
15
+ (input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
16
+ close(): Promise<void>;
17
+ [Symbol.asyncDispose](): Promise<void>;
18
+ readonly client: HttpClient;
19
+ }
20
+ /**
21
+ * Normalizes any supported header input into a {@link Headers} instance.
22
+ *
23
+ * @remarks
24
+ * If the input is already a {@link Headers} object, the same instance is returned.
25
+ * Tuple arrays and plain records are copied into a new {@link Headers}.
26
+ */
27
+ export declare function normalizeHeaders(headers?: HeadersInit): Headers;
28
+ /**
29
+ * Creates a fetch-compatible client backed by {@link HttpClient}.
30
+ *
31
+ * @remarks
32
+ * The returned function follows the standard fetch shape, but uses this library's
33
+ * connection pooling, proxy support and body/error mapping rules.
34
+ *
35
+ * When no client is provided, an internal {@link HttpClient} is created and owned
36
+ * by the returned fetch-like function. Calling {@link FetchLike.close} closes that
37
+ * internal client and any proxy-specific clients created on demand.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const fetchLike = createFetch();
42
+ * const response = await fetchLike("https://httpbin.org/anything");
43
+ * const data = await response.json();
44
+ * await fetchLike.close();
45
+ * ```
46
+ */
47
+ export declare function createFetch(client?: HttpClient): FetchLike;
48
+ export type { HttpClientOptions, ProxyInfo };
49
+ export { HttpClient };
50
+ /**
51
+ * Default fetch-compatible client created with {@link createFetch}.
52
+ *
53
+ * @remarks
54
+ * This singleton owns its internal {@link HttpClient}. Call {@link FetchLike.close}
55
+ * when you want to release pooled connections explicitly.
56
+ */
57
+ export declare const fetch: FetchLike;
58
+ export default fetch;