@npora/request 1.8.0 → 1.9.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 +33 -2
- package/dist/index.cjs +320 -8
- package/dist/index.d.cts +39 -2
- package/dist/index.d.ts +39 -2
- package/dist/index.js +320 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,8 +16,9 @@ pnpm add @npora/request
|
|
|
16
16
|
npm install @npora/request
|
|
17
17
|
```
|
|
18
18
|
|
|
19
|
-
Node.js 22 or newer is required. Modern Chromium
|
|
20
|
-
Workers are supported through their native Fetch
|
|
19
|
+
Node.js 22 or newer is required. Modern Chromium-based browsers, Firefox,
|
|
20
|
+
Safari/WebKit, and Web Workers are supported through their native Fetch
|
|
21
|
+
implementations.
|
|
21
22
|
|
|
22
23
|
## Quick start
|
|
23
24
|
|
|
@@ -52,6 +53,32 @@ console.log(response.headers)
|
|
|
52
53
|
console.log(response.raw)
|
|
53
54
|
```
|
|
54
55
|
|
|
56
|
+
## Streaming responses
|
|
57
|
+
|
|
58
|
+
SSE and NDJSON responses are decoded incrementally as async iterables. The
|
|
59
|
+
client also detects `text/event-stream` and common NDJSON content types
|
|
60
|
+
automatically:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import type { ServerSentEvent } from '@npora/request'
|
|
64
|
+
|
|
65
|
+
const events = await api.sse('/events')
|
|
66
|
+
|
|
67
|
+
for await (const event of events) {
|
|
68
|
+
console.log(event.event, event.data, event.id)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const records = await api.ndjson<User>('/users/export')
|
|
72
|
+
|
|
73
|
+
for await (const user of records) {
|
|
74
|
+
console.log(user.name)
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Iteration is lazy and does not buffer the complete response. Breaking out of
|
|
79
|
+
the loop cancels the response reader. `maxResponseSize` remains enforced while
|
|
80
|
+
the stream is consumed.
|
|
81
|
+
|
|
55
82
|
## Request configuration
|
|
56
83
|
|
|
57
84
|
```ts
|
|
@@ -99,6 +126,8 @@ api.patch(url, config)
|
|
|
99
126
|
api.delete(url, config)
|
|
100
127
|
api.head(url, config)
|
|
101
128
|
api.options(url, config)
|
|
129
|
+
api.sse(url, config)
|
|
130
|
+
api.ndjson(url, config)
|
|
102
131
|
|
|
103
132
|
api.getResponse(url, config)
|
|
104
133
|
api.postResponse(url, config)
|
|
@@ -107,6 +136,8 @@ api.patchResponse(url, config)
|
|
|
107
136
|
api.deleteResponse(url, config)
|
|
108
137
|
api.headResponse(url, config)
|
|
109
138
|
api.optionsResponse(url, config)
|
|
139
|
+
api.sseResponse(url, config)
|
|
140
|
+
api.ndjsonResponse(url, config)
|
|
110
141
|
```
|
|
111
142
|
|
|
112
143
|
## Plugins
|
package/dist/index.cjs
CHANGED
|
@@ -177,6 +177,140 @@ function isPlainObject$1(value) {
|
|
|
177
177
|
return Object.prototype.toString.call(value) === "[object Object]";
|
|
178
178
|
}
|
|
179
179
|
//#endregion
|
|
180
|
+
//#region src/utils/parseStreamingResponse.ts
|
|
181
|
+
/**
|
|
182
|
+
* Decode a server-sent event response without buffering the complete body.
|
|
183
|
+
*/
|
|
184
|
+
function parseServerSentEvents(response, config) {
|
|
185
|
+
return decodeServerSentEvents(response.body, {
|
|
186
|
+
config,
|
|
187
|
+
response
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Decode a newline-delimited JSON response without buffering the complete
|
|
192
|
+
* body.
|
|
193
|
+
*/
|
|
194
|
+
function parseNdjson(response, config) {
|
|
195
|
+
return decodeNdjson(response.body, {
|
|
196
|
+
config,
|
|
197
|
+
response
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
async function* decodeServerSentEvents(stream, context) {
|
|
201
|
+
let data = [];
|
|
202
|
+
let event = "";
|
|
203
|
+
let lastEventId = "";
|
|
204
|
+
let retry;
|
|
205
|
+
for await (const line of decodeLines(stream, context)) {
|
|
206
|
+
if (line === "") {
|
|
207
|
+
if (data.length > 0) yield {
|
|
208
|
+
data: data.join("\n"),
|
|
209
|
+
event: event || "message",
|
|
210
|
+
id: lastEventId,
|
|
211
|
+
...retry === void 0 ? {} : { retry }
|
|
212
|
+
};
|
|
213
|
+
data = [];
|
|
214
|
+
event = "";
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (line.startsWith(":")) continue;
|
|
218
|
+
const separator = line.indexOf(":");
|
|
219
|
+
const field = separator === -1 ? line : line.slice(0, separator);
|
|
220
|
+
let value = separator === -1 ? "" : line.slice(separator + 1);
|
|
221
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
222
|
+
switch (field) {
|
|
223
|
+
case "data":
|
|
224
|
+
data.push(value);
|
|
225
|
+
break;
|
|
226
|
+
case "event":
|
|
227
|
+
event = value;
|
|
228
|
+
break;
|
|
229
|
+
case "id":
|
|
230
|
+
if (!value.includes("\0")) lastEventId = value;
|
|
231
|
+
break;
|
|
232
|
+
case "retry": if (/^\d+$/.test(value)) {
|
|
233
|
+
const milliseconds = Number(value);
|
|
234
|
+
if (Number.isSafeInteger(milliseconds)) retry = milliseconds;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
async function* decodeNdjson(stream, context) {
|
|
240
|
+
let lineNumber = 0;
|
|
241
|
+
for await (const line of decodeLines(stream, context)) {
|
|
242
|
+
lineNumber += 1;
|
|
243
|
+
if (line.trim() === "") continue;
|
|
244
|
+
try {
|
|
245
|
+
yield JSON.parse(line);
|
|
246
|
+
} catch (error) {
|
|
247
|
+
throw parserError(`Failed to parse NDJSON at line ${lineNumber}`, context, error);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
async function* decodeLines(stream, context) {
|
|
252
|
+
if (!stream) return;
|
|
253
|
+
const reader = stream.getReader();
|
|
254
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
255
|
+
let buffer = "";
|
|
256
|
+
let completed = false;
|
|
257
|
+
try {
|
|
258
|
+
while (true) {
|
|
259
|
+
const result = await reader.read();
|
|
260
|
+
if (result.done) {
|
|
261
|
+
completed = true;
|
|
262
|
+
buffer += decoder.decode();
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
buffer += decoder.decode(result.value, { stream: true });
|
|
266
|
+
const lines = takeCompleteLines(buffer, false);
|
|
267
|
+
buffer = lines.rest;
|
|
268
|
+
for (const line of lines.values) yield line;
|
|
269
|
+
}
|
|
270
|
+
const lines = takeCompleteLines(buffer, true);
|
|
271
|
+
for (const line of lines.values) yield line;
|
|
272
|
+
if (lines.rest !== "") yield lines.rest;
|
|
273
|
+
} catch (error) {
|
|
274
|
+
if (error instanceof RequestError) throw error;
|
|
275
|
+
throw parserError("Failed to parse streaming response", context, error);
|
|
276
|
+
} finally {
|
|
277
|
+
try {
|
|
278
|
+
if (!completed) await reader.cancel();
|
|
279
|
+
} catch {} finally {
|
|
280
|
+
reader.releaseLock();
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
function takeCompleteLines(input, ended) {
|
|
285
|
+
const values = [];
|
|
286
|
+
let start = 0;
|
|
287
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
288
|
+
const character = input[index];
|
|
289
|
+
if (character === "\n") {
|
|
290
|
+
values.push(input.slice(start, index));
|
|
291
|
+
start = index + 1;
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (character !== "\r") continue;
|
|
295
|
+
if (index + 1 === input.length && !ended) break;
|
|
296
|
+
values.push(input.slice(start, index));
|
|
297
|
+
if (input[index + 1] === "\n") index += 1;
|
|
298
|
+
start = index + 1;
|
|
299
|
+
}
|
|
300
|
+
return {
|
|
301
|
+
values,
|
|
302
|
+
rest: input.slice(start)
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
function parserError(message, context, cause) {
|
|
306
|
+
return new RequestError(message, {
|
|
307
|
+
code: "PARSER_ERROR",
|
|
308
|
+
status: context.response.status,
|
|
309
|
+
config: context.config,
|
|
310
|
+
cause
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
//#endregion
|
|
180
314
|
//#region src/utils/parseResponse.ts
|
|
181
315
|
/**
|
|
182
316
|
* Bound a Fetch response before it can be cloned into multiple body branches.
|
|
@@ -199,16 +333,95 @@ function limitResponseSize(response, config) {
|
|
|
199
333
|
return limited;
|
|
200
334
|
}
|
|
201
335
|
/**
|
|
336
|
+
* Keep request cancellation resources alive until a streaming response body
|
|
337
|
+
* settles instead of releasing them as soon as response headers arrive.
|
|
338
|
+
*/
|
|
339
|
+
function finalizeStreamingResponse(response, signal, config, finalize) {
|
|
340
|
+
if (!response.body) {
|
|
341
|
+
finalize();
|
|
342
|
+
return response;
|
|
343
|
+
}
|
|
344
|
+
const reader = response.body.getReader();
|
|
345
|
+
let settled = false;
|
|
346
|
+
let pendingAbortError;
|
|
347
|
+
let onAbort;
|
|
348
|
+
const settle = () => {
|
|
349
|
+
if (settled) return;
|
|
350
|
+
settled = true;
|
|
351
|
+
if (onAbort) {
|
|
352
|
+
signal?.removeEventListener("abort", onAbort);
|
|
353
|
+
onAbort = void 0;
|
|
354
|
+
}
|
|
355
|
+
reader.releaseLock();
|
|
356
|
+
finalize();
|
|
357
|
+
};
|
|
358
|
+
const stream = new ReadableStream({
|
|
359
|
+
start(controller) {
|
|
360
|
+
onAbort = () => {
|
|
361
|
+
const error = streamingReadError(signal?.reason, signal, config);
|
|
362
|
+
pendingAbortError = error;
|
|
363
|
+
reader.cancel(error).catch(() => {}).finally(() => {
|
|
364
|
+
if (!settled) {
|
|
365
|
+
settle();
|
|
366
|
+
controller.error(error);
|
|
367
|
+
}
|
|
368
|
+
});
|
|
369
|
+
};
|
|
370
|
+
if (signal?.aborted) onAbort();
|
|
371
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
372
|
+
},
|
|
373
|
+
async pull(controller) {
|
|
374
|
+
try {
|
|
375
|
+
const result = await reader.read();
|
|
376
|
+
if (pendingAbortError) {
|
|
377
|
+
const error = pendingAbortError;
|
|
378
|
+
settle();
|
|
379
|
+
controller.error(error);
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
if (settled) return;
|
|
383
|
+
if (result.done) {
|
|
384
|
+
settle();
|
|
385
|
+
controller.close();
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
controller.enqueue(result.value);
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (settled) return;
|
|
391
|
+
settle();
|
|
392
|
+
controller.error(streamingReadError(error, signal, config));
|
|
393
|
+
}
|
|
394
|
+
},
|
|
395
|
+
async cancel(reason) {
|
|
396
|
+
try {
|
|
397
|
+
await reader.cancel(reason);
|
|
398
|
+
} finally {
|
|
399
|
+
settle();
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
const wrapped = new Response(stream, {
|
|
404
|
+
status: response.status,
|
|
405
|
+
statusText: response.statusText,
|
|
406
|
+
headers: response.headers
|
|
407
|
+
});
|
|
408
|
+
copyResponseMetadata(response, wrapped);
|
|
409
|
+
return wrapped;
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
202
412
|
* Parse a Fetch response according to the request configuration.
|
|
203
413
|
*/
|
|
204
414
|
async function parseResponse(response, config) {
|
|
205
415
|
if (config.method === "HEAD" || response.status === 204 || response.status === 205) return;
|
|
206
|
-
const responseType =
|
|
416
|
+
const responseType = resolveResponseType(response, config);
|
|
207
417
|
const maxSize = config.maxResponseSize;
|
|
208
418
|
try {
|
|
209
419
|
if (maxSize !== void 0 && Number.isFinite(maxSize)) {
|
|
210
420
|
await rejectOversizedContentLength(response, maxSize, config);
|
|
211
|
-
if (responseType
|
|
421
|
+
if (isStreamingResponseType(responseType)) {
|
|
422
|
+
const stream = limitResponseStream(response, maxSize, config);
|
|
423
|
+
return parseStreamingResponse(new Response(stream, response), responseType, config);
|
|
424
|
+
}
|
|
212
425
|
return parseBufferedResponse(await readLimitedBody(response, maxSize, config), responseType, response);
|
|
213
426
|
}
|
|
214
427
|
switch (responseType) {
|
|
@@ -217,6 +430,8 @@ async function parseResponse(response, config) {
|
|
|
217
430
|
case "blob": return await response.blob();
|
|
218
431
|
case "arrayBuffer": return await response.arrayBuffer();
|
|
219
432
|
case "stream": return response.body;
|
|
433
|
+
case "sse": return parseServerSentEvents(response, config);
|
|
434
|
+
case "ndjson": return parseNdjson(response, config);
|
|
220
435
|
default: return await response.text();
|
|
221
436
|
}
|
|
222
437
|
} catch (error) {
|
|
@@ -272,6 +487,19 @@ function parseBufferedResponse(bytes, responseType, response) {
|
|
|
272
487
|
default: return new TextDecoder().decode(bytes);
|
|
273
488
|
}
|
|
274
489
|
}
|
|
490
|
+
function parseStreamingResponse(response, responseType, config) {
|
|
491
|
+
switch (responseType) {
|
|
492
|
+
case "sse": return parseServerSentEvents(response, config);
|
|
493
|
+
case "ndjson": return parseNdjson(response, config);
|
|
494
|
+
default: return response.body;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
function isStreamingResponseType(responseType) {
|
|
498
|
+
return responseType === "stream" || responseType === "sse" || responseType === "ndjson";
|
|
499
|
+
}
|
|
500
|
+
function resolveResponseType(response, config) {
|
|
501
|
+
return config.responseType ?? detectResponseType(response);
|
|
502
|
+
}
|
|
275
503
|
function toArrayBuffer(bytes) {
|
|
276
504
|
if (bytes.buffer instanceof ArrayBuffer) return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
277
505
|
return Uint8Array.from(bytes).buffer;
|
|
@@ -334,6 +562,22 @@ function createSizeError(response, maxSize, config) {
|
|
|
334
562
|
config
|
|
335
563
|
});
|
|
336
564
|
}
|
|
565
|
+
function streamingReadError(error, signal, config) {
|
|
566
|
+
if (!signal?.aborted) return error;
|
|
567
|
+
if (signal.reason instanceof RequestError) return new RequestError(signal.reason.message, {
|
|
568
|
+
code: signal.reason.code,
|
|
569
|
+
status: signal.reason.status,
|
|
570
|
+
data: signal.reason.data,
|
|
571
|
+
response: signal.reason.response,
|
|
572
|
+
config,
|
|
573
|
+
cause: signal.reason
|
|
574
|
+
});
|
|
575
|
+
return new RequestError("Request aborted while consuming response", {
|
|
576
|
+
code: "ABORT_ERROR",
|
|
577
|
+
config,
|
|
578
|
+
cause: signal.reason ?? error
|
|
579
|
+
});
|
|
580
|
+
}
|
|
337
581
|
function copyResponseMetadata(source, target) {
|
|
338
582
|
for (const key of [
|
|
339
583
|
"url",
|
|
@@ -348,9 +592,18 @@ function copyResponseMetadata(source, target) {
|
|
|
348
592
|
}
|
|
349
593
|
function detectResponseType(response) {
|
|
350
594
|
const contentType = response.headers.get("content-type") ?? "";
|
|
351
|
-
|
|
595
|
+
const parameterStart = contentType.indexOf(";");
|
|
596
|
+
const mediaType = contentType.slice(0, parameterStart === -1 ? void 0 : parameterStart).trim().toLowerCase();
|
|
597
|
+
if (mediaType === "text/event-stream") return "sse";
|
|
598
|
+
if (mediaType === "application/x-ndjson" || mediaType === "application/ndjson" || hasStructuredSuffix(mediaType, "+ndjson")) return "ndjson";
|
|
599
|
+
if (mediaType === "application/json" || hasStructuredSuffix(mediaType, "+json")) return "json";
|
|
352
600
|
return "text";
|
|
353
601
|
}
|
|
602
|
+
function hasStructuredSuffix(mediaType, suffix) {
|
|
603
|
+
const slashIndex = mediaType.indexOf("/");
|
|
604
|
+
const suffixStart = mediaType.length - suffix.length;
|
|
605
|
+
return slashIndex > 0 && suffixStart > slashIndex + 1 && mediaType.endsWith(suffix);
|
|
606
|
+
}
|
|
354
607
|
//#endregion
|
|
355
608
|
//#region src/utils/validateRequestConfig.ts
|
|
356
609
|
const BODY_FIELDS = [
|
|
@@ -424,18 +677,26 @@ var FetchAdapter = class {
|
|
|
424
677
|
}
|
|
425
678
|
async execute(config, headers, preserveRaw) {
|
|
426
679
|
let request;
|
|
680
|
+
let deferCleanup = false;
|
|
681
|
+
let responseExposed = false;
|
|
427
682
|
try {
|
|
428
683
|
request = buildRequestWithHeaders(config, headers);
|
|
429
|
-
|
|
684
|
+
let response = limitResponseSize(await fetch(request.url, request.init), config);
|
|
430
685
|
const validStatus = (config.validateStatus ?? defaultValidateStatus$2)(response.status);
|
|
686
|
+
const streaming = isStreamingResponseType(resolveResponseType(response, config));
|
|
687
|
+
if (streaming) {
|
|
688
|
+
response = finalizeStreamingResponse(response, request.init.signal, config, request.clear);
|
|
689
|
+
deferCleanup = Boolean(response.body);
|
|
690
|
+
}
|
|
431
691
|
const nporaResponse = {
|
|
432
|
-
data: await parseResponse(
|
|
692
|
+
data: await parseResponse(streaming || !preserveRaw && validStatus ? response : response.clone(), config),
|
|
433
693
|
status: response.status,
|
|
434
694
|
statusText: response.statusText,
|
|
435
695
|
headers: response.headers,
|
|
436
696
|
config,
|
|
437
697
|
raw: response
|
|
438
698
|
};
|
|
699
|
+
responseExposed = true;
|
|
439
700
|
if (!validStatus) throw new RequestError(response.statusText || "Request failed", {
|
|
440
701
|
code: "HTTP_ERROR",
|
|
441
702
|
response: nporaResponse
|
|
@@ -471,7 +732,7 @@ var FetchAdapter = class {
|
|
|
471
732
|
cause: error
|
|
472
733
|
});
|
|
473
734
|
} finally {
|
|
474
|
-
request?.clear();
|
|
735
|
+
if (!deferCleanup || !responseExposed) request?.clear();
|
|
475
736
|
}
|
|
476
737
|
}
|
|
477
738
|
};
|
|
@@ -1428,6 +1689,42 @@ var Client = class Client {
|
|
|
1428
1689
|
method: "OPTIONS"
|
|
1429
1690
|
});
|
|
1430
1691
|
}
|
|
1692
|
+
/**
|
|
1693
|
+
* Consume a server-sent event response as a lazy async iterable.
|
|
1694
|
+
*/
|
|
1695
|
+
sse(url, config = {}) {
|
|
1696
|
+
return this.get(url, {
|
|
1697
|
+
...config,
|
|
1698
|
+
responseType: "sse"
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
/**
|
|
1702
|
+
* Consume a server-sent event response with complete response metadata.
|
|
1703
|
+
*/
|
|
1704
|
+
sseResponse(url, config = {}) {
|
|
1705
|
+
return this.getResponse(url, {
|
|
1706
|
+
...config,
|
|
1707
|
+
responseType: "sse"
|
|
1708
|
+
});
|
|
1709
|
+
}
|
|
1710
|
+
/**
|
|
1711
|
+
* Consume newline-delimited JSON records as a lazy async iterable.
|
|
1712
|
+
*/
|
|
1713
|
+
ndjson(url, config = {}) {
|
|
1714
|
+
return this.get(url, {
|
|
1715
|
+
...config,
|
|
1716
|
+
responseType: "ndjson"
|
|
1717
|
+
});
|
|
1718
|
+
}
|
|
1719
|
+
/**
|
|
1720
|
+
* Consume newline-delimited JSON with complete response metadata.
|
|
1721
|
+
*/
|
|
1722
|
+
ndjsonResponse(url, config = {}) {
|
|
1723
|
+
return this.getResponse(url, {
|
|
1724
|
+
...config,
|
|
1725
|
+
responseType: "ndjson"
|
|
1726
|
+
});
|
|
1727
|
+
}
|
|
1431
1728
|
createPipeline(adapter) {
|
|
1432
1729
|
return new Pipeline(adapter, this.interceptors, this.hooks);
|
|
1433
1730
|
}
|
|
@@ -1597,6 +1894,7 @@ function cachePlugin(options = {}) {
|
|
|
1597
1894
|
const cacheHits = /* @__PURE__ */ new WeakSet();
|
|
1598
1895
|
const leaders = /* @__PURE__ */ new WeakMap();
|
|
1599
1896
|
const completedRecords = /* @__PURE__ */ new WeakMap();
|
|
1897
|
+
const uncacheableLeaders = /* @__PURE__ */ new WeakSet();
|
|
1600
1898
|
const inFlight = /* @__PURE__ */ new Map();
|
|
1601
1899
|
const methods = new Set(options.methods ?? DEFAULT_CACHE_METHODS);
|
|
1602
1900
|
const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
|
|
@@ -1627,7 +1925,9 @@ function cachePlugin(options = {}) {
|
|
|
1627
1925
|
if (!(cache.dedupe ?? options.dedupe ?? true)) return;
|
|
1628
1926
|
const pending = inFlight.get(key);
|
|
1629
1927
|
if (pending) {
|
|
1630
|
-
|
|
1928
|
+
const sharedRecord = await waitForSharedRecord(pending.promise, requestContext.config);
|
|
1929
|
+
if (!sharedRecord) return;
|
|
1930
|
+
requestContext.response = createCachedResponse(sharedRecord, requestContext.config);
|
|
1631
1931
|
cacheHits.add(requestContext);
|
|
1632
1932
|
return;
|
|
1633
1933
|
}
|
|
@@ -1641,6 +1941,11 @@ function cachePlugin(options = {}) {
|
|
|
1641
1941
|
const cache = resolveExtensionConfig(requestContext.config, "cache");
|
|
1642
1942
|
if (!cache?.enabled || !requestContext.response || !isCacheableRequest(requestContext.config, methods)) return;
|
|
1643
1943
|
const key = createCacheKey(requestContext.config, cache, varyHeaders);
|
|
1944
|
+
if (isAsyncIterable(requestContext.response.data)) {
|
|
1945
|
+
uncacheableLeaders.add(requestContext);
|
|
1946
|
+
await deleteStore(store, key);
|
|
1947
|
+
return;
|
|
1948
|
+
}
|
|
1644
1949
|
const ttl = cache.ttl ?? 3e4;
|
|
1645
1950
|
const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
|
|
1646
1951
|
completedRecords.set(requestContext, record);
|
|
@@ -1658,6 +1963,10 @@ function cachePlugin(options = {}) {
|
|
|
1658
1963
|
const pending = inFlight.get(key);
|
|
1659
1964
|
if (!pending || pending.owner !== requestContext) return;
|
|
1660
1965
|
inFlight.delete(key);
|
|
1966
|
+
if (uncacheableLeaders.delete(requestContext)) {
|
|
1967
|
+
pending.resolve(void 0);
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1661
1970
|
const record = completedRecords.get(requestContext);
|
|
1662
1971
|
completedRecords.delete(requestContext);
|
|
1663
1972
|
if (record && requestContext.response && !requestContext.error) {
|
|
@@ -1789,7 +2098,10 @@ function restoreCacheEntry(record, config) {
|
|
|
1789
2098
|
}
|
|
1790
2099
|
}
|
|
1791
2100
|
function isCacheableRequest(config, methods) {
|
|
1792
|
-
return methods.has(config.method ?? "GET") && config.responseType !== "stream";
|
|
2101
|
+
return methods.has(config.method ?? "GET") && config.responseType !== "stream" && config.responseType !== "sse" && config.responseType !== "ndjson";
|
|
2102
|
+
}
|
|
2103
|
+
function isAsyncIterable(value) {
|
|
2104
|
+
return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
1793
2105
|
}
|
|
1794
2106
|
function allowsPersistentCaching(response) {
|
|
1795
2107
|
if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
|
package/dist/index.d.cts
CHANGED
|
@@ -225,7 +225,7 @@ interface DownloadOptions {
|
|
|
225
225
|
//#region src/types/config.d.ts
|
|
226
226
|
type QueryValue = string | number | boolean | null | undefined;
|
|
227
227
|
type QueryParams = Record<string, QueryValue | QueryValue[]>;
|
|
228
|
-
type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream';
|
|
228
|
+
type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'sse' | 'ndjson';
|
|
229
229
|
/**
|
|
230
230
|
* Native Fetch options passed to the underlying adapter.
|
|
231
231
|
*
|
|
@@ -279,6 +279,27 @@ interface RequestConfig {
|
|
|
279
279
|
}
|
|
280
280
|
//#endregion
|
|
281
281
|
//#region src/types/response.d.ts
|
|
282
|
+
/**
|
|
283
|
+
* A message decoded from a `text/event-stream` response.
|
|
284
|
+
*/
|
|
285
|
+
interface ServerSentEvent {
|
|
286
|
+
/**
|
|
287
|
+
* Event payload with multiple `data` fields joined by newlines.
|
|
288
|
+
*/
|
|
289
|
+
data: string;
|
|
290
|
+
/**
|
|
291
|
+
* Event type, defaulting to `message`.
|
|
292
|
+
*/
|
|
293
|
+
event: string;
|
|
294
|
+
/**
|
|
295
|
+
* Most recently observed event identifier.
|
|
296
|
+
*/
|
|
297
|
+
id: string;
|
|
298
|
+
/**
|
|
299
|
+
* Most recently observed server reconnection delay in milliseconds.
|
|
300
|
+
*/
|
|
301
|
+
retry?: number;
|
|
302
|
+
}
|
|
282
303
|
/**
|
|
283
304
|
* Npora response.
|
|
284
305
|
*/
|
|
@@ -547,6 +568,22 @@ declare class Client {
|
|
|
547
568
|
headResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<void>>;
|
|
548
569
|
options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
|
|
549
570
|
optionsResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
|
|
571
|
+
/**
|
|
572
|
+
* Consume a server-sent event response as a lazy async iterable.
|
|
573
|
+
*/
|
|
574
|
+
sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<ServerSentEvent>>;
|
|
575
|
+
/**
|
|
576
|
+
* Consume a server-sent event response with complete response metadata.
|
|
577
|
+
*/
|
|
578
|
+
sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
|
|
579
|
+
/**
|
|
580
|
+
* Consume newline-delimited JSON records as a lazy async iterable.
|
|
581
|
+
*/
|
|
582
|
+
ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<T>>;
|
|
583
|
+
/**
|
|
584
|
+
* Consume newline-delimited JSON with complete response metadata.
|
|
585
|
+
*/
|
|
586
|
+
ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<T>>>;
|
|
550
587
|
private createPipeline;
|
|
551
588
|
private validatePlugin;
|
|
552
589
|
private findDependent;
|
|
@@ -868,4 +905,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
|
|
|
868
905
|
//#region src/plugins/uploadPlugin.d.ts
|
|
869
906
|
declare function uploadPlugin(): Plugin;
|
|
870
907
|
//#endregion
|
|
871
|
-
export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
|
|
908
|
+
export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, ServerSentEvent, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
|
package/dist/index.d.ts
CHANGED
|
@@ -225,7 +225,7 @@ interface DownloadOptions {
|
|
|
225
225
|
//#region src/types/config.d.ts
|
|
226
226
|
type QueryValue = string | number | boolean | null | undefined;
|
|
227
227
|
type QueryParams = Record<string, QueryValue | QueryValue[]>;
|
|
228
|
-
type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream';
|
|
228
|
+
type ResponseType = 'json' | 'text' | 'blob' | 'arrayBuffer' | 'stream' | 'sse' | 'ndjson';
|
|
229
229
|
/**
|
|
230
230
|
* Native Fetch options passed to the underlying adapter.
|
|
231
231
|
*
|
|
@@ -279,6 +279,27 @@ interface RequestConfig {
|
|
|
279
279
|
}
|
|
280
280
|
//#endregion
|
|
281
281
|
//#region src/types/response.d.ts
|
|
282
|
+
/**
|
|
283
|
+
* A message decoded from a `text/event-stream` response.
|
|
284
|
+
*/
|
|
285
|
+
interface ServerSentEvent {
|
|
286
|
+
/**
|
|
287
|
+
* Event payload with multiple `data` fields joined by newlines.
|
|
288
|
+
*/
|
|
289
|
+
data: string;
|
|
290
|
+
/**
|
|
291
|
+
* Event type, defaulting to `message`.
|
|
292
|
+
*/
|
|
293
|
+
event: string;
|
|
294
|
+
/**
|
|
295
|
+
* Most recently observed event identifier.
|
|
296
|
+
*/
|
|
297
|
+
id: string;
|
|
298
|
+
/**
|
|
299
|
+
* Most recently observed server reconnection delay in milliseconds.
|
|
300
|
+
*/
|
|
301
|
+
retry?: number;
|
|
302
|
+
}
|
|
282
303
|
/**
|
|
283
304
|
* Npora response.
|
|
284
305
|
*/
|
|
@@ -547,6 +568,22 @@ declare class Client {
|
|
|
547
568
|
headResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<void>>;
|
|
548
569
|
options<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<T>;
|
|
549
570
|
optionsResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method'>): Promise<NporaResponse<T>>;
|
|
571
|
+
/**
|
|
572
|
+
* Consume a server-sent event response as a lazy async iterable.
|
|
573
|
+
*/
|
|
574
|
+
sse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<ServerSentEvent>>;
|
|
575
|
+
/**
|
|
576
|
+
* Consume a server-sent event response with complete response metadata.
|
|
577
|
+
*/
|
|
578
|
+
sseResponse(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<ServerSentEvent>>>;
|
|
579
|
+
/**
|
|
580
|
+
* Consume newline-delimited JSON records as a lazy async iterable.
|
|
581
|
+
*/
|
|
582
|
+
ndjson<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<AsyncIterable<T>>;
|
|
583
|
+
/**
|
|
584
|
+
* Consume newline-delimited JSON with complete response metadata.
|
|
585
|
+
*/
|
|
586
|
+
ndjsonResponse<T = unknown>(url: string, config?: Omit<RequestConfig, 'url' | 'method' | 'responseType'>): Promise<NporaResponse<AsyncIterable<T>>>;
|
|
550
587
|
private createPipeline;
|
|
551
588
|
private validatePlugin;
|
|
552
589
|
private findDependent;
|
|
@@ -868,4 +905,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
|
|
|
868
905
|
//#region src/plugins/uploadPlugin.d.ts
|
|
869
906
|
declare function uploadPlugin(): Plugin;
|
|
870
907
|
//#endregion
|
|
871
|
-
export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
|
|
908
|
+
export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, ServerSentEvent, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
|
package/dist/index.js
CHANGED
|
@@ -176,6 +176,140 @@ function isPlainObject$1(value) {
|
|
|
176
176
|
return Object.prototype.toString.call(value) === "[object Object]";
|
|
177
177
|
}
|
|
178
178
|
//#endregion
|
|
179
|
+
//#region src/utils/parseStreamingResponse.ts
|
|
180
|
+
/**
|
|
181
|
+
* Decode a server-sent event response without buffering the complete body.
|
|
182
|
+
*/
|
|
183
|
+
function parseServerSentEvents(response, config) {
|
|
184
|
+
return decodeServerSentEvents(response.body, {
|
|
185
|
+
config,
|
|
186
|
+
response
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Decode a newline-delimited JSON response without buffering the complete
|
|
191
|
+
* body.
|
|
192
|
+
*/
|
|
193
|
+
function parseNdjson(response, config) {
|
|
194
|
+
return decodeNdjson(response.body, {
|
|
195
|
+
config,
|
|
196
|
+
response
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
async function* decodeServerSentEvents(stream, context) {
|
|
200
|
+
let data = [];
|
|
201
|
+
let event = "";
|
|
202
|
+
let lastEventId = "";
|
|
203
|
+
let retry;
|
|
204
|
+
for await (const line of decodeLines(stream, context)) {
|
|
205
|
+
if (line === "") {
|
|
206
|
+
if (data.length > 0) yield {
|
|
207
|
+
data: data.join("\n"),
|
|
208
|
+
event: event || "message",
|
|
209
|
+
id: lastEventId,
|
|
210
|
+
...retry === void 0 ? {} : { retry }
|
|
211
|
+
};
|
|
212
|
+
data = [];
|
|
213
|
+
event = "";
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (line.startsWith(":")) continue;
|
|
217
|
+
const separator = line.indexOf(":");
|
|
218
|
+
const field = separator === -1 ? line : line.slice(0, separator);
|
|
219
|
+
let value = separator === -1 ? "" : line.slice(separator + 1);
|
|
220
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
221
|
+
switch (field) {
|
|
222
|
+
case "data":
|
|
223
|
+
data.push(value);
|
|
224
|
+
break;
|
|
225
|
+
case "event":
|
|
226
|
+
event = value;
|
|
227
|
+
break;
|
|
228
|
+
case "id":
|
|
229
|
+
if (!value.includes("\0")) lastEventId = value;
|
|
230
|
+
break;
|
|
231
|
+
case "retry": if (/^\d+$/.test(value)) {
|
|
232
|
+
const milliseconds = Number(value);
|
|
233
|
+
if (Number.isSafeInteger(milliseconds)) retry = milliseconds;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
async function* decodeNdjson(stream, context) {
|
|
239
|
+
let lineNumber = 0;
|
|
240
|
+
for await (const line of decodeLines(stream, context)) {
|
|
241
|
+
lineNumber += 1;
|
|
242
|
+
if (line.trim() === "") continue;
|
|
243
|
+
try {
|
|
244
|
+
yield JSON.parse(line);
|
|
245
|
+
} catch (error) {
|
|
246
|
+
throw parserError(`Failed to parse NDJSON at line ${lineNumber}`, context, error);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
async function* decodeLines(stream, context) {
|
|
251
|
+
if (!stream) return;
|
|
252
|
+
const reader = stream.getReader();
|
|
253
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
254
|
+
let buffer = "";
|
|
255
|
+
let completed = false;
|
|
256
|
+
try {
|
|
257
|
+
while (true) {
|
|
258
|
+
const result = await reader.read();
|
|
259
|
+
if (result.done) {
|
|
260
|
+
completed = true;
|
|
261
|
+
buffer += decoder.decode();
|
|
262
|
+
break;
|
|
263
|
+
}
|
|
264
|
+
buffer += decoder.decode(result.value, { stream: true });
|
|
265
|
+
const lines = takeCompleteLines(buffer, false);
|
|
266
|
+
buffer = lines.rest;
|
|
267
|
+
for (const line of lines.values) yield line;
|
|
268
|
+
}
|
|
269
|
+
const lines = takeCompleteLines(buffer, true);
|
|
270
|
+
for (const line of lines.values) yield line;
|
|
271
|
+
if (lines.rest !== "") yield lines.rest;
|
|
272
|
+
} catch (error) {
|
|
273
|
+
if (error instanceof RequestError) throw error;
|
|
274
|
+
throw parserError("Failed to parse streaming response", context, error);
|
|
275
|
+
} finally {
|
|
276
|
+
try {
|
|
277
|
+
if (!completed) await reader.cancel();
|
|
278
|
+
} catch {} finally {
|
|
279
|
+
reader.releaseLock();
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
function takeCompleteLines(input, ended) {
|
|
284
|
+
const values = [];
|
|
285
|
+
let start = 0;
|
|
286
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
287
|
+
const character = input[index];
|
|
288
|
+
if (character === "\n") {
|
|
289
|
+
values.push(input.slice(start, index));
|
|
290
|
+
start = index + 1;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (character !== "\r") continue;
|
|
294
|
+
if (index + 1 === input.length && !ended) break;
|
|
295
|
+
values.push(input.slice(start, index));
|
|
296
|
+
if (input[index + 1] === "\n") index += 1;
|
|
297
|
+
start = index + 1;
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
values,
|
|
301
|
+
rest: input.slice(start)
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
function parserError(message, context, cause) {
|
|
305
|
+
return new RequestError(message, {
|
|
306
|
+
code: "PARSER_ERROR",
|
|
307
|
+
status: context.response.status,
|
|
308
|
+
config: context.config,
|
|
309
|
+
cause
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
//#endregion
|
|
179
313
|
//#region src/utils/parseResponse.ts
|
|
180
314
|
/**
|
|
181
315
|
* Bound a Fetch response before it can be cloned into multiple body branches.
|
|
@@ -198,16 +332,95 @@ function limitResponseSize(response, config) {
|
|
|
198
332
|
return limited;
|
|
199
333
|
}
|
|
200
334
|
/**
|
|
335
|
+
* Keep request cancellation resources alive until a streaming response body
|
|
336
|
+
* settles instead of releasing them as soon as response headers arrive.
|
|
337
|
+
*/
|
|
338
|
+
function finalizeStreamingResponse(response, signal, config, finalize) {
|
|
339
|
+
if (!response.body) {
|
|
340
|
+
finalize();
|
|
341
|
+
return response;
|
|
342
|
+
}
|
|
343
|
+
const reader = response.body.getReader();
|
|
344
|
+
let settled = false;
|
|
345
|
+
let pendingAbortError;
|
|
346
|
+
let onAbort;
|
|
347
|
+
const settle = () => {
|
|
348
|
+
if (settled) return;
|
|
349
|
+
settled = true;
|
|
350
|
+
if (onAbort) {
|
|
351
|
+
signal?.removeEventListener("abort", onAbort);
|
|
352
|
+
onAbort = void 0;
|
|
353
|
+
}
|
|
354
|
+
reader.releaseLock();
|
|
355
|
+
finalize();
|
|
356
|
+
};
|
|
357
|
+
const stream = new ReadableStream({
|
|
358
|
+
start(controller) {
|
|
359
|
+
onAbort = () => {
|
|
360
|
+
const error = streamingReadError(signal?.reason, signal, config);
|
|
361
|
+
pendingAbortError = error;
|
|
362
|
+
reader.cancel(error).catch(() => {}).finally(() => {
|
|
363
|
+
if (!settled) {
|
|
364
|
+
settle();
|
|
365
|
+
controller.error(error);
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
};
|
|
369
|
+
if (signal?.aborted) onAbort();
|
|
370
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
371
|
+
},
|
|
372
|
+
async pull(controller) {
|
|
373
|
+
try {
|
|
374
|
+
const result = await reader.read();
|
|
375
|
+
if (pendingAbortError) {
|
|
376
|
+
const error = pendingAbortError;
|
|
377
|
+
settle();
|
|
378
|
+
controller.error(error);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (settled) return;
|
|
382
|
+
if (result.done) {
|
|
383
|
+
settle();
|
|
384
|
+
controller.close();
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
controller.enqueue(result.value);
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (settled) return;
|
|
390
|
+
settle();
|
|
391
|
+
controller.error(streamingReadError(error, signal, config));
|
|
392
|
+
}
|
|
393
|
+
},
|
|
394
|
+
async cancel(reason) {
|
|
395
|
+
try {
|
|
396
|
+
await reader.cancel(reason);
|
|
397
|
+
} finally {
|
|
398
|
+
settle();
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
});
|
|
402
|
+
const wrapped = new Response(stream, {
|
|
403
|
+
status: response.status,
|
|
404
|
+
statusText: response.statusText,
|
|
405
|
+
headers: response.headers
|
|
406
|
+
});
|
|
407
|
+
copyResponseMetadata(response, wrapped);
|
|
408
|
+
return wrapped;
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
201
411
|
* Parse a Fetch response according to the request configuration.
|
|
202
412
|
*/
|
|
203
413
|
async function parseResponse(response, config) {
|
|
204
414
|
if (config.method === "HEAD" || response.status === 204 || response.status === 205) return;
|
|
205
|
-
const responseType =
|
|
415
|
+
const responseType = resolveResponseType(response, config);
|
|
206
416
|
const maxSize = config.maxResponseSize;
|
|
207
417
|
try {
|
|
208
418
|
if (maxSize !== void 0 && Number.isFinite(maxSize)) {
|
|
209
419
|
await rejectOversizedContentLength(response, maxSize, config);
|
|
210
|
-
if (responseType
|
|
420
|
+
if (isStreamingResponseType(responseType)) {
|
|
421
|
+
const stream = limitResponseStream(response, maxSize, config);
|
|
422
|
+
return parseStreamingResponse(new Response(stream, response), responseType, config);
|
|
423
|
+
}
|
|
211
424
|
return parseBufferedResponse(await readLimitedBody(response, maxSize, config), responseType, response);
|
|
212
425
|
}
|
|
213
426
|
switch (responseType) {
|
|
@@ -216,6 +429,8 @@ async function parseResponse(response, config) {
|
|
|
216
429
|
case "blob": return await response.blob();
|
|
217
430
|
case "arrayBuffer": return await response.arrayBuffer();
|
|
218
431
|
case "stream": return response.body;
|
|
432
|
+
case "sse": return parseServerSentEvents(response, config);
|
|
433
|
+
case "ndjson": return parseNdjson(response, config);
|
|
219
434
|
default: return await response.text();
|
|
220
435
|
}
|
|
221
436
|
} catch (error) {
|
|
@@ -271,6 +486,19 @@ function parseBufferedResponse(bytes, responseType, response) {
|
|
|
271
486
|
default: return new TextDecoder().decode(bytes);
|
|
272
487
|
}
|
|
273
488
|
}
|
|
489
|
+
function parseStreamingResponse(response, responseType, config) {
|
|
490
|
+
switch (responseType) {
|
|
491
|
+
case "sse": return parseServerSentEvents(response, config);
|
|
492
|
+
case "ndjson": return parseNdjson(response, config);
|
|
493
|
+
default: return response.body;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
function isStreamingResponseType(responseType) {
|
|
497
|
+
return responseType === "stream" || responseType === "sse" || responseType === "ndjson";
|
|
498
|
+
}
|
|
499
|
+
function resolveResponseType(response, config) {
|
|
500
|
+
return config.responseType ?? detectResponseType(response);
|
|
501
|
+
}
|
|
274
502
|
function toArrayBuffer(bytes) {
|
|
275
503
|
if (bytes.buffer instanceof ArrayBuffer) return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
276
504
|
return Uint8Array.from(bytes).buffer;
|
|
@@ -333,6 +561,22 @@ function createSizeError(response, maxSize, config) {
|
|
|
333
561
|
config
|
|
334
562
|
});
|
|
335
563
|
}
|
|
564
|
+
function streamingReadError(error, signal, config) {
|
|
565
|
+
if (!signal?.aborted) return error;
|
|
566
|
+
if (signal.reason instanceof RequestError) return new RequestError(signal.reason.message, {
|
|
567
|
+
code: signal.reason.code,
|
|
568
|
+
status: signal.reason.status,
|
|
569
|
+
data: signal.reason.data,
|
|
570
|
+
response: signal.reason.response,
|
|
571
|
+
config,
|
|
572
|
+
cause: signal.reason
|
|
573
|
+
});
|
|
574
|
+
return new RequestError("Request aborted while consuming response", {
|
|
575
|
+
code: "ABORT_ERROR",
|
|
576
|
+
config,
|
|
577
|
+
cause: signal.reason ?? error
|
|
578
|
+
});
|
|
579
|
+
}
|
|
336
580
|
function copyResponseMetadata(source, target) {
|
|
337
581
|
for (const key of [
|
|
338
582
|
"url",
|
|
@@ -347,9 +591,18 @@ function copyResponseMetadata(source, target) {
|
|
|
347
591
|
}
|
|
348
592
|
function detectResponseType(response) {
|
|
349
593
|
const contentType = response.headers.get("content-type") ?? "";
|
|
350
|
-
|
|
594
|
+
const parameterStart = contentType.indexOf(";");
|
|
595
|
+
const mediaType = contentType.slice(0, parameterStart === -1 ? void 0 : parameterStart).trim().toLowerCase();
|
|
596
|
+
if (mediaType === "text/event-stream") return "sse";
|
|
597
|
+
if (mediaType === "application/x-ndjson" || mediaType === "application/ndjson" || hasStructuredSuffix(mediaType, "+ndjson")) return "ndjson";
|
|
598
|
+
if (mediaType === "application/json" || hasStructuredSuffix(mediaType, "+json")) return "json";
|
|
351
599
|
return "text";
|
|
352
600
|
}
|
|
601
|
+
function hasStructuredSuffix(mediaType, suffix) {
|
|
602
|
+
const slashIndex = mediaType.indexOf("/");
|
|
603
|
+
const suffixStart = mediaType.length - suffix.length;
|
|
604
|
+
return slashIndex > 0 && suffixStart > slashIndex + 1 && mediaType.endsWith(suffix);
|
|
605
|
+
}
|
|
353
606
|
//#endregion
|
|
354
607
|
//#region src/utils/validateRequestConfig.ts
|
|
355
608
|
const BODY_FIELDS = [
|
|
@@ -423,18 +676,26 @@ var FetchAdapter = class {
|
|
|
423
676
|
}
|
|
424
677
|
async execute(config, headers, preserveRaw) {
|
|
425
678
|
let request;
|
|
679
|
+
let deferCleanup = false;
|
|
680
|
+
let responseExposed = false;
|
|
426
681
|
try {
|
|
427
682
|
request = buildRequestWithHeaders(config, headers);
|
|
428
|
-
|
|
683
|
+
let response = limitResponseSize(await fetch(request.url, request.init), config);
|
|
429
684
|
const validStatus = (config.validateStatus ?? defaultValidateStatus$2)(response.status);
|
|
685
|
+
const streaming = isStreamingResponseType(resolveResponseType(response, config));
|
|
686
|
+
if (streaming) {
|
|
687
|
+
response = finalizeStreamingResponse(response, request.init.signal, config, request.clear);
|
|
688
|
+
deferCleanup = Boolean(response.body);
|
|
689
|
+
}
|
|
430
690
|
const nporaResponse = {
|
|
431
|
-
data: await parseResponse(
|
|
691
|
+
data: await parseResponse(streaming || !preserveRaw && validStatus ? response : response.clone(), config),
|
|
432
692
|
status: response.status,
|
|
433
693
|
statusText: response.statusText,
|
|
434
694
|
headers: response.headers,
|
|
435
695
|
config,
|
|
436
696
|
raw: response
|
|
437
697
|
};
|
|
698
|
+
responseExposed = true;
|
|
438
699
|
if (!validStatus) throw new RequestError(response.statusText || "Request failed", {
|
|
439
700
|
code: "HTTP_ERROR",
|
|
440
701
|
response: nporaResponse
|
|
@@ -470,7 +731,7 @@ var FetchAdapter = class {
|
|
|
470
731
|
cause: error
|
|
471
732
|
});
|
|
472
733
|
} finally {
|
|
473
|
-
request?.clear();
|
|
734
|
+
if (!deferCleanup || !responseExposed) request?.clear();
|
|
474
735
|
}
|
|
475
736
|
}
|
|
476
737
|
};
|
|
@@ -1427,6 +1688,42 @@ var Client = class Client {
|
|
|
1427
1688
|
method: "OPTIONS"
|
|
1428
1689
|
});
|
|
1429
1690
|
}
|
|
1691
|
+
/**
|
|
1692
|
+
* Consume a server-sent event response as a lazy async iterable.
|
|
1693
|
+
*/
|
|
1694
|
+
sse(url, config = {}) {
|
|
1695
|
+
return this.get(url, {
|
|
1696
|
+
...config,
|
|
1697
|
+
responseType: "sse"
|
|
1698
|
+
});
|
|
1699
|
+
}
|
|
1700
|
+
/**
|
|
1701
|
+
* Consume a server-sent event response with complete response metadata.
|
|
1702
|
+
*/
|
|
1703
|
+
sseResponse(url, config = {}) {
|
|
1704
|
+
return this.getResponse(url, {
|
|
1705
|
+
...config,
|
|
1706
|
+
responseType: "sse"
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
/**
|
|
1710
|
+
* Consume newline-delimited JSON records as a lazy async iterable.
|
|
1711
|
+
*/
|
|
1712
|
+
ndjson(url, config = {}) {
|
|
1713
|
+
return this.get(url, {
|
|
1714
|
+
...config,
|
|
1715
|
+
responseType: "ndjson"
|
|
1716
|
+
});
|
|
1717
|
+
}
|
|
1718
|
+
/**
|
|
1719
|
+
* Consume newline-delimited JSON with complete response metadata.
|
|
1720
|
+
*/
|
|
1721
|
+
ndjsonResponse(url, config = {}) {
|
|
1722
|
+
return this.getResponse(url, {
|
|
1723
|
+
...config,
|
|
1724
|
+
responseType: "ndjson"
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1430
1727
|
createPipeline(adapter) {
|
|
1431
1728
|
return new Pipeline(adapter, this.interceptors, this.hooks);
|
|
1432
1729
|
}
|
|
@@ -1596,6 +1893,7 @@ function cachePlugin(options = {}) {
|
|
|
1596
1893
|
const cacheHits = /* @__PURE__ */ new WeakSet();
|
|
1597
1894
|
const leaders = /* @__PURE__ */ new WeakMap();
|
|
1598
1895
|
const completedRecords = /* @__PURE__ */ new WeakMap();
|
|
1896
|
+
const uncacheableLeaders = /* @__PURE__ */ new WeakSet();
|
|
1599
1897
|
const inFlight = /* @__PURE__ */ new Map();
|
|
1600
1898
|
const methods = new Set(options.methods ?? DEFAULT_CACHE_METHODS);
|
|
1601
1899
|
const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
|
|
@@ -1626,7 +1924,9 @@ function cachePlugin(options = {}) {
|
|
|
1626
1924
|
if (!(cache.dedupe ?? options.dedupe ?? true)) return;
|
|
1627
1925
|
const pending = inFlight.get(key);
|
|
1628
1926
|
if (pending) {
|
|
1629
|
-
|
|
1927
|
+
const sharedRecord = await waitForSharedRecord(pending.promise, requestContext.config);
|
|
1928
|
+
if (!sharedRecord) return;
|
|
1929
|
+
requestContext.response = createCachedResponse(sharedRecord, requestContext.config);
|
|
1630
1930
|
cacheHits.add(requestContext);
|
|
1631
1931
|
return;
|
|
1632
1932
|
}
|
|
@@ -1640,6 +1940,11 @@ function cachePlugin(options = {}) {
|
|
|
1640
1940
|
const cache = resolveExtensionConfig(requestContext.config, "cache");
|
|
1641
1941
|
if (!cache?.enabled || !requestContext.response || !isCacheableRequest(requestContext.config, methods)) return;
|
|
1642
1942
|
const key = createCacheKey(requestContext.config, cache, varyHeaders);
|
|
1943
|
+
if (isAsyncIterable(requestContext.response.data)) {
|
|
1944
|
+
uncacheableLeaders.add(requestContext);
|
|
1945
|
+
await deleteStore(store, key);
|
|
1946
|
+
return;
|
|
1947
|
+
}
|
|
1643
1948
|
const ttl = cache.ttl ?? 3e4;
|
|
1644
1949
|
const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
|
|
1645
1950
|
completedRecords.set(requestContext, record);
|
|
@@ -1657,6 +1962,10 @@ function cachePlugin(options = {}) {
|
|
|
1657
1962
|
const pending = inFlight.get(key);
|
|
1658
1963
|
if (!pending || pending.owner !== requestContext) return;
|
|
1659
1964
|
inFlight.delete(key);
|
|
1965
|
+
if (uncacheableLeaders.delete(requestContext)) {
|
|
1966
|
+
pending.resolve(void 0);
|
|
1967
|
+
return;
|
|
1968
|
+
}
|
|
1660
1969
|
const record = completedRecords.get(requestContext);
|
|
1661
1970
|
completedRecords.delete(requestContext);
|
|
1662
1971
|
if (record && requestContext.response && !requestContext.error) {
|
|
@@ -1788,7 +2097,10 @@ function restoreCacheEntry(record, config) {
|
|
|
1788
2097
|
}
|
|
1789
2098
|
}
|
|
1790
2099
|
function isCacheableRequest(config, methods) {
|
|
1791
|
-
return methods.has(config.method ?? "GET") && config.responseType !== "stream";
|
|
2100
|
+
return methods.has(config.method ?? "GET") && config.responseType !== "stream" && config.responseType !== "sse" && config.responseType !== "ndjson";
|
|
2101
|
+
}
|
|
2102
|
+
function isAsyncIterable(value) {
|
|
2103
|
+
return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
1792
2104
|
}
|
|
1793
2105
|
function allowsPersistentCaching(response) {
|
|
1794
2106
|
if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
|