deps: update undici to 6.4.0

PR-URL: https://github.com/nodejs/node/pull/51527
Reviewed-By: Matthew Aitken <maitken033380023@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
Node.js GitHub Bot authored and marco-ippolito committed 2024-05-02 10:57:32 +02:00
1 parent dde9e08224
commit 7a1e321d95
28 files changed
+2276 -499

No files matched your search

+17 -30
View File
@@ -18,34 +18,23 @@ npm i undici
## Benchmarks
The benchmark is a simple `hello world` [example](benchmarks/benchmark.js) using a
number of unix sockets (connections) with a pipelining depth of 10 running on Node 20.6.0.
### Connections 1
| Tests | Samples | Result | Tolerance | Difference with slowest |
|---------------------|---------|---------------|-----------|-------------------------|
| http - no keepalive | 15 | 5.32 req/sec | ± 2.61 % | - |
| http - keepalive | 10 | 5.35 req/sec | ± 2.47 % | + 0.44 % |
| undici - fetch | 15 | 41.85 req/sec | ± 2.49 % | + 686.04 % |
| undici - pipeline | 40 | 50.36 req/sec | ± 2.77 % | + 845.92 % |
| undici - stream | 15 | 60.58 req/sec | ± 2.75 % | + 1037.72 % |
| undici - request | 10 | 61.19 req/sec | ± 2.60 % | + 1049.24 % |
| undici - dispatch | 20 | 64.84 req/sec | ± 2.81 % | + 1117.81 % |
### Connections 50
| Tests | Samples | Result | Tolerance | Difference with slowest |
|---------------------|---------|------------------|-----------|-------------------------|
| undici - fetch | 30 | 2107.19 req/sec | ± 2.69 % | - |
| http - no keepalive | 10 | 2698.90 req/sec | ± 2.68 % | + 28.08 % |
| http - keepalive | 10 | 4639.49 req/sec | ± 2.55 % | + 120.17 % |
| undici - pipeline | 40 | 6123.33 req/sec | ± 2.97 % | + 190.59 % |
| undici - stream | 50 | 9426.51 req/sec | ± 2.92 % | + 347.35 % |
| undici - request | 10 | 10162.88 req/sec | ± 2.13 % | + 382.29 % |
| undici - dispatch | 50 | 11191.11 req/sec | ± 2.98 % | + 431.09 % |
50 TCP connections with a pipelining depth of 10 running on Node 20.10.0.
```
│ Tests │ Samples │ Result │ Tolerance │ Difference with slowest │
|─────────────────────|─────────|─────────────────|───────────|─────────────────────────|
│ got │ 45 │ 1661.71 req/sec │ ± 2.93 % │ - │
│ node-fetch │ 20 │ 2164.81 req/sec │ ± 2.63 % │ + 30.28 % │
│ undici - fetch │ 35 │ 2274.27 req/sec │ ± 2.70 % │ + 36.86 % │
│ http - no keepalive │ 15 │ 2376.04 req/sec │ ± 2.99 % │ + 42.99 % │
│ axios │ 25 │ 2612.93 req/sec │ ± 2.89 % │ + 57.24 % │
│ request │ 40 │ 2712.19 req/sec │ ± 2.92 % │ + 63.22 % │
│ http - keepalive │ 45 │ 4393.25 req/sec │ ± 2.86 % │ + 164.38 % │
│ undici - pipeline │ 45 │ 5484.69 req/sec │ ± 2.87 % │ + 230.06 % │
│ undici - request │ 55 │ 7773.98 req/sec │ ± 2.93 % │ + 367.83 % │
│ undici - stream │ 70 │ 8425.96 req/sec │ ± 2.91 % │ + 407.07 % │
│ undici - dispatch │ 50 │ 9488.99 req/sec │ ± 2.85 % │ + 471.04 % │
```
## Quick Start
@@ -62,9 +51,7 @@ const {
console.log('response received', statusCode)
console.log('headers', headers)
for await (const data of body) {
console.log('data', data)
}
for await (const data of body) { console.log('data', data) }
console.log('trailers', trailers)
```
+2 -2
View File
@@ -53,10 +53,10 @@ This flag enables debug statements for the `Websocket` API.
> **Note**: statements can overlap with `UNDICI` ones if `undici` or `fetch` flag has been enabled as well.
```sh
NODE_DEBUG=fetch node script.js
NODE_DEBUG=websocket node script.js
WEBSOCKET 18309: connecting to echo.websocket.org using https:h1
WEBSOCKET 18309: connected to echo.websocket.org using https:h1
WEBSOCKET 18309: sending request to GET https://echo.websocket.org//
WEBSOCKET 18309: connection opened <ip_address>
```
```
+21
View File
@@ -0,0 +1,21 @@
# EventSource
Undici exposes a WHATWG spec-compliant implementation of [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)
for [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
## Instantiating EventSource
Undici exports a EventSource class. You can instantiate the EventSource as
follows:
```mjs
import { EventSource } from 'undici'
const evenSource = new EventSource('http://localhost:3000')
evenSource.onmessage = (event) => {
console.log(event.data)
}
```
More information about the EventSource API can be found on
[MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventSource).
+96
View File
@@ -0,0 +1,96 @@
# Class: RedirectHandler
A class that handles redirection logic for HTTP requests.
## `new RedirectHandler(dispatch, maxRedirections, opts, handler, redirectionLimitReached)`
Arguments:
- **dispatch** `function` - The dispatch function to be called after every retry.
- **maxRedirections** `number` - Maximum number of redirections allowed.
- **opts** `object` - Options for handling redirection.
- **handler** `object` - An object containing handlers for different stages of the request lifecycle.
- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior.
Returns: `RedirectHandler`
### Parameters
- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandlers) => Promise<Dispatch.DispatchResponse>` (required) - Dispatch function to be called after every redirection.
- **maxRedirections** `number` (required) - Maximum number of redirections allowed.
- **opts** `object` (required) - Options for handling redirection.
- **handler** `object` (required) - Handlers for different stages of the request lifecycle.
- **redirectionLimitReached** `boolean` (default: `false`) - A flag that the implementer can provide to enable or disable the feature. If set to `false`, it indicates that the caller doesn't want to use the feature and prefers the old behavior.
### Properties
- **location** `string` - The current redirection location.
- **abort** `function` - The abort function.
- **opts** `object` - The options for handling redirection.
- **maxRedirections** `number` - Maximum number of redirections allowed.
- **handler** `object` - Handlers for different stages of the request lifecycle.
- **history** `Array` - An array representing the history of URLs during redirection.
- **redirectionLimitReached** `boolean` - Indicates whether the redirection limit has been reached.
### Methods
#### `onConnect(abort)`
Called when the connection is established.
Parameters:
- **abort** `function` - The abort function.
#### `onUpgrade(statusCode, headers, socket)`
Called when an upgrade is requested.
Parameters:
- **statusCode** `number` - The HTTP status code.
- **headers** `object` - The headers received in the response.
- **socket** `object` - The socket object.
#### `onError(error)`
Called when an error occurs.
Parameters:
- **error** `Error` - The error that occurred.
#### `onHeaders(statusCode, headers, resume, statusText)`
Called when headers are received.
Parameters:
- **statusCode** `number` - The HTTP status code.
- **headers** `object` - The headers received in the response.
- **resume** `function` - The resume function.
- **statusText** `string` - The status text.
#### `onData(chunk)`
Called when data is received.
Parameters:
- **chunk** `Buffer` - The data chunk received.
#### `onComplete(trailers)`
Called when the request is complete.
Parameters:
- **trailers** `object` - The trailers received.
#### `onBodySent(chunk)`
Called when the request body is sent.
Parameters:
- **chunk** `Buffer` - The chunk of the request body sent.
+8 -20
View File
@@ -21,14 +21,6 @@ const DecoratorHandler = require('./lib/handler/DecoratorHandler')
const RedirectHandler = require('./lib/handler/RedirectHandler')
const createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor')
let hasCrypto
try {
require('crypto')
hasCrypto = true
} catch {
hasCrypto = false
}
Object.assign(Dispatcher.prototype, api)
module.exports.Dispatcher = Dispatcher
@@ -102,14 +94,10 @@ function makeDispatcher (fn) {
module.exports.setGlobalDispatcher = setGlobalDispatcher
module.exports.getGlobalDispatcher = getGlobalDispatcher
let fetchImpl = null
module.exports.fetch = async function fetch (resource) {
if (!fetchImpl) {
fetchImpl = require('./lib/fetch').fetch
}
const fetchImpl = require('./lib/fetch').fetch
module.exports.fetch = async function fetch (init, options = undefined) {
try {
return await fetchImpl(...arguments)
return await fetchImpl(init, options)
} catch (err) {
if (typeof err === 'object') {
Error.captureStackTrace(err, this)
@@ -149,11 +137,7 @@ const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL')
module.exports.parseMIMEType = parseMIMEType
module.exports.serializeAMimeType = serializeAMimeType
if (hasCrypto) {
const { WebSocket } = require('./lib/websocket/websocket')
module.exports.WebSocket = WebSocket
}
module.exports.WebSocket = require('./lib/websocket/websocket').WebSocket
module.exports.request = makeDispatcher(api.request)
module.exports.stream = makeDispatcher(api.stream)
@@ -165,3 +149,7 @@ module.exports.MockClient = MockClient
module.exports.MockPool = MockPool
module.exports.MockAgent = MockAgent
module.exports.mockErrors = mockErrors
const { EventSource } = require('./lib/eventsource/eventsource')
module.exports.EventSource = EventSource
+31 -21
View File
@@ -94,7 +94,7 @@ module.exports = class BodyReadable extends Readable {
}
push (chunk) {
if (this[kConsume] && chunk !== null && this.readableLength === 0) {
if (this[kConsume] && chunk !== null) {
consumePush(this[kConsume], chunk)
return this[kReading] ? super.push(chunk) : true
}
@@ -215,26 +215,28 @@ async function consume (stream, type) {
reject(rState.errored ?? new TypeError('unusable'))
}
} else {
stream[kConsume] = {
type,
stream,
resolve,
reject,
length: 0,
body: []
}
queueMicrotask(() => {
stream[kConsume] = {
type,
stream,
resolve,
reject,
length: 0,
body: []
}
stream
.on('error', function (err) {
consumeFinish(this[kConsume], err)
})
.on('close', function () {
if (this[kConsume].body !== null) {
consumeFinish(this[kConsume], new RequestAbortedError())
}
})
stream
.on('error', function (err) {
consumeFinish(this[kConsume], err)
})
.on('close', function () {
if (this[kConsume].body !== null) {
consumeFinish(this[kConsume], new RequestAbortedError())
}
})
queueMicrotask(() => consumeStart(stream[kConsume]))
consumeStart(stream[kConsume])
})
}
})
}
@@ -246,8 +248,16 @@ function consumeStart (consume) {
const { _readableState: state } = consume.stream
for (const chunk of state.buffer) {
consumePush(consume, chunk)
if (state.bufferIndex) {
const start = state.bufferIndex
const end = state.buffer.length
for (let n = start; n < end; n++) {
consumePush(consume, state.buffer[n])
}
} else {
for (const chunk of state.buffer) {
consumePush(consume, chunk)
}
}
if (state.endEmitted) {
+78 -68
View File
@@ -6,8 +6,9 @@ const { kEnumerableProperty, isDisturbed } = require('../core/util')
const { kHeadersList } = require('../core/symbols')
const { webidl } = require('../fetch/webidl')
const { Response, cloneResponse } = require('../fetch/response')
const { Request } = require('../fetch/request')
const { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols')
const { Request, fromInnerRequest } = require('../fetch/request')
const { Headers } = require('../fetch/headers')
const { kState, kHeaders, kGuard } = require('../fetch/symbols')
const { fetching } = require('../fetch/index')
const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')
const assert = require('assert')
@@ -49,7 +50,7 @@ class Cache {
request = webidl.converters.RequestInfo(request)
options = webidl.converters.CacheQueryOptions(options)
const p = await this.matchAll(request, options)
const p = this.#internalMatchAll(request, options, 1)
if (p.length === 0) {
return
@@ -64,64 +65,7 @@ class Cache {
if (request !== undefined) request = webidl.converters.RequestInfo(request)
options = webidl.converters.CacheQueryOptions(options)
// 1.
let r = null
// 2.
if (request !== undefined) {
if (request instanceof Request) {
// 2.1.1
r = request[kState]
// 2.1.2
if (r.method !== 'GET' && !options.ignoreMethod) {
return []
}
} else if (typeof request === 'string') {
// 2.2.1
r = new Request(request)[kState]
}
}
// 5.
// 5.1
const responses = []
// 5.2
if (request === undefined) {
// 5.2.1
for (const requestResponse of this.#relevantRequestResponseList) {
responses.push(requestResponse[1])
}
} else { // 5.3
// 5.3.1
const requestResponses = this.#queryCache(r, options)
// 5.3.2
for (const requestResponse of requestResponses) {
responses.push(requestResponse[1])
}
}
// 5.4
// We don't implement CORs so we don't need to loop over the responses, yay!
// 5.5.1
const responseList = []
// 5.5.2
for (const response of responses) {
// 5.5.2.1
const responseObject = new Response(null)
responseObject[kState] = response
responseObject[kHeaders][kHeadersList] = response.headersList
responseObject[kHeaders][kGuard] = 'immutable'
responseList.push(responseObject.clone())
}
// 6.
return Object.freeze(responseList)
return this.#internalMatchAll(request, options)
}
async add (request) {
@@ -500,7 +444,7 @@ class Cache {
* @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
* @param {any} request
* @param {import('../../types/cache').CacheQueryOptions} options
* @returns {readonly Request[]}
* @returns {Promise<readonly Request[]>}
*/
async keys (request = undefined, options = {}) {
webidl.brandCheck(this, Cache)
@@ -559,12 +503,12 @@ class Cache {
// 5.4.2
for (const request of requests) {
const requestObject = new Request('https://a')
requestObject[kState] = request
requestObject[kHeaders][kHeadersList] = request.headersList
requestObject[kHeaders][kGuard] = 'immutable'
requestObject[kRealm] = request.client
const requestObject = fromInnerRequest(
request,
new AbortController().signal,
'immutable',
{ settingsObject: request.client }
)
// 5.4.2.1
requestList.push(requestObject)
}
@@ -789,6 +733,72 @@ class Cache {
return true
}
#internalMatchAll (request, options, maxResponses = Infinity) {
// 1.
let r = null
// 2.
if (request !== undefined) {
if (request instanceof Request) {
// 2.1.1
r = request[kState]
// 2.1.2
if (r.method !== 'GET' && !options.ignoreMethod) {
return []
}
} else if (typeof request === 'string') {
// 2.2.1
r = new Request(request)[kState]
}
}
// 5.
// 5.1
const responses = []
// 5.2
if (request === undefined) {
// 5.2.1
for (const requestResponse of this.#relevantRequestResponseList) {
responses.push(requestResponse[1])
}
} else { // 5.3
// 5.3.1
const requestResponses = this.#queryCache(r, options)
// 5.3.2
for (const requestResponse of requestResponses) {
responses.push(requestResponse[1])
}
}
// 5.4
// We don't implement CORs so we don't need to loop over the responses, yay!
// 5.5.1
const responseList = []
// 5.5.2
for (const response of responses) {
// 5.5.2.1
const responseObject = new Response(kConstruct)
responseObject[kState] = response
responseObject[kHeaders] = new Headers(kConstruct)
responseObject[kHeaders][kHeadersList] = response.headersList
responseObject[kHeaders][kGuard] = 'immutable'
responseList.push(responseObject.clone())
if (responseList.length >= maxResponses) {
break
}
}
// 6.
return Object.freeze(responseList)
}
}
Object.defineProperties(Cache.prototype, {
+1 -1
View File
@@ -114,7 +114,7 @@ class CacheStorage {
/**
* @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
* @returns {string[]}
* @returns {Promise<string[]>}
*/
async keys () {
webidl.brandCheck(this, CacheStorage)
+1 -1
View File
@@ -1769,7 +1769,7 @@ function writeH2 (client, session, request) {
session.ref()
const shouldEndStream = method === 'GET' || method === 'HEAD'
const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null
if (expectContinue) {
headers[HTTP2_HEADER_EXPECT] = '100-continue'
stream = session.request(headers, { endStream: shouldEndStream, signal })
+2 -8
View File
@@ -349,14 +349,8 @@ function validateHandler (handler, method, upgrade) {
// A body is disturbed if it has been read from and it cannot
// be re-used without losing state or data.
function isDisturbed (body) {
return !!(body && (
stream.isDisturbed
? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
: body[kBodyUsed] ||
body.readableDidRead ||
(body._readableState && body._readableState.dataEmitted) ||
isReadableAborted(body)
))
// TODO (fix): Why is body[kBodyUsed] needed?
return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]))
}
function isErrored (body) {
+398
View File
@@ -0,0 +1,398 @@
'use strict'
const { Transform } = require('node:stream')
const { isASCIINumber, isValidLastEventId } = require('./util')
/**
* @type {number[]} BOM
*/
const BOM = [0xEF, 0xBB, 0xBF]
/**
* @type {10} LF
*/
const LF = 0x0A
/**
* @type {13} CR
*/
const CR = 0x0D
/**
* @type {58} COLON
*/
const COLON = 0x3A
/**
* @type {32} SPACE
*/
const SPACE = 0x20
/**
* @typedef {object} EventSourceStreamEvent
* @type {object}
* @property {string} [event] The event type.
* @property {string} [data] The data of the message.
* @property {string} [id] A unique ID for the event.
* @property {string} [retry] The reconnection time, in milliseconds.
*/
/**
* @typedef eventSourceSettings
* @type {object}
* @property {string} lastEventId The last event ID received from the server.
* @property {string} origin The origin of the event source.
* @property {number} reconnectionTime The reconnection time, in milliseconds.
*/
class EventSourceStream extends Transform {
/**
* @type {eventSourceSettings}
*/
state = null
/**
* Leading byte-order-mark check.
* @type {boolean}
*/
checkBOM = true
/**
* @type {boolean}
*/
crlfCheck = false
/**
* @type {boolean}
*/
eventEndCheck = false
/**
* @type {Buffer}
*/
buffer = null
pos = 0
event = {
data: undefined,
event: undefined,
id: undefined,
retry: undefined
}
/**
* @param {object} options
* @param {eventSourceSettings} options.eventSourceSettings
* @param {Function} [options.push]
*/
constructor (options = {}) {
// Enable object mode as EventSourceStream emits objects of shape
// EventSourceStreamEvent
options.readableObjectMode = true
super(options)
this.state = options.eventSourceSettings || {}
if (options.push) {
this.push = options.push
}
}
/**
* @param {Buffer} chunk
* @param {string} _encoding
* @param {Function} callback
* @returns {void}
*/
_transform (chunk, _encoding, callback) {
if (chunk.length === 0) {
callback()
return
}
// Cache the chunk in the buffer, as the data might not be complete while
// processing it
// TODO: Investigate if there is a more performant way to handle
// incoming chunks
// see: https://github.com/nodejs/undici/issues/2630
if (this.buffer) {
this.buffer = Buffer.concat([this.buffer, chunk])
} else {
this.buffer = chunk
}
// Strip leading byte-order-mark if we opened the stream and started
// the processing of the incoming data
if (this.checkBOM) {
switch (this.buffer.length) {
case 1:
// Check if the first byte is the same as the first byte of the BOM
if (this.buffer[0] === BOM[0]) {
// If it is, we need to wait for more data
callback()
return
}
// Set the checkBOM flag to false as we don't need to check for the
// BOM anymore
this.checkBOM = false
// The buffer only contains one byte so we need to wait for more data
callback()
return
case 2:
// Check if the first two bytes are the same as the first two bytes
// of the BOM
if (
this.buffer[0] === BOM[0] &&
this.buffer[1] === BOM[1]
) {
// If it is, we need to wait for more data, because the third byte
// is needed to determine if it is the BOM or not
callback()
return
}
// Set the checkBOM flag to false as we don't need to check for the
// BOM anymore
this.checkBOM = false
break
case 3:
// Check if the first three bytes are the same as the first three
// bytes of the BOM
if (
this.buffer[0] === BOM[0] &&
this.buffer[1] === BOM[1] &&
this.buffer[2] === BOM[2]
) {
// If it is, we can drop the buffered data, as it is only the BOM
this.buffer = Buffer.alloc(0)
// Set the checkBOM flag to false as we don't need to check for the
// BOM anymore
this.checkBOM = false
// Await more data
callback()
return
}
// If it is not the BOM, we can start processing the data
this.checkBOM = false
break
default:
// The buffer is longer than 3 bytes, so we can drop the BOM if it is
// present
if (
this.buffer[0] === BOM[0] &&
this.buffer[1] === BOM[1] &&
this.buffer[2] === BOM[2]
) {
// Remove the BOM from the buffer
this.buffer = this.buffer.subarray(3)
}
// Set the checkBOM flag to false as we don't need to check for the
this.checkBOM = false
break
}
}
while (this.pos < this.buffer.length) {
// If the previous line ended with an end-of-line, we need to check
// if the next character is also an end-of-line.
if (this.eventEndCheck) {
// If the the current character is an end-of-line, then the event
// is finished and we can process it
// If the previous line ended with a carriage return, we need to
// check if the current character is a line feed and remove it
// from the buffer.
if (this.crlfCheck) {
// If the current character is a line feed, we can remove it
// from the buffer and reset the crlfCheck flag
if (this.buffer[this.pos] === LF) {
this.buffer = this.buffer.subarray(this.pos + 1)
this.pos = 0
this.crlfCheck = false
// It is possible that the line feed is not the end of the
// event. We need to check if the next character is an
// end-of-line character to determine if the event is
// finished. We simply continue the loop to check the next
// character.
// As we removed the line feed from the buffer and set the
// crlfCheck flag to false, we basically don't make any
// distinction between a line feed and a carriage return.
continue
}
this.crlfCheck = false
}
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
// If the current character is a carriage return, we need to
// set the crlfCheck flag to true, as we need to check if the
// next character is a line feed so we can remove it from the
// buffer
if (this.buffer[this.pos] === CR) {
this.crlfCheck = true
}
this.buffer = this.buffer.subarray(this.pos + 1)
this.pos = 0
if (
this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) {
this.processEvent(this.event)
}
this.clearEvent()
continue
}
// If the current character is not an end-of-line, then the event
// is not finished and we have to reset the eventEndCheck flag
this.eventEndCheck = false
continue
}
// If the current character is an end-of-line, we can process the
// line
if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {
// If the current character is a carriage return, we need to
// set the crlfCheck flag to true, as we need to check if the
// next character is a line feed
if (this.buffer[this.pos] === CR) {
this.crlfCheck = true
}
// In any case, we can process the line as we reached an
// end-of-line character
this.parseLine(this.buffer.subarray(0, this.pos), this.event)
// Remove the processed line from the buffer
this.buffer = this.buffer.subarray(this.pos + 1)
// Reset the position as we removed the processed line from the buffer
this.pos = 0
// A line was processed and this could be the end of the event. We need
// to check if the next line is empty to determine if the event is
// finished.
this.eventEndCheck = true
continue
}
this.pos++
}
callback()
}
/**
* @param {Buffer} line
* @param {EventStreamEvent} event
*/
parseLine (line, event) {
// If the line is empty (a blank line)
// Dispatch the event, as defined below.
// This will be handled in the _transform method
if (line.length === 0) {
return
}
// If the line starts with a U+003A COLON character (:)
// Ignore the line.
const colonPosition = line.indexOf(COLON)
if (colonPosition === 0) {
return
}
let field = ''
let value = ''
// If the line contains a U+003A COLON character (:)
if (colonPosition !== -1) {
// Collect the characters on the line before the first U+003A COLON
// character (:), and let field be that string.
// TODO: Investigate if there is a more performant way to extract the
// field
// see: https://github.com/nodejs/undici/issues/2630
field = line.subarray(0, colonPosition).toString('utf8')
// Collect the characters on the line after the first U+003A COLON
// character (:), and let value be that string.
// If value starts with a U+0020 SPACE character, remove it from value.
let valueStart = colonPosition + 1
if (line[valueStart] === SPACE) {
++valueStart
}
// TODO: Investigate if there is a more performant way to extract the
// value
// see: https://github.com/nodejs/undici/issues/2630
value = line.subarray(valueStart).toString('utf8')
// Otherwise, the string is not empty but does not contain a U+003A COLON
// character (:)
} else {
// Process the field using the steps described below, using the whole
// line as the field name, and the empty string as the field value.
field = line.toString('utf8')
value = ''
}
// Modify the event with the field name and value. The value is also
// decoded as UTF-8
switch (field) {
case 'data':
if (event[field] === undefined) {
event[field] = value
} else {
event[field] += '\n' + value
}
break
case 'retry':
if (isASCIINumber(value)) {
event[field] = value
}
break
case 'id':
if (isValidLastEventId(value)) {
event[field] = value
}
break
case 'event':
if (value.length > 0) {
event[field] = value
}
break
}
}
/**
* @param {EventSourceStreamEvent} event
*/
processEvent (event) {
if (event.retry && isASCIINumber(event.retry)) {
this.state.reconnectionTime = parseInt(event.retry, 10)
}
if (event.id && isValidLastEventId(event.id)) {
this.state.lastEventId = event.id
}
// only dispatch event, when data is provided
if (event.data !== undefined) {
this.push({
type: event.event || 'message',
options: {
data: event.data,
lastEventId: this.state.lastEventId,
origin: this.state.origin
}
})
}
}
clearEvent () {
this.event = {
data: undefined,
event: undefined,
id: undefined,
retry: undefined
}
}
}
module.exports = {
EventSourceStream
}
+473
View File
@@ -0,0 +1,473 @@
'use strict'
const { setTimeout } = require('node:timers/promises')
const { pipeline } = require('node:stream')
const { fetching } = require('../fetch')
const { makeRequest } = require('../fetch/request')
const { getGlobalOrigin } = require('../fetch/global')
const { webidl } = require('../fetch/webidl')
const { EventSourceStream } = require('./eventsource-stream')
const { parseMIMEType } = require('../fetch/dataURL')
const { MessageEvent } = require('../websocket/events')
const { isNetworkError } = require('../fetch/response')
const { getGlobalDispatcher } = require('../global')
let experimentalWarned = false
/**
* A reconnection time, in milliseconds. This must initially be an implementation-defined value,
* probably in the region of a few seconds.
*
* In Comparison:
* - Chrome uses 3000ms.
* - Deno uses 5000ms.
*
* @type {3000}
*/
const defaultReconnectionTime = 3000
/**
* The readyState attribute represents the state of the connection.
* @enum
* @readonly
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev
*/
/**
* The connection has not yet been established, or it was closed and the user
* agent is reconnecting.
* @type {0}
*/
const CONNECTING = 0
/**
* The user agent has an open connection and is dispatching events as it
* receives them.
* @type {1}
*/
const OPEN = 1
/**
* The connection is not open, and the user agent is not trying to reconnect.
* @type {2}
*/
const CLOSED = 2
/**
* Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin".
* @type {'anonymous'}
*/
const ANONYMOUS = 'anonymous'
/**
* Requests for the element will have their mode set to "cors" and their credentials mode set to "include".
* @type {'use-credentials'}
*/
const USE_CREDENTIALS = 'use-credentials'
/**
* @typedef {object} EventSourceInit
* @property {boolean} [withCredentials] indicates whether the request
* should include credentials.
*/
/**
* The EventSource interface is used to receive server-sent events. It
* connects to a server over HTTP and receives events in text/event-stream
* format without closing the connection.
* @extends {EventTarget}
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events
* @api public
*/
class EventSource extends EventTarget {
#events = {
open: null,
error: null,
message: null
}
#url = null
#withCredentials = false
#readyState = CONNECTING
#request = null
#controller = null
/**
* @type {object}
* @property {string} lastEventId
* @property {number} reconnectionTime
* @property {any} reconnectionTimer
*/
#settings = null
/**
* Creates a new EventSource object.
* @param {string} url
* @param {EventSourceInit} [eventSourceInitDict]
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
*/
constructor (url, eventSourceInitDict = {}) {
// 1. Let ev be a new EventSource object.
super()
webidl.argumentLengthCheck(arguments, 1, { header: 'EventSource constructor' })
if (!experimentalWarned) {
experimentalWarned = true
process.emitWarning('EventSource is experimental, expect them to change at any time.', {
code: 'UNDICI-ES'
})
}
url = webidl.converters.USVString(url)
eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict)
// 2. Let settings be ev's relevant settings object.
// https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
this.#settings = {
origin: getGlobalOrigin(),
policyContainer: {
referrerPolicy: 'no-referrer'
},
lastEventId: '',
reconnectionTime: defaultReconnectionTime
}
let urlRecord
try {
// 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
urlRecord = new URL(url, this.#settings.origin)
this.#settings.origin = urlRecord.origin
} catch (e) {
// 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
throw new DOMException(e, 'SyntaxError')
}
// 5. Set ev's url to urlRecord.
this.#url = urlRecord.href
// 6. Let corsAttributeState be Anonymous.
let corsAttributeState = ANONYMOUS
// 7. If the value of eventSourceInitDict's withCredentials member is true,
// then set corsAttributeState to Use Credentials and set ev's
// withCredentials attribute to true.
if (eventSourceInitDict.withCredentials) {
corsAttributeState = USE_CREDENTIALS
this.#withCredentials = true
}
// 8. Let request be the result of creating a potential-CORS request given
// urlRecord, the empty string, and corsAttributeState.
const initRequest = {
redirect: 'follow',
keepalive: true,
// @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
mode: 'cors',
credentials: corsAttributeState === 'anonymous'
? 'same-origin'
: 'omit',
referrer: 'no-referrer'
}
// 9. Set request's client to settings.
initRequest.client = this.#settings
// 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]
// 11. Set request's cache mode to "no-store".
initRequest.cache = 'no-store'
// 12. Set request's initiator type to "other".
initRequest.initiator = 'other'
initRequest.urlList = [new URL(this.#url)]
// 13. Set ev's request to request.
this.#request = makeRequest(initRequest)
this.#connect()
}
/**
* Returns the state of this EventSource object's connection. It can have the
* values described below.
* @returns {0|1|2}
* @readonly
*/
get readyState () {
return this.#readyState
}
/**
* Returns the URL providing the event stream.
* @readonly
* @returns {string}
*/
get url () {
return this.#url
}
/**
* Returns a boolean indicating whether the EventSource object was
* instantiated with CORS credentials set (true), or not (false, the default).
*/
get withCredentials () {
return this.#withCredentials
}
#connect () {
if (this.#readyState === CLOSED) return
this.#readyState = CONNECTING
const fetchParam = {
request: this.#request
}
// 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.
const processEventSourceEndOfBody = (response) => {
if (isNetworkError(response)) {
this.dispatchEvent(new Event('error'))
this.close()
}
this.#reconnect()
}
// 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...
fetchParam.processResponseEndOfBody = processEventSourceEndOfBody
// and processResponse set to the following steps given response res:
fetchParam.processResponse = (response) => {
// 1. If res is an aborted network error, then fail the connection.
if (isNetworkError(response)) {
// 1. When a user agent is to fail the connection, the user agent
// must queue a task which, if the readyState attribute is set to a
// value other than CLOSED, sets the readyState attribute to CLOSED
// and fires an event named error at the EventSource object. Once the
// user agent has failed the connection, it does not attempt to
// reconnect.
if (response.aborted) {
this.close()
this.dispatchEvent(new Event('error'))
return
// 2. Otherwise, if res is a network error, then reestablish the
// connection, unless the user agent knows that to be futile, in
// which case the user agent may fail the connection.
} else {
this.#reconnect()
return
}
}
// 3. Otherwise, if res's status is not 200, or if res's `Content-Type`
// is not `text/event-stream`, then fail the connection.
const contentType = response.headersList.get('content-type', true)
const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'
const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'
if (
response.status !== 200 ||
contentTypeValid === false
) {
this.close()
this.dispatchEvent(new Event('error'))
return
}
// 4. Otherwise, announce the connection and interpret res's body
// line by line.
// When a user agent is to announce the connection, the user agent
// must queue a task which, if the readyState attribute is set to a
// value other than CLOSED, sets the readyState attribute to OPEN
// and fires an event named open at the EventSource object.
// @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
this.#readyState = OPEN
this.dispatchEvent(new Event('open'))
// If redirected to a different origin, set the origin to the new origin.
this.#settings.origin = response.urlList[response.urlList.length - 1].origin
const eventSourceStream = new EventSourceStream({
eventSourceSettings: this.#settings,
push: (event) => {
this.dispatchEvent(new MessageEvent(
event.type,
event.options
))
}
})
pipeline(response.body.stream,
eventSourceStream,
(error) => {
if (
error?.aborted === false
) {
this.close()
this.dispatchEvent(new Event('error'))
}
})
}
this.#controller = fetching({
...fetchParam,
dispatcher: getGlobalDispatcher()
})
}
/**
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
* @returns {Promise<void>}
*/
async #reconnect () {
// When a user agent is to reestablish the connection, the user agent must
// run the following steps. These steps are run in parallel, not as part of
// a task. (The tasks that it queues, of course, are run like normal tasks
// and not themselves in parallel.)
// 1. Queue a task to run the following steps:
// 1. If the readyState attribute is set to CLOSED, abort the task.
if (this.#readyState === CLOSED) return
// 2. Set the readyState attribute to CONNECTING.
this.#readyState = CONNECTING
// 3. Fire an event named error at the EventSource object.
this.dispatchEvent(new Event('error'))
// 2. Wait a delay equal to the reconnection time of the event source.
await setTimeout(this.#settings.reconnectionTime, { ref: false })
// 5. Queue a task to run the following steps:
// 1. If the EventSource object's readyState attribute is not set to
// CONNECTING, then return.
if (this.#readyState !== CONNECTING) return
// 2. Let request be the EventSource object's request.
// 3. If the EventSource object's last event ID string is not the empty
// string, then:
// 1. Let lastEventIDValue be the EventSource object's last event ID
// string, encoded as UTF-8.
// 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header
// list.
if (this.#settings.lastEventId !== '') {
this.#request.headersList.set('last-event-id', this.#settings.lastEventId, true)
}
// 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
this.#connect()
}
/**
* Closes the connection, if any, and sets the readyState attribute to
* CLOSED.
*/
close () {
webidl.brandCheck(this, EventSource)
if (this.#readyState === CLOSED) return
this.#readyState = CLOSED
clearTimeout(this.#settings.reconnectionTimer)
this.#controller.abort()
if (this.#request) {
this.#request = null
}
}
get onopen () {
return this.#events.open
}
set onopen (fn) {
if (this.#events.open) {
this.removeEventListener('open', this.#events.open)
}
if (typeof fn === 'function') {
this.#events.open = fn
this.addEventListener('open', fn)
} else {
this.#events.open = null
}
}
get onmessage () {
return this.#events.message
}
set onmessage (fn) {
if (this.#events.message) {
this.removeEventListener('message', this.#events.message)
}
if (typeof fn === 'function') {
this.#events.message = fn
this.addEventListener('message', fn)
} else {
this.#events.message = null
}
}
get onerror () {
return this.#events.error
}
set onerror (fn) {
if (this.#events.error) {
this.removeEventListener('error', this.#events.error)
}
if (typeof fn === 'function') {
this.#events.error = fn
this.addEventListener('error', fn)
} else {
this.#events.error = null
}
}
}
const constantsPropertyDescriptors = {
CONNECTING: {
__proto__: null,
configurable: false,
enumerable: true,
value: CONNECTING,
writable: false
},
OPEN: {
__proto__: null,
configurable: false,
enumerable: true,
value: OPEN,
writable: false
},
CLOSED: {
__proto__: null,
configurable: false,
enumerable: true,
value: CLOSED,
writable: false
}
}
Object.defineProperties(EventSource, constantsPropertyDescriptors)
Object.defineProperties(EventSource.prototype, constantsPropertyDescriptors)
webidl.converters.EventSourceInitDict = webidl.dictionaryConverter([
{ key: 'withCredentials', converter: webidl.converters.boolean, defaultValue: false }
])
module.exports = {
EventSource,
defaultReconnectionTime
}
+29
View File
@@ -0,0 +1,29 @@
'use strict'
/**
* Checks if the given value is a valid LastEventId.
* @param {string} value
* @returns {boolean}
*/
function isValidLastEventId (value) {
// LastEventId should not contain U+0000 NULL
return value.indexOf('\u0000') === -1
}
/**
* Checks if the given value is a base 10 digit.
* @param {string} value
* @returns {boolean}
*/
function isASCIINumber (value) {
if (value.length === 0) return false
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false
}
return true
}
module.exports = {
isValidLastEventId,
isASCIINumber
}
+5 -9
View File
@@ -122,7 +122,7 @@ class Fetch extends EE {
}
// https://fetch.spec.whatwg.org/#fetch-method
function fetch (input, init = {}) {
function fetch (input, init = undefined) {
webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
// 1. Let p be a new promise.
@@ -248,7 +248,7 @@ function fetch (input, init = {}) {
request,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
dispatcher: init?.dispatcher ?? getGlobalDispatcher() // undici
})
// 14. Return p.
@@ -327,13 +327,6 @@ function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis,
// https://fetch.spec.whatwg.org/#abort-fetch
function abortFetch (p, request, responseObject, error) {
// Note: AbortSignal.reason was added in node v17.2.0
// which would give us an undefined error to reject with.
// Remove this once node v16 is no longer supported.
if (!error) {
error = new DOMException('The operation was aborted.', 'AbortError')
}
// 1. Reject promise with error.
p.reject(error)
@@ -381,6 +374,9 @@ function fetching ({
useParallelQueue = false,
dispatcher // undici
}) {
// This has bitten me in the ass more times than I'd like to admit.
assert(dispatcher)
// 1. Let taskDestination be null.
let taskDestination = null
+22 -11
View File
@@ -751,14 +751,6 @@ class Request {
// 3. Let clonedRequestObject be the result of creating a Request object,
// given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
const clonedRequestObject = new Request(kConstruct)
clonedRequestObject[kState] = clonedRequest
clonedRequestObject[kRealm] = this[kRealm]
clonedRequestObject[kHeaders] = new Headers(kConstruct)
clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
// 4. Make clonedRequestObject’s signal follow this’s signal.
const ac = new AbortController()
if (this.signal.aborted) {
@@ -771,10 +763,9 @@ class Request {
}
)
}
clonedRequestObject[kSignal] = ac.signal
// 4. Return clonedRequestObject.
return clonedRequestObject
return fromInnerRequest(clonedRequest, ac.signal, this[kHeaders][kGuard], this[kRealm])
}
}
@@ -844,6 +835,26 @@ function cloneRequest (request) {
return newRequest
}
/**
* @param {any} innerRequest
* @param {AbortSignal} signal
* @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard
* @param {any} [realm]
* @returns {Request}
*/
function fromInnerRequest (innerRequest, signal, guard, realm) {
const request = new Request(kConstruct)
request[kState] = innerRequest
request[kRealm] = realm
request[kSignal] = signal
request[kSignal][kRealm] = realm
request[kHeaders] = new Headers(kConstruct)
request[kHeaders][kHeadersList] = innerRequest.headersList
request[kHeaders][kGuard] = guard
request[kHeaders][kRealm] = realm
return request
}
Object.defineProperties(Request.prototype, {
method: kEnumerableProperty,
url: kEnumerableProperty,
@@ -970,4 +981,4 @@ webidl.converters.RequestInit = webidl.dictionaryConverter([
}
])
module.exports = { Request, makeRequest }
module.exports = { Request, makeRequest, fromInnerRequest }
+11
View File
@@ -364,6 +364,16 @@ function makeNetworkError (reason) {
})
}
// @see https://fetch.spec.whatwg.org/#concept-network-error
function isNetworkError (response) {
return (
// A network error is a response whose type is "error",
response.type === 'error' &&
// status is 0
response.status === 0
)
}
function makeFilteredResponse (response, state) {
state = {
internalResponse: response,
@@ -572,6 +582,7 @@ webidl.converters.ResponseInit = webidl.dictionaryConverter([
])
module.exports = {
isNetworkError,
makeNetworkError,
makeResponse,
makeAppropriateNetworkError,
+11
View File
@@ -38,6 +38,7 @@ class RedirectHandler {
this.maxRedirections = maxRedirections
this.handler = handler
this.history = []
this.redirectionLimitReached = false
if (util.isStream(this.opts.body)) {
// TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
@@ -91,6 +92,16 @@ class RedirectHandler {
? null
: parseLocation(statusCode, headers)
if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
if (this.request) {
this.request.abort(new Error('max redirects'))
}
this.redirectionLimitReached = true
this.abort(new Error('max redirects'))
return
}
if (this.opts.origin) {
this.history.push(new URL(this.opts.path, this.opts.origin))
}
+15 -5
View File
@@ -188,11 +188,21 @@ function buildKey (opts) {
}
function generateKeyValues (data) {
return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
...keyValuePairs,
Buffer.from(`${key}`),
Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
], [])
const keys = Object.keys(data)
const result = []
for (let i = 0; i < keys.length; ++i) {
const key = keys[i]
const value = data[key]
const name = Buffer.from(`${key}`)
if (Array.isArray(value)) {
for (let j = 0; j < value.length; ++j) {
result.push(name, Buffer.from(`${value[j]}`))
}
} else {
result.push(name, Buffer.from(`${value}`))
}
}
return result
}
/**
+902 -290
View File
File diff suppressed because it is too large. Load diff
+11 -6
View File
@@ -1,6 +1,6 @@
{
"name": "undici",
"version": "6.3.0",
"version": "6.5.0",
"description": "An HTTP/1.1 client, written from scratch for Node.js",
"homepage": "https://undici.nodejs.org",
"bugs": {
@@ -75,9 +75,10 @@
"build:wasm": "node build/wasm.js --docker",
"lint": "standard | snazzy",
"lint:fix": "standard --fix | snazzy",
"test": "node scripts/generate-pem && npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:wpt && npm run test:websocket && npm run test:jest && npm run test:typescript && npm run test:node-test",
"test": "node scripts/generate-pem && npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:eventsource && npm run test:wpt && npm run test:websocket && npm run test:jest && npm run test:typescript && npm run test:node-test",
"test:cookies": "borp --coverage -p \"test/cookie/*.js\"",
"test:node-fetch": "mocha --exit test/node-fetch",
"test:eventsource": "npm run build:node && borp --expose-gc --coverage -p \"test/eventsource/*.js\"",
"test:fetch": "npm run build:node && borp --expose-gc --coverage -p \"test/fetch/*.js\" && borp --coverage -p \"test/webidl/*.js\"",
"test:jest": "jest",
"test:tap": "tap test/*.js",
@@ -86,13 +87,13 @@
"test:tdd:node-test": "borp -p \"test/node-test/**/*.js\" -w",
"test:typescript": "tsd && tsc --skipLibCheck test/imports/undici-import.ts",
"test:websocket": "borp --coverage -p \"test/websocket/*.js\"",
"test:wpt": "node test/wpt/start-fetch.mjs && node test/wpt/start-FileAPI.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node test/wpt/start-websockets.mjs && node test/wpt/start-cacheStorage.mjs",
"test:wpt": "node test/wpt/start-fetch.mjs && node test/wpt/start-FileAPI.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node test/wpt/start-websockets.mjs && node test/wpt/start-cacheStorage.mjs && node test/wpt/start-eventsource.mjs",
"coverage": "nyc --reporter=text --reporter=html npm run test",
"coverage:ci": "nyc --reporter=lcov npm run test",
"bench": "PORT=3042 concurrently -k -s first npm:bench:server npm:bench:run",
"bench:server": "node benchmarks/server.js",
"prebench:run": "node benchmarks/wait.js",
"bench:run": "CONNECTIONS=1 node benchmarks/benchmark.js; CONNECTIONS=50 node benchmarks/benchmark.js",
"bench:run": "SAMPLES=100 CONNECTIONS=50 node benchmarks/benchmark.js",
"serve:website": "docsify serve .",
"prepare": "husky install",
"fuzz": "jsfuzz test/fuzzing/fuzz.js corpus"
@@ -119,7 +120,7 @@
"husky": "^8.0.1",
"import-fresh": "^3.3.0",
"jest": "^29.0.2",
"jsdom": "^23.0.0",
"jsdom": "^24.0.0",
"jsfuzz": "^1.0.15",
"mitata": "^0.1.6",
"mocha": "^10.0.0",
@@ -136,7 +137,11 @@
"tsd": "^0.30.1",
"typescript": "^5.0.2",
"wait-on": "^7.0.1",
"ws": "^8.11.0"
"ws": "^8.11.0",
"axios": "^1.6.5",
"got": "^14.0.0",
"node-fetch": "^3.3.2",
"request": "^2.88.2"
},
"engines": {
"node": ">=18.0"
+7 -1
View File
@@ -131,6 +131,8 @@ declare namespace Dispatcher {
opaque?: unknown;
/** Default: 0 */
maxRedirections?: number;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
responseHeader?: 'raw' | null;
}
@@ -141,6 +143,8 @@ declare namespace Dispatcher {
signal?: AbortSignal | EventEmitter | null;
/** Default: 0 */
maxRedirections?: number;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
onInfo?: (info: { statusCode: number, headers: Record<string, string | string[]> }) => void;
/** Default: `null` */
@@ -164,6 +168,8 @@ declare namespace Dispatcher {
signal?: AbortSignal | EventEmitter | null;
/** Default: 0 */
maxRedirections?: number;
/** Default: false */
redirectionLimitReached?: boolean;
/** Default: `null` */
responseHeader?: 'raw' | null;
}
@@ -229,7 +235,7 @@ declare namespace Dispatcher {
* @link https://fetch.spec.whatwg.org/#body-mixin
*/
interface BodyMixin {
readonly body?: never; // throws on node v16.6.0
readonly body?: never;
readonly bodyUsed: boolean;
arrayBuffer(): Promise<ArrayBuffer>;
blob(): Promise<Blob>;
+61
View File
@@ -0,0 +1,61 @@
import { MessageEvent, ErrorEvent } from './websocket'
import {
EventTarget,
Event,
EventListenerOptions,
AddEventListenerOptions,
EventListenerOrEventListenerObject
} from './patch'
interface EventSourceEventMap {
error: ErrorEvent
message: MessageEvent
open: Event
}
interface EventSource extends EventTarget {
close(): void
readonly CLOSED: 2
readonly CONNECTING: 0
readonly OPEN: 1
onerror: (this: EventSource, ev: ErrorEvent) => any
onmessage: (this: EventSource, ev: MessageEvent) => any
onopen: (this: EventSource, ev: Event) => any
readonly readyState: 0 | 1 | 2
readonly url: string
readonly withCredentials: boolean
addEventListener<K extends keyof EventSourceEventMap>(
type: K,
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): void
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions
): void
removeEventListener<K extends keyof EventSourceEventMap>(
type: K,
listener: (this: EventSource, ev: EventSourceEventMap[K]) => any,
options?: boolean | EventListenerOptions
): void
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions
): void
}
export declare const EventSource: {
prototype: EventSource
new (url: string | URL, init: EventSourceInit): EventSource
readonly CLOSED: 2
readonly CONNECTING: 0
readonly OPEN: 1
}
interface EventSourceInit {
withCredentials?: boolean
}
+10 -4
View File
@@ -1,9 +1,15 @@
import Dispatcher from "./dispatcher";
export declare class RedirectHandler implements Dispatcher.DispatchHandlers{
constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers)
export declare class RedirectHandler implements Dispatcher.DispatchHandlers {
constructor(
dispatch: Dispatcher,
maxRedirections: number,
opts: Dispatcher.DispatchOptions,
handler: Dispatcher.DispatchHandlers,
redirectionLimitReached: boolean
);
}
export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{
constructor (handler: Dispatcher.DispatchHandlers)
export declare class DecoratorHandler implements Dispatcher.DispatchHandlers {
constructor(handler: Dispatcher.DispatchHandlers);
}
+1
View File
@@ -19,6 +19,7 @@ import { request, pipeline, stream, connect, upgrade } from './api'
export * from './util'
export * from './cookies'
export * from './eventsource'
export * from './fetch'
export * from './file'
export * from './filereader'
+2 -3
View File
@@ -44,9 +44,8 @@ declare class BodyReadable extends Readable {
*/
readonly bodyUsed: boolean
/** Throws on node 16.6.0
*
* If body is null, it should return null as the body
/**
* If body is null, it should return null as the body
*
* If body is not null, should return the body as a ReadableStream
*
+22 -1
View File
@@ -17,7 +17,7 @@ export type BinaryType = 'blob' | 'arraybuffer'
interface WebSocketEventMap {
close: CloseEvent
error: Event
error: ErrorEvent
message: MessageEvent
open: Event
}
@@ -124,6 +124,27 @@ export declare const MessageEvent: {
new<T>(type: string, eventInitDict?: MessageEventInit<T>): MessageEvent<T>
}
interface ErrorEventInit extends EventInit {
message?: string
filename?: string
lineno?: number
colno?: number
error?: any
}
interface ErrorEvent extends Event {
readonly message: string
readonly filename: string
readonly lineno: number
readonly colno: number
readonly error: any
}
export declare const ErrorEvent: {
prototype: ErrorEvent
new (type: string, eventInitDict?: ErrorEventInit): ErrorEvent
}
interface WebSocketInit {
protocols?: string | string[],
dispatcher?: Dispatcher,
+38 -17
View File
@@ -873,7 +873,7 @@ var require_util = __commonJS({
}
__name(validateHandler, "validateHandler");
function isDisturbed(body) {
return !!(body && (stream.isDisturbed ? stream.isDisturbed(body) || body[kBodyUsed] : body[kBodyUsed] || body.readableDidRead || body._readableState && body._readableState.dataEmitted || isReadableAborted(body)));
return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]));
}
__name(isDisturbed, "isDisturbed");
function isErrored(body) {
@@ -6090,6 +6090,14 @@ var require_response = __commonJS({
});
}
__name(makeNetworkError, "makeNetworkError");
function isNetworkError(response) {
return (
// A network error is a response whose type is "error",
response.type === "error" && // status is 0
response.status === 0
);
}
__name(isNetworkError, "isNetworkError");
function makeFilteredResponse(response, state) {
state = {
internalResponse: response,
@@ -6229,6 +6237,7 @@ var require_response = __commonJS({
}
]);
module2.exports = {
isNetworkError,
makeNetworkError,
makeResponse,
makeAppropriateNetworkError,
@@ -6744,13 +6753,6 @@ var require_request = __commonJS({
throw new TypeError("unusable");
}
const clonedRequest = cloneRequest(this[kState]);
const clonedRequestObject = new _Request(kConstruct);
clonedRequestObject[kState] = clonedRequest;
clonedRequestObject[kRealm] = this[kRealm];
clonedRequestObject[kHeaders] = new Headers(kConstruct);
clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList;
clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard];
clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm];
const ac = new AbortController();
if (this.signal.aborted) {
ac.abort(this.signal.reason);
@@ -6762,8 +6764,7 @@ var require_request = __commonJS({
}
);
}
clonedRequestObject[kSignal] = ac.signal;
return clonedRequestObject;
return fromInnerRequest(clonedRequest, ac.signal, this[kHeaders][kGuard], this[kRealm]);
}
};
mixinBody(Request);
@@ -6819,6 +6820,19 @@ var require_request = __commonJS({
return newRequest;
}
__name(cloneRequest, "cloneRequest");
function fromInnerRequest(innerRequest, signal, guard, realm) {
const request = new Request(kConstruct);
request[kState] = innerRequest;
request[kRealm] = realm;
request[kSignal] = signal;
request[kSignal][kRealm] = realm;
request[kHeaders] = new Headers(kConstruct);
request[kHeaders][kHeadersList] = innerRequest.headersList;
request[kHeaders][kGuard] = guard;
request[kHeaders][kRealm] = realm;
return request;
}
__name(fromInnerRequest, "fromInnerRequest");
Object.defineProperties(Request.prototype, {
method: kEnumerableProperty,
url: kEnumerableProperty,
@@ -6936,7 +6950,7 @@ var require_request = __commonJS({
allowedValues: requestDuplex
}
]);
module2.exports = { Request, makeRequest };
module2.exports = { Request, makeRequest, fromInnerRequest };
}
});
@@ -8580,6 +8594,7 @@ var require_RedirectHandler = __commonJS({
this.maxRedirections = maxRedirections;
this.handler = handler;
this.history = [];
this.redirectionLimitReached = false;
if (util.isStream(this.opts.body)) {
if (util.bodyLength(this.opts.body) === 0) {
this.opts.body.on("data", function() {
@@ -8610,6 +8625,14 @@ var require_RedirectHandler = __commonJS({
}
onHeaders(statusCode, headers, resume, statusText) {
this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) ? null : parseLocation(statusCode, headers);
if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {
if (this.request) {
this.request.abort(new Error("max redirects"));
}
this.redirectionLimitReached = true;
this.abort(new Error("max redirects"));
return;
}
if (this.opts.origin) {
this.history.push(new URL(this.opts.path, this.opts.origin));
}
@@ -10073,7 +10096,7 @@ upgrade: ${upgrade}\r
headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`;
}
session.ref();
const shouldEndStream = method === "GET" || method === "HEAD";
const shouldEndStream = method === "GET" || method === "HEAD" || body === null;
if (expectContinue) {
headers[HTTP2_HEADER_EXPECT] = "100-continue";
stream = session.request(headers, { endStream: shouldEndStream, signal });
@@ -10807,7 +10830,7 @@ var require_fetch = __commonJS({
this.emit("terminated", error);
}
};
function fetch2(input, init = {}) {
function fetch2(input, init = void 0) {
webidl.argumentLengthCheck(arguments, 1, { header: "globalThis.fetch" });
const p = createDeferredPromise();
let requestObject;
@@ -10867,7 +10890,7 @@ var require_fetch = __commonJS({
request,
processResponseEndOfBody: handleFetchDone,
processResponse,
dispatcher: init.dispatcher ?? getGlobalDispatcher()
dispatcher: init?.dispatcher ?? getGlobalDispatcher()
// undici
});
return p.promise;
@@ -10913,9 +10936,6 @@ var require_fetch = __commonJS({
}
__name(markResourceTiming, "markResourceTiming");
function abortFetch(p, request, responseObject, error) {
if (!error) {
error = new DOMException("The operation was aborted.", "AbortError");
}
p.reject(error);
if (request.body != null && isReadable(request.body?.stream)) {
request.body.stream.cancel(error).catch((err) => {
@@ -10950,6 +10970,7 @@ var require_fetch = __commonJS({
dispatcher
// undici
}) {
assert(dispatcher);
let taskDestination = null;
let crossOriginIsolatedCapability = false;
if (request.client != null) {
+1 -1
View File
@@ -2,5 +2,5 @@
// Refer to tools/dep_updaters/update-undici.sh
#ifndef SRC_UNDICI_VERSION_H_
#define SRC_UNDICI_VERSION_H_
#define UNDICI_VERSION "6.3.0"
#define UNDICI_VERSION "6.5.0"
#endif // SRC_UNDICI_VERSION_H_