@npora/request 1.8.0 → 1.9.0
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 +29 -2
- package/dist/index.cjs +312 -7
- package/dist/index.d.cts +39 -2
- package/dist/index.d.ts +39 -2
- package/dist/index.js +312 -7
- 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
|
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,6 +592,8 @@ function copyResponseMetadata(source, target) {
|
|
|
348
592
|
}
|
|
349
593
|
function detectResponseType(response) {
|
|
350
594
|
const contentType = response.headers.get("content-type") ?? "";
|
|
595
|
+
if (contentType.includes("text/event-stream")) return "sse";
|
|
596
|
+
if (contentType.includes("application/x-ndjson") || contentType.includes("application/ndjson") || contentType.includes("+ndjson")) return "ndjson";
|
|
351
597
|
if (contentType.includes("application/json") || contentType.includes("+json")) return "json";
|
|
352
598
|
return "text";
|
|
353
599
|
}
|
|
@@ -424,18 +670,26 @@ var FetchAdapter = class {
|
|
|
424
670
|
}
|
|
425
671
|
async execute(config, headers, preserveRaw) {
|
|
426
672
|
let request;
|
|
673
|
+
let deferCleanup = false;
|
|
674
|
+
let responseExposed = false;
|
|
427
675
|
try {
|
|
428
676
|
request = buildRequestWithHeaders(config, headers);
|
|
429
|
-
|
|
677
|
+
let response = limitResponseSize(await fetch(request.url, request.init), config);
|
|
430
678
|
const validStatus = (config.validateStatus ?? defaultValidateStatus$2)(response.status);
|
|
679
|
+
const streaming = isStreamingResponseType(resolveResponseType(response, config));
|
|
680
|
+
if (streaming) {
|
|
681
|
+
response = finalizeStreamingResponse(response, request.init.signal, config, request.clear);
|
|
682
|
+
deferCleanup = Boolean(response.body);
|
|
683
|
+
}
|
|
431
684
|
const nporaResponse = {
|
|
432
|
-
data: await parseResponse(
|
|
685
|
+
data: await parseResponse(streaming || !preserveRaw && validStatus ? response : response.clone(), config),
|
|
433
686
|
status: response.status,
|
|
434
687
|
statusText: response.statusText,
|
|
435
688
|
headers: response.headers,
|
|
436
689
|
config,
|
|
437
690
|
raw: response
|
|
438
691
|
};
|
|
692
|
+
responseExposed = true;
|
|
439
693
|
if (!validStatus) throw new RequestError(response.statusText || "Request failed", {
|
|
440
694
|
code: "HTTP_ERROR",
|
|
441
695
|
response: nporaResponse
|
|
@@ -471,7 +725,7 @@ var FetchAdapter = class {
|
|
|
471
725
|
cause: error
|
|
472
726
|
});
|
|
473
727
|
} finally {
|
|
474
|
-
request?.clear();
|
|
728
|
+
if (!deferCleanup || !responseExposed) request?.clear();
|
|
475
729
|
}
|
|
476
730
|
}
|
|
477
731
|
};
|
|
@@ -1428,6 +1682,42 @@ var Client = class Client {
|
|
|
1428
1682
|
method: "OPTIONS"
|
|
1429
1683
|
});
|
|
1430
1684
|
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Consume a server-sent event response as a lazy async iterable.
|
|
1687
|
+
*/
|
|
1688
|
+
sse(url, config = {}) {
|
|
1689
|
+
return this.get(url, {
|
|
1690
|
+
...config,
|
|
1691
|
+
responseType: "sse"
|
|
1692
|
+
});
|
|
1693
|
+
}
|
|
1694
|
+
/**
|
|
1695
|
+
* Consume a server-sent event response with complete response metadata.
|
|
1696
|
+
*/
|
|
1697
|
+
sseResponse(url, config = {}) {
|
|
1698
|
+
return this.getResponse(url, {
|
|
1699
|
+
...config,
|
|
1700
|
+
responseType: "sse"
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
/**
|
|
1704
|
+
* Consume newline-delimited JSON records as a lazy async iterable.
|
|
1705
|
+
*/
|
|
1706
|
+
ndjson(url, config = {}) {
|
|
1707
|
+
return this.get(url, {
|
|
1708
|
+
...config,
|
|
1709
|
+
responseType: "ndjson"
|
|
1710
|
+
});
|
|
1711
|
+
}
|
|
1712
|
+
/**
|
|
1713
|
+
* Consume newline-delimited JSON with complete response metadata.
|
|
1714
|
+
*/
|
|
1715
|
+
ndjsonResponse(url, config = {}) {
|
|
1716
|
+
return this.getResponse(url, {
|
|
1717
|
+
...config,
|
|
1718
|
+
responseType: "ndjson"
|
|
1719
|
+
});
|
|
1720
|
+
}
|
|
1431
1721
|
createPipeline(adapter) {
|
|
1432
1722
|
return new Pipeline(adapter, this.interceptors, this.hooks);
|
|
1433
1723
|
}
|
|
@@ -1597,6 +1887,7 @@ function cachePlugin(options = {}) {
|
|
|
1597
1887
|
const cacheHits = /* @__PURE__ */ new WeakSet();
|
|
1598
1888
|
const leaders = /* @__PURE__ */ new WeakMap();
|
|
1599
1889
|
const completedRecords = /* @__PURE__ */ new WeakMap();
|
|
1890
|
+
const uncacheableLeaders = /* @__PURE__ */ new WeakSet();
|
|
1600
1891
|
const inFlight = /* @__PURE__ */ new Map();
|
|
1601
1892
|
const methods = new Set(options.methods ?? DEFAULT_CACHE_METHODS);
|
|
1602
1893
|
const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
|
|
@@ -1627,7 +1918,9 @@ function cachePlugin(options = {}) {
|
|
|
1627
1918
|
if (!(cache.dedupe ?? options.dedupe ?? true)) return;
|
|
1628
1919
|
const pending = inFlight.get(key);
|
|
1629
1920
|
if (pending) {
|
|
1630
|
-
|
|
1921
|
+
const sharedRecord = await waitForSharedRecord(pending.promise, requestContext.config);
|
|
1922
|
+
if (!sharedRecord) return;
|
|
1923
|
+
requestContext.response = createCachedResponse(sharedRecord, requestContext.config);
|
|
1631
1924
|
cacheHits.add(requestContext);
|
|
1632
1925
|
return;
|
|
1633
1926
|
}
|
|
@@ -1641,6 +1934,11 @@ function cachePlugin(options = {}) {
|
|
|
1641
1934
|
const cache = resolveExtensionConfig(requestContext.config, "cache");
|
|
1642
1935
|
if (!cache?.enabled || !requestContext.response || !isCacheableRequest(requestContext.config, methods)) return;
|
|
1643
1936
|
const key = createCacheKey(requestContext.config, cache, varyHeaders);
|
|
1937
|
+
if (isAsyncIterable(requestContext.response.data)) {
|
|
1938
|
+
uncacheableLeaders.add(requestContext);
|
|
1939
|
+
await deleteStore(store, key);
|
|
1940
|
+
return;
|
|
1941
|
+
}
|
|
1644
1942
|
const ttl = cache.ttl ?? 3e4;
|
|
1645
1943
|
const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
|
|
1646
1944
|
completedRecords.set(requestContext, record);
|
|
@@ -1658,6 +1956,10 @@ function cachePlugin(options = {}) {
|
|
|
1658
1956
|
const pending = inFlight.get(key);
|
|
1659
1957
|
if (!pending || pending.owner !== requestContext) return;
|
|
1660
1958
|
inFlight.delete(key);
|
|
1959
|
+
if (uncacheableLeaders.delete(requestContext)) {
|
|
1960
|
+
pending.resolve(void 0);
|
|
1961
|
+
return;
|
|
1962
|
+
}
|
|
1661
1963
|
const record = completedRecords.get(requestContext);
|
|
1662
1964
|
completedRecords.delete(requestContext);
|
|
1663
1965
|
if (record && requestContext.response && !requestContext.error) {
|
|
@@ -1789,7 +2091,10 @@ function restoreCacheEntry(record, config) {
|
|
|
1789
2091
|
}
|
|
1790
2092
|
}
|
|
1791
2093
|
function isCacheableRequest(config, methods) {
|
|
1792
|
-
return methods.has(config.method ?? "GET") && config.responseType !== "stream";
|
|
2094
|
+
return methods.has(config.method ?? "GET") && config.responseType !== "stream" && config.responseType !== "sse" && config.responseType !== "ndjson";
|
|
2095
|
+
}
|
|
2096
|
+
function isAsyncIterable(value) {
|
|
2097
|
+
return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
1793
2098
|
}
|
|
1794
2099
|
function allowsPersistentCaching(response) {
|
|
1795
2100
|
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,6 +591,8 @@ function copyResponseMetadata(source, target) {
|
|
|
347
591
|
}
|
|
348
592
|
function detectResponseType(response) {
|
|
349
593
|
const contentType = response.headers.get("content-type") ?? "";
|
|
594
|
+
if (contentType.includes("text/event-stream")) return "sse";
|
|
595
|
+
if (contentType.includes("application/x-ndjson") || contentType.includes("application/ndjson") || contentType.includes("+ndjson")) return "ndjson";
|
|
350
596
|
if (contentType.includes("application/json") || contentType.includes("+json")) return "json";
|
|
351
597
|
return "text";
|
|
352
598
|
}
|
|
@@ -423,18 +669,26 @@ var FetchAdapter = class {
|
|
|
423
669
|
}
|
|
424
670
|
async execute(config, headers, preserveRaw) {
|
|
425
671
|
let request;
|
|
672
|
+
let deferCleanup = false;
|
|
673
|
+
let responseExposed = false;
|
|
426
674
|
try {
|
|
427
675
|
request = buildRequestWithHeaders(config, headers);
|
|
428
|
-
|
|
676
|
+
let response = limitResponseSize(await fetch(request.url, request.init), config);
|
|
429
677
|
const validStatus = (config.validateStatus ?? defaultValidateStatus$2)(response.status);
|
|
678
|
+
const streaming = isStreamingResponseType(resolveResponseType(response, config));
|
|
679
|
+
if (streaming) {
|
|
680
|
+
response = finalizeStreamingResponse(response, request.init.signal, config, request.clear);
|
|
681
|
+
deferCleanup = Boolean(response.body);
|
|
682
|
+
}
|
|
430
683
|
const nporaResponse = {
|
|
431
|
-
data: await parseResponse(
|
|
684
|
+
data: await parseResponse(streaming || !preserveRaw && validStatus ? response : response.clone(), config),
|
|
432
685
|
status: response.status,
|
|
433
686
|
statusText: response.statusText,
|
|
434
687
|
headers: response.headers,
|
|
435
688
|
config,
|
|
436
689
|
raw: response
|
|
437
690
|
};
|
|
691
|
+
responseExposed = true;
|
|
438
692
|
if (!validStatus) throw new RequestError(response.statusText || "Request failed", {
|
|
439
693
|
code: "HTTP_ERROR",
|
|
440
694
|
response: nporaResponse
|
|
@@ -470,7 +724,7 @@ var FetchAdapter = class {
|
|
|
470
724
|
cause: error
|
|
471
725
|
});
|
|
472
726
|
} finally {
|
|
473
|
-
request?.clear();
|
|
727
|
+
if (!deferCleanup || !responseExposed) request?.clear();
|
|
474
728
|
}
|
|
475
729
|
}
|
|
476
730
|
};
|
|
@@ -1427,6 +1681,42 @@ var Client = class Client {
|
|
|
1427
1681
|
method: "OPTIONS"
|
|
1428
1682
|
});
|
|
1429
1683
|
}
|
|
1684
|
+
/**
|
|
1685
|
+
* Consume a server-sent event response as a lazy async iterable.
|
|
1686
|
+
*/
|
|
1687
|
+
sse(url, config = {}) {
|
|
1688
|
+
return this.get(url, {
|
|
1689
|
+
...config,
|
|
1690
|
+
responseType: "sse"
|
|
1691
|
+
});
|
|
1692
|
+
}
|
|
1693
|
+
/**
|
|
1694
|
+
* Consume a server-sent event response with complete response metadata.
|
|
1695
|
+
*/
|
|
1696
|
+
sseResponse(url, config = {}) {
|
|
1697
|
+
return this.getResponse(url, {
|
|
1698
|
+
...config,
|
|
1699
|
+
responseType: "sse"
|
|
1700
|
+
});
|
|
1701
|
+
}
|
|
1702
|
+
/**
|
|
1703
|
+
* Consume newline-delimited JSON records as a lazy async iterable.
|
|
1704
|
+
*/
|
|
1705
|
+
ndjson(url, config = {}) {
|
|
1706
|
+
return this.get(url, {
|
|
1707
|
+
...config,
|
|
1708
|
+
responseType: "ndjson"
|
|
1709
|
+
});
|
|
1710
|
+
}
|
|
1711
|
+
/**
|
|
1712
|
+
* Consume newline-delimited JSON with complete response metadata.
|
|
1713
|
+
*/
|
|
1714
|
+
ndjsonResponse(url, config = {}) {
|
|
1715
|
+
return this.getResponse(url, {
|
|
1716
|
+
...config,
|
|
1717
|
+
responseType: "ndjson"
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1430
1720
|
createPipeline(adapter) {
|
|
1431
1721
|
return new Pipeline(adapter, this.interceptors, this.hooks);
|
|
1432
1722
|
}
|
|
@@ -1596,6 +1886,7 @@ function cachePlugin(options = {}) {
|
|
|
1596
1886
|
const cacheHits = /* @__PURE__ */ new WeakSet();
|
|
1597
1887
|
const leaders = /* @__PURE__ */ new WeakMap();
|
|
1598
1888
|
const completedRecords = /* @__PURE__ */ new WeakMap();
|
|
1889
|
+
const uncacheableLeaders = /* @__PURE__ */ new WeakSet();
|
|
1599
1890
|
const inFlight = /* @__PURE__ */ new Map();
|
|
1600
1891
|
const methods = new Set(options.methods ?? DEFAULT_CACHE_METHODS);
|
|
1601
1892
|
const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
|
|
@@ -1626,7 +1917,9 @@ function cachePlugin(options = {}) {
|
|
|
1626
1917
|
if (!(cache.dedupe ?? options.dedupe ?? true)) return;
|
|
1627
1918
|
const pending = inFlight.get(key);
|
|
1628
1919
|
if (pending) {
|
|
1629
|
-
|
|
1920
|
+
const sharedRecord = await waitForSharedRecord(pending.promise, requestContext.config);
|
|
1921
|
+
if (!sharedRecord) return;
|
|
1922
|
+
requestContext.response = createCachedResponse(sharedRecord, requestContext.config);
|
|
1630
1923
|
cacheHits.add(requestContext);
|
|
1631
1924
|
return;
|
|
1632
1925
|
}
|
|
@@ -1640,6 +1933,11 @@ function cachePlugin(options = {}) {
|
|
|
1640
1933
|
const cache = resolveExtensionConfig(requestContext.config, "cache");
|
|
1641
1934
|
if (!cache?.enabled || !requestContext.response || !isCacheableRequest(requestContext.config, methods)) return;
|
|
1642
1935
|
const key = createCacheKey(requestContext.config, cache, varyHeaders);
|
|
1936
|
+
if (isAsyncIterable(requestContext.response.data)) {
|
|
1937
|
+
uncacheableLeaders.add(requestContext);
|
|
1938
|
+
await deleteStore(store, key);
|
|
1939
|
+
return;
|
|
1940
|
+
}
|
|
1643
1941
|
const ttl = cache.ttl ?? 3e4;
|
|
1644
1942
|
const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
|
|
1645
1943
|
completedRecords.set(requestContext, record);
|
|
@@ -1657,6 +1955,10 @@ function cachePlugin(options = {}) {
|
|
|
1657
1955
|
const pending = inFlight.get(key);
|
|
1658
1956
|
if (!pending || pending.owner !== requestContext) return;
|
|
1659
1957
|
inFlight.delete(key);
|
|
1958
|
+
if (uncacheableLeaders.delete(requestContext)) {
|
|
1959
|
+
pending.resolve(void 0);
|
|
1960
|
+
return;
|
|
1961
|
+
}
|
|
1660
1962
|
const record = completedRecords.get(requestContext);
|
|
1661
1963
|
completedRecords.delete(requestContext);
|
|
1662
1964
|
if (record && requestContext.response && !requestContext.error) {
|
|
@@ -1788,7 +2090,10 @@ function restoreCacheEntry(record, config) {
|
|
|
1788
2090
|
}
|
|
1789
2091
|
}
|
|
1790
2092
|
function isCacheableRequest(config, methods) {
|
|
1791
|
-
return methods.has(config.method ?? "GET") && config.responseType !== "stream";
|
|
2093
|
+
return methods.has(config.method ?? "GET") && config.responseType !== "stream" && config.responseType !== "sse" && config.responseType !== "ndjson";
|
|
2094
|
+
}
|
|
2095
|
+
function isAsyncIterable(value) {
|
|
2096
|
+
return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
|
|
1792
2097
|
}
|
|
1793
2098
|
function allowsPersistentCaching(response) {
|
|
1794
2099
|
if (response.headers.get("cache-control")?.split(",").some((directive) => directive.trim().toLowerCase() === "no-store")) return false;
|