noahluckyrobots commited on
Commit
abfcf57
·
verified ·
1 Parent(s): d8ae8ed

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. worker/node_modules/undici/lib/agent.js +148 -0
  2. worker/node_modules/undici/lib/api/abort-signal.js +54 -0
  3. worker/node_modules/undici/lib/api/api-connect.js +104 -0
  4. worker/node_modules/undici/lib/api/api-pipeline.js +249 -0
  5. worker/node_modules/undici/lib/api/api-request.js +180 -0
  6. worker/node_modules/undici/lib/api/api-stream.js +220 -0
  7. worker/node_modules/undici/lib/api/api-upgrade.js +105 -0
  8. worker/node_modules/undici/lib/api/index.js +7 -0
  9. worker/node_modules/undici/lib/api/readable.js +322 -0
  10. worker/node_modules/undici/lib/api/util.js +46 -0
  11. worker/node_modules/undici/lib/balanced-pool.js +190 -0
  12. worker/node_modules/undici/lib/cache/cache.js +838 -0
  13. worker/node_modules/undici/lib/cache/cachestorage.js +144 -0
  14. worker/node_modules/undici/lib/cache/symbols.js +5 -0
  15. worker/node_modules/undici/lib/cache/util.js +49 -0
  16. worker/node_modules/undici/lib/client.js +2283 -0
  17. worker/node_modules/undici/lib/compat/dispatcher-weakref.js +48 -0
  18. worker/node_modules/undici/lib/cookies/constants.js +12 -0
  19. worker/node_modules/undici/lib/cookies/index.js +183 -0
  20. worker/node_modules/undici/lib/cookies/parse.js +317 -0
  21. worker/node_modules/undici/lib/cookies/util.js +274 -0
  22. worker/node_modules/undici/lib/core/connect.js +189 -0
  23. worker/node_modules/undici/lib/core/constants.js +118 -0
  24. worker/node_modules/undici/lib/core/errors.js +230 -0
  25. worker/node_modules/undici/lib/core/request.js +499 -0
  26. worker/node_modules/undici/lib/core/symbols.js +63 -0
  27. worker/node_modules/undici/lib/core/util.js +522 -0
  28. worker/node_modules/undici/lib/dispatcher-base.js +192 -0
  29. worker/node_modules/undici/lib/dispatcher.js +19 -0
  30. worker/node_modules/undici/lib/fetch/LICENSE +21 -0
  31. worker/node_modules/undici/lib/fetch/body.js +613 -0
  32. worker/node_modules/undici/lib/fetch/constants.js +151 -0
  33. worker/node_modules/undici/lib/fetch/dataURL.js +627 -0
  34. worker/node_modules/undici/lib/fetch/file.js +344 -0
  35. worker/node_modules/undici/lib/fetch/formdata.js +265 -0
  36. worker/node_modules/undici/lib/fetch/global.js +40 -0
  37. worker/node_modules/undici/lib/fetch/headers.js +593 -0
  38. worker/node_modules/undici/lib/fetch/index.js +2148 -0
  39. worker/node_modules/undici/lib/fetch/request.js +946 -0
  40. worker/node_modules/undici/lib/fetch/response.js +571 -0
  41. worker/node_modules/undici/lib/fetch/symbols.js +10 -0
  42. worker/node_modules/undici/lib/fetch/util.js +1144 -0
  43. worker/node_modules/undici/lib/fetch/webidl.js +646 -0
  44. worker/node_modules/undici/lib/fileapi/encoding.js +290 -0
  45. worker/node_modules/undici/lib/fileapi/filereader.js +344 -0
  46. worker/node_modules/undici/lib/fileapi/progressevent.js +78 -0
  47. worker/node_modules/undici/lib/fileapi/symbols.js +10 -0
  48. worker/node_modules/undici/lib/fileapi/util.js +392 -0
  49. worker/node_modules/undici/lib/global.js +32 -0
  50. worker/node_modules/undici/lib/handler/DecoratorHandler.js +35 -0
worker/node_modules/undici/lib/agent.js ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { InvalidArgumentError } = require('./core/errors')
4
+ const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols')
5
+ const DispatcherBase = require('./dispatcher-base')
6
+ const Pool = require('./pool')
7
+ const Client = require('./client')
8
+ const util = require('./core/util')
9
+ const createRedirectInterceptor = require('./interceptor/redirectInterceptor')
10
+ const { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')()
11
+
12
+ const kOnConnect = Symbol('onConnect')
13
+ const kOnDisconnect = Symbol('onDisconnect')
14
+ const kOnConnectionError = Symbol('onConnectionError')
15
+ const kMaxRedirections = Symbol('maxRedirections')
16
+ const kOnDrain = Symbol('onDrain')
17
+ const kFactory = Symbol('factory')
18
+ const kFinalizer = Symbol('finalizer')
19
+ const kOptions = Symbol('options')
20
+
21
+ function defaultFactory (origin, opts) {
22
+ return opts && opts.connections === 1
23
+ ? new Client(origin, opts)
24
+ : new Pool(origin, opts)
25
+ }
26
+
27
+ class Agent extends DispatcherBase {
28
+ constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
29
+ super()
30
+
31
+ if (typeof factory !== 'function') {
32
+ throw new InvalidArgumentError('factory must be a function.')
33
+ }
34
+
35
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
36
+ throw new InvalidArgumentError('connect must be a function or an object')
37
+ }
38
+
39
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
40
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
41
+ }
42
+
43
+ if (connect && typeof connect !== 'function') {
44
+ connect = { ...connect }
45
+ }
46
+
47
+ this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
48
+ ? options.interceptors.Agent
49
+ : [createRedirectInterceptor({ maxRedirections })]
50
+
51
+ this[kOptions] = { ...util.deepClone(options), connect }
52
+ this[kOptions].interceptors = options.interceptors
53
+ ? { ...options.interceptors }
54
+ : undefined
55
+ this[kMaxRedirections] = maxRedirections
56
+ this[kFactory] = factory
57
+ this[kClients] = new Map()
58
+ this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
59
+ const ref = this[kClients].get(key)
60
+ if (ref !== undefined && ref.deref() === undefined) {
61
+ this[kClients].delete(key)
62
+ }
63
+ })
64
+
65
+ const agent = this
66
+
67
+ this[kOnDrain] = (origin, targets) => {
68
+ agent.emit('drain', origin, [agent, ...targets])
69
+ }
70
+
71
+ this[kOnConnect] = (origin, targets) => {
72
+ agent.emit('connect', origin, [agent, ...targets])
73
+ }
74
+
75
+ this[kOnDisconnect] = (origin, targets, err) => {
76
+ agent.emit('disconnect', origin, [agent, ...targets], err)
77
+ }
78
+
79
+ this[kOnConnectionError] = (origin, targets, err) => {
80
+ agent.emit('connectionError', origin, [agent, ...targets], err)
81
+ }
82
+ }
83
+
84
+ get [kRunning] () {
85
+ let ret = 0
86
+ for (const ref of this[kClients].values()) {
87
+ const client = ref.deref()
88
+ /* istanbul ignore next: gc is undeterministic */
89
+ if (client) {
90
+ ret += client[kRunning]
91
+ }
92
+ }
93
+ return ret
94
+ }
95
+
96
+ [kDispatch] (opts, handler) {
97
+ let key
98
+ if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
99
+ key = String(opts.origin)
100
+ } else {
101
+ throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
102
+ }
103
+
104
+ const ref = this[kClients].get(key)
105
+
106
+ let dispatcher = ref ? ref.deref() : null
107
+ if (!dispatcher) {
108
+ dispatcher = this[kFactory](opts.origin, this[kOptions])
109
+ .on('drain', this[kOnDrain])
110
+ .on('connect', this[kOnConnect])
111
+ .on('disconnect', this[kOnDisconnect])
112
+ .on('connectionError', this[kOnConnectionError])
113
+
114
+ this[kClients].set(key, new WeakRef(dispatcher))
115
+ this[kFinalizer].register(dispatcher, key)
116
+ }
117
+
118
+ return dispatcher.dispatch(opts, handler)
119
+ }
120
+
121
+ async [kClose] () {
122
+ const closePromises = []
123
+ for (const ref of this[kClients].values()) {
124
+ const client = ref.deref()
125
+ /* istanbul ignore else: gc is undeterministic */
126
+ if (client) {
127
+ closePromises.push(client.close())
128
+ }
129
+ }
130
+
131
+ await Promise.all(closePromises)
132
+ }
133
+
134
+ async [kDestroy] (err) {
135
+ const destroyPromises = []
136
+ for (const ref of this[kClients].values()) {
137
+ const client = ref.deref()
138
+ /* istanbul ignore else: gc is undeterministic */
139
+ if (client) {
140
+ destroyPromises.push(client.destroy(err))
141
+ }
142
+ }
143
+
144
+ await Promise.all(destroyPromises)
145
+ }
146
+ }
147
+
148
+ module.exports = Agent
worker/node_modules/undici/lib/api/abort-signal.js ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { addAbortListener } = require('../core/util')
2
+ const { RequestAbortedError } = require('../core/errors')
3
+
4
+ const kListener = Symbol('kListener')
5
+ const kSignal = Symbol('kSignal')
6
+
7
+ function abort (self) {
8
+ if (self.abort) {
9
+ self.abort()
10
+ } else {
11
+ self.onError(new RequestAbortedError())
12
+ }
13
+ }
14
+
15
+ function addSignal (self, signal) {
16
+ self[kSignal] = null
17
+ self[kListener] = null
18
+
19
+ if (!signal) {
20
+ return
21
+ }
22
+
23
+ if (signal.aborted) {
24
+ abort(self)
25
+ return
26
+ }
27
+
28
+ self[kSignal] = signal
29
+ self[kListener] = () => {
30
+ abort(self)
31
+ }
32
+
33
+ addAbortListener(self[kSignal], self[kListener])
34
+ }
35
+
36
+ function removeSignal (self) {
37
+ if (!self[kSignal]) {
38
+ return
39
+ }
40
+
41
+ if ('removeEventListener' in self[kSignal]) {
42
+ self[kSignal].removeEventListener('abort', self[kListener])
43
+ } else {
44
+ self[kSignal].removeListener('abort', self[kListener])
45
+ }
46
+
47
+ self[kSignal] = null
48
+ self[kListener] = null
49
+ }
50
+
51
+ module.exports = {
52
+ addSignal,
53
+ removeSignal
54
+ }
worker/node_modules/undici/lib/api/api-connect.js ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { AsyncResource } = require('async_hooks')
4
+ const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')
5
+ const util = require('../core/util')
6
+ const { addSignal, removeSignal } = require('./abort-signal')
7
+
8
+ class ConnectHandler extends AsyncResource {
9
+ constructor (opts, callback) {
10
+ if (!opts || typeof opts !== 'object') {
11
+ throw new InvalidArgumentError('invalid opts')
12
+ }
13
+
14
+ if (typeof callback !== 'function') {
15
+ throw new InvalidArgumentError('invalid callback')
16
+ }
17
+
18
+ const { signal, opaque, responseHeaders } = opts
19
+
20
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
21
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
22
+ }
23
+
24
+ super('UNDICI_CONNECT')
25
+
26
+ this.opaque = opaque || null
27
+ this.responseHeaders = responseHeaders || null
28
+ this.callback = callback
29
+ this.abort = null
30
+
31
+ addSignal(this, signal)
32
+ }
33
+
34
+ onConnect (abort, context) {
35
+ if (!this.callback) {
36
+ throw new RequestAbortedError()
37
+ }
38
+
39
+ this.abort = abort
40
+ this.context = context
41
+ }
42
+
43
+ onHeaders () {
44
+ throw new SocketError('bad connect', null)
45
+ }
46
+
47
+ onUpgrade (statusCode, rawHeaders, socket) {
48
+ const { callback, opaque, context } = this
49
+
50
+ removeSignal(this)
51
+
52
+ this.callback = null
53
+
54
+ let headers = rawHeaders
55
+ // Indicates is an HTTP2Session
56
+ if (headers != null) {
57
+ headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
58
+ }
59
+
60
+ this.runInAsyncScope(callback, null, null, {
61
+ statusCode,
62
+ headers,
63
+ socket,
64
+ opaque,
65
+ context
66
+ })
67
+ }
68
+
69
+ onError (err) {
70
+ const { callback, opaque } = this
71
+
72
+ removeSignal(this)
73
+
74
+ if (callback) {
75
+ this.callback = null
76
+ queueMicrotask(() => {
77
+ this.runInAsyncScope(callback, null, err, { opaque })
78
+ })
79
+ }
80
+ }
81
+ }
82
+
83
+ function connect (opts, callback) {
84
+ if (callback === undefined) {
85
+ return new Promise((resolve, reject) => {
86
+ connect.call(this, opts, (err, data) => {
87
+ return err ? reject(err) : resolve(data)
88
+ })
89
+ })
90
+ }
91
+
92
+ try {
93
+ const connectHandler = new ConnectHandler(opts, callback)
94
+ this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
95
+ } catch (err) {
96
+ if (typeof callback !== 'function') {
97
+ throw err
98
+ }
99
+ const opaque = opts && opts.opaque
100
+ queueMicrotask(() => callback(err, { opaque }))
101
+ }
102
+ }
103
+
104
+ module.exports = connect
worker/node_modules/undici/lib/api/api-pipeline.js ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const {
4
+ Readable,
5
+ Duplex,
6
+ PassThrough
7
+ } = require('stream')
8
+ const {
9
+ InvalidArgumentError,
10
+ InvalidReturnValueError,
11
+ RequestAbortedError
12
+ } = require('../core/errors')
13
+ const util = require('../core/util')
14
+ const { AsyncResource } = require('async_hooks')
15
+ const { addSignal, removeSignal } = require('./abort-signal')
16
+ const assert = require('assert')
17
+
18
+ const kResume = Symbol('resume')
19
+
20
+ class PipelineRequest extends Readable {
21
+ constructor () {
22
+ super({ autoDestroy: true })
23
+
24
+ this[kResume] = null
25
+ }
26
+
27
+ _read () {
28
+ const { [kResume]: resume } = this
29
+
30
+ if (resume) {
31
+ this[kResume] = null
32
+ resume()
33
+ }
34
+ }
35
+
36
+ _destroy (err, callback) {
37
+ this._read()
38
+
39
+ callback(err)
40
+ }
41
+ }
42
+
43
+ class PipelineResponse extends Readable {
44
+ constructor (resume) {
45
+ super({ autoDestroy: true })
46
+ this[kResume] = resume
47
+ }
48
+
49
+ _read () {
50
+ this[kResume]()
51
+ }
52
+
53
+ _destroy (err, callback) {
54
+ if (!err && !this._readableState.endEmitted) {
55
+ err = new RequestAbortedError()
56
+ }
57
+
58
+ callback(err)
59
+ }
60
+ }
61
+
62
+ class PipelineHandler extends AsyncResource {
63
+ constructor (opts, handler) {
64
+ if (!opts || typeof opts !== 'object') {
65
+ throw new InvalidArgumentError('invalid opts')
66
+ }
67
+
68
+ if (typeof handler !== 'function') {
69
+ throw new InvalidArgumentError('invalid handler')
70
+ }
71
+
72
+ const { signal, method, opaque, onInfo, responseHeaders } = opts
73
+
74
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
75
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
76
+ }
77
+
78
+ if (method === 'CONNECT') {
79
+ throw new InvalidArgumentError('invalid method')
80
+ }
81
+
82
+ if (onInfo && typeof onInfo !== 'function') {
83
+ throw new InvalidArgumentError('invalid onInfo callback')
84
+ }
85
+
86
+ super('UNDICI_PIPELINE')
87
+
88
+ this.opaque = opaque || null
89
+ this.responseHeaders = responseHeaders || null
90
+ this.handler = handler
91
+ this.abort = null
92
+ this.context = null
93
+ this.onInfo = onInfo || null
94
+
95
+ this.req = new PipelineRequest().on('error', util.nop)
96
+
97
+ this.ret = new Duplex({
98
+ readableObjectMode: opts.objectMode,
99
+ autoDestroy: true,
100
+ read: () => {
101
+ const { body } = this
102
+
103
+ if (body && body.resume) {
104
+ body.resume()
105
+ }
106
+ },
107
+ write: (chunk, encoding, callback) => {
108
+ const { req } = this
109
+
110
+ if (req.push(chunk, encoding) || req._readableState.destroyed) {
111
+ callback()
112
+ } else {
113
+ req[kResume] = callback
114
+ }
115
+ },
116
+ destroy: (err, callback) => {
117
+ const { body, req, res, ret, abort } = this
118
+
119
+ if (!err && !ret._readableState.endEmitted) {
120
+ err = new RequestAbortedError()
121
+ }
122
+
123
+ if (abort && err) {
124
+ abort()
125
+ }
126
+
127
+ util.destroy(body, err)
128
+ util.destroy(req, err)
129
+ util.destroy(res, err)
130
+
131
+ removeSignal(this)
132
+
133
+ callback(err)
134
+ }
135
+ }).on('prefinish', () => {
136
+ const { req } = this
137
+
138
+ // Node < 15 does not call _final in same tick.
139
+ req.push(null)
140
+ })
141
+
142
+ this.res = null
143
+
144
+ addSignal(this, signal)
145
+ }
146
+
147
+ onConnect (abort, context) {
148
+ const { ret, res } = this
149
+
150
+ assert(!res, 'pipeline cannot be retried')
151
+
152
+ if (ret.destroyed) {
153
+ throw new RequestAbortedError()
154
+ }
155
+
156
+ this.abort = abort
157
+ this.context = context
158
+ }
159
+
160
+ onHeaders (statusCode, rawHeaders, resume) {
161
+ const { opaque, handler, context } = this
162
+
163
+ if (statusCode < 200) {
164
+ if (this.onInfo) {
165
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
166
+ this.onInfo({ statusCode, headers })
167
+ }
168
+ return
169
+ }
170
+
171
+ this.res = new PipelineResponse(resume)
172
+
173
+ let body
174
+ try {
175
+ this.handler = null
176
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
177
+ body = this.runInAsyncScope(handler, null, {
178
+ statusCode,
179
+ headers,
180
+ opaque,
181
+ body: this.res,
182
+ context
183
+ })
184
+ } catch (err) {
185
+ this.res.on('error', util.nop)
186
+ throw err
187
+ }
188
+
189
+ if (!body || typeof body.on !== 'function') {
190
+ throw new InvalidReturnValueError('expected Readable')
191
+ }
192
+
193
+ body
194
+ .on('data', (chunk) => {
195
+ const { ret, body } = this
196
+
197
+ if (!ret.push(chunk) && body.pause) {
198
+ body.pause()
199
+ }
200
+ })
201
+ .on('error', (err) => {
202
+ const { ret } = this
203
+
204
+ util.destroy(ret, err)
205
+ })
206
+ .on('end', () => {
207
+ const { ret } = this
208
+
209
+ ret.push(null)
210
+ })
211
+ .on('close', () => {
212
+ const { ret } = this
213
+
214
+ if (!ret._readableState.ended) {
215
+ util.destroy(ret, new RequestAbortedError())
216
+ }
217
+ })
218
+
219
+ this.body = body
220
+ }
221
+
222
+ onData (chunk) {
223
+ const { res } = this
224
+ return res.push(chunk)
225
+ }
226
+
227
+ onComplete (trailers) {
228
+ const { res } = this
229
+ res.push(null)
230
+ }
231
+
232
+ onError (err) {
233
+ const { ret } = this
234
+ this.handler = null
235
+ util.destroy(ret, err)
236
+ }
237
+ }
238
+
239
+ function pipeline (opts, handler) {
240
+ try {
241
+ const pipelineHandler = new PipelineHandler(opts, handler)
242
+ this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
243
+ return pipelineHandler.ret
244
+ } catch (err) {
245
+ return new PassThrough().destroy(err)
246
+ }
247
+ }
248
+
249
+ module.exports = pipeline
worker/node_modules/undici/lib/api/api-request.js ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const Readable = require('./readable')
4
+ const {
5
+ InvalidArgumentError,
6
+ RequestAbortedError
7
+ } = require('../core/errors')
8
+ const util = require('../core/util')
9
+ const { getResolveErrorBodyCallback } = require('./util')
10
+ const { AsyncResource } = require('async_hooks')
11
+ const { addSignal, removeSignal } = require('./abort-signal')
12
+
13
+ class RequestHandler extends AsyncResource {
14
+ constructor (opts, callback) {
15
+ if (!opts || typeof opts !== 'object') {
16
+ throw new InvalidArgumentError('invalid opts')
17
+ }
18
+
19
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
20
+
21
+ try {
22
+ if (typeof callback !== 'function') {
23
+ throw new InvalidArgumentError('invalid callback')
24
+ }
25
+
26
+ if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
27
+ throw new InvalidArgumentError('invalid highWaterMark')
28
+ }
29
+
30
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
31
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
32
+ }
33
+
34
+ if (method === 'CONNECT') {
35
+ throw new InvalidArgumentError('invalid method')
36
+ }
37
+
38
+ if (onInfo && typeof onInfo !== 'function') {
39
+ throw new InvalidArgumentError('invalid onInfo callback')
40
+ }
41
+
42
+ super('UNDICI_REQUEST')
43
+ } catch (err) {
44
+ if (util.isStream(body)) {
45
+ util.destroy(body.on('error', util.nop), err)
46
+ }
47
+ throw err
48
+ }
49
+
50
+ this.responseHeaders = responseHeaders || null
51
+ this.opaque = opaque || null
52
+ this.callback = callback
53
+ this.res = null
54
+ this.abort = null
55
+ this.body = body
56
+ this.trailers = {}
57
+ this.context = null
58
+ this.onInfo = onInfo || null
59
+ this.throwOnError = throwOnError
60
+ this.highWaterMark = highWaterMark
61
+
62
+ if (util.isStream(body)) {
63
+ body.on('error', (err) => {
64
+ this.onError(err)
65
+ })
66
+ }
67
+
68
+ addSignal(this, signal)
69
+ }
70
+
71
+ onConnect (abort, context) {
72
+ if (!this.callback) {
73
+ throw new RequestAbortedError()
74
+ }
75
+
76
+ this.abort = abort
77
+ this.context = context
78
+ }
79
+
80
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
81
+ const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
82
+
83
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
84
+
85
+ if (statusCode < 200) {
86
+ if (this.onInfo) {
87
+ this.onInfo({ statusCode, headers })
88
+ }
89
+ return
90
+ }
91
+
92
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
93
+ const contentType = parsedHeaders['content-type']
94
+ const body = new Readable({ resume, abort, contentType, highWaterMark })
95
+
96
+ this.callback = null
97
+ this.res = body
98
+ if (callback !== null) {
99
+ if (this.throwOnError && statusCode >= 400) {
100
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
101
+ { callback, body, contentType, statusCode, statusMessage, headers }
102
+ )
103
+ } else {
104
+ this.runInAsyncScope(callback, null, null, {
105
+ statusCode,
106
+ headers,
107
+ trailers: this.trailers,
108
+ opaque,
109
+ body,
110
+ context
111
+ })
112
+ }
113
+ }
114
+ }
115
+
116
+ onData (chunk) {
117
+ const { res } = this
118
+ return res.push(chunk)
119
+ }
120
+
121
+ onComplete (trailers) {
122
+ const { res } = this
123
+
124
+ removeSignal(this)
125
+
126
+ util.parseHeaders(trailers, this.trailers)
127
+
128
+ res.push(null)
129
+ }
130
+
131
+ onError (err) {
132
+ const { res, callback, body, opaque } = this
133
+
134
+ removeSignal(this)
135
+
136
+ if (callback) {
137
+ // TODO: Does this need queueMicrotask?
138
+ this.callback = null
139
+ queueMicrotask(() => {
140
+ this.runInAsyncScope(callback, null, err, { opaque })
141
+ })
142
+ }
143
+
144
+ if (res) {
145
+ this.res = null
146
+ // Ensure all queued handlers are invoked before destroying res.
147
+ queueMicrotask(() => {
148
+ util.destroy(res, err)
149
+ })
150
+ }
151
+
152
+ if (body) {
153
+ this.body = null
154
+ util.destroy(body, err)
155
+ }
156
+ }
157
+ }
158
+
159
+ function request (opts, callback) {
160
+ if (callback === undefined) {
161
+ return new Promise((resolve, reject) => {
162
+ request.call(this, opts, (err, data) => {
163
+ return err ? reject(err) : resolve(data)
164
+ })
165
+ })
166
+ }
167
+
168
+ try {
169
+ this.dispatch(opts, new RequestHandler(opts, callback))
170
+ } catch (err) {
171
+ if (typeof callback !== 'function') {
172
+ throw err
173
+ }
174
+ const opaque = opts && opts.opaque
175
+ queueMicrotask(() => callback(err, { opaque }))
176
+ }
177
+ }
178
+
179
+ module.exports = request
180
+ module.exports.RequestHandler = RequestHandler
worker/node_modules/undici/lib/api/api-stream.js ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { finished, PassThrough } = require('stream')
4
+ const {
5
+ InvalidArgumentError,
6
+ InvalidReturnValueError,
7
+ RequestAbortedError
8
+ } = require('../core/errors')
9
+ const util = require('../core/util')
10
+ const { getResolveErrorBodyCallback } = require('./util')
11
+ const { AsyncResource } = require('async_hooks')
12
+ const { addSignal, removeSignal } = require('./abort-signal')
13
+
14
+ class StreamHandler extends AsyncResource {
15
+ constructor (opts, factory, callback) {
16
+ if (!opts || typeof opts !== 'object') {
17
+ throw new InvalidArgumentError('invalid opts')
18
+ }
19
+
20
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
21
+
22
+ try {
23
+ if (typeof callback !== 'function') {
24
+ throw new InvalidArgumentError('invalid callback')
25
+ }
26
+
27
+ if (typeof factory !== 'function') {
28
+ throw new InvalidArgumentError('invalid factory')
29
+ }
30
+
31
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
32
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
33
+ }
34
+
35
+ if (method === 'CONNECT') {
36
+ throw new InvalidArgumentError('invalid method')
37
+ }
38
+
39
+ if (onInfo && typeof onInfo !== 'function') {
40
+ throw new InvalidArgumentError('invalid onInfo callback')
41
+ }
42
+
43
+ super('UNDICI_STREAM')
44
+ } catch (err) {
45
+ if (util.isStream(body)) {
46
+ util.destroy(body.on('error', util.nop), err)
47
+ }
48
+ throw err
49
+ }
50
+
51
+ this.responseHeaders = responseHeaders || null
52
+ this.opaque = opaque || null
53
+ this.factory = factory
54
+ this.callback = callback
55
+ this.res = null
56
+ this.abort = null
57
+ this.context = null
58
+ this.trailers = null
59
+ this.body = body
60
+ this.onInfo = onInfo || null
61
+ this.throwOnError = throwOnError || false
62
+
63
+ if (util.isStream(body)) {
64
+ body.on('error', (err) => {
65
+ this.onError(err)
66
+ })
67
+ }
68
+
69
+ addSignal(this, signal)
70
+ }
71
+
72
+ onConnect (abort, context) {
73
+ if (!this.callback) {
74
+ throw new RequestAbortedError()
75
+ }
76
+
77
+ this.abort = abort
78
+ this.context = context
79
+ }
80
+
81
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
82
+ const { factory, opaque, context, callback, responseHeaders } = this
83
+
84
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
85
+
86
+ if (statusCode < 200) {
87
+ if (this.onInfo) {
88
+ this.onInfo({ statusCode, headers })
89
+ }
90
+ return
91
+ }
92
+
93
+ this.factory = null
94
+
95
+ let res
96
+
97
+ if (this.throwOnError && statusCode >= 400) {
98
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
99
+ const contentType = parsedHeaders['content-type']
100
+ res = new PassThrough()
101
+
102
+ this.callback = null
103
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
104
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
105
+ )
106
+ } else {
107
+ if (factory === null) {
108
+ return
109
+ }
110
+
111
+ res = this.runInAsyncScope(factory, null, {
112
+ statusCode,
113
+ headers,
114
+ opaque,
115
+ context
116
+ })
117
+
118
+ if (
119
+ !res ||
120
+ typeof res.write !== 'function' ||
121
+ typeof res.end !== 'function' ||
122
+ typeof res.on !== 'function'
123
+ ) {
124
+ throw new InvalidReturnValueError('expected Writable')
125
+ }
126
+
127
+ // TODO: Avoid finished. It registers an unnecessary amount of listeners.
128
+ finished(res, { readable: false }, (err) => {
129
+ const { callback, res, opaque, trailers, abort } = this
130
+
131
+ this.res = null
132
+ if (err || !res.readable) {
133
+ util.destroy(res, err)
134
+ }
135
+
136
+ this.callback = null
137
+ this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
138
+
139
+ if (err) {
140
+ abort()
141
+ }
142
+ })
143
+ }
144
+
145
+ res.on('drain', resume)
146
+
147
+ this.res = res
148
+
149
+ const needDrain = res.writableNeedDrain !== undefined
150
+ ? res.writableNeedDrain
151
+ : res._writableState && res._writableState.needDrain
152
+
153
+ return needDrain !== true
154
+ }
155
+
156
+ onData (chunk) {
157
+ const { res } = this
158
+
159
+ return res ? res.write(chunk) : true
160
+ }
161
+
162
+ onComplete (trailers) {
163
+ const { res } = this
164
+
165
+ removeSignal(this)
166
+
167
+ if (!res) {
168
+ return
169
+ }
170
+
171
+ this.trailers = util.parseHeaders(trailers)
172
+
173
+ res.end()
174
+ }
175
+
176
+ onError (err) {
177
+ const { res, callback, opaque, body } = this
178
+
179
+ removeSignal(this)
180
+
181
+ this.factory = null
182
+
183
+ if (res) {
184
+ this.res = null
185
+ util.destroy(res, err)
186
+ } else if (callback) {
187
+ this.callback = null
188
+ queueMicrotask(() => {
189
+ this.runInAsyncScope(callback, null, err, { opaque })
190
+ })
191
+ }
192
+
193
+ if (body) {
194
+ this.body = null
195
+ util.destroy(body, err)
196
+ }
197
+ }
198
+ }
199
+
200
+ function stream (opts, factory, callback) {
201
+ if (callback === undefined) {
202
+ return new Promise((resolve, reject) => {
203
+ stream.call(this, opts, factory, (err, data) => {
204
+ return err ? reject(err) : resolve(data)
205
+ })
206
+ })
207
+ }
208
+
209
+ try {
210
+ this.dispatch(opts, new StreamHandler(opts, factory, callback))
211
+ } catch (err) {
212
+ if (typeof callback !== 'function') {
213
+ throw err
214
+ }
215
+ const opaque = opts && opts.opaque
216
+ queueMicrotask(() => callback(err, { opaque }))
217
+ }
218
+ }
219
+
220
+ module.exports = stream
worker/node_modules/undici/lib/api/api-upgrade.js ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors')
4
+ const { AsyncResource } = require('async_hooks')
5
+ const util = require('../core/util')
6
+ const { addSignal, removeSignal } = require('./abort-signal')
7
+ const assert = require('assert')
8
+
9
+ class UpgradeHandler extends AsyncResource {
10
+ constructor (opts, callback) {
11
+ if (!opts || typeof opts !== 'object') {
12
+ throw new InvalidArgumentError('invalid opts')
13
+ }
14
+
15
+ if (typeof callback !== 'function') {
16
+ throw new InvalidArgumentError('invalid callback')
17
+ }
18
+
19
+ const { signal, opaque, responseHeaders } = opts
20
+
21
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
22
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
23
+ }
24
+
25
+ super('UNDICI_UPGRADE')
26
+
27
+ this.responseHeaders = responseHeaders || null
28
+ this.opaque = opaque || null
29
+ this.callback = callback
30
+ this.abort = null
31
+ this.context = null
32
+
33
+ addSignal(this, signal)
34
+ }
35
+
36
+ onConnect (abort, context) {
37
+ if (!this.callback) {
38
+ throw new RequestAbortedError()
39
+ }
40
+
41
+ this.abort = abort
42
+ this.context = null
43
+ }
44
+
45
+ onHeaders () {
46
+ throw new SocketError('bad upgrade', null)
47
+ }
48
+
49
+ onUpgrade (statusCode, rawHeaders, socket) {
50
+ const { callback, opaque, context } = this
51
+
52
+ assert.strictEqual(statusCode, 101)
53
+
54
+ removeSignal(this)
55
+
56
+ this.callback = null
57
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
58
+ this.runInAsyncScope(callback, null, null, {
59
+ headers,
60
+ socket,
61
+ opaque,
62
+ context
63
+ })
64
+ }
65
+
66
+ onError (err) {
67
+ const { callback, opaque } = this
68
+
69
+ removeSignal(this)
70
+
71
+ if (callback) {
72
+ this.callback = null
73
+ queueMicrotask(() => {
74
+ this.runInAsyncScope(callback, null, err, { opaque })
75
+ })
76
+ }
77
+ }
78
+ }
79
+
80
+ function upgrade (opts, callback) {
81
+ if (callback === undefined) {
82
+ return new Promise((resolve, reject) => {
83
+ upgrade.call(this, opts, (err, data) => {
84
+ return err ? reject(err) : resolve(data)
85
+ })
86
+ })
87
+ }
88
+
89
+ try {
90
+ const upgradeHandler = new UpgradeHandler(opts, callback)
91
+ this.dispatch({
92
+ ...opts,
93
+ method: opts.method || 'GET',
94
+ upgrade: opts.protocol || 'Websocket'
95
+ }, upgradeHandler)
96
+ } catch (err) {
97
+ if (typeof callback !== 'function') {
98
+ throw err
99
+ }
100
+ const opaque = opts && opts.opaque
101
+ queueMicrotask(() => callback(err, { opaque }))
102
+ }
103
+ }
104
+
105
+ module.exports = upgrade
worker/node_modules/undici/lib/api/index.js ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ module.exports.request = require('./api-request')
4
+ module.exports.stream = require('./api-stream')
5
+ module.exports.pipeline = require('./api-pipeline')
6
+ module.exports.upgrade = require('./api-upgrade')
7
+ module.exports.connect = require('./api-connect')
worker/node_modules/undici/lib/api/readable.js ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Ported from https://github.com/nodejs/undici/pull/907
2
+
3
+ 'use strict'
4
+
5
+ const assert = require('assert')
6
+ const { Readable } = require('stream')
7
+ const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors')
8
+ const util = require('../core/util')
9
+ const { ReadableStreamFrom, toUSVString } = require('../core/util')
10
+
11
+ let Blob
12
+
13
+ const kConsume = Symbol('kConsume')
14
+ const kReading = Symbol('kReading')
15
+ const kBody = Symbol('kBody')
16
+ const kAbort = Symbol('abort')
17
+ const kContentType = Symbol('kContentType')
18
+
19
+ const noop = () => {}
20
+
21
+ module.exports = class BodyReadable extends Readable {
22
+ constructor ({
23
+ resume,
24
+ abort,
25
+ contentType = '',
26
+ highWaterMark = 64 * 1024 // Same as nodejs fs streams.
27
+ }) {
28
+ super({
29
+ autoDestroy: true,
30
+ read: resume,
31
+ highWaterMark
32
+ })
33
+
34
+ this._readableState.dataEmitted = false
35
+
36
+ this[kAbort] = abort
37
+ this[kConsume] = null
38
+ this[kBody] = null
39
+ this[kContentType] = contentType
40
+
41
+ // Is stream being consumed through Readable API?
42
+ // This is an optimization so that we avoid checking
43
+ // for 'data' and 'readable' listeners in the hot path
44
+ // inside push().
45
+ this[kReading] = false
46
+ }
47
+
48
+ destroy (err) {
49
+ if (this.destroyed) {
50
+ // Node < 16
51
+ return this
52
+ }
53
+
54
+ if (!err && !this._readableState.endEmitted) {
55
+ err = new RequestAbortedError()
56
+ }
57
+
58
+ if (err) {
59
+ this[kAbort]()
60
+ }
61
+
62
+ return super.destroy(err)
63
+ }
64
+
65
+ emit (ev, ...args) {
66
+ if (ev === 'data') {
67
+ // Node < 16.7
68
+ this._readableState.dataEmitted = true
69
+ } else if (ev === 'error') {
70
+ // Node < 16
71
+ this._readableState.errorEmitted = true
72
+ }
73
+ return super.emit(ev, ...args)
74
+ }
75
+
76
+ on (ev, ...args) {
77
+ if (ev === 'data' || ev === 'readable') {
78
+ this[kReading] = true
79
+ }
80
+ return super.on(ev, ...args)
81
+ }
82
+
83
+ addListener (ev, ...args) {
84
+ return this.on(ev, ...args)
85
+ }
86
+
87
+ off (ev, ...args) {
88
+ const ret = super.off(ev, ...args)
89
+ if (ev === 'data' || ev === 'readable') {
90
+ this[kReading] = (
91
+ this.listenerCount('data') > 0 ||
92
+ this.listenerCount('readable') > 0
93
+ )
94
+ }
95
+ return ret
96
+ }
97
+
98
+ removeListener (ev, ...args) {
99
+ return this.off(ev, ...args)
100
+ }
101
+
102
+ push (chunk) {
103
+ if (this[kConsume] && chunk !== null && this.readableLength === 0) {
104
+ consumePush(this[kConsume], chunk)
105
+ return this[kReading] ? super.push(chunk) : true
106
+ }
107
+ return super.push(chunk)
108
+ }
109
+
110
+ // https://fetch.spec.whatwg.org/#dom-body-text
111
+ async text () {
112
+ return consume(this, 'text')
113
+ }
114
+
115
+ // https://fetch.spec.whatwg.org/#dom-body-json
116
+ async json () {
117
+ return consume(this, 'json')
118
+ }
119
+
120
+ // https://fetch.spec.whatwg.org/#dom-body-blob
121
+ async blob () {
122
+ return consume(this, 'blob')
123
+ }
124
+
125
+ // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
126
+ async arrayBuffer () {
127
+ return consume(this, 'arrayBuffer')
128
+ }
129
+
130
+ // https://fetch.spec.whatwg.org/#dom-body-formdata
131
+ async formData () {
132
+ // TODO: Implement.
133
+ throw new NotSupportedError()
134
+ }
135
+
136
+ // https://fetch.spec.whatwg.org/#dom-body-bodyused
137
+ get bodyUsed () {
138
+ return util.isDisturbed(this)
139
+ }
140
+
141
+ // https://fetch.spec.whatwg.org/#dom-body-body
142
+ get body () {
143
+ if (!this[kBody]) {
144
+ this[kBody] = ReadableStreamFrom(this)
145
+ if (this[kConsume]) {
146
+ // TODO: Is this the best way to force a lock?
147
+ this[kBody].getReader() // Ensure stream is locked.
148
+ assert(this[kBody].locked)
149
+ }
150
+ }
151
+ return this[kBody]
152
+ }
153
+
154
+ dump (opts) {
155
+ let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
156
+ const signal = opts && opts.signal
157
+
158
+ if (signal) {
159
+ try {
160
+ if (typeof signal !== 'object' || !('aborted' in signal)) {
161
+ throw new InvalidArgumentError('signal must be an AbortSignal')
162
+ }
163
+ util.throwIfAborted(signal)
164
+ } catch (err) {
165
+ return Promise.reject(err)
166
+ }
167
+ }
168
+
169
+ if (this.closed) {
170
+ return Promise.resolve(null)
171
+ }
172
+
173
+ return new Promise((resolve, reject) => {
174
+ const signalListenerCleanup = signal
175
+ ? util.addAbortListener(signal, () => {
176
+ this.destroy()
177
+ })
178
+ : noop
179
+
180
+ this
181
+ .on('close', function () {
182
+ signalListenerCleanup()
183
+ if (signal && signal.aborted) {
184
+ reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
185
+ } else {
186
+ resolve(null)
187
+ }
188
+ })
189
+ .on('error', noop)
190
+ .on('data', function (chunk) {
191
+ limit -= chunk.length
192
+ if (limit <= 0) {
193
+ this.destroy()
194
+ }
195
+ })
196
+ .resume()
197
+ })
198
+ }
199
+ }
200
+
201
+ // https://streams.spec.whatwg.org/#readablestream-locked
202
+ function isLocked (self) {
203
+ // Consume is an implicit lock.
204
+ return (self[kBody] && self[kBody].locked === true) || self[kConsume]
205
+ }
206
+
207
+ // https://fetch.spec.whatwg.org/#body-unusable
208
+ function isUnusable (self) {
209
+ return util.isDisturbed(self) || isLocked(self)
210
+ }
211
+
212
+ async function consume (stream, type) {
213
+ if (isUnusable(stream)) {
214
+ throw new TypeError('unusable')
215
+ }
216
+
217
+ assert(!stream[kConsume])
218
+
219
+ return new Promise((resolve, reject) => {
220
+ stream[kConsume] = {
221
+ type,
222
+ stream,
223
+ resolve,
224
+ reject,
225
+ length: 0,
226
+ body: []
227
+ }
228
+
229
+ stream
230
+ .on('error', function (err) {
231
+ consumeFinish(this[kConsume], err)
232
+ })
233
+ .on('close', function () {
234
+ if (this[kConsume].body !== null) {
235
+ consumeFinish(this[kConsume], new RequestAbortedError())
236
+ }
237
+ })
238
+
239
+ process.nextTick(consumeStart, stream[kConsume])
240
+ })
241
+ }
242
+
243
+ function consumeStart (consume) {
244
+ if (consume.body === null) {
245
+ return
246
+ }
247
+
248
+ const { _readableState: state } = consume.stream
249
+
250
+ for (const chunk of state.buffer) {
251
+ consumePush(consume, chunk)
252
+ }
253
+
254
+ if (state.endEmitted) {
255
+ consumeEnd(this[kConsume])
256
+ } else {
257
+ consume.stream.on('end', function () {
258
+ consumeEnd(this[kConsume])
259
+ })
260
+ }
261
+
262
+ consume.stream.resume()
263
+
264
+ while (consume.stream.read() != null) {
265
+ // Loop
266
+ }
267
+ }
268
+
269
+ function consumeEnd (consume) {
270
+ const { type, body, resolve, stream, length } = consume
271
+
272
+ try {
273
+ if (type === 'text') {
274
+ resolve(toUSVString(Buffer.concat(body)))
275
+ } else if (type === 'json') {
276
+ resolve(JSON.parse(Buffer.concat(body)))
277
+ } else if (type === 'arrayBuffer') {
278
+ const dst = new Uint8Array(length)
279
+
280
+ let pos = 0
281
+ for (const buf of body) {
282
+ dst.set(buf, pos)
283
+ pos += buf.byteLength
284
+ }
285
+
286
+ resolve(dst.buffer)
287
+ } else if (type === 'blob') {
288
+ if (!Blob) {
289
+ Blob = require('buffer').Blob
290
+ }
291
+ resolve(new Blob(body, { type: stream[kContentType] }))
292
+ }
293
+
294
+ consumeFinish(consume)
295
+ } catch (err) {
296
+ stream.destroy(err)
297
+ }
298
+ }
299
+
300
+ function consumePush (consume, chunk) {
301
+ consume.length += chunk.length
302
+ consume.body.push(chunk)
303
+ }
304
+
305
+ function consumeFinish (consume, err) {
306
+ if (consume.body === null) {
307
+ return
308
+ }
309
+
310
+ if (err) {
311
+ consume.reject(err)
312
+ } else {
313
+ consume.resolve()
314
+ }
315
+
316
+ consume.type = null
317
+ consume.stream = null
318
+ consume.resolve = null
319
+ consume.reject = null
320
+ consume.length = 0
321
+ consume.body = null
322
+ }
worker/node_modules/undici/lib/api/util.js ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const assert = require('assert')
2
+ const {
3
+ ResponseStatusCodeError
4
+ } = require('../core/errors')
5
+ const { toUSVString } = require('../core/util')
6
+
7
+ async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
8
+ assert(body)
9
+
10
+ let chunks = []
11
+ let limit = 0
12
+
13
+ for await (const chunk of body) {
14
+ chunks.push(chunk)
15
+ limit += chunk.length
16
+ if (limit > 128 * 1024) {
17
+ chunks = null
18
+ break
19
+ }
20
+ }
21
+
22
+ if (statusCode === 204 || !contentType || !chunks) {
23
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
24
+ return
25
+ }
26
+
27
+ try {
28
+ if (contentType.startsWith('application/json')) {
29
+ const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
30
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
31
+ return
32
+ }
33
+
34
+ if (contentType.startsWith('text/')) {
35
+ const payload = toUSVString(Buffer.concat(chunks))
36
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
37
+ return
38
+ }
39
+ } catch (err) {
40
+ // Process in a fallback if error
41
+ }
42
+
43
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
44
+ }
45
+
46
+ module.exports = { getResolveErrorBodyCallback }
worker/node_modules/undici/lib/balanced-pool.js ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const {
4
+ BalancedPoolMissingUpstreamError,
5
+ InvalidArgumentError
6
+ } = require('./core/errors')
7
+ const {
8
+ PoolBase,
9
+ kClients,
10
+ kNeedDrain,
11
+ kAddClient,
12
+ kRemoveClient,
13
+ kGetDispatcher
14
+ } = require('./pool-base')
15
+ const Pool = require('./pool')
16
+ const { kUrl, kInterceptors } = require('./core/symbols')
17
+ const { parseOrigin } = require('./core/util')
18
+ const kFactory = Symbol('factory')
19
+
20
+ const kOptions = Symbol('options')
21
+ const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
22
+ const kCurrentWeight = Symbol('kCurrentWeight')
23
+ const kIndex = Symbol('kIndex')
24
+ const kWeight = Symbol('kWeight')
25
+ const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
26
+ const kErrorPenalty = Symbol('kErrorPenalty')
27
+
28
+ function getGreatestCommonDivisor (a, b) {
29
+ if (b === 0) return a
30
+ return getGreatestCommonDivisor(b, a % b)
31
+ }
32
+
33
+ function defaultFactory (origin, opts) {
34
+ return new Pool(origin, opts)
35
+ }
36
+
37
+ class BalancedPool extends PoolBase {
38
+ constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
39
+ super()
40
+
41
+ this[kOptions] = opts
42
+ this[kIndex] = -1
43
+ this[kCurrentWeight] = 0
44
+
45
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
46
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15
47
+
48
+ if (!Array.isArray(upstreams)) {
49
+ upstreams = [upstreams]
50
+ }
51
+
52
+ if (typeof factory !== 'function') {
53
+ throw new InvalidArgumentError('factory must be a function.')
54
+ }
55
+
56
+ this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
57
+ ? opts.interceptors.BalancedPool
58
+ : []
59
+ this[kFactory] = factory
60
+
61
+ for (const upstream of upstreams) {
62
+ this.addUpstream(upstream)
63
+ }
64
+ this._updateBalancedPoolStats()
65
+ }
66
+
67
+ addUpstream (upstream) {
68
+ const upstreamOrigin = parseOrigin(upstream).origin
69
+
70
+ if (this[kClients].find((pool) => (
71
+ pool[kUrl].origin === upstreamOrigin &&
72
+ pool.closed !== true &&
73
+ pool.destroyed !== true
74
+ ))) {
75
+ return this
76
+ }
77
+ const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
78
+
79
+ this[kAddClient](pool)
80
+ pool.on('connect', () => {
81
+ pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
82
+ })
83
+
84
+ pool.on('connectionError', () => {
85
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
86
+ this._updateBalancedPoolStats()
87
+ })
88
+
89
+ pool.on('disconnect', (...args) => {
90
+ const err = args[2]
91
+ if (err && err.code === 'UND_ERR_SOCKET') {
92
+ // decrease the weight of the pool.
93
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
94
+ this._updateBalancedPoolStats()
95
+ }
96
+ })
97
+
98
+ for (const client of this[kClients]) {
99
+ client[kWeight] = this[kMaxWeightPerServer]
100
+ }
101
+
102
+ this._updateBalancedPoolStats()
103
+
104
+ return this
105
+ }
106
+
107
+ _updateBalancedPoolStats () {
108
+ this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
109
+ }
110
+
111
+ removeUpstream (upstream) {
112
+ const upstreamOrigin = parseOrigin(upstream).origin
113
+
114
+ const pool = this[kClients].find((pool) => (
115
+ pool[kUrl].origin === upstreamOrigin &&
116
+ pool.closed !== true &&
117
+ pool.destroyed !== true
118
+ ))
119
+
120
+ if (pool) {
121
+ this[kRemoveClient](pool)
122
+ }
123
+
124
+ return this
125
+ }
126
+
127
+ get upstreams () {
128
+ return this[kClients]
129
+ .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
130
+ .map((p) => p[kUrl].origin)
131
+ }
132
+
133
+ [kGetDispatcher] () {
134
+ // We validate that pools is greater than 0,
135
+ // otherwise we would have to wait until an upstream
136
+ // is added, which might never happen.
137
+ if (this[kClients].length === 0) {
138
+ throw new BalancedPoolMissingUpstreamError()
139
+ }
140
+
141
+ const dispatcher = this[kClients].find(dispatcher => (
142
+ !dispatcher[kNeedDrain] &&
143
+ dispatcher.closed !== true &&
144
+ dispatcher.destroyed !== true
145
+ ))
146
+
147
+ if (!dispatcher) {
148
+ return
149
+ }
150
+
151
+ const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
152
+
153
+ if (allClientsBusy) {
154
+ return
155
+ }
156
+
157
+ let counter = 0
158
+
159
+ let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
160
+
161
+ while (counter++ < this[kClients].length) {
162
+ this[kIndex] = (this[kIndex] + 1) % this[kClients].length
163
+ const pool = this[kClients][this[kIndex]]
164
+
165
+ // find pool index with the largest weight
166
+ if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
167
+ maxWeightIndex = this[kIndex]
168
+ }
169
+
170
+ // decrease the current weight every `this[kClients].length`.
171
+ if (this[kIndex] === 0) {
172
+ // Set the current weight to the next lower weight.
173
+ this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
174
+
175
+ if (this[kCurrentWeight] <= 0) {
176
+ this[kCurrentWeight] = this[kMaxWeightPerServer]
177
+ }
178
+ }
179
+ if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
180
+ return pool
181
+ }
182
+ }
183
+
184
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
185
+ this[kIndex] = maxWeightIndex
186
+ return this[kClients][maxWeightIndex]
187
+ }
188
+ }
189
+
190
+ module.exports = BalancedPool
worker/node_modules/undici/lib/cache/cache.js ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { kConstruct } = require('./symbols')
4
+ const { urlEquals, fieldValues: getFieldValues } = require('./util')
5
+ const { kEnumerableProperty, isDisturbed } = require('../core/util')
6
+ const { kHeadersList } = require('../core/symbols')
7
+ const { webidl } = require('../fetch/webidl')
8
+ const { Response, cloneResponse } = require('../fetch/response')
9
+ const { Request } = require('../fetch/request')
10
+ const { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols')
11
+ const { fetching } = require('../fetch/index')
12
+ const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')
13
+ const assert = require('assert')
14
+ const { getGlobalDispatcher } = require('../global')
15
+
16
+ /**
17
+ * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
18
+ * @typedef {Object} CacheBatchOperation
19
+ * @property {'delete' | 'put'} type
20
+ * @property {any} request
21
+ * @property {any} response
22
+ * @property {import('../../types/cache').CacheQueryOptions} options
23
+ */
24
+
25
+ /**
26
+ * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
27
+ * @typedef {[any, any][]} requestResponseList
28
+ */
29
+
30
+ class Cache {
31
+ /**
32
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
33
+ * @type {requestResponseList}
34
+ */
35
+ #relevantRequestResponseList
36
+
37
+ constructor () {
38
+ if (arguments[0] !== kConstruct) {
39
+ webidl.illegalConstructor()
40
+ }
41
+
42
+ this.#relevantRequestResponseList = arguments[1]
43
+ }
44
+
45
+ async match (request, options = {}) {
46
+ webidl.brandCheck(this, Cache)
47
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
48
+
49
+ request = webidl.converters.RequestInfo(request)
50
+ options = webidl.converters.CacheQueryOptions(options)
51
+
52
+ const p = await this.matchAll(request, options)
53
+
54
+ if (p.length === 0) {
55
+ return
56
+ }
57
+
58
+ return p[0]
59
+ }
60
+
61
+ async matchAll (request = undefined, options = {}) {
62
+ webidl.brandCheck(this, Cache)
63
+
64
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
65
+ options = webidl.converters.CacheQueryOptions(options)
66
+
67
+ // 1.
68
+ let r = null
69
+
70
+ // 2.
71
+ if (request !== undefined) {
72
+ if (request instanceof Request) {
73
+ // 2.1.1
74
+ r = request[kState]
75
+
76
+ // 2.1.2
77
+ if (r.method !== 'GET' && !options.ignoreMethod) {
78
+ return []
79
+ }
80
+ } else if (typeof request === 'string') {
81
+ // 2.2.1
82
+ r = new Request(request)[kState]
83
+ }
84
+ }
85
+
86
+ // 5.
87
+ // 5.1
88
+ const responses = []
89
+
90
+ // 5.2
91
+ if (request === undefined) {
92
+ // 5.2.1
93
+ for (const requestResponse of this.#relevantRequestResponseList) {
94
+ responses.push(requestResponse[1])
95
+ }
96
+ } else { // 5.3
97
+ // 5.3.1
98
+ const requestResponses = this.#queryCache(r, options)
99
+
100
+ // 5.3.2
101
+ for (const requestResponse of requestResponses) {
102
+ responses.push(requestResponse[1])
103
+ }
104
+ }
105
+
106
+ // 5.4
107
+ // We don't implement CORs so we don't need to loop over the responses, yay!
108
+
109
+ // 5.5.1
110
+ const responseList = []
111
+
112
+ // 5.5.2
113
+ for (const response of responses) {
114
+ // 5.5.2.1
115
+ const responseObject = new Response(response.body?.source ?? null)
116
+ const body = responseObject[kState].body
117
+ responseObject[kState] = response
118
+ responseObject[kState].body = body
119
+ responseObject[kHeaders][kHeadersList] = response.headersList
120
+ responseObject[kHeaders][kGuard] = 'immutable'
121
+
122
+ responseList.push(responseObject)
123
+ }
124
+
125
+ // 6.
126
+ return Object.freeze(responseList)
127
+ }
128
+
129
+ async add (request) {
130
+ webidl.brandCheck(this, Cache)
131
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
132
+
133
+ request = webidl.converters.RequestInfo(request)
134
+
135
+ // 1.
136
+ const requests = [request]
137
+
138
+ // 2.
139
+ const responseArrayPromise = this.addAll(requests)
140
+
141
+ // 3.
142
+ return await responseArrayPromise
143
+ }
144
+
145
+ async addAll (requests) {
146
+ webidl.brandCheck(this, Cache)
147
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
148
+
149
+ requests = webidl.converters['sequence<RequestInfo>'](requests)
150
+
151
+ // 1.
152
+ const responsePromises = []
153
+
154
+ // 2.
155
+ const requestList = []
156
+
157
+ // 3.
158
+ for (const request of requests) {
159
+ if (typeof request === 'string') {
160
+ continue
161
+ }
162
+
163
+ // 3.1
164
+ const r = request[kState]
165
+
166
+ // 3.2
167
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
168
+ throw webidl.errors.exception({
169
+ header: 'Cache.addAll',
170
+ message: 'Expected http/s scheme when method is not GET.'
171
+ })
172
+ }
173
+ }
174
+
175
+ // 4.
176
+ /** @type {ReturnType<typeof fetching>[]} */
177
+ const fetchControllers = []
178
+
179
+ // 5.
180
+ for (const request of requests) {
181
+ // 5.1
182
+ const r = new Request(request)[kState]
183
+
184
+ // 5.2
185
+ if (!urlIsHttpHttpsScheme(r.url)) {
186
+ throw webidl.errors.exception({
187
+ header: 'Cache.addAll',
188
+ message: 'Expected http/s scheme.'
189
+ })
190
+ }
191
+
192
+ // 5.4
193
+ r.initiator = 'fetch'
194
+ r.destination = 'subresource'
195
+
196
+ // 5.5
197
+ requestList.push(r)
198
+
199
+ // 5.6
200
+ const responsePromise = createDeferredPromise()
201
+
202
+ // 5.7
203
+ fetchControllers.push(fetching({
204
+ request: r,
205
+ dispatcher: getGlobalDispatcher(),
206
+ processResponse (response) {
207
+ // 1.
208
+ if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
209
+ responsePromise.reject(webidl.errors.exception({
210
+ header: 'Cache.addAll',
211
+ message: 'Received an invalid status code or the request failed.'
212
+ }))
213
+ } else if (response.headersList.contains('vary')) { // 2.
214
+ // 2.1
215
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
216
+
217
+ // 2.2
218
+ for (const fieldValue of fieldValues) {
219
+ // 2.2.1
220
+ if (fieldValue === '*') {
221
+ responsePromise.reject(webidl.errors.exception({
222
+ header: 'Cache.addAll',
223
+ message: 'invalid vary field value'
224
+ }))
225
+
226
+ for (const controller of fetchControllers) {
227
+ controller.abort()
228
+ }
229
+
230
+ return
231
+ }
232
+ }
233
+ }
234
+ },
235
+ processResponseEndOfBody (response) {
236
+ // 1.
237
+ if (response.aborted) {
238
+ responsePromise.reject(new DOMException('aborted', 'AbortError'))
239
+ return
240
+ }
241
+
242
+ // 2.
243
+ responsePromise.resolve(response)
244
+ }
245
+ }))
246
+
247
+ // 5.8
248
+ responsePromises.push(responsePromise.promise)
249
+ }
250
+
251
+ // 6.
252
+ const p = Promise.all(responsePromises)
253
+
254
+ // 7.
255
+ const responses = await p
256
+
257
+ // 7.1
258
+ const operations = []
259
+
260
+ // 7.2
261
+ let index = 0
262
+
263
+ // 7.3
264
+ for (const response of responses) {
265
+ // 7.3.1
266
+ /** @type {CacheBatchOperation} */
267
+ const operation = {
268
+ type: 'put', // 7.3.2
269
+ request: requestList[index], // 7.3.3
270
+ response // 7.3.4
271
+ }
272
+
273
+ operations.push(operation) // 7.3.5
274
+
275
+ index++ // 7.3.6
276
+ }
277
+
278
+ // 7.5
279
+ const cacheJobPromise = createDeferredPromise()
280
+
281
+ // 7.6.1
282
+ let errorData = null
283
+
284
+ // 7.6.2
285
+ try {
286
+ this.#batchCacheOperations(operations)
287
+ } catch (e) {
288
+ errorData = e
289
+ }
290
+
291
+ // 7.6.3
292
+ queueMicrotask(() => {
293
+ // 7.6.3.1
294
+ if (errorData === null) {
295
+ cacheJobPromise.resolve(undefined)
296
+ } else {
297
+ // 7.6.3.2
298
+ cacheJobPromise.reject(errorData)
299
+ }
300
+ })
301
+
302
+ // 7.7
303
+ return cacheJobPromise.promise
304
+ }
305
+
306
+ async put (request, response) {
307
+ webidl.brandCheck(this, Cache)
308
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
309
+
310
+ request = webidl.converters.RequestInfo(request)
311
+ response = webidl.converters.Response(response)
312
+
313
+ // 1.
314
+ let innerRequest = null
315
+
316
+ // 2.
317
+ if (request instanceof Request) {
318
+ innerRequest = request[kState]
319
+ } else { // 3.
320
+ innerRequest = new Request(request)[kState]
321
+ }
322
+
323
+ // 4.
324
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
325
+ throw webidl.errors.exception({
326
+ header: 'Cache.put',
327
+ message: 'Expected an http/s scheme when method is not GET'
328
+ })
329
+ }
330
+
331
+ // 5.
332
+ const innerResponse = response[kState]
333
+
334
+ // 6.
335
+ if (innerResponse.status === 206) {
336
+ throw webidl.errors.exception({
337
+ header: 'Cache.put',
338
+ message: 'Got 206 status'
339
+ })
340
+ }
341
+
342
+ // 7.
343
+ if (innerResponse.headersList.contains('vary')) {
344
+ // 7.1.
345
+ const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
346
+
347
+ // 7.2.
348
+ for (const fieldValue of fieldValues) {
349
+ // 7.2.1
350
+ if (fieldValue === '*') {
351
+ throw webidl.errors.exception({
352
+ header: 'Cache.put',
353
+ message: 'Got * vary field value'
354
+ })
355
+ }
356
+ }
357
+ }
358
+
359
+ // 8.
360
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
361
+ throw webidl.errors.exception({
362
+ header: 'Cache.put',
363
+ message: 'Response body is locked or disturbed'
364
+ })
365
+ }
366
+
367
+ // 9.
368
+ const clonedResponse = cloneResponse(innerResponse)
369
+
370
+ // 10.
371
+ const bodyReadPromise = createDeferredPromise()
372
+
373
+ // 11.
374
+ if (innerResponse.body != null) {
375
+ // 11.1
376
+ const stream = innerResponse.body.stream
377
+
378
+ // 11.2
379
+ const reader = stream.getReader()
380
+
381
+ // 11.3
382
+ readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
383
+ } else {
384
+ bodyReadPromise.resolve(undefined)
385
+ }
386
+
387
+ // 12.
388
+ /** @type {CacheBatchOperation[]} */
389
+ const operations = []
390
+
391
+ // 13.
392
+ /** @type {CacheBatchOperation} */
393
+ const operation = {
394
+ type: 'put', // 14.
395
+ request: innerRequest, // 15.
396
+ response: clonedResponse // 16.
397
+ }
398
+
399
+ // 17.
400
+ operations.push(operation)
401
+
402
+ // 19.
403
+ const bytes = await bodyReadPromise.promise
404
+
405
+ if (clonedResponse.body != null) {
406
+ clonedResponse.body.source = bytes
407
+ }
408
+
409
+ // 19.1
410
+ const cacheJobPromise = createDeferredPromise()
411
+
412
+ // 19.2.1
413
+ let errorData = null
414
+
415
+ // 19.2.2
416
+ try {
417
+ this.#batchCacheOperations(operations)
418
+ } catch (e) {
419
+ errorData = e
420
+ }
421
+
422
+ // 19.2.3
423
+ queueMicrotask(() => {
424
+ // 19.2.3.1
425
+ if (errorData === null) {
426
+ cacheJobPromise.resolve()
427
+ } else { // 19.2.3.2
428
+ cacheJobPromise.reject(errorData)
429
+ }
430
+ })
431
+
432
+ return cacheJobPromise.promise
433
+ }
434
+
435
+ async delete (request, options = {}) {
436
+ webidl.brandCheck(this, Cache)
437
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
438
+
439
+ request = webidl.converters.RequestInfo(request)
440
+ options = webidl.converters.CacheQueryOptions(options)
441
+
442
+ /**
443
+ * @type {Request}
444
+ */
445
+ let r = null
446
+
447
+ if (request instanceof Request) {
448
+ r = request[kState]
449
+
450
+ if (r.method !== 'GET' && !options.ignoreMethod) {
451
+ return false
452
+ }
453
+ } else {
454
+ assert(typeof request === 'string')
455
+
456
+ r = new Request(request)[kState]
457
+ }
458
+
459
+ /** @type {CacheBatchOperation[]} */
460
+ const operations = []
461
+
462
+ /** @type {CacheBatchOperation} */
463
+ const operation = {
464
+ type: 'delete',
465
+ request: r,
466
+ options
467
+ }
468
+
469
+ operations.push(operation)
470
+
471
+ const cacheJobPromise = createDeferredPromise()
472
+
473
+ let errorData = null
474
+ let requestResponses
475
+
476
+ try {
477
+ requestResponses = this.#batchCacheOperations(operations)
478
+ } catch (e) {
479
+ errorData = e
480
+ }
481
+
482
+ queueMicrotask(() => {
483
+ if (errorData === null) {
484
+ cacheJobPromise.resolve(!!requestResponses?.length)
485
+ } else {
486
+ cacheJobPromise.reject(errorData)
487
+ }
488
+ })
489
+
490
+ return cacheJobPromise.promise
491
+ }
492
+
493
+ /**
494
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
495
+ * @param {any} request
496
+ * @param {import('../../types/cache').CacheQueryOptions} options
497
+ * @returns {readonly Request[]}
498
+ */
499
+ async keys (request = undefined, options = {}) {
500
+ webidl.brandCheck(this, Cache)
501
+
502
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
503
+ options = webidl.converters.CacheQueryOptions(options)
504
+
505
+ // 1.
506
+ let r = null
507
+
508
+ // 2.
509
+ if (request !== undefined) {
510
+ // 2.1
511
+ if (request instanceof Request) {
512
+ // 2.1.1
513
+ r = request[kState]
514
+
515
+ // 2.1.2
516
+ if (r.method !== 'GET' && !options.ignoreMethod) {
517
+ return []
518
+ }
519
+ } else if (typeof request === 'string') { // 2.2
520
+ r = new Request(request)[kState]
521
+ }
522
+ }
523
+
524
+ // 4.
525
+ const promise = createDeferredPromise()
526
+
527
+ // 5.
528
+ // 5.1
529
+ const requests = []
530
+
531
+ // 5.2
532
+ if (request === undefined) {
533
+ // 5.2.1
534
+ for (const requestResponse of this.#relevantRequestResponseList) {
535
+ // 5.2.1.1
536
+ requests.push(requestResponse[0])
537
+ }
538
+ } else { // 5.3
539
+ // 5.3.1
540
+ const requestResponses = this.#queryCache(r, options)
541
+
542
+ // 5.3.2
543
+ for (const requestResponse of requestResponses) {
544
+ // 5.3.2.1
545
+ requests.push(requestResponse[0])
546
+ }
547
+ }
548
+
549
+ // 5.4
550
+ queueMicrotask(() => {
551
+ // 5.4.1
552
+ const requestList = []
553
+
554
+ // 5.4.2
555
+ for (const request of requests) {
556
+ const requestObject = new Request('https://a')
557
+ requestObject[kState] = request
558
+ requestObject[kHeaders][kHeadersList] = request.headersList
559
+ requestObject[kHeaders][kGuard] = 'immutable'
560
+ requestObject[kRealm] = request.client
561
+
562
+ // 5.4.2.1
563
+ requestList.push(requestObject)
564
+ }
565
+
566
+ // 5.4.3
567
+ promise.resolve(Object.freeze(requestList))
568
+ })
569
+
570
+ return promise.promise
571
+ }
572
+
573
+ /**
574
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
575
+ * @param {CacheBatchOperation[]} operations
576
+ * @returns {requestResponseList}
577
+ */
578
+ #batchCacheOperations (operations) {
579
+ // 1.
580
+ const cache = this.#relevantRequestResponseList
581
+
582
+ // 2.
583
+ const backupCache = [...cache]
584
+
585
+ // 3.
586
+ const addedItems = []
587
+
588
+ // 4.1
589
+ const resultList = []
590
+
591
+ try {
592
+ // 4.2
593
+ for (const operation of operations) {
594
+ // 4.2.1
595
+ if (operation.type !== 'delete' && operation.type !== 'put') {
596
+ throw webidl.errors.exception({
597
+ header: 'Cache.#batchCacheOperations',
598
+ message: 'operation type does not match "delete" or "put"'
599
+ })
600
+ }
601
+
602
+ // 4.2.2
603
+ if (operation.type === 'delete' && operation.response != null) {
604
+ throw webidl.errors.exception({
605
+ header: 'Cache.#batchCacheOperations',
606
+ message: 'delete operation should not have an associated response'
607
+ })
608
+ }
609
+
610
+ // 4.2.3
611
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
612
+ throw new DOMException('???', 'InvalidStateError')
613
+ }
614
+
615
+ // 4.2.4
616
+ let requestResponses
617
+
618
+ // 4.2.5
619
+ if (operation.type === 'delete') {
620
+ // 4.2.5.1
621
+ requestResponses = this.#queryCache(operation.request, operation.options)
622
+
623
+ // TODO: the spec is wrong, this is needed to pass WPTs
624
+ if (requestResponses.length === 0) {
625
+ return []
626
+ }
627
+
628
+ // 4.2.5.2
629
+ for (const requestResponse of requestResponses) {
630
+ const idx = cache.indexOf(requestResponse)
631
+ assert(idx !== -1)
632
+
633
+ // 4.2.5.2.1
634
+ cache.splice(idx, 1)
635
+ }
636
+ } else if (operation.type === 'put') { // 4.2.6
637
+ // 4.2.6.1
638
+ if (operation.response == null) {
639
+ throw webidl.errors.exception({
640
+ header: 'Cache.#batchCacheOperations',
641
+ message: 'put operation should have an associated response'
642
+ })
643
+ }
644
+
645
+ // 4.2.6.2
646
+ const r = operation.request
647
+
648
+ // 4.2.6.3
649
+ if (!urlIsHttpHttpsScheme(r.url)) {
650
+ throw webidl.errors.exception({
651
+ header: 'Cache.#batchCacheOperations',
652
+ message: 'expected http or https scheme'
653
+ })
654
+ }
655
+
656
+ // 4.2.6.4
657
+ if (r.method !== 'GET') {
658
+ throw webidl.errors.exception({
659
+ header: 'Cache.#batchCacheOperations',
660
+ message: 'not get method'
661
+ })
662
+ }
663
+
664
+ // 4.2.6.5
665
+ if (operation.options != null) {
666
+ throw webidl.errors.exception({
667
+ header: 'Cache.#batchCacheOperations',
668
+ message: 'options must not be defined'
669
+ })
670
+ }
671
+
672
+ // 4.2.6.6
673
+ requestResponses = this.#queryCache(operation.request)
674
+
675
+ // 4.2.6.7
676
+ for (const requestResponse of requestResponses) {
677
+ const idx = cache.indexOf(requestResponse)
678
+ assert(idx !== -1)
679
+
680
+ // 4.2.6.7.1
681
+ cache.splice(idx, 1)
682
+ }
683
+
684
+ // 4.2.6.8
685
+ cache.push([operation.request, operation.response])
686
+
687
+ // 4.2.6.10
688
+ addedItems.push([operation.request, operation.response])
689
+ }
690
+
691
+ // 4.2.7
692
+ resultList.push([operation.request, operation.response])
693
+ }
694
+
695
+ // 4.3
696
+ return resultList
697
+ } catch (e) { // 5.
698
+ // 5.1
699
+ this.#relevantRequestResponseList.length = 0
700
+
701
+ // 5.2
702
+ this.#relevantRequestResponseList = backupCache
703
+
704
+ // 5.3
705
+ throw e
706
+ }
707
+ }
708
+
709
+ /**
710
+ * @see https://w3c.github.io/ServiceWorker/#query-cache
711
+ * @param {any} requestQuery
712
+ * @param {import('../../types/cache').CacheQueryOptions} options
713
+ * @param {requestResponseList} targetStorage
714
+ * @returns {requestResponseList}
715
+ */
716
+ #queryCache (requestQuery, options, targetStorage) {
717
+ /** @type {requestResponseList} */
718
+ const resultList = []
719
+
720
+ const storage = targetStorage ?? this.#relevantRequestResponseList
721
+
722
+ for (const requestResponse of storage) {
723
+ const [cachedRequest, cachedResponse] = requestResponse
724
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
725
+ resultList.push(requestResponse)
726
+ }
727
+ }
728
+
729
+ return resultList
730
+ }
731
+
732
+ /**
733
+ * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
734
+ * @param {any} requestQuery
735
+ * @param {any} request
736
+ * @param {any | null} response
737
+ * @param {import('../../types/cache').CacheQueryOptions | undefined} options
738
+ * @returns {boolean}
739
+ */
740
+ #requestMatchesCachedItem (requestQuery, request, response = null, options) {
741
+ // if (options?.ignoreMethod === false && request.method === 'GET') {
742
+ // return false
743
+ // }
744
+
745
+ const queryURL = new URL(requestQuery.url)
746
+
747
+ const cachedURL = new URL(request.url)
748
+
749
+ if (options?.ignoreSearch) {
750
+ cachedURL.search = ''
751
+
752
+ queryURL.search = ''
753
+ }
754
+
755
+ if (!urlEquals(queryURL, cachedURL, true)) {
756
+ return false
757
+ }
758
+
759
+ if (
760
+ response == null ||
761
+ options?.ignoreVary ||
762
+ !response.headersList.contains('vary')
763
+ ) {
764
+ return true
765
+ }
766
+
767
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
768
+
769
+ for (const fieldValue of fieldValues) {
770
+ if (fieldValue === '*') {
771
+ return false
772
+ }
773
+
774
+ const requestValue = request.headersList.get(fieldValue)
775
+ const queryValue = requestQuery.headersList.get(fieldValue)
776
+
777
+ // If one has the header and the other doesn't, or one has
778
+ // a different value than the other, return false
779
+ if (requestValue !== queryValue) {
780
+ return false
781
+ }
782
+ }
783
+
784
+ return true
785
+ }
786
+ }
787
+
788
+ Object.defineProperties(Cache.prototype, {
789
+ [Symbol.toStringTag]: {
790
+ value: 'Cache',
791
+ configurable: true
792
+ },
793
+ match: kEnumerableProperty,
794
+ matchAll: kEnumerableProperty,
795
+ add: kEnumerableProperty,
796
+ addAll: kEnumerableProperty,
797
+ put: kEnumerableProperty,
798
+ delete: kEnumerableProperty,
799
+ keys: kEnumerableProperty
800
+ })
801
+
802
+ const cacheQueryOptionConverters = [
803
+ {
804
+ key: 'ignoreSearch',
805
+ converter: webidl.converters.boolean,
806
+ defaultValue: false
807
+ },
808
+ {
809
+ key: 'ignoreMethod',
810
+ converter: webidl.converters.boolean,
811
+ defaultValue: false
812
+ },
813
+ {
814
+ key: 'ignoreVary',
815
+ converter: webidl.converters.boolean,
816
+ defaultValue: false
817
+ }
818
+ ]
819
+
820
+ webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
821
+
822
+ webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
823
+ ...cacheQueryOptionConverters,
824
+ {
825
+ key: 'cacheName',
826
+ converter: webidl.converters.DOMString
827
+ }
828
+ ])
829
+
830
+ webidl.converters.Response = webidl.interfaceConverter(Response)
831
+
832
+ webidl.converters['sequence<RequestInfo>'] = webidl.sequenceConverter(
833
+ webidl.converters.RequestInfo
834
+ )
835
+
836
+ module.exports = {
837
+ Cache
838
+ }
worker/node_modules/undici/lib/cache/cachestorage.js ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { kConstruct } = require('./symbols')
4
+ const { Cache } = require('./cache')
5
+ const { webidl } = require('../fetch/webidl')
6
+ const { kEnumerableProperty } = require('../core/util')
7
+
8
+ class CacheStorage {
9
+ /**
10
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
11
+ * @type {Map<string, import('./cache').requestResponseList}
12
+ */
13
+ #caches = new Map()
14
+
15
+ constructor () {
16
+ if (arguments[0] !== kConstruct) {
17
+ webidl.illegalConstructor()
18
+ }
19
+ }
20
+
21
+ async match (request, options = {}) {
22
+ webidl.brandCheck(this, CacheStorage)
23
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.match' })
24
+
25
+ request = webidl.converters.RequestInfo(request)
26
+ options = webidl.converters.MultiCacheQueryOptions(options)
27
+
28
+ // 1.
29
+ if (options.cacheName != null) {
30
+ // 1.1.1.1
31
+ if (this.#caches.has(options.cacheName)) {
32
+ // 1.1.1.1.1
33
+ const cacheList = this.#caches.get(options.cacheName)
34
+ const cache = new Cache(kConstruct, cacheList)
35
+
36
+ return await cache.match(request, options)
37
+ }
38
+ } else { // 2.
39
+ // 2.2
40
+ for (const cacheList of this.#caches.values()) {
41
+ const cache = new Cache(kConstruct, cacheList)
42
+
43
+ // 2.2.1.2
44
+ const response = await cache.match(request, options)
45
+
46
+ if (response !== undefined) {
47
+ return response
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+ /**
54
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
55
+ * @param {string} cacheName
56
+ * @returns {Promise<boolean>}
57
+ */
58
+ async has (cacheName) {
59
+ webidl.brandCheck(this, CacheStorage)
60
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
61
+
62
+ cacheName = webidl.converters.DOMString(cacheName)
63
+
64
+ // 2.1.1
65
+ // 2.2
66
+ return this.#caches.has(cacheName)
67
+ }
68
+
69
+ /**
70
+ * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
71
+ * @param {string} cacheName
72
+ * @returns {Promise<Cache>}
73
+ */
74
+ async open (cacheName) {
75
+ webidl.brandCheck(this, CacheStorage)
76
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
77
+
78
+ cacheName = webidl.converters.DOMString(cacheName)
79
+
80
+ // 2.1
81
+ if (this.#caches.has(cacheName)) {
82
+ // await caches.open('v1') !== await caches.open('v1')
83
+
84
+ // 2.1.1
85
+ const cache = this.#caches.get(cacheName)
86
+
87
+ // 2.1.1.1
88
+ return new Cache(kConstruct, cache)
89
+ }
90
+
91
+ // 2.2
92
+ const cache = []
93
+
94
+ // 2.3
95
+ this.#caches.set(cacheName, cache)
96
+
97
+ // 2.4
98
+ return new Cache(kConstruct, cache)
99
+ }
100
+
101
+ /**
102
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
103
+ * @param {string} cacheName
104
+ * @returns {Promise<boolean>}
105
+ */
106
+ async delete (cacheName) {
107
+ webidl.brandCheck(this, CacheStorage)
108
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
109
+
110
+ cacheName = webidl.converters.DOMString(cacheName)
111
+
112
+ return this.#caches.delete(cacheName)
113
+ }
114
+
115
+ /**
116
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
117
+ * @returns {string[]}
118
+ */
119
+ async keys () {
120
+ webidl.brandCheck(this, CacheStorage)
121
+
122
+ // 2.1
123
+ const keys = this.#caches.keys()
124
+
125
+ // 2.2
126
+ return [...keys]
127
+ }
128
+ }
129
+
130
+ Object.defineProperties(CacheStorage.prototype, {
131
+ [Symbol.toStringTag]: {
132
+ value: 'CacheStorage',
133
+ configurable: true
134
+ },
135
+ match: kEnumerableProperty,
136
+ has: kEnumerableProperty,
137
+ open: kEnumerableProperty,
138
+ delete: kEnumerableProperty,
139
+ keys: kEnumerableProperty
140
+ })
141
+
142
+ module.exports = {
143
+ CacheStorage
144
+ }
worker/node_modules/undici/lib/cache/symbols.js ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ module.exports = {
4
+ kConstruct: require('../core/symbols').kConstruct
5
+ }
worker/node_modules/undici/lib/cache/util.js ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const assert = require('assert')
4
+ const { URLSerializer } = require('../fetch/dataURL')
5
+ const { isValidHeaderName } = require('../fetch/util')
6
+
7
+ /**
8
+ * @see https://url.spec.whatwg.org/#concept-url-equals
9
+ * @param {URL} A
10
+ * @param {URL} B
11
+ * @param {boolean | undefined} excludeFragment
12
+ * @returns {boolean}
13
+ */
14
+ function urlEquals (A, B, excludeFragment = false) {
15
+ const serializedA = URLSerializer(A, excludeFragment)
16
+
17
+ const serializedB = URLSerializer(B, excludeFragment)
18
+
19
+ return serializedA === serializedB
20
+ }
21
+
22
+ /**
23
+ * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
24
+ * @param {string} header
25
+ */
26
+ function fieldValues (header) {
27
+ assert(header !== null)
28
+
29
+ const values = []
30
+
31
+ for (let value of header.split(',')) {
32
+ value = value.trim()
33
+
34
+ if (!value.length) {
35
+ continue
36
+ } else if (!isValidHeaderName(value)) {
37
+ continue
38
+ }
39
+
40
+ values.push(value)
41
+ }
42
+
43
+ return values
44
+ }
45
+
46
+ module.exports = {
47
+ urlEquals,
48
+ fieldValues
49
+ }
worker/node_modules/undici/lib/client.js ADDED
@@ -0,0 +1,2283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // @ts-check
2
+
3
+ 'use strict'
4
+
5
+ /* global WebAssembly */
6
+
7
+ const assert = require('assert')
8
+ const net = require('net')
9
+ const http = require('http')
10
+ const { pipeline } = require('stream')
11
+ const util = require('./core/util')
12
+ const timers = require('./timers')
13
+ const Request = require('./core/request')
14
+ const DispatcherBase = require('./dispatcher-base')
15
+ const {
16
+ RequestContentLengthMismatchError,
17
+ ResponseContentLengthMismatchError,
18
+ InvalidArgumentError,
19
+ RequestAbortedError,
20
+ HeadersTimeoutError,
21
+ HeadersOverflowError,
22
+ SocketError,
23
+ InformationalError,
24
+ BodyTimeoutError,
25
+ HTTPParserError,
26
+ ResponseExceededMaxSizeError,
27
+ ClientDestroyedError
28
+ } = require('./core/errors')
29
+ const buildConnector = require('./core/connect')
30
+ const {
31
+ kUrl,
32
+ kReset,
33
+ kServerName,
34
+ kClient,
35
+ kBusy,
36
+ kParser,
37
+ kConnect,
38
+ kBlocking,
39
+ kResuming,
40
+ kRunning,
41
+ kPending,
42
+ kSize,
43
+ kWriting,
44
+ kQueue,
45
+ kConnected,
46
+ kConnecting,
47
+ kNeedDrain,
48
+ kNoRef,
49
+ kKeepAliveDefaultTimeout,
50
+ kHostHeader,
51
+ kPendingIdx,
52
+ kRunningIdx,
53
+ kError,
54
+ kPipelining,
55
+ kSocket,
56
+ kKeepAliveTimeoutValue,
57
+ kMaxHeadersSize,
58
+ kKeepAliveMaxTimeout,
59
+ kKeepAliveTimeoutThreshold,
60
+ kHeadersTimeout,
61
+ kBodyTimeout,
62
+ kStrictContentLength,
63
+ kConnector,
64
+ kMaxRedirections,
65
+ kMaxRequests,
66
+ kCounter,
67
+ kClose,
68
+ kDestroy,
69
+ kDispatch,
70
+ kInterceptors,
71
+ kLocalAddress,
72
+ kMaxResponseSize,
73
+ kHTTPConnVersion,
74
+ // HTTP2
75
+ kHost,
76
+ kHTTP2Session,
77
+ kHTTP2SessionState,
78
+ kHTTP2BuildRequest,
79
+ kHTTP2CopyHeaders,
80
+ kHTTP1BuildRequest
81
+ } = require('./core/symbols')
82
+
83
+ /** @type {import('http2')} */
84
+ let http2
85
+ try {
86
+ http2 = require('http2')
87
+ } catch {
88
+ // @ts-ignore
89
+ http2 = { constants: {} }
90
+ }
91
+
92
+ const {
93
+ constants: {
94
+ HTTP2_HEADER_AUTHORITY,
95
+ HTTP2_HEADER_METHOD,
96
+ HTTP2_HEADER_PATH,
97
+ HTTP2_HEADER_SCHEME,
98
+ HTTP2_HEADER_CONTENT_LENGTH,
99
+ HTTP2_HEADER_EXPECT,
100
+ HTTP2_HEADER_STATUS
101
+ }
102
+ } = http2
103
+
104
+ // Experimental
105
+ let h2ExperimentalWarned = false
106
+
107
+ const FastBuffer = Buffer[Symbol.species]
108
+
109
+ const kClosedResolve = Symbol('kClosedResolve')
110
+
111
+ const channels = {}
112
+
113
+ try {
114
+ const diagnosticsChannel = require('diagnostics_channel')
115
+ channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
116
+ channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
117
+ channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
118
+ channels.connected = diagnosticsChannel.channel('undici:client:connected')
119
+ } catch {
120
+ channels.sendHeaders = { hasSubscribers: false }
121
+ channels.beforeConnect = { hasSubscribers: false }
122
+ channels.connectError = { hasSubscribers: false }
123
+ channels.connected = { hasSubscribers: false }
124
+ }
125
+
126
+ /**
127
+ * @type {import('../types/client').default}
128
+ */
129
+ class Client extends DispatcherBase {
130
+ /**
131
+ *
132
+ * @param {string|URL} url
133
+ * @param {import('../types/client').Client.Options} options
134
+ */
135
+ constructor (url, {
136
+ interceptors,
137
+ maxHeaderSize,
138
+ headersTimeout,
139
+ socketTimeout,
140
+ requestTimeout,
141
+ connectTimeout,
142
+ bodyTimeout,
143
+ idleTimeout,
144
+ keepAlive,
145
+ keepAliveTimeout,
146
+ maxKeepAliveTimeout,
147
+ keepAliveMaxTimeout,
148
+ keepAliveTimeoutThreshold,
149
+ socketPath,
150
+ pipelining,
151
+ tls,
152
+ strictContentLength,
153
+ maxCachedSessions,
154
+ maxRedirections,
155
+ connect,
156
+ maxRequestsPerClient,
157
+ localAddress,
158
+ maxResponseSize,
159
+ autoSelectFamily,
160
+ autoSelectFamilyAttemptTimeout,
161
+ // h2
162
+ allowH2,
163
+ maxConcurrentStreams
164
+ } = {}) {
165
+ super()
166
+
167
+ if (keepAlive !== undefined) {
168
+ throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
169
+ }
170
+
171
+ if (socketTimeout !== undefined) {
172
+ throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
173
+ }
174
+
175
+ if (requestTimeout !== undefined) {
176
+ throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
177
+ }
178
+
179
+ if (idleTimeout !== undefined) {
180
+ throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
181
+ }
182
+
183
+ if (maxKeepAliveTimeout !== undefined) {
184
+ throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
185
+ }
186
+
187
+ if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
188
+ throw new InvalidArgumentError('invalid maxHeaderSize')
189
+ }
190
+
191
+ if (socketPath != null && typeof socketPath !== 'string') {
192
+ throw new InvalidArgumentError('invalid socketPath')
193
+ }
194
+
195
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
196
+ throw new InvalidArgumentError('invalid connectTimeout')
197
+ }
198
+
199
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
200
+ throw new InvalidArgumentError('invalid keepAliveTimeout')
201
+ }
202
+
203
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
204
+ throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
205
+ }
206
+
207
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
208
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
209
+ }
210
+
211
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
212
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
213
+ }
214
+
215
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
216
+ throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
217
+ }
218
+
219
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
220
+ throw new InvalidArgumentError('connect must be a function or an object')
221
+ }
222
+
223
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
224
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
225
+ }
226
+
227
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
228
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
229
+ }
230
+
231
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
232
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
233
+ }
234
+
235
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
236
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
237
+ }
238
+
239
+ if (
240
+ autoSelectFamilyAttemptTimeout != null &&
241
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
242
+ ) {
243
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
244
+ }
245
+
246
+ // h2
247
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
248
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
249
+ }
250
+
251
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
252
+ throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
253
+ }
254
+
255
+ if (typeof connect !== 'function') {
256
+ connect = buildConnector({
257
+ ...tls,
258
+ maxCachedSessions,
259
+ allowH2,
260
+ socketPath,
261
+ timeout: connectTimeout,
262
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
263
+ ...connect
264
+ })
265
+ }
266
+
267
+ this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
268
+ ? interceptors.Client
269
+ : [createRedirectInterceptor({ maxRedirections })]
270
+ this[kUrl] = util.parseOrigin(url)
271
+ this[kConnector] = connect
272
+ this[kSocket] = null
273
+ this[kPipelining] = pipelining != null ? pipelining : 1
274
+ this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
275
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
276
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
277
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
278
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
279
+ this[kServerName] = null
280
+ this[kLocalAddress] = localAddress != null ? localAddress : null
281
+ this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
282
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
283
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
284
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
285
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
286
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
287
+ this[kMaxRedirections] = maxRedirections
288
+ this[kMaxRequests] = maxRequestsPerClient
289
+ this[kClosedResolve] = null
290
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
291
+ this[kHTTPConnVersion] = 'h1'
292
+
293
+ // HTTP/2
294
+ this[kHTTP2Session] = null
295
+ this[kHTTP2SessionState] = !allowH2
296
+ ? null
297
+ : {
298
+ // streams: null, // Fixed queue of streams - For future support of `push`
299
+ openStreams: 0, // Keep track of them to decide wether or not unref the session
300
+ maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
301
+ }
302
+ this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
303
+
304
+ // kQueue is built up of 3 sections separated by
305
+ // the kRunningIdx and kPendingIdx indices.
306
+ // | complete | running | pending |
307
+ // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
308
+ // kRunningIdx points to the first running element.
309
+ // kPendingIdx points to the first pending element.
310
+ // This implements a fast queue with an amortized
311
+ // time of O(1).
312
+
313
+ this[kQueue] = []
314
+ this[kRunningIdx] = 0
315
+ this[kPendingIdx] = 0
316
+ }
317
+
318
+ get pipelining () {
319
+ return this[kPipelining]
320
+ }
321
+
322
+ set pipelining (value) {
323
+ this[kPipelining] = value
324
+ resume(this, true)
325
+ }
326
+
327
+ get [kPending] () {
328
+ return this[kQueue].length - this[kPendingIdx]
329
+ }
330
+
331
+ get [kRunning] () {
332
+ return this[kPendingIdx] - this[kRunningIdx]
333
+ }
334
+
335
+ get [kSize] () {
336
+ return this[kQueue].length - this[kRunningIdx]
337
+ }
338
+
339
+ get [kConnected] () {
340
+ return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
341
+ }
342
+
343
+ get [kBusy] () {
344
+ const socket = this[kSocket]
345
+ return (
346
+ (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
347
+ (this[kSize] >= (this[kPipelining] || 1)) ||
348
+ this[kPending] > 0
349
+ )
350
+ }
351
+
352
+ /* istanbul ignore: only used for test */
353
+ [kConnect] (cb) {
354
+ connect(this)
355
+ this.once('connect', cb)
356
+ }
357
+
358
+ [kDispatch] (opts, handler) {
359
+ const origin = opts.origin || this[kUrl].origin
360
+
361
+ const request = this[kHTTPConnVersion] === 'h2'
362
+ ? Request[kHTTP2BuildRequest](origin, opts, handler)
363
+ : Request[kHTTP1BuildRequest](origin, opts, handler)
364
+
365
+ this[kQueue].push(request)
366
+ if (this[kResuming]) {
367
+ // Do nothing.
368
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
369
+ // Wait a tick in case stream/iterator is ended in the same tick.
370
+ this[kResuming] = 1
371
+ process.nextTick(resume, this)
372
+ } else {
373
+ resume(this, true)
374
+ }
375
+
376
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
377
+ this[kNeedDrain] = 2
378
+ }
379
+
380
+ return this[kNeedDrain] < 2
381
+ }
382
+
383
+ async [kClose] () {
384
+ // TODO: for H2 we need to gracefully flush the remaining enqueued
385
+ // request and close each stream.
386
+ return new Promise((resolve) => {
387
+ if (!this[kSize]) {
388
+ resolve(null)
389
+ } else {
390
+ this[kClosedResolve] = resolve
391
+ }
392
+ })
393
+ }
394
+
395
+ async [kDestroy] (err) {
396
+ return new Promise((resolve) => {
397
+ const requests = this[kQueue].splice(this[kPendingIdx])
398
+ for (let i = 0; i < requests.length; i++) {
399
+ const request = requests[i]
400
+ errorRequest(this, request, err)
401
+ }
402
+
403
+ const callback = () => {
404
+ if (this[kClosedResolve]) {
405
+ // TODO (fix): Should we error here with ClientDestroyedError?
406
+ this[kClosedResolve]()
407
+ this[kClosedResolve] = null
408
+ }
409
+ resolve()
410
+ }
411
+
412
+ if (this[kHTTP2Session] != null) {
413
+ util.destroy(this[kHTTP2Session], err)
414
+ this[kHTTP2Session] = null
415
+ this[kHTTP2SessionState] = null
416
+ }
417
+
418
+ if (!this[kSocket]) {
419
+ queueMicrotask(callback)
420
+ } else {
421
+ util.destroy(this[kSocket].on('close', callback), err)
422
+ }
423
+
424
+ resume(this)
425
+ })
426
+ }
427
+ }
428
+
429
+ function onHttp2SessionError (err) {
430
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
431
+
432
+ this[kSocket][kError] = err
433
+
434
+ onError(this[kClient], err)
435
+ }
436
+
437
+ function onHttp2FrameError (type, code, id) {
438
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
439
+
440
+ if (id === 0) {
441
+ this[kSocket][kError] = err
442
+ onError(this[kClient], err)
443
+ }
444
+ }
445
+
446
+ function onHttp2SessionEnd () {
447
+ util.destroy(this, new SocketError('other side closed'))
448
+ util.destroy(this[kSocket], new SocketError('other side closed'))
449
+ }
450
+
451
+ function onHTTP2GoAway (code) {
452
+ const client = this[kClient]
453
+ const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
454
+ client[kSocket] = null
455
+ client[kHTTP2Session] = null
456
+
457
+ if (client.destroyed) {
458
+ assert(this[kPending] === 0)
459
+
460
+ // Fail entire queue.
461
+ const requests = client[kQueue].splice(client[kRunningIdx])
462
+ for (let i = 0; i < requests.length; i++) {
463
+ const request = requests[i]
464
+ errorRequest(this, request, err)
465
+ }
466
+ } else if (client[kRunning] > 0) {
467
+ // Fail head of pipeline.
468
+ const request = client[kQueue][client[kRunningIdx]]
469
+ client[kQueue][client[kRunningIdx]++] = null
470
+
471
+ errorRequest(client, request, err)
472
+ }
473
+
474
+ client[kPendingIdx] = client[kRunningIdx]
475
+
476
+ assert(client[kRunning] === 0)
477
+
478
+ client.emit('disconnect',
479
+ client[kUrl],
480
+ [client],
481
+ err
482
+ )
483
+
484
+ resume(client)
485
+ }
486
+
487
+ const constants = require('./llhttp/constants')
488
+ const createRedirectInterceptor = require('./interceptor/redirectInterceptor')
489
+ const EMPTY_BUF = Buffer.alloc(0)
490
+
491
+ async function lazyllhttp () {
492
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp-wasm.js') : undefined
493
+
494
+ let mod
495
+ try {
496
+ mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd-wasm.js'), 'base64'))
497
+ } catch (e) {
498
+ /* istanbul ignore next */
499
+
500
+ // We could check if the error was caused by the simd option not
501
+ // being enabled, but the occurring of this other error
502
+ // * https://github.com/emscripten-core/emscripten/issues/11495
503
+ // got me to remove that check to avoid breaking Node 12.
504
+ mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp-wasm.js'), 'base64'))
505
+ }
506
+
507
+ return await WebAssembly.instantiate(mod, {
508
+ env: {
509
+ /* eslint-disable camelcase */
510
+
511
+ wasm_on_url: (p, at, len) => {
512
+ /* istanbul ignore next */
513
+ return 0
514
+ },
515
+ wasm_on_status: (p, at, len) => {
516
+ assert.strictEqual(currentParser.ptr, p)
517
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
518
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
519
+ },
520
+ wasm_on_message_begin: (p) => {
521
+ assert.strictEqual(currentParser.ptr, p)
522
+ return currentParser.onMessageBegin() || 0
523
+ },
524
+ wasm_on_header_field: (p, at, len) => {
525
+ assert.strictEqual(currentParser.ptr, p)
526
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
527
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
528
+ },
529
+ wasm_on_header_value: (p, at, len) => {
530
+ assert.strictEqual(currentParser.ptr, p)
531
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
532
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
533
+ },
534
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
535
+ assert.strictEqual(currentParser.ptr, p)
536
+ return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
537
+ },
538
+ wasm_on_body: (p, at, len) => {
539
+ assert.strictEqual(currentParser.ptr, p)
540
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
541
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
542
+ },
543
+ wasm_on_message_complete: (p) => {
544
+ assert.strictEqual(currentParser.ptr, p)
545
+ return currentParser.onMessageComplete() || 0
546
+ }
547
+
548
+ /* eslint-enable camelcase */
549
+ }
550
+ })
551
+ }
552
+
553
+ let llhttpInstance = null
554
+ let llhttpPromise = lazyllhttp()
555
+ llhttpPromise.catch()
556
+
557
+ let currentParser = null
558
+ let currentBufferRef = null
559
+ let currentBufferSize = 0
560
+ let currentBufferPtr = null
561
+
562
+ const TIMEOUT_HEADERS = 1
563
+ const TIMEOUT_BODY = 2
564
+ const TIMEOUT_IDLE = 3
565
+
566
+ class Parser {
567
+ constructor (client, socket, { exports }) {
568
+ assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
569
+
570
+ this.llhttp = exports
571
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
572
+ this.client = client
573
+ this.socket = socket
574
+ this.timeout = null
575
+ this.timeoutValue = null
576
+ this.timeoutType = null
577
+ this.statusCode = null
578
+ this.statusText = ''
579
+ this.upgrade = false
580
+ this.headers = []
581
+ this.headersSize = 0
582
+ this.headersMaxSize = client[kMaxHeadersSize]
583
+ this.shouldKeepAlive = false
584
+ this.paused = false
585
+ this.resume = this.resume.bind(this)
586
+
587
+ this.bytesRead = 0
588
+
589
+ this.keepAlive = ''
590
+ this.contentLength = ''
591
+ this.connection = ''
592
+ this.maxResponseSize = client[kMaxResponseSize]
593
+ }
594
+
595
+ setTimeout (value, type) {
596
+ this.timeoutType = type
597
+ if (value !== this.timeoutValue) {
598
+ timers.clearTimeout(this.timeout)
599
+ if (value) {
600
+ this.timeout = timers.setTimeout(onParserTimeout, value, this)
601
+ // istanbul ignore else: only for jest
602
+ if (this.timeout.unref) {
603
+ this.timeout.unref()
604
+ }
605
+ } else {
606
+ this.timeout = null
607
+ }
608
+ this.timeoutValue = value
609
+ } else if (this.timeout) {
610
+ // istanbul ignore else: only for jest
611
+ if (this.timeout.refresh) {
612
+ this.timeout.refresh()
613
+ }
614
+ }
615
+ }
616
+
617
+ resume () {
618
+ if (this.socket.destroyed || !this.paused) {
619
+ return
620
+ }
621
+
622
+ assert(this.ptr != null)
623
+ assert(currentParser == null)
624
+
625
+ this.llhttp.llhttp_resume(this.ptr)
626
+
627
+ assert(this.timeoutType === TIMEOUT_BODY)
628
+ if (this.timeout) {
629
+ // istanbul ignore else: only for jest
630
+ if (this.timeout.refresh) {
631
+ this.timeout.refresh()
632
+ }
633
+ }
634
+
635
+ this.paused = false
636
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
637
+ this.readMore()
638
+ }
639
+
640
+ readMore () {
641
+ while (!this.paused && this.ptr) {
642
+ const chunk = this.socket.read()
643
+ if (chunk === null) {
644
+ break
645
+ }
646
+ this.execute(chunk)
647
+ }
648
+ }
649
+
650
+ execute (data) {
651
+ assert(this.ptr != null)
652
+ assert(currentParser == null)
653
+ assert(!this.paused)
654
+
655
+ const { socket, llhttp } = this
656
+
657
+ if (data.length > currentBufferSize) {
658
+ if (currentBufferPtr) {
659
+ llhttp.free(currentBufferPtr)
660
+ }
661
+ currentBufferSize = Math.ceil(data.length / 4096) * 4096
662
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
663
+ }
664
+
665
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
666
+
667
+ // Call `execute` on the wasm parser.
668
+ // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
669
+ // and finally the length of bytes to parse.
670
+ // The return value is an error code or `constants.ERROR.OK`.
671
+ try {
672
+ let ret
673
+
674
+ try {
675
+ currentBufferRef = data
676
+ currentParser = this
677
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
678
+ /* eslint-disable-next-line no-useless-catch */
679
+ } catch (err) {
680
+ /* istanbul ignore next: difficult to make a test case for */
681
+ throw err
682
+ } finally {
683
+ currentParser = null
684
+ currentBufferRef = null
685
+ }
686
+
687
+ const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
688
+
689
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
690
+ this.onUpgrade(data.slice(offset))
691
+ } else if (ret === constants.ERROR.PAUSED) {
692
+ this.paused = true
693
+ socket.unshift(data.slice(offset))
694
+ } else if (ret !== constants.ERROR.OK) {
695
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr)
696
+ let message = ''
697
+ /* istanbul ignore else: difficult to make a test case for */
698
+ if (ptr) {
699
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
700
+ message =
701
+ 'Response does not match the HTTP/1.1 protocol (' +
702
+ Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
703
+ ')'
704
+ }
705
+ throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
706
+ }
707
+ } catch (err) {
708
+ util.destroy(socket, err)
709
+ }
710
+ }
711
+
712
+ destroy () {
713
+ assert(this.ptr != null)
714
+ assert(currentParser == null)
715
+
716
+ this.llhttp.llhttp_free(this.ptr)
717
+ this.ptr = null
718
+
719
+ timers.clearTimeout(this.timeout)
720
+ this.timeout = null
721
+ this.timeoutValue = null
722
+ this.timeoutType = null
723
+
724
+ this.paused = false
725
+ }
726
+
727
+ onStatus (buf) {
728
+ this.statusText = buf.toString()
729
+ }
730
+
731
+ onMessageBegin () {
732
+ const { socket, client } = this
733
+
734
+ /* istanbul ignore next: difficult to make a test case for */
735
+ if (socket.destroyed) {
736
+ return -1
737
+ }
738
+
739
+ const request = client[kQueue][client[kRunningIdx]]
740
+ if (!request) {
741
+ return -1
742
+ }
743
+ }
744
+
745
+ onHeaderField (buf) {
746
+ const len = this.headers.length
747
+
748
+ if ((len & 1) === 0) {
749
+ this.headers.push(buf)
750
+ } else {
751
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
752
+ }
753
+
754
+ this.trackHeader(buf.length)
755
+ }
756
+
757
+ onHeaderValue (buf) {
758
+ let len = this.headers.length
759
+
760
+ if ((len & 1) === 1) {
761
+ this.headers.push(buf)
762
+ len += 1
763
+ } else {
764
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
765
+ }
766
+
767
+ const key = this.headers[len - 2]
768
+ if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
769
+ this.keepAlive += buf.toString()
770
+ } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
771
+ this.connection += buf.toString()
772
+ } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
773
+ this.contentLength += buf.toString()
774
+ }
775
+
776
+ this.trackHeader(buf.length)
777
+ }
778
+
779
+ trackHeader (len) {
780
+ this.headersSize += len
781
+ if (this.headersSize >= this.headersMaxSize) {
782
+ util.destroy(this.socket, new HeadersOverflowError())
783
+ }
784
+ }
785
+
786
+ onUpgrade (head) {
787
+ const { upgrade, client, socket, headers, statusCode } = this
788
+
789
+ assert(upgrade)
790
+
791
+ const request = client[kQueue][client[kRunningIdx]]
792
+ assert(request)
793
+
794
+ assert(!socket.destroyed)
795
+ assert(socket === client[kSocket])
796
+ assert(!this.paused)
797
+ assert(request.upgrade || request.method === 'CONNECT')
798
+
799
+ this.statusCode = null
800
+ this.statusText = ''
801
+ this.shouldKeepAlive = null
802
+
803
+ assert(this.headers.length % 2 === 0)
804
+ this.headers = []
805
+ this.headersSize = 0
806
+
807
+ socket.unshift(head)
808
+
809
+ socket[kParser].destroy()
810
+ socket[kParser] = null
811
+
812
+ socket[kClient] = null
813
+ socket[kError] = null
814
+ socket
815
+ .removeListener('error', onSocketError)
816
+ .removeListener('readable', onSocketReadable)
817
+ .removeListener('end', onSocketEnd)
818
+ .removeListener('close', onSocketClose)
819
+
820
+ client[kSocket] = null
821
+ client[kQueue][client[kRunningIdx]++] = null
822
+ client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
823
+
824
+ try {
825
+ request.onUpgrade(statusCode, headers, socket)
826
+ } catch (err) {
827
+ util.destroy(socket, err)
828
+ }
829
+
830
+ resume(client)
831
+ }
832
+
833
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
834
+ const { client, socket, headers, statusText } = this
835
+
836
+ /* istanbul ignore next: difficult to make a test case for */
837
+ if (socket.destroyed) {
838
+ return -1
839
+ }
840
+
841
+ const request = client[kQueue][client[kRunningIdx]]
842
+
843
+ /* istanbul ignore next: difficult to make a test case for */
844
+ if (!request) {
845
+ return -1
846
+ }
847
+
848
+ assert(!this.upgrade)
849
+ assert(this.statusCode < 200)
850
+
851
+ if (statusCode === 100) {
852
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
853
+ return -1
854
+ }
855
+
856
+ /* this can only happen if server is misbehaving */
857
+ if (upgrade && !request.upgrade) {
858
+ util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
859
+ return -1
860
+ }
861
+
862
+ assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
863
+
864
+ this.statusCode = statusCode
865
+ this.shouldKeepAlive = (
866
+ shouldKeepAlive ||
867
+ // Override llhttp value which does not allow keepAlive for HEAD.
868
+ (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
869
+ )
870
+
871
+ if (this.statusCode >= 200) {
872
+ const bodyTimeout = request.bodyTimeout != null
873
+ ? request.bodyTimeout
874
+ : client[kBodyTimeout]
875
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY)
876
+ } else if (this.timeout) {
877
+ // istanbul ignore else: only for jest
878
+ if (this.timeout.refresh) {
879
+ this.timeout.refresh()
880
+ }
881
+ }
882
+
883
+ if (request.method === 'CONNECT') {
884
+ assert(client[kRunning] === 1)
885
+ this.upgrade = true
886
+ return 2
887
+ }
888
+
889
+ if (upgrade) {
890
+ assert(client[kRunning] === 1)
891
+ this.upgrade = true
892
+ return 2
893
+ }
894
+
895
+ assert(this.headers.length % 2 === 0)
896
+ this.headers = []
897
+ this.headersSize = 0
898
+
899
+ if (this.shouldKeepAlive && client[kPipelining]) {
900
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
901
+
902
+ if (keepAliveTimeout != null) {
903
+ const timeout = Math.min(
904
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
905
+ client[kKeepAliveMaxTimeout]
906
+ )
907
+ if (timeout <= 0) {
908
+ socket[kReset] = true
909
+ } else {
910
+ client[kKeepAliveTimeoutValue] = timeout
911
+ }
912
+ } else {
913
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
914
+ }
915
+ } else {
916
+ // Stop more requests from being dispatched.
917
+ socket[kReset] = true
918
+ }
919
+
920
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
921
+
922
+ if (request.aborted) {
923
+ return -1
924
+ }
925
+
926
+ if (request.method === 'HEAD') {
927
+ return 1
928
+ }
929
+
930
+ if (statusCode < 200) {
931
+ return 1
932
+ }
933
+
934
+ if (socket[kBlocking]) {
935
+ socket[kBlocking] = false
936
+ resume(client)
937
+ }
938
+
939
+ return pause ? constants.ERROR.PAUSED : 0
940
+ }
941
+
942
+ onBody (buf) {
943
+ const { client, socket, statusCode, maxResponseSize } = this
944
+
945
+ if (socket.destroyed) {
946
+ return -1
947
+ }
948
+
949
+ const request = client[kQueue][client[kRunningIdx]]
950
+ assert(request)
951
+
952
+ assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
953
+ if (this.timeout) {
954
+ // istanbul ignore else: only for jest
955
+ if (this.timeout.refresh) {
956
+ this.timeout.refresh()
957
+ }
958
+ }
959
+
960
+ assert(statusCode >= 200)
961
+
962
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
963
+ util.destroy(socket, new ResponseExceededMaxSizeError())
964
+ return -1
965
+ }
966
+
967
+ this.bytesRead += buf.length
968
+
969
+ if (request.onData(buf) === false) {
970
+ return constants.ERROR.PAUSED
971
+ }
972
+ }
973
+
974
+ onMessageComplete () {
975
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
976
+
977
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
978
+ return -1
979
+ }
980
+
981
+ if (upgrade) {
982
+ return
983
+ }
984
+
985
+ const request = client[kQueue][client[kRunningIdx]]
986
+ assert(request)
987
+
988
+ assert(statusCode >= 100)
989
+
990
+ this.statusCode = null
991
+ this.statusText = ''
992
+ this.bytesRead = 0
993
+ this.contentLength = ''
994
+ this.keepAlive = ''
995
+ this.connection = ''
996
+
997
+ assert(this.headers.length % 2 === 0)
998
+ this.headers = []
999
+ this.headersSize = 0
1000
+
1001
+ if (statusCode < 200) {
1002
+ return
1003
+ }
1004
+
1005
+ /* istanbul ignore next: should be handled by llhttp? */
1006
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
1007
+ util.destroy(socket, new ResponseContentLengthMismatchError())
1008
+ return -1
1009
+ }
1010
+
1011
+ request.onComplete(headers)
1012
+
1013
+ client[kQueue][client[kRunningIdx]++] = null
1014
+
1015
+ if (socket[kWriting]) {
1016
+ assert.strictEqual(client[kRunning], 0)
1017
+ // Response completed before request.
1018
+ util.destroy(socket, new InformationalError('reset'))
1019
+ return constants.ERROR.PAUSED
1020
+ } else if (!shouldKeepAlive) {
1021
+ util.destroy(socket, new InformationalError('reset'))
1022
+ return constants.ERROR.PAUSED
1023
+ } else if (socket[kReset] && client[kRunning] === 0) {
1024
+ // Destroy socket once all requests have completed.
1025
+ // The request at the tail of the pipeline is the one
1026
+ // that requested reset and no further requests should
1027
+ // have been queued since then.
1028
+ util.destroy(socket, new InformationalError('reset'))
1029
+ return constants.ERROR.PAUSED
1030
+ } else if (client[kPipelining] === 1) {
1031
+ // We must wait a full event loop cycle to reuse this socket to make sure
1032
+ // that non-spec compliant servers are not closing the connection even if they
1033
+ // said they won't.
1034
+ setImmediate(resume, client)
1035
+ } else {
1036
+ resume(client)
1037
+ }
1038
+ }
1039
+ }
1040
+
1041
+ function onParserTimeout (parser) {
1042
+ const { socket, timeoutType, client } = parser
1043
+
1044
+ /* istanbul ignore else */
1045
+ if (timeoutType === TIMEOUT_HEADERS) {
1046
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
1047
+ assert(!parser.paused, 'cannot be paused while waiting for headers')
1048
+ util.destroy(socket, new HeadersTimeoutError())
1049
+ }
1050
+ } else if (timeoutType === TIMEOUT_BODY) {
1051
+ if (!parser.paused) {
1052
+ util.destroy(socket, new BodyTimeoutError())
1053
+ }
1054
+ } else if (timeoutType === TIMEOUT_IDLE) {
1055
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
1056
+ util.destroy(socket, new InformationalError('socket idle timeout'))
1057
+ }
1058
+ }
1059
+
1060
+ function onSocketReadable () {
1061
+ const { [kParser]: parser } = this
1062
+ if (parser) {
1063
+ parser.readMore()
1064
+ }
1065
+ }
1066
+
1067
+ function onSocketError (err) {
1068
+ const { [kClient]: client, [kParser]: parser } = this
1069
+
1070
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
1071
+
1072
+ if (client[kHTTPConnVersion] !== 'h2') {
1073
+ // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
1074
+ // to the user.
1075
+ if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
1076
+ // We treat all incoming data so for as a valid response.
1077
+ parser.onMessageComplete()
1078
+ return
1079
+ }
1080
+ }
1081
+
1082
+ this[kError] = err
1083
+
1084
+ onError(this[kClient], err)
1085
+ }
1086
+
1087
+ function onError (client, err) {
1088
+ if (
1089
+ client[kRunning] === 0 &&
1090
+ err.code !== 'UND_ERR_INFO' &&
1091
+ err.code !== 'UND_ERR_SOCKET'
1092
+ ) {
1093
+ // Error is not caused by running request and not a recoverable
1094
+ // socket error.
1095
+
1096
+ assert(client[kPendingIdx] === client[kRunningIdx])
1097
+
1098
+ const requests = client[kQueue].splice(client[kRunningIdx])
1099
+ for (let i = 0; i < requests.length; i++) {
1100
+ const request = requests[i]
1101
+ errorRequest(client, request, err)
1102
+ }
1103
+ assert(client[kSize] === 0)
1104
+ }
1105
+ }
1106
+
1107
+ function onSocketEnd () {
1108
+ const { [kParser]: parser, [kClient]: client } = this
1109
+
1110
+ if (client[kHTTPConnVersion] !== 'h2') {
1111
+ if (parser.statusCode && !parser.shouldKeepAlive) {
1112
+ // We treat all incoming data so far as a valid response.
1113
+ parser.onMessageComplete()
1114
+ return
1115
+ }
1116
+ }
1117
+
1118
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
1119
+ }
1120
+
1121
+ function onSocketClose () {
1122
+ const { [kClient]: client, [kParser]: parser } = this
1123
+
1124
+ if (client[kHTTPConnVersion] === 'h1' && parser) {
1125
+ if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
1126
+ // We treat all incoming data so far as a valid response.
1127
+ parser.onMessageComplete()
1128
+ }
1129
+
1130
+ this[kParser].destroy()
1131
+ this[kParser] = null
1132
+ }
1133
+
1134
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
1135
+
1136
+ client[kSocket] = null
1137
+
1138
+ if (client.destroyed) {
1139
+ assert(client[kPending] === 0)
1140
+
1141
+ // Fail entire queue.
1142
+ const requests = client[kQueue].splice(client[kRunningIdx])
1143
+ for (let i = 0; i < requests.length; i++) {
1144
+ const request = requests[i]
1145
+ errorRequest(client, request, err)
1146
+ }
1147
+ } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
1148
+ // Fail head of pipeline.
1149
+ const request = client[kQueue][client[kRunningIdx]]
1150
+ client[kQueue][client[kRunningIdx]++] = null
1151
+
1152
+ errorRequest(client, request, err)
1153
+ }
1154
+
1155
+ client[kPendingIdx] = client[kRunningIdx]
1156
+
1157
+ assert(client[kRunning] === 0)
1158
+
1159
+ client.emit('disconnect', client[kUrl], [client], err)
1160
+
1161
+ resume(client)
1162
+ }
1163
+
1164
+ async function connect (client) {
1165
+ assert(!client[kConnecting])
1166
+ assert(!client[kSocket])
1167
+
1168
+ let { host, hostname, protocol, port } = client[kUrl]
1169
+
1170
+ // Resolve ipv6
1171
+ if (hostname[0] === '[') {
1172
+ const idx = hostname.indexOf(']')
1173
+
1174
+ assert(idx !== -1)
1175
+ const ip = hostname.substring(1, idx)
1176
+
1177
+ assert(net.isIP(ip))
1178
+ hostname = ip
1179
+ }
1180
+
1181
+ client[kConnecting] = true
1182
+
1183
+ if (channels.beforeConnect.hasSubscribers) {
1184
+ channels.beforeConnect.publish({
1185
+ connectParams: {
1186
+ host,
1187
+ hostname,
1188
+ protocol,
1189
+ port,
1190
+ servername: client[kServerName],
1191
+ localAddress: client[kLocalAddress]
1192
+ },
1193
+ connector: client[kConnector]
1194
+ })
1195
+ }
1196
+
1197
+ try {
1198
+ const socket = await new Promise((resolve, reject) => {
1199
+ client[kConnector]({
1200
+ host,
1201
+ hostname,
1202
+ protocol,
1203
+ port,
1204
+ servername: client[kServerName],
1205
+ localAddress: client[kLocalAddress]
1206
+ }, (err, socket) => {
1207
+ if (err) {
1208
+ reject(err)
1209
+ } else {
1210
+ resolve(socket)
1211
+ }
1212
+ })
1213
+ })
1214
+
1215
+ if (client.destroyed) {
1216
+ util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
1217
+ return
1218
+ }
1219
+
1220
+ client[kConnecting] = false
1221
+
1222
+ assert(socket)
1223
+
1224
+ const isH2 = socket.alpnProtocol === 'h2'
1225
+ if (isH2) {
1226
+ if (!h2ExperimentalWarned) {
1227
+ h2ExperimentalWarned = true
1228
+ process.emitWarning('H2 support is experimental, expect them to change at any time.', {
1229
+ code: 'UNDICI-H2'
1230
+ })
1231
+ }
1232
+
1233
+ const session = http2.connect(client[kUrl], {
1234
+ createConnection: () => socket,
1235
+ peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
1236
+ })
1237
+
1238
+ client[kHTTPConnVersion] = 'h2'
1239
+ session[kClient] = client
1240
+ session[kSocket] = socket
1241
+ session.on('error', onHttp2SessionError)
1242
+ session.on('frameError', onHttp2FrameError)
1243
+ session.on('end', onHttp2SessionEnd)
1244
+ session.on('goaway', onHTTP2GoAway)
1245
+ session.on('close', onSocketClose)
1246
+ session.unref()
1247
+
1248
+ client[kHTTP2Session] = session
1249
+ socket[kHTTP2Session] = session
1250
+ } else {
1251
+ if (!llhttpInstance) {
1252
+ llhttpInstance = await llhttpPromise
1253
+ llhttpPromise = null
1254
+ }
1255
+
1256
+ socket[kNoRef] = false
1257
+ socket[kWriting] = false
1258
+ socket[kReset] = false
1259
+ socket[kBlocking] = false
1260
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
1261
+ }
1262
+
1263
+ socket[kCounter] = 0
1264
+ socket[kMaxRequests] = client[kMaxRequests]
1265
+ socket[kClient] = client
1266
+ socket[kError] = null
1267
+
1268
+ socket
1269
+ .on('error', onSocketError)
1270
+ .on('readable', onSocketReadable)
1271
+ .on('end', onSocketEnd)
1272
+ .on('close', onSocketClose)
1273
+
1274
+ client[kSocket] = socket
1275
+
1276
+ if (channels.connected.hasSubscribers) {
1277
+ channels.connected.publish({
1278
+ connectParams: {
1279
+ host,
1280
+ hostname,
1281
+ protocol,
1282
+ port,
1283
+ servername: client[kServerName],
1284
+ localAddress: client[kLocalAddress]
1285
+ },
1286
+ connector: client[kConnector],
1287
+ socket
1288
+ })
1289
+ }
1290
+ client.emit('connect', client[kUrl], [client])
1291
+ } catch (err) {
1292
+ if (client.destroyed) {
1293
+ return
1294
+ }
1295
+
1296
+ client[kConnecting] = false
1297
+
1298
+ if (channels.connectError.hasSubscribers) {
1299
+ channels.connectError.publish({
1300
+ connectParams: {
1301
+ host,
1302
+ hostname,
1303
+ protocol,
1304
+ port,
1305
+ servername: client[kServerName],
1306
+ localAddress: client[kLocalAddress]
1307
+ },
1308
+ connector: client[kConnector],
1309
+ error: err
1310
+ })
1311
+ }
1312
+
1313
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
1314
+ assert(client[kRunning] === 0)
1315
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
1316
+ const request = client[kQueue][client[kPendingIdx]++]
1317
+ errorRequest(client, request, err)
1318
+ }
1319
+ } else {
1320
+ onError(client, err)
1321
+ }
1322
+
1323
+ client.emit('connectionError', client[kUrl], [client], err)
1324
+ }
1325
+
1326
+ resume(client)
1327
+ }
1328
+
1329
+ function emitDrain (client) {
1330
+ client[kNeedDrain] = 0
1331
+ client.emit('drain', client[kUrl], [client])
1332
+ }
1333
+
1334
+ function resume (client, sync) {
1335
+ if (client[kResuming] === 2) {
1336
+ return
1337
+ }
1338
+
1339
+ client[kResuming] = 2
1340
+
1341
+ _resume(client, sync)
1342
+ client[kResuming] = 0
1343
+
1344
+ if (client[kRunningIdx] > 256) {
1345
+ client[kQueue].splice(0, client[kRunningIdx])
1346
+ client[kPendingIdx] -= client[kRunningIdx]
1347
+ client[kRunningIdx] = 0
1348
+ }
1349
+ }
1350
+
1351
+ function _resume (client, sync) {
1352
+ while (true) {
1353
+ if (client.destroyed) {
1354
+ assert(client[kPending] === 0)
1355
+ return
1356
+ }
1357
+
1358
+ if (client[kClosedResolve] && !client[kSize]) {
1359
+ client[kClosedResolve]()
1360
+ client[kClosedResolve] = null
1361
+ return
1362
+ }
1363
+
1364
+ const socket = client[kSocket]
1365
+
1366
+ if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
1367
+ if (client[kSize] === 0) {
1368
+ if (!socket[kNoRef] && socket.unref) {
1369
+ socket.unref()
1370
+ socket[kNoRef] = true
1371
+ }
1372
+ } else if (socket[kNoRef] && socket.ref) {
1373
+ socket.ref()
1374
+ socket[kNoRef] = false
1375
+ }
1376
+
1377
+ if (client[kSize] === 0) {
1378
+ if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
1379
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
1380
+ }
1381
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
1382
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
1383
+ const request = client[kQueue][client[kRunningIdx]]
1384
+ const headersTimeout = request.headersTimeout != null
1385
+ ? request.headersTimeout
1386
+ : client[kHeadersTimeout]
1387
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
1388
+ }
1389
+ }
1390
+ }
1391
+
1392
+ if (client[kBusy]) {
1393
+ client[kNeedDrain] = 2
1394
+ } else if (client[kNeedDrain] === 2) {
1395
+ if (sync) {
1396
+ client[kNeedDrain] = 1
1397
+ process.nextTick(emitDrain, client)
1398
+ } else {
1399
+ emitDrain(client)
1400
+ }
1401
+ continue
1402
+ }
1403
+
1404
+ if (client[kPending] === 0) {
1405
+ return
1406
+ }
1407
+
1408
+ if (client[kRunning] >= (client[kPipelining] || 1)) {
1409
+ return
1410
+ }
1411
+
1412
+ const request = client[kQueue][client[kPendingIdx]]
1413
+
1414
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
1415
+ if (client[kRunning] > 0) {
1416
+ return
1417
+ }
1418
+
1419
+ client[kServerName] = request.servername
1420
+
1421
+ if (socket && socket.servername !== request.servername) {
1422
+ util.destroy(socket, new InformationalError('servername changed'))
1423
+ return
1424
+ }
1425
+ }
1426
+
1427
+ if (client[kConnecting]) {
1428
+ return
1429
+ }
1430
+
1431
+ if (!socket && !client[kHTTP2Session]) {
1432
+ connect(client)
1433
+ return
1434
+ }
1435
+
1436
+ if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
1437
+ return
1438
+ }
1439
+
1440
+ if (client[kRunning] > 0 && !request.idempotent) {
1441
+ // Non-idempotent request cannot be retried.
1442
+ // Ensure that no other requests are inflight and
1443
+ // could cause failure.
1444
+ return
1445
+ }
1446
+
1447
+ if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
1448
+ // Don't dispatch an upgrade until all preceding requests have completed.
1449
+ // A misbehaving server might upgrade the connection before all pipelined
1450
+ // request has completed.
1451
+ return
1452
+ }
1453
+
1454
+ if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
1455
+ (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
1456
+ // Request with stream or iterator body can error while other requests
1457
+ // are inflight and indirectly error those as well.
1458
+ // Ensure this doesn't happen by waiting for inflight
1459
+ // to complete before dispatching.
1460
+
1461
+ // Request with stream or iterator body cannot be retried.
1462
+ // Ensure that no other requests are inflight and
1463
+ // could cause failure.
1464
+ return
1465
+ }
1466
+
1467
+ if (!request.aborted && write(client, request)) {
1468
+ client[kPendingIdx]++
1469
+ } else {
1470
+ client[kQueue].splice(client[kPendingIdx], 1)
1471
+ }
1472
+ }
1473
+ }
1474
+
1475
+ // https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
1476
+ function shouldSendContentLength (method) {
1477
+ return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
1478
+ }
1479
+
1480
+ function write (client, request) {
1481
+ if (client[kHTTPConnVersion] === 'h2') {
1482
+ writeH2(client, client[kHTTP2Session], request)
1483
+ return
1484
+ }
1485
+
1486
+ const { body, method, path, host, upgrade, headers, blocking, reset } = request
1487
+
1488
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
1489
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
1490
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
1491
+
1492
+ // Sending a payload body on a request that does not
1493
+ // expect it can cause undefined behavior on some
1494
+ // servers and corrupt connection state. Do not
1495
+ // re-use the connection for further requests.
1496
+
1497
+ const expectsPayload = (
1498
+ method === 'PUT' ||
1499
+ method === 'POST' ||
1500
+ method === 'PATCH'
1501
+ )
1502
+
1503
+ if (body && typeof body.read === 'function') {
1504
+ // Try to read EOF in order to get length.
1505
+ body.read(0)
1506
+ }
1507
+
1508
+ const bodyLength = util.bodyLength(body)
1509
+
1510
+ let contentLength = bodyLength
1511
+
1512
+ if (contentLength === null) {
1513
+ contentLength = request.contentLength
1514
+ }
1515
+
1516
+ if (contentLength === 0 && !expectsPayload) {
1517
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
1518
+ // A user agent SHOULD NOT send a Content-Length header field when
1519
+ // the request message does not contain a payload body and the method
1520
+ // semantics do not anticipate such a body.
1521
+
1522
+ contentLength = null
1523
+ }
1524
+
1525
+ // https://github.com/nodejs/undici/issues/2046
1526
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
1527
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
1528
+ if (client[kStrictContentLength]) {
1529
+ errorRequest(client, request, new RequestContentLengthMismatchError())
1530
+ return false
1531
+ }
1532
+
1533
+ process.emitWarning(new RequestContentLengthMismatchError())
1534
+ }
1535
+
1536
+ const socket = client[kSocket]
1537
+
1538
+ try {
1539
+ request.onConnect((err) => {
1540
+ if (request.aborted || request.completed) {
1541
+ return
1542
+ }
1543
+
1544
+ errorRequest(client, request, err || new RequestAbortedError())
1545
+
1546
+ util.destroy(socket, new InformationalError('aborted'))
1547
+ })
1548
+ } catch (err) {
1549
+ errorRequest(client, request, err)
1550
+ }
1551
+
1552
+ if (request.aborted) {
1553
+ return false
1554
+ }
1555
+
1556
+ if (method === 'HEAD') {
1557
+ // https://github.com/mcollina/undici/issues/258
1558
+ // Close after a HEAD request to interop with misbehaving servers
1559
+ // that may send a body in the response.
1560
+
1561
+ socket[kReset] = true
1562
+ }
1563
+
1564
+ if (upgrade || method === 'CONNECT') {
1565
+ // On CONNECT or upgrade, block pipeline from dispatching further
1566
+ // requests on this connection.
1567
+
1568
+ socket[kReset] = true
1569
+ }
1570
+
1571
+ if (reset != null) {
1572
+ socket[kReset] = reset
1573
+ }
1574
+
1575
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
1576
+ socket[kReset] = true
1577
+ }
1578
+
1579
+ if (blocking) {
1580
+ socket[kBlocking] = true
1581
+ }
1582
+
1583
+ let header = `${method} ${path} HTTP/1.1\r\n`
1584
+
1585
+ if (typeof host === 'string') {
1586
+ header += `host: ${host}\r\n`
1587
+ } else {
1588
+ header += client[kHostHeader]
1589
+ }
1590
+
1591
+ if (upgrade) {
1592
+ header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
1593
+ } else if (client[kPipelining] && !socket[kReset]) {
1594
+ header += 'connection: keep-alive\r\n'
1595
+ } else {
1596
+ header += 'connection: close\r\n'
1597
+ }
1598
+
1599
+ if (headers) {
1600
+ header += headers
1601
+ }
1602
+
1603
+ if (channels.sendHeaders.hasSubscribers) {
1604
+ channels.sendHeaders.publish({ request, headers: header, socket })
1605
+ }
1606
+
1607
+ /* istanbul ignore else: assertion */
1608
+ if (!body || bodyLength === 0) {
1609
+ if (contentLength === 0) {
1610
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
1611
+ } else {
1612
+ assert(contentLength === null, 'no body must not have content length')
1613
+ socket.write(`${header}\r\n`, 'latin1')
1614
+ }
1615
+ request.onRequestSent()
1616
+ } else if (util.isBuffer(body)) {
1617
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
1618
+
1619
+ socket.cork()
1620
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
1621
+ socket.write(body)
1622
+ socket.uncork()
1623
+ request.onBodySent(body)
1624
+ request.onRequestSent()
1625
+ if (!expectsPayload) {
1626
+ socket[kReset] = true
1627
+ }
1628
+ } else if (util.isBlobLike(body)) {
1629
+ if (typeof body.stream === 'function') {
1630
+ writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
1631
+ } else {
1632
+ writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
1633
+ }
1634
+ } else if (util.isStream(body)) {
1635
+ writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
1636
+ } else if (util.isIterable(body)) {
1637
+ writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
1638
+ } else {
1639
+ assert(false)
1640
+ }
1641
+
1642
+ return true
1643
+ }
1644
+
1645
+ function writeH2 (client, session, request) {
1646
+ const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
1647
+
1648
+ let headers
1649
+ if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
1650
+ else headers = reqHeaders
1651
+
1652
+ if (upgrade) {
1653
+ errorRequest(client, request, new Error('Upgrade not supported for H2'))
1654
+ return false
1655
+ }
1656
+
1657
+ try {
1658
+ // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
1659
+ request.onConnect((err) => {
1660
+ if (request.aborted || request.completed) {
1661
+ return
1662
+ }
1663
+
1664
+ errorRequest(client, request, err || new RequestAbortedError())
1665
+ })
1666
+ } catch (err) {
1667
+ errorRequest(client, request, err)
1668
+ }
1669
+
1670
+ if (request.aborted) {
1671
+ return false
1672
+ }
1673
+
1674
+ /** @type {import('node:http2').ClientHttp2Stream} */
1675
+ let stream
1676
+ const h2State = client[kHTTP2SessionState]
1677
+
1678
+ headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
1679
+ headers[HTTP2_HEADER_METHOD] = method
1680
+
1681
+ if (method === 'CONNECT') {
1682
+ session.ref()
1683
+ // we are already connected, streams are pending, first request
1684
+ // will create a new stream. We trigger a request to create the stream and wait until
1685
+ // `ready` event is triggered
1686
+ // We disabled endStream to allow the user to write to the stream
1687
+ stream = session.request(headers, { endStream: false, signal })
1688
+
1689
+ if (stream.id && !stream.pending) {
1690
+ request.onUpgrade(null, null, stream)
1691
+ ++h2State.openStreams
1692
+ } else {
1693
+ stream.once('ready', () => {
1694
+ request.onUpgrade(null, null, stream)
1695
+ ++h2State.openStreams
1696
+ })
1697
+ }
1698
+
1699
+ stream.once('close', () => {
1700
+ h2State.openStreams -= 1
1701
+ // TODO(HTTP/2): unref only if current streams count is 0
1702
+ if (h2State.openStreams === 0) session.unref()
1703
+ })
1704
+
1705
+ return true
1706
+ }
1707
+
1708
+ // https://tools.ietf.org/html/rfc7540#section-8.3
1709
+ // :path and :scheme headers must be omited when sending CONNECT
1710
+
1711
+ headers[HTTP2_HEADER_PATH] = path
1712
+ headers[HTTP2_HEADER_SCHEME] = 'https'
1713
+
1714
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
1715
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
1716
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
1717
+
1718
+ // Sending a payload body on a request that does not
1719
+ // expect it can cause undefined behavior on some
1720
+ // servers and corrupt connection state. Do not
1721
+ // re-use the connection for further requests.
1722
+
1723
+ const expectsPayload = (
1724
+ method === 'PUT' ||
1725
+ method === 'POST' ||
1726
+ method === 'PATCH'
1727
+ )
1728
+
1729
+ if (body && typeof body.read === 'function') {
1730
+ // Try to read EOF in order to get length.
1731
+ body.read(0)
1732
+ }
1733
+
1734
+ let contentLength = util.bodyLength(body)
1735
+
1736
+ if (contentLength == null) {
1737
+ contentLength = request.contentLength
1738
+ }
1739
+
1740
+ if (contentLength === 0 || !expectsPayload) {
1741
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
1742
+ // A user agent SHOULD NOT send a Content-Length header field when
1743
+ // the request message does not contain a payload body and the method
1744
+ // semantics do not anticipate such a body.
1745
+
1746
+ contentLength = null
1747
+ }
1748
+
1749
+ // https://github.com/nodejs/undici/issues/2046
1750
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
1751
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
1752
+ if (client[kStrictContentLength]) {
1753
+ errorRequest(client, request, new RequestContentLengthMismatchError())
1754
+ return false
1755
+ }
1756
+
1757
+ process.emitWarning(new RequestContentLengthMismatchError())
1758
+ }
1759
+
1760
+ if (contentLength != null) {
1761
+ assert(body, 'no body must not have content length')
1762
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
1763
+ }
1764
+
1765
+ session.ref()
1766
+
1767
+ const shouldEndStream = method === 'GET' || method === 'HEAD'
1768
+ if (expectContinue) {
1769
+ headers[HTTP2_HEADER_EXPECT] = '100-continue'
1770
+ stream = session.request(headers, { endStream: shouldEndStream, signal })
1771
+
1772
+ stream.once('continue', writeBodyH2)
1773
+ } else {
1774
+ stream = session.request(headers, {
1775
+ endStream: shouldEndStream,
1776
+ signal
1777
+ })
1778
+ writeBodyH2()
1779
+ }
1780
+
1781
+ // Increment counter as we have new several streams open
1782
+ ++h2State.openStreams
1783
+
1784
+ stream.once('response', headers => {
1785
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
1786
+
1787
+ if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
1788
+ stream.pause()
1789
+ }
1790
+ })
1791
+
1792
+ stream.once('end', () => {
1793
+ request.onComplete([])
1794
+ })
1795
+
1796
+ stream.on('data', (chunk) => {
1797
+ if (request.onData(chunk) === false) {
1798
+ stream.pause()
1799
+ }
1800
+ })
1801
+
1802
+ stream.once('close', () => {
1803
+ h2State.openStreams -= 1
1804
+ // TODO(HTTP/2): unref only if current streams count is 0
1805
+ if (h2State.openStreams === 0) {
1806
+ session.unref()
1807
+ }
1808
+ })
1809
+
1810
+ stream.once('error', function (err) {
1811
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
1812
+ h2State.streams -= 1
1813
+ util.destroy(stream, err)
1814
+ }
1815
+ })
1816
+
1817
+ stream.once('frameError', (type, code) => {
1818
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
1819
+ errorRequest(client, request, err)
1820
+
1821
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
1822
+ h2State.streams -= 1
1823
+ util.destroy(stream, err)
1824
+ }
1825
+ })
1826
+
1827
+ // stream.on('aborted', () => {
1828
+ // // TODO(HTTP/2): Support aborted
1829
+ // })
1830
+
1831
+ // stream.on('timeout', () => {
1832
+ // // TODO(HTTP/2): Support timeout
1833
+ // })
1834
+
1835
+ // stream.on('push', headers => {
1836
+ // // TODO(HTTP/2): Suppor push
1837
+ // })
1838
+
1839
+ // stream.on('trailers', headers => {
1840
+ // // TODO(HTTP/2): Support trailers
1841
+ // })
1842
+
1843
+ return true
1844
+
1845
+ function writeBodyH2 () {
1846
+ /* istanbul ignore else: assertion */
1847
+ if (!body) {
1848
+ request.onRequestSent()
1849
+ } else if (util.isBuffer(body)) {
1850
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
1851
+ stream.cork()
1852
+ stream.write(body)
1853
+ stream.uncork()
1854
+ stream.end()
1855
+ request.onBodySent(body)
1856
+ request.onRequestSent()
1857
+ } else if (util.isBlobLike(body)) {
1858
+ if (typeof body.stream === 'function') {
1859
+ writeIterable({
1860
+ client,
1861
+ request,
1862
+ contentLength,
1863
+ h2stream: stream,
1864
+ expectsPayload,
1865
+ body: body.stream(),
1866
+ socket: client[kSocket],
1867
+ header: ''
1868
+ })
1869
+ } else {
1870
+ writeBlob({
1871
+ body,
1872
+ client,
1873
+ request,
1874
+ contentLength,
1875
+ expectsPayload,
1876
+ h2stream: stream,
1877
+ header: '',
1878
+ socket: client[kSocket]
1879
+ })
1880
+ }
1881
+ } else if (util.isStream(body)) {
1882
+ writeStream({
1883
+ body,
1884
+ client,
1885
+ request,
1886
+ contentLength,
1887
+ expectsPayload,
1888
+ socket: client[kSocket],
1889
+ h2stream: stream,
1890
+ header: ''
1891
+ })
1892
+ } else if (util.isIterable(body)) {
1893
+ writeIterable({
1894
+ body,
1895
+ client,
1896
+ request,
1897
+ contentLength,
1898
+ expectsPayload,
1899
+ header: '',
1900
+ h2stream: stream,
1901
+ socket: client[kSocket]
1902
+ })
1903
+ } else {
1904
+ assert(false)
1905
+ }
1906
+ }
1907
+ }
1908
+
1909
+ function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
1910
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
1911
+
1912
+ if (client[kHTTPConnVersion] === 'h2') {
1913
+ // For HTTP/2, is enough to pipe the stream
1914
+ const pipe = pipeline(
1915
+ body,
1916
+ h2stream,
1917
+ (err) => {
1918
+ if (err) {
1919
+ util.destroy(body, err)
1920
+ util.destroy(h2stream, err)
1921
+ } else {
1922
+ request.onRequestSent()
1923
+ }
1924
+ }
1925
+ )
1926
+
1927
+ pipe.on('data', onPipeData)
1928
+ pipe.once('end', () => {
1929
+ pipe.removeListener('data', onPipeData)
1930
+ util.destroy(pipe)
1931
+ })
1932
+
1933
+ function onPipeData (chunk) {
1934
+ request.onBodySent(chunk)
1935
+ }
1936
+
1937
+ return
1938
+ }
1939
+
1940
+ let finished = false
1941
+
1942
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
1943
+
1944
+ const onData = function (chunk) {
1945
+ if (finished) {
1946
+ return
1947
+ }
1948
+
1949
+ try {
1950
+ if (!writer.write(chunk) && this.pause) {
1951
+ this.pause()
1952
+ }
1953
+ } catch (err) {
1954
+ util.destroy(this, err)
1955
+ }
1956
+ }
1957
+ const onDrain = function () {
1958
+ if (finished) {
1959
+ return
1960
+ }
1961
+
1962
+ if (body.resume) {
1963
+ body.resume()
1964
+ }
1965
+ }
1966
+ const onAbort = function () {
1967
+ if (finished) {
1968
+ return
1969
+ }
1970
+ const err = new RequestAbortedError()
1971
+ queueMicrotask(() => onFinished(err))
1972
+ }
1973
+ const onFinished = function (err) {
1974
+ if (finished) {
1975
+ return
1976
+ }
1977
+
1978
+ finished = true
1979
+
1980
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
1981
+
1982
+ socket
1983
+ .off('drain', onDrain)
1984
+ .off('error', onFinished)
1985
+
1986
+ body
1987
+ .removeListener('data', onData)
1988
+ .removeListener('end', onFinished)
1989
+ .removeListener('error', onFinished)
1990
+ .removeListener('close', onAbort)
1991
+
1992
+ if (!err) {
1993
+ try {
1994
+ writer.end()
1995
+ } catch (er) {
1996
+ err = er
1997
+ }
1998
+ }
1999
+
2000
+ writer.destroy(err)
2001
+
2002
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
2003
+ util.destroy(body, err)
2004
+ } else {
2005
+ util.destroy(body)
2006
+ }
2007
+ }
2008
+
2009
+ body
2010
+ .on('data', onData)
2011
+ .on('end', onFinished)
2012
+ .on('error', onFinished)
2013
+ .on('close', onAbort)
2014
+
2015
+ if (body.resume) {
2016
+ body.resume()
2017
+ }
2018
+
2019
+ socket
2020
+ .on('drain', onDrain)
2021
+ .on('error', onFinished)
2022
+ }
2023
+
2024
+ async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
2025
+ assert(contentLength === body.size, 'blob body must have content length')
2026
+
2027
+ const isH2 = client[kHTTPConnVersion] === 'h2'
2028
+ try {
2029
+ if (contentLength != null && contentLength !== body.size) {
2030
+ throw new RequestContentLengthMismatchError()
2031
+ }
2032
+
2033
+ const buffer = Buffer.from(await body.arrayBuffer())
2034
+
2035
+ if (isH2) {
2036
+ h2stream.cork()
2037
+ h2stream.write(buffer)
2038
+ h2stream.uncork()
2039
+ } else {
2040
+ socket.cork()
2041
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
2042
+ socket.write(buffer)
2043
+ socket.uncork()
2044
+ }
2045
+
2046
+ request.onBodySent(buffer)
2047
+ request.onRequestSent()
2048
+
2049
+ if (!expectsPayload) {
2050
+ socket[kReset] = true
2051
+ }
2052
+
2053
+ resume(client)
2054
+ } catch (err) {
2055
+ util.destroy(isH2 ? h2stream : socket, err)
2056
+ }
2057
+ }
2058
+
2059
+ async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
2060
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
2061
+
2062
+ let callback = null
2063
+ function onDrain () {
2064
+ if (callback) {
2065
+ const cb = callback
2066
+ callback = null
2067
+ cb()
2068
+ }
2069
+ }
2070
+
2071
+ const waitForDrain = () => new Promise((resolve, reject) => {
2072
+ assert(callback === null)
2073
+
2074
+ if (socket[kError]) {
2075
+ reject(socket[kError])
2076
+ } else {
2077
+ callback = resolve
2078
+ }
2079
+ })
2080
+
2081
+ if (client[kHTTPConnVersion] === 'h2') {
2082
+ h2stream
2083
+ .on('close', onDrain)
2084
+ .on('drain', onDrain)
2085
+
2086
+ try {
2087
+ // It's up to the user to somehow abort the async iterable.
2088
+ for await (const chunk of body) {
2089
+ if (socket[kError]) {
2090
+ throw socket[kError]
2091
+ }
2092
+
2093
+ const res = h2stream.write(chunk)
2094
+ request.onBodySent(chunk)
2095
+ if (!res) {
2096
+ await waitForDrain()
2097
+ }
2098
+ }
2099
+ } catch (err) {
2100
+ h2stream.destroy(err)
2101
+ } finally {
2102
+ request.onRequestSent()
2103
+ h2stream.end()
2104
+ h2stream
2105
+ .off('close', onDrain)
2106
+ .off('drain', onDrain)
2107
+ }
2108
+
2109
+ return
2110
+ }
2111
+
2112
+ socket
2113
+ .on('close', onDrain)
2114
+ .on('drain', onDrain)
2115
+
2116
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
2117
+ try {
2118
+ // It's up to the user to somehow abort the async iterable.
2119
+ for await (const chunk of body) {
2120
+ if (socket[kError]) {
2121
+ throw socket[kError]
2122
+ }
2123
+
2124
+ if (!writer.write(chunk)) {
2125
+ await waitForDrain()
2126
+ }
2127
+ }
2128
+
2129
+ writer.end()
2130
+ } catch (err) {
2131
+ writer.destroy(err)
2132
+ } finally {
2133
+ socket
2134
+ .off('close', onDrain)
2135
+ .off('drain', onDrain)
2136
+ }
2137
+ }
2138
+
2139
+ class AsyncWriter {
2140
+ constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
2141
+ this.socket = socket
2142
+ this.request = request
2143
+ this.contentLength = contentLength
2144
+ this.client = client
2145
+ this.bytesWritten = 0
2146
+ this.expectsPayload = expectsPayload
2147
+ this.header = header
2148
+
2149
+ socket[kWriting] = true
2150
+ }
2151
+
2152
+ write (chunk) {
2153
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
2154
+
2155
+ if (socket[kError]) {
2156
+ throw socket[kError]
2157
+ }
2158
+
2159
+ if (socket.destroyed) {
2160
+ return false
2161
+ }
2162
+
2163
+ const len = Buffer.byteLength(chunk)
2164
+ if (!len) {
2165
+ return true
2166
+ }
2167
+
2168
+ // We should defer writing chunks.
2169
+ if (contentLength !== null && bytesWritten + len > contentLength) {
2170
+ if (client[kStrictContentLength]) {
2171
+ throw new RequestContentLengthMismatchError()
2172
+ }
2173
+
2174
+ process.emitWarning(new RequestContentLengthMismatchError())
2175
+ }
2176
+
2177
+ socket.cork()
2178
+
2179
+ if (bytesWritten === 0) {
2180
+ if (!expectsPayload) {
2181
+ socket[kReset] = true
2182
+ }
2183
+
2184
+ if (contentLength === null) {
2185
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
2186
+ } else {
2187
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
2188
+ }
2189
+ }
2190
+
2191
+ if (contentLength === null) {
2192
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
2193
+ }
2194
+
2195
+ this.bytesWritten += len
2196
+
2197
+ const ret = socket.write(chunk)
2198
+
2199
+ socket.uncork()
2200
+
2201
+ request.onBodySent(chunk)
2202
+
2203
+ if (!ret) {
2204
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
2205
+ // istanbul ignore else: only for jest
2206
+ if (socket[kParser].timeout.refresh) {
2207
+ socket[kParser].timeout.refresh()
2208
+ }
2209
+ }
2210
+ }
2211
+
2212
+ return ret
2213
+ }
2214
+
2215
+ end () {
2216
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
2217
+ request.onRequestSent()
2218
+
2219
+ socket[kWriting] = false
2220
+
2221
+ if (socket[kError]) {
2222
+ throw socket[kError]
2223
+ }
2224
+
2225
+ if (socket.destroyed) {
2226
+ return
2227
+ }
2228
+
2229
+ if (bytesWritten === 0) {
2230
+ if (expectsPayload) {
2231
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
2232
+ // A user agent SHOULD send a Content-Length in a request message when
2233
+ // no Transfer-Encoding is sent and the request method defines a meaning
2234
+ // for an enclosed payload body.
2235
+
2236
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
2237
+ } else {
2238
+ socket.write(`${header}\r\n`, 'latin1')
2239
+ }
2240
+ } else if (contentLength === null) {
2241
+ socket.write('\r\n0\r\n\r\n', 'latin1')
2242
+ }
2243
+
2244
+ if (contentLength !== null && bytesWritten !== contentLength) {
2245
+ if (client[kStrictContentLength]) {
2246
+ throw new RequestContentLengthMismatchError()
2247
+ } else {
2248
+ process.emitWarning(new RequestContentLengthMismatchError())
2249
+ }
2250
+ }
2251
+
2252
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
2253
+ // istanbul ignore else: only for jest
2254
+ if (socket[kParser].timeout.refresh) {
2255
+ socket[kParser].timeout.refresh()
2256
+ }
2257
+ }
2258
+
2259
+ resume(client)
2260
+ }
2261
+
2262
+ destroy (err) {
2263
+ const { socket, client } = this
2264
+
2265
+ socket[kWriting] = false
2266
+
2267
+ if (err) {
2268
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
2269
+ util.destroy(socket, err)
2270
+ }
2271
+ }
2272
+ }
2273
+
2274
+ function errorRequest (client, request, err) {
2275
+ try {
2276
+ request.onError(err)
2277
+ assert(request.aborted)
2278
+ } catch (err) {
2279
+ client.emit('error', err)
2280
+ }
2281
+ }
2282
+
2283
+ module.exports = Client
worker/node_modules/undici/lib/compat/dispatcher-weakref.js ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ /* istanbul ignore file: only for Node 12 */
4
+
5
+ const { kConnected, kSize } = require('../core/symbols')
6
+
7
+ class CompatWeakRef {
8
+ constructor (value) {
9
+ this.value = value
10
+ }
11
+
12
+ deref () {
13
+ return this.value[kConnected] === 0 && this.value[kSize] === 0
14
+ ? undefined
15
+ : this.value
16
+ }
17
+ }
18
+
19
+ class CompatFinalizer {
20
+ constructor (finalizer) {
21
+ this.finalizer = finalizer
22
+ }
23
+
24
+ register (dispatcher, key) {
25
+ if (dispatcher.on) {
26
+ dispatcher.on('disconnect', () => {
27
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
28
+ this.finalizer(key)
29
+ }
30
+ })
31
+ }
32
+ }
33
+ }
34
+
35
+ module.exports = function () {
36
+ // FIXME: remove workaround when the Node bug is fixed
37
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
38
+ if (process.env.NODE_V8_COVERAGE) {
39
+ return {
40
+ WeakRef: CompatWeakRef,
41
+ FinalizationRegistry: CompatFinalizer
42
+ }
43
+ }
44
+ return {
45
+ WeakRef: global.WeakRef || CompatWeakRef,
46
+ FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
47
+ }
48
+ }
worker/node_modules/undici/lib/cookies/constants.js ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
4
+ const maxAttributeValueSize = 1024
5
+
6
+ // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
7
+ const maxNameValuePairSize = 4096
8
+
9
+ module.exports = {
10
+ maxAttributeValueSize,
11
+ maxNameValuePairSize
12
+ }
worker/node_modules/undici/lib/cookies/index.js ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { parseSetCookie } = require('./parse')
4
+ const { stringify } = require('./util')
5
+ const { webidl } = require('../fetch/webidl')
6
+ const { Headers } = require('../fetch/headers')
7
+
8
+ /**
9
+ * @typedef {Object} Cookie
10
+ * @property {string} name
11
+ * @property {string} value
12
+ * @property {Date|number|undefined} expires
13
+ * @property {number|undefined} maxAge
14
+ * @property {string|undefined} domain
15
+ * @property {string|undefined} path
16
+ * @property {boolean|undefined} secure
17
+ * @property {boolean|undefined} httpOnly
18
+ * @property {'Strict'|'Lax'|'None'} sameSite
19
+ * @property {string[]} unparsed
20
+ */
21
+
22
+ /**
23
+ * @param {Headers} headers
24
+ * @returns {Record<string, string>}
25
+ */
26
+ function getCookies (headers) {
27
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
28
+
29
+ webidl.brandCheck(headers, Headers, { strict: false })
30
+
31
+ const cookie = headers.get('cookie')
32
+ const out = {}
33
+
34
+ if (!cookie) {
35
+ return out
36
+ }
37
+
38
+ for (const piece of cookie.split(';')) {
39
+ const [name, ...value] = piece.split('=')
40
+
41
+ out[name.trim()] = value.join('=')
42
+ }
43
+
44
+ return out
45
+ }
46
+
47
+ /**
48
+ * @param {Headers} headers
49
+ * @param {string} name
50
+ * @param {{ path?: string, domain?: string }|undefined} attributes
51
+ * @returns {void}
52
+ */
53
+ function deleteCookie (headers, name, attributes) {
54
+ webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
55
+
56
+ webidl.brandCheck(headers, Headers, { strict: false })
57
+
58
+ name = webidl.converters.DOMString(name)
59
+ attributes = webidl.converters.DeleteCookieAttributes(attributes)
60
+
61
+ // Matches behavior of
62
+ // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
63
+ setCookie(headers, {
64
+ name,
65
+ value: '',
66
+ expires: new Date(0),
67
+ ...attributes
68
+ })
69
+ }
70
+
71
+ /**
72
+ * @param {Headers} headers
73
+ * @returns {Cookie[]}
74
+ */
75
+ function getSetCookies (headers) {
76
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
77
+
78
+ webidl.brandCheck(headers, Headers, { strict: false })
79
+
80
+ const cookies = headers.getSetCookie()
81
+
82
+ if (!cookies) {
83
+ return []
84
+ }
85
+
86
+ return cookies.map((pair) => parseSetCookie(pair))
87
+ }
88
+
89
+ /**
90
+ * @param {Headers} headers
91
+ * @param {Cookie} cookie
92
+ * @returns {void}
93
+ */
94
+ function setCookie (headers, cookie) {
95
+ webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
96
+
97
+ webidl.brandCheck(headers, Headers, { strict: false })
98
+
99
+ cookie = webidl.converters.Cookie(cookie)
100
+
101
+ const str = stringify(cookie)
102
+
103
+ if (str) {
104
+ headers.append('Set-Cookie', stringify(cookie))
105
+ }
106
+ }
107
+
108
+ webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
109
+ {
110
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
111
+ key: 'path',
112
+ defaultValue: null
113
+ },
114
+ {
115
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
116
+ key: 'domain',
117
+ defaultValue: null
118
+ }
119
+ ])
120
+
121
+ webidl.converters.Cookie = webidl.dictionaryConverter([
122
+ {
123
+ converter: webidl.converters.DOMString,
124
+ key: 'name'
125
+ },
126
+ {
127
+ converter: webidl.converters.DOMString,
128
+ key: 'value'
129
+ },
130
+ {
131
+ converter: webidl.nullableConverter((value) => {
132
+ if (typeof value === 'number') {
133
+ return webidl.converters['unsigned long long'](value)
134
+ }
135
+
136
+ return new Date(value)
137
+ }),
138
+ key: 'expires',
139
+ defaultValue: null
140
+ },
141
+ {
142
+ converter: webidl.nullableConverter(webidl.converters['long long']),
143
+ key: 'maxAge',
144
+ defaultValue: null
145
+ },
146
+ {
147
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
148
+ key: 'domain',
149
+ defaultValue: null
150
+ },
151
+ {
152
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
153
+ key: 'path',
154
+ defaultValue: null
155
+ },
156
+ {
157
+ converter: webidl.nullableConverter(webidl.converters.boolean),
158
+ key: 'secure',
159
+ defaultValue: null
160
+ },
161
+ {
162
+ converter: webidl.nullableConverter(webidl.converters.boolean),
163
+ key: 'httpOnly',
164
+ defaultValue: null
165
+ },
166
+ {
167
+ converter: webidl.converters.USVString,
168
+ key: 'sameSite',
169
+ allowedValues: ['Strict', 'Lax', 'None']
170
+ },
171
+ {
172
+ converter: webidl.sequenceConverter(webidl.converters.DOMString),
173
+ key: 'unparsed',
174
+ defaultValue: []
175
+ }
176
+ ])
177
+
178
+ module.exports = {
179
+ getCookies,
180
+ deleteCookie,
181
+ getSetCookies,
182
+ setCookie
183
+ }
worker/node_modules/undici/lib/cookies/parse.js ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants')
4
+ const { isCTLExcludingHtab } = require('./util')
5
+ const { collectASequenceOfCodePointsFast } = require('../fetch/dataURL')
6
+ const assert = require('assert')
7
+
8
+ /**
9
+ * @description Parses the field-value attributes of a set-cookie header string.
10
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
11
+ * @param {string} header
12
+ * @returns if the header is invalid, null will be returned
13
+ */
14
+ function parseSetCookie (header) {
15
+ // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
16
+ // character (CTL characters excluding HTAB): Abort these steps and
17
+ // ignore the set-cookie-string entirely.
18
+ if (isCTLExcludingHtab(header)) {
19
+ return null
20
+ }
21
+
22
+ let nameValuePair = ''
23
+ let unparsedAttributes = ''
24
+ let name = ''
25
+ let value = ''
26
+
27
+ // 2. If the set-cookie-string contains a %x3B (";") character:
28
+ if (header.includes(';')) {
29
+ // 1. The name-value-pair string consists of the characters up to,
30
+ // but not including, the first %x3B (";"), and the unparsed-
31
+ // attributes consist of the remainder of the set-cookie-string
32
+ // (including the %x3B (";") in question).
33
+ const position = { position: 0 }
34
+
35
+ nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
36
+ unparsedAttributes = header.slice(position.position)
37
+ } else {
38
+ // Otherwise:
39
+
40
+ // 1. The name-value-pair string consists of all the characters
41
+ // contained in the set-cookie-string, and the unparsed-
42
+ // attributes is the empty string.
43
+ nameValuePair = header
44
+ }
45
+
46
+ // 3. If the name-value-pair string lacks a %x3D ("=") character, then
47
+ // the name string is empty, and the value string is the value of
48
+ // name-value-pair.
49
+ if (!nameValuePair.includes('=')) {
50
+ value = nameValuePair
51
+ } else {
52
+ // Otherwise, the name string consists of the characters up to, but
53
+ // not including, the first %x3D ("=") character, and the (possibly
54
+ // empty) value string consists of the characters after the first
55
+ // %x3D ("=") character.
56
+ const position = { position: 0 }
57
+ name = collectASequenceOfCodePointsFast(
58
+ '=',
59
+ nameValuePair,
60
+ position
61
+ )
62
+ value = nameValuePair.slice(position.position + 1)
63
+ }
64
+
65
+ // 4. Remove any leading or trailing WSP characters from the name
66
+ // string and the value string.
67
+ name = name.trim()
68
+ value = value.trim()
69
+
70
+ // 5. If the sum of the lengths of the name string and the value string
71
+ // is more than 4096 octets, abort these steps and ignore the set-
72
+ // cookie-string entirely.
73
+ if (name.length + value.length > maxNameValuePairSize) {
74
+ return null
75
+ }
76
+
77
+ // 6. The cookie-name is the name string, and the cookie-value is the
78
+ // value string.
79
+ return {
80
+ name, value, ...parseUnparsedAttributes(unparsedAttributes)
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Parses the remaining attributes of a set-cookie header
86
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
87
+ * @param {string} unparsedAttributes
88
+ * @param {[Object.<string, unknown>]={}} cookieAttributeList
89
+ */
90
+ function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
91
+ // 1. If the unparsed-attributes string is empty, skip the rest of
92
+ // these steps.
93
+ if (unparsedAttributes.length === 0) {
94
+ return cookieAttributeList
95
+ }
96
+
97
+ // 2. Discard the first character of the unparsed-attributes (which
98
+ // will be a %x3B (";") character).
99
+ assert(unparsedAttributes[0] === ';')
100
+ unparsedAttributes = unparsedAttributes.slice(1)
101
+
102
+ let cookieAv = ''
103
+
104
+ // 3. If the remaining unparsed-attributes contains a %x3B (";")
105
+ // character:
106
+ if (unparsedAttributes.includes(';')) {
107
+ // 1. Consume the characters of the unparsed-attributes up to, but
108
+ // not including, the first %x3B (";") character.
109
+ cookieAv = collectASequenceOfCodePointsFast(
110
+ ';',
111
+ unparsedAttributes,
112
+ { position: 0 }
113
+ )
114
+ unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
115
+ } else {
116
+ // Otherwise:
117
+
118
+ // 1. Consume the remainder of the unparsed-attributes.
119
+ cookieAv = unparsedAttributes
120
+ unparsedAttributes = ''
121
+ }
122
+
123
+ // Let the cookie-av string be the characters consumed in this step.
124
+
125
+ let attributeName = ''
126
+ let attributeValue = ''
127
+
128
+ // 4. If the cookie-av string contains a %x3D ("=") character:
129
+ if (cookieAv.includes('=')) {
130
+ // 1. The (possibly empty) attribute-name string consists of the
131
+ // characters up to, but not including, the first %x3D ("=")
132
+ // character, and the (possibly empty) attribute-value string
133
+ // consists of the characters after the first %x3D ("=")
134
+ // character.
135
+ const position = { position: 0 }
136
+
137
+ attributeName = collectASequenceOfCodePointsFast(
138
+ '=',
139
+ cookieAv,
140
+ position
141
+ )
142
+ attributeValue = cookieAv.slice(position.position + 1)
143
+ } else {
144
+ // Otherwise:
145
+
146
+ // 1. The attribute-name string consists of the entire cookie-av
147
+ // string, and the attribute-value string is empty.
148
+ attributeName = cookieAv
149
+ }
150
+
151
+ // 5. Remove any leading or trailing WSP characters from the attribute-
152
+ // name string and the attribute-value string.
153
+ attributeName = attributeName.trim()
154
+ attributeValue = attributeValue.trim()
155
+
156
+ // 6. If the attribute-value is longer than 1024 octets, ignore the
157
+ // cookie-av string and return to Step 1 of this algorithm.
158
+ if (attributeValue.length > maxAttributeValueSize) {
159
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
160
+ }
161
+
162
+ // 7. Process the attribute-name and attribute-value according to the
163
+ // requirements in the following subsections. (Notice that
164
+ // attributes with unrecognized attribute-names are ignored.)
165
+ const attributeNameLowercase = attributeName.toLowerCase()
166
+
167
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
168
+ // If the attribute-name case-insensitively matches the string
169
+ // "Expires", the user agent MUST process the cookie-av as follows.
170
+ if (attributeNameLowercase === 'expires') {
171
+ // 1. Let the expiry-time be the result of parsing the attribute-value
172
+ // as cookie-date (see Section 5.1.1).
173
+ const expiryTime = new Date(attributeValue)
174
+
175
+ // 2. If the attribute-value failed to parse as a cookie date, ignore
176
+ // the cookie-av.
177
+
178
+ cookieAttributeList.expires = expiryTime
179
+ } else if (attributeNameLowercase === 'max-age') {
180
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
181
+ // If the attribute-name case-insensitively matches the string "Max-
182
+ // Age", the user agent MUST process the cookie-av as follows.
183
+
184
+ // 1. If the first character of the attribute-value is not a DIGIT or a
185
+ // "-" character, ignore the cookie-av.
186
+ const charCode = attributeValue.charCodeAt(0)
187
+
188
+ if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
189
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
190
+ }
191
+
192
+ // 2. If the remainder of attribute-value contains a non-DIGIT
193
+ // character, ignore the cookie-av.
194
+ if (!/^\d+$/.test(attributeValue)) {
195
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
196
+ }
197
+
198
+ // 3. Let delta-seconds be the attribute-value converted to an integer.
199
+ const deltaSeconds = Number(attributeValue)
200
+
201
+ // 4. Let cookie-age-limit be the maximum age of the cookie (which
202
+ // SHOULD be 400 days or less, see Section 4.1.2.2).
203
+
204
+ // 5. Set delta-seconds to the smaller of its present value and cookie-
205
+ // age-limit.
206
+ // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
207
+
208
+ // 6. If delta-seconds is less than or equal to zero (0), let expiry-
209
+ // time be the earliest representable date and time. Otherwise, let
210
+ // the expiry-time be the current date and time plus delta-seconds
211
+ // seconds.
212
+ // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
213
+
214
+ // 7. Append an attribute to the cookie-attribute-list with an
215
+ // attribute-name of Max-Age and an attribute-value of expiry-time.
216
+ cookieAttributeList.maxAge = deltaSeconds
217
+ } else if (attributeNameLowercase === 'domain') {
218
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
219
+ // If the attribute-name case-insensitively matches the string "Domain",
220
+ // the user agent MUST process the cookie-av as follows.
221
+
222
+ // 1. Let cookie-domain be the attribute-value.
223
+ let cookieDomain = attributeValue
224
+
225
+ // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
226
+ // cookie-domain without its leading %x2E (".").
227
+ if (cookieDomain[0] === '.') {
228
+ cookieDomain = cookieDomain.slice(1)
229
+ }
230
+
231
+ // 3. Convert the cookie-domain to lower case.
232
+ cookieDomain = cookieDomain.toLowerCase()
233
+
234
+ // 4. Append an attribute to the cookie-attribute-list with an
235
+ // attribute-name of Domain and an attribute-value of cookie-domain.
236
+ cookieAttributeList.domain = cookieDomain
237
+ } else if (attributeNameLowercase === 'path') {
238
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
239
+ // If the attribute-name case-insensitively matches the string "Path",
240
+ // the user agent MUST process the cookie-av as follows.
241
+
242
+ // 1. If the attribute-value is empty or if the first character of the
243
+ // attribute-value is not %x2F ("/"):
244
+ let cookiePath = ''
245
+ if (attributeValue.length === 0 || attributeValue[0] !== '/') {
246
+ // 1. Let cookie-path be the default-path.
247
+ cookiePath = '/'
248
+ } else {
249
+ // Otherwise:
250
+
251
+ // 1. Let cookie-path be the attribute-value.
252
+ cookiePath = attributeValue
253
+ }
254
+
255
+ // 2. Append an attribute to the cookie-attribute-list with an
256
+ // attribute-name of Path and an attribute-value of cookie-path.
257
+ cookieAttributeList.path = cookiePath
258
+ } else if (attributeNameLowercase === 'secure') {
259
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
260
+ // If the attribute-name case-insensitively matches the string "Secure",
261
+ // the user agent MUST append an attribute to the cookie-attribute-list
262
+ // with an attribute-name of Secure and an empty attribute-value.
263
+
264
+ cookieAttributeList.secure = true
265
+ } else if (attributeNameLowercase === 'httponly') {
266
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
267
+ // If the attribute-name case-insensitively matches the string
268
+ // "HttpOnly", the user agent MUST append an attribute to the cookie-
269
+ // attribute-list with an attribute-name of HttpOnly and an empty
270
+ // attribute-value.
271
+
272
+ cookieAttributeList.httpOnly = true
273
+ } else if (attributeNameLowercase === 'samesite') {
274
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
275
+ // If the attribute-name case-insensitively matches the string
276
+ // "SameSite", the user agent MUST process the cookie-av as follows:
277
+
278
+ // 1. Let enforcement be "Default".
279
+ let enforcement = 'Default'
280
+
281
+ const attributeValueLowercase = attributeValue.toLowerCase()
282
+ // 2. If cookie-av's attribute-value is a case-insensitive match for
283
+ // "None", set enforcement to "None".
284
+ if (attributeValueLowercase.includes('none')) {
285
+ enforcement = 'None'
286
+ }
287
+
288
+ // 3. If cookie-av's attribute-value is a case-insensitive match for
289
+ // "Strict", set enforcement to "Strict".
290
+ if (attributeValueLowercase.includes('strict')) {
291
+ enforcement = 'Strict'
292
+ }
293
+
294
+ // 4. If cookie-av's attribute-value is a case-insensitive match for
295
+ // "Lax", set enforcement to "Lax".
296
+ if (attributeValueLowercase.includes('lax')) {
297
+ enforcement = 'Lax'
298
+ }
299
+
300
+ // 5. Append an attribute to the cookie-attribute-list with an
301
+ // attribute-name of "SameSite" and an attribute-value of
302
+ // enforcement.
303
+ cookieAttributeList.sameSite = enforcement
304
+ } else {
305
+ cookieAttributeList.unparsed ??= []
306
+
307
+ cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
308
+ }
309
+
310
+ // 8. Return to Step 1 of this algorithm.
311
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
312
+ }
313
+
314
+ module.exports = {
315
+ parseSetCookie,
316
+ parseUnparsedAttributes
317
+ }
worker/node_modules/undici/lib/cookies/util.js ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ /**
4
+ * @param {string} value
5
+ * @returns {boolean}
6
+ */
7
+ function isCTLExcludingHtab (value) {
8
+ if (value.length === 0) {
9
+ return false
10
+ }
11
+
12
+ for (const char of value) {
13
+ const code = char.charCodeAt(0)
14
+
15
+ if (
16
+ (code >= 0x00 || code <= 0x08) ||
17
+ (code >= 0x0A || code <= 0x1F) ||
18
+ code === 0x7F
19
+ ) {
20
+ return false
21
+ }
22
+ }
23
+ }
24
+
25
+ /**
26
+ CHAR = <any US-ASCII character (octets 0 - 127)>
27
+ token = 1*<any CHAR except CTLs or separators>
28
+ separators = "(" | ")" | "<" | ">" | "@"
29
+ | "," | ";" | ":" | "\" | <">
30
+ | "/" | "[" | "]" | "?" | "="
31
+ | "{" | "}" | SP | HT
32
+ * @param {string} name
33
+ */
34
+ function validateCookieName (name) {
35
+ for (const char of name) {
36
+ const code = char.charCodeAt(0)
37
+
38
+ if (
39
+ (code <= 0x20 || code > 0x7F) ||
40
+ char === '(' ||
41
+ char === ')' ||
42
+ char === '>' ||
43
+ char === '<' ||
44
+ char === '@' ||
45
+ char === ',' ||
46
+ char === ';' ||
47
+ char === ':' ||
48
+ char === '\\' ||
49
+ char === '"' ||
50
+ char === '/' ||
51
+ char === '[' ||
52
+ char === ']' ||
53
+ char === '?' ||
54
+ char === '=' ||
55
+ char === '{' ||
56
+ char === '}'
57
+ ) {
58
+ throw new Error('Invalid cookie name')
59
+ }
60
+ }
61
+ }
62
+
63
+ /**
64
+ cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
65
+ cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
66
+ ; US-ASCII characters excluding CTLs,
67
+ ; whitespace DQUOTE, comma, semicolon,
68
+ ; and backslash
69
+ * @param {string} value
70
+ */
71
+ function validateCookieValue (value) {
72
+ for (const char of value) {
73
+ const code = char.charCodeAt(0)
74
+
75
+ if (
76
+ code < 0x21 || // exclude CTLs (0-31)
77
+ code === 0x22 ||
78
+ code === 0x2C ||
79
+ code === 0x3B ||
80
+ code === 0x5C ||
81
+ code > 0x7E // non-ascii
82
+ ) {
83
+ throw new Error('Invalid header value')
84
+ }
85
+ }
86
+ }
87
+
88
+ /**
89
+ * path-value = <any CHAR except CTLs or ";">
90
+ * @param {string} path
91
+ */
92
+ function validateCookiePath (path) {
93
+ for (const char of path) {
94
+ const code = char.charCodeAt(0)
95
+
96
+ if (code < 0x21 || char === ';') {
97
+ throw new Error('Invalid cookie path')
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * I have no idea why these values aren't allowed to be honest,
104
+ * but Deno tests these. - Khafra
105
+ * @param {string} domain
106
+ */
107
+ function validateCookieDomain (domain) {
108
+ if (
109
+ domain.startsWith('-') ||
110
+ domain.endsWith('.') ||
111
+ domain.endsWith('-')
112
+ ) {
113
+ throw new Error('Invalid cookie domain')
114
+ }
115
+ }
116
+
117
+ /**
118
+ * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
119
+ * @param {number|Date} date
120
+ IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
121
+ ; fixed length/zone/capitalization subset of the format
122
+ ; see Section 3.3 of [RFC5322]
123
+
124
+ day-name = %x4D.6F.6E ; "Mon", case-sensitive
125
+ / %x54.75.65 ; "Tue", case-sensitive
126
+ / %x57.65.64 ; "Wed", case-sensitive
127
+ / %x54.68.75 ; "Thu", case-sensitive
128
+ / %x46.72.69 ; "Fri", case-sensitive
129
+ / %x53.61.74 ; "Sat", case-sensitive
130
+ / %x53.75.6E ; "Sun", case-sensitive
131
+ date1 = day SP month SP year
132
+ ; e.g., 02 Jun 1982
133
+
134
+ day = 2DIGIT
135
+ month = %x4A.61.6E ; "Jan", case-sensitive
136
+ / %x46.65.62 ; "Feb", case-sensitive
137
+ / %x4D.61.72 ; "Mar", case-sensitive
138
+ / %x41.70.72 ; "Apr", case-sensitive
139
+ / %x4D.61.79 ; "May", case-sensitive
140
+ / %x4A.75.6E ; "Jun", case-sensitive
141
+ / %x4A.75.6C ; "Jul", case-sensitive
142
+ / %x41.75.67 ; "Aug", case-sensitive
143
+ / %x53.65.70 ; "Sep", case-sensitive
144
+ / %x4F.63.74 ; "Oct", case-sensitive
145
+ / %x4E.6F.76 ; "Nov", case-sensitive
146
+ / %x44.65.63 ; "Dec", case-sensitive
147
+ year = 4DIGIT
148
+
149
+ GMT = %x47.4D.54 ; "GMT", case-sensitive
150
+
151
+ time-of-day = hour ":" minute ":" second
152
+ ; 00:00:00 - 23:59:60 (leap second)
153
+
154
+ hour = 2DIGIT
155
+ minute = 2DIGIT
156
+ second = 2DIGIT
157
+ */
158
+ function toIMFDate (date) {
159
+ if (typeof date === 'number') {
160
+ date = new Date(date)
161
+ }
162
+
163
+ const days = [
164
+ 'Sun', 'Mon', 'Tue', 'Wed',
165
+ 'Thu', 'Fri', 'Sat'
166
+ ]
167
+
168
+ const months = [
169
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
170
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
171
+ ]
172
+
173
+ const dayName = days[date.getUTCDay()]
174
+ const day = date.getUTCDate().toString().padStart(2, '0')
175
+ const month = months[date.getUTCMonth()]
176
+ const year = date.getUTCFullYear()
177
+ const hour = date.getUTCHours().toString().padStart(2, '0')
178
+ const minute = date.getUTCMinutes().toString().padStart(2, '0')
179
+ const second = date.getUTCSeconds().toString().padStart(2, '0')
180
+
181
+ return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
182
+ }
183
+
184
+ /**
185
+ max-age-av = "Max-Age=" non-zero-digit *DIGIT
186
+ ; In practice, both expires-av and max-age-av
187
+ ; are limited to dates representable by the
188
+ ; user agent.
189
+ * @param {number} maxAge
190
+ */
191
+ function validateCookieMaxAge (maxAge) {
192
+ if (maxAge < 0) {
193
+ throw new Error('Invalid cookie max-age')
194
+ }
195
+ }
196
+
197
+ /**
198
+ * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
199
+ * @param {import('./index').Cookie} cookie
200
+ */
201
+ function stringify (cookie) {
202
+ if (cookie.name.length === 0) {
203
+ return null
204
+ }
205
+
206
+ validateCookieName(cookie.name)
207
+ validateCookieValue(cookie.value)
208
+
209
+ const out = [`${cookie.name}=${cookie.value}`]
210
+
211
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
212
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
213
+ if (cookie.name.startsWith('__Secure-')) {
214
+ cookie.secure = true
215
+ }
216
+
217
+ if (cookie.name.startsWith('__Host-')) {
218
+ cookie.secure = true
219
+ cookie.domain = null
220
+ cookie.path = '/'
221
+ }
222
+
223
+ if (cookie.secure) {
224
+ out.push('Secure')
225
+ }
226
+
227
+ if (cookie.httpOnly) {
228
+ out.push('HttpOnly')
229
+ }
230
+
231
+ if (typeof cookie.maxAge === 'number') {
232
+ validateCookieMaxAge(cookie.maxAge)
233
+ out.push(`Max-Age=${cookie.maxAge}`)
234
+ }
235
+
236
+ if (cookie.domain) {
237
+ validateCookieDomain(cookie.domain)
238
+ out.push(`Domain=${cookie.domain}`)
239
+ }
240
+
241
+ if (cookie.path) {
242
+ validateCookiePath(cookie.path)
243
+ out.push(`Path=${cookie.path}`)
244
+ }
245
+
246
+ if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
247
+ out.push(`Expires=${toIMFDate(cookie.expires)}`)
248
+ }
249
+
250
+ if (cookie.sameSite) {
251
+ out.push(`SameSite=${cookie.sameSite}`)
252
+ }
253
+
254
+ for (const part of cookie.unparsed) {
255
+ if (!part.includes('=')) {
256
+ throw new Error('Invalid unparsed')
257
+ }
258
+
259
+ const [key, ...value] = part.split('=')
260
+
261
+ out.push(`${key.trim()}=${value.join('=')}`)
262
+ }
263
+
264
+ return out.join('; ')
265
+ }
266
+
267
+ module.exports = {
268
+ isCTLExcludingHtab,
269
+ validateCookieName,
270
+ validateCookiePath,
271
+ validateCookieValue,
272
+ toIMFDate,
273
+ stringify
274
+ }
worker/node_modules/undici/lib/core/connect.js ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const net = require('net')
4
+ const assert = require('assert')
5
+ const util = require('./util')
6
+ const { InvalidArgumentError, ConnectTimeoutError } = require('./errors')
7
+
8
+ let tls // include tls conditionally since it is not always available
9
+
10
+ // TODO: session re-use does not wait for the first
11
+ // connection to resolve the session and might therefore
12
+ // resolve the same servername multiple times even when
13
+ // re-use is enabled.
14
+
15
+ let SessionCache
16
+ // FIXME: remove workaround when the Node bug is fixed
17
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
18
+ if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
19
+ SessionCache = class WeakSessionCache {
20
+ constructor (maxCachedSessions) {
21
+ this._maxCachedSessions = maxCachedSessions
22
+ this._sessionCache = new Map()
23
+ this._sessionRegistry = new global.FinalizationRegistry((key) => {
24
+ if (this._sessionCache.size < this._maxCachedSessions) {
25
+ return
26
+ }
27
+
28
+ const ref = this._sessionCache.get(key)
29
+ if (ref !== undefined && ref.deref() === undefined) {
30
+ this._sessionCache.delete(key)
31
+ }
32
+ })
33
+ }
34
+
35
+ get (sessionKey) {
36
+ const ref = this._sessionCache.get(sessionKey)
37
+ return ref ? ref.deref() : null
38
+ }
39
+
40
+ set (sessionKey, session) {
41
+ if (this._maxCachedSessions === 0) {
42
+ return
43
+ }
44
+
45
+ this._sessionCache.set(sessionKey, new WeakRef(session))
46
+ this._sessionRegistry.register(session, sessionKey)
47
+ }
48
+ }
49
+ } else {
50
+ SessionCache = class SimpleSessionCache {
51
+ constructor (maxCachedSessions) {
52
+ this._maxCachedSessions = maxCachedSessions
53
+ this._sessionCache = new Map()
54
+ }
55
+
56
+ get (sessionKey) {
57
+ return this._sessionCache.get(sessionKey)
58
+ }
59
+
60
+ set (sessionKey, session) {
61
+ if (this._maxCachedSessions === 0) {
62
+ return
63
+ }
64
+
65
+ if (this._sessionCache.size >= this._maxCachedSessions) {
66
+ // remove the oldest session
67
+ const { value: oldestKey } = this._sessionCache.keys().next()
68
+ this._sessionCache.delete(oldestKey)
69
+ }
70
+
71
+ this._sessionCache.set(sessionKey, session)
72
+ }
73
+ }
74
+ }
75
+
76
+ function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
77
+ if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
78
+ throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
79
+ }
80
+
81
+ const options = { path: socketPath, ...opts }
82
+ const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
83
+ timeout = timeout == null ? 10e3 : timeout
84
+ allowH2 = allowH2 != null ? allowH2 : false
85
+ return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
86
+ let socket
87
+ if (protocol === 'https:') {
88
+ if (!tls) {
89
+ tls = require('tls')
90
+ }
91
+ servername = servername || options.servername || util.getServerName(host) || null
92
+
93
+ const sessionKey = servername || hostname
94
+ const session = sessionCache.get(sessionKey) || null
95
+
96
+ assert(sessionKey)
97
+
98
+ socket = tls.connect({
99
+ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
100
+ ...options,
101
+ servername,
102
+ session,
103
+ localAddress,
104
+ // TODO(HTTP/2): Add support for h2c
105
+ ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
106
+ socket: httpSocket, // upgrade socket connection
107
+ port: port || 443,
108
+ host: hostname
109
+ })
110
+
111
+ socket
112
+ .on('session', function (session) {
113
+ // TODO (fix): Can a session become invalid once established? Don't think so?
114
+ sessionCache.set(sessionKey, session)
115
+ })
116
+ } else {
117
+ assert(!httpSocket, 'httpSocket can only be sent on TLS update')
118
+ socket = net.connect({
119
+ highWaterMark: 64 * 1024, // Same as nodejs fs streams.
120
+ ...options,
121
+ localAddress,
122
+ port: port || 80,
123
+ host: hostname
124
+ })
125
+ }
126
+
127
+ // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
128
+ if (options.keepAlive == null || options.keepAlive) {
129
+ const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
130
+ socket.setKeepAlive(true, keepAliveInitialDelay)
131
+ }
132
+
133
+ const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
134
+
135
+ socket
136
+ .setNoDelay(true)
137
+ .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
138
+ cancelTimeout()
139
+
140
+ if (callback) {
141
+ const cb = callback
142
+ callback = null
143
+ cb(null, this)
144
+ }
145
+ })
146
+ .on('error', function (err) {
147
+ cancelTimeout()
148
+
149
+ if (callback) {
150
+ const cb = callback
151
+ callback = null
152
+ cb(err)
153
+ }
154
+ })
155
+
156
+ return socket
157
+ }
158
+ }
159
+
160
+ function setupTimeout (onConnectTimeout, timeout) {
161
+ if (!timeout) {
162
+ return () => {}
163
+ }
164
+
165
+ let s1 = null
166
+ let s2 = null
167
+ const timeoutId = setTimeout(() => {
168
+ // setImmediate is added to make sure that we priotorise socket error events over timeouts
169
+ s1 = setImmediate(() => {
170
+ if (process.platform === 'win32') {
171
+ // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
172
+ s2 = setImmediate(() => onConnectTimeout())
173
+ } else {
174
+ onConnectTimeout()
175
+ }
176
+ })
177
+ }, timeout)
178
+ return () => {
179
+ clearTimeout(timeoutId)
180
+ clearImmediate(s1)
181
+ clearImmediate(s2)
182
+ }
183
+ }
184
+
185
+ function onConnectTimeout (socket) {
186
+ util.destroy(socket, new ConnectTimeoutError())
187
+ }
188
+
189
+ module.exports = buildConnector
worker/node_modules/undici/lib/core/constants.js ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ /** @type {Record<string, string | undefined>} */
4
+ const headerNameLowerCasedRecord = {}
5
+
6
+ // https://developer.mozilla.org/docs/Web/HTTP/Headers
7
+ const wellknownHeaderNames = [
8
+ 'Accept',
9
+ 'Accept-Encoding',
10
+ 'Accept-Language',
11
+ 'Accept-Ranges',
12
+ 'Access-Control-Allow-Credentials',
13
+ 'Access-Control-Allow-Headers',
14
+ 'Access-Control-Allow-Methods',
15
+ 'Access-Control-Allow-Origin',
16
+ 'Access-Control-Expose-Headers',
17
+ 'Access-Control-Max-Age',
18
+ 'Access-Control-Request-Headers',
19
+ 'Access-Control-Request-Method',
20
+ 'Age',
21
+ 'Allow',
22
+ 'Alt-Svc',
23
+ 'Alt-Used',
24
+ 'Authorization',
25
+ 'Cache-Control',
26
+ 'Clear-Site-Data',
27
+ 'Connection',
28
+ 'Content-Disposition',
29
+ 'Content-Encoding',
30
+ 'Content-Language',
31
+ 'Content-Length',
32
+ 'Content-Location',
33
+ 'Content-Range',
34
+ 'Content-Security-Policy',
35
+ 'Content-Security-Policy-Report-Only',
36
+ 'Content-Type',
37
+ 'Cookie',
38
+ 'Cross-Origin-Embedder-Policy',
39
+ 'Cross-Origin-Opener-Policy',
40
+ 'Cross-Origin-Resource-Policy',
41
+ 'Date',
42
+ 'Device-Memory',
43
+ 'Downlink',
44
+ 'ECT',
45
+ 'ETag',
46
+ 'Expect',
47
+ 'Expect-CT',
48
+ 'Expires',
49
+ 'Forwarded',
50
+ 'From',
51
+ 'Host',
52
+ 'If-Match',
53
+ 'If-Modified-Since',
54
+ 'If-None-Match',
55
+ 'If-Range',
56
+ 'If-Unmodified-Since',
57
+ 'Keep-Alive',
58
+ 'Last-Modified',
59
+ 'Link',
60
+ 'Location',
61
+ 'Max-Forwards',
62
+ 'Origin',
63
+ 'Permissions-Policy',
64
+ 'Pragma',
65
+ 'Proxy-Authenticate',
66
+ 'Proxy-Authorization',
67
+ 'RTT',
68
+ 'Range',
69
+ 'Referer',
70
+ 'Referrer-Policy',
71
+ 'Refresh',
72
+ 'Retry-After',
73
+ 'Sec-WebSocket-Accept',
74
+ 'Sec-WebSocket-Extensions',
75
+ 'Sec-WebSocket-Key',
76
+ 'Sec-WebSocket-Protocol',
77
+ 'Sec-WebSocket-Version',
78
+ 'Server',
79
+ 'Server-Timing',
80
+ 'Service-Worker-Allowed',
81
+ 'Service-Worker-Navigation-Preload',
82
+ 'Set-Cookie',
83
+ 'SourceMap',
84
+ 'Strict-Transport-Security',
85
+ 'Supports-Loading-Mode',
86
+ 'TE',
87
+ 'Timing-Allow-Origin',
88
+ 'Trailer',
89
+ 'Transfer-Encoding',
90
+ 'Upgrade',
91
+ 'Upgrade-Insecure-Requests',
92
+ 'User-Agent',
93
+ 'Vary',
94
+ 'Via',
95
+ 'WWW-Authenticate',
96
+ 'X-Content-Type-Options',
97
+ 'X-DNS-Prefetch-Control',
98
+ 'X-Frame-Options',
99
+ 'X-Permitted-Cross-Domain-Policies',
100
+ 'X-Powered-By',
101
+ 'X-Requested-With',
102
+ 'X-XSS-Protection'
103
+ ]
104
+
105
+ for (let i = 0; i < wellknownHeaderNames.length; ++i) {
106
+ const key = wellknownHeaderNames[i]
107
+ const lowerCasedKey = key.toLowerCase()
108
+ headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
109
+ lowerCasedKey
110
+ }
111
+
112
+ // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
113
+ Object.setPrototypeOf(headerNameLowerCasedRecord, null)
114
+
115
+ module.exports = {
116
+ wellknownHeaderNames,
117
+ headerNameLowerCasedRecord
118
+ }
worker/node_modules/undici/lib/core/errors.js ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ class UndiciError extends Error {
4
+ constructor (message) {
5
+ super(message)
6
+ this.name = 'UndiciError'
7
+ this.code = 'UND_ERR'
8
+ }
9
+ }
10
+
11
+ class ConnectTimeoutError extends UndiciError {
12
+ constructor (message) {
13
+ super(message)
14
+ Error.captureStackTrace(this, ConnectTimeoutError)
15
+ this.name = 'ConnectTimeoutError'
16
+ this.message = message || 'Connect Timeout Error'
17
+ this.code = 'UND_ERR_CONNECT_TIMEOUT'
18
+ }
19
+ }
20
+
21
+ class HeadersTimeoutError extends UndiciError {
22
+ constructor (message) {
23
+ super(message)
24
+ Error.captureStackTrace(this, HeadersTimeoutError)
25
+ this.name = 'HeadersTimeoutError'
26
+ this.message = message || 'Headers Timeout Error'
27
+ this.code = 'UND_ERR_HEADERS_TIMEOUT'
28
+ }
29
+ }
30
+
31
+ class HeadersOverflowError extends UndiciError {
32
+ constructor (message) {
33
+ super(message)
34
+ Error.captureStackTrace(this, HeadersOverflowError)
35
+ this.name = 'HeadersOverflowError'
36
+ this.message = message || 'Headers Overflow Error'
37
+ this.code = 'UND_ERR_HEADERS_OVERFLOW'
38
+ }
39
+ }
40
+
41
+ class BodyTimeoutError extends UndiciError {
42
+ constructor (message) {
43
+ super(message)
44
+ Error.captureStackTrace(this, BodyTimeoutError)
45
+ this.name = 'BodyTimeoutError'
46
+ this.message = message || 'Body Timeout Error'
47
+ this.code = 'UND_ERR_BODY_TIMEOUT'
48
+ }
49
+ }
50
+
51
+ class ResponseStatusCodeError extends UndiciError {
52
+ constructor (message, statusCode, headers, body) {
53
+ super(message)
54
+ Error.captureStackTrace(this, ResponseStatusCodeError)
55
+ this.name = 'ResponseStatusCodeError'
56
+ this.message = message || 'Response Status Code Error'
57
+ this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
58
+ this.body = body
59
+ this.status = statusCode
60
+ this.statusCode = statusCode
61
+ this.headers = headers
62
+ }
63
+ }
64
+
65
+ class InvalidArgumentError extends UndiciError {
66
+ constructor (message) {
67
+ super(message)
68
+ Error.captureStackTrace(this, InvalidArgumentError)
69
+ this.name = 'InvalidArgumentError'
70
+ this.message = message || 'Invalid Argument Error'
71
+ this.code = 'UND_ERR_INVALID_ARG'
72
+ }
73
+ }
74
+
75
+ class InvalidReturnValueError extends UndiciError {
76
+ constructor (message) {
77
+ super(message)
78
+ Error.captureStackTrace(this, InvalidReturnValueError)
79
+ this.name = 'InvalidReturnValueError'
80
+ this.message = message || 'Invalid Return Value Error'
81
+ this.code = 'UND_ERR_INVALID_RETURN_VALUE'
82
+ }
83
+ }
84
+
85
+ class RequestAbortedError extends UndiciError {
86
+ constructor (message) {
87
+ super(message)
88
+ Error.captureStackTrace(this, RequestAbortedError)
89
+ this.name = 'AbortError'
90
+ this.message = message || 'Request aborted'
91
+ this.code = 'UND_ERR_ABORTED'
92
+ }
93
+ }
94
+
95
+ class InformationalError extends UndiciError {
96
+ constructor (message) {
97
+ super(message)
98
+ Error.captureStackTrace(this, InformationalError)
99
+ this.name = 'InformationalError'
100
+ this.message = message || 'Request information'
101
+ this.code = 'UND_ERR_INFO'
102
+ }
103
+ }
104
+
105
+ class RequestContentLengthMismatchError extends UndiciError {
106
+ constructor (message) {
107
+ super(message)
108
+ Error.captureStackTrace(this, RequestContentLengthMismatchError)
109
+ this.name = 'RequestContentLengthMismatchError'
110
+ this.message = message || 'Request body length does not match content-length header'
111
+ this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
112
+ }
113
+ }
114
+
115
+ class ResponseContentLengthMismatchError extends UndiciError {
116
+ constructor (message) {
117
+ super(message)
118
+ Error.captureStackTrace(this, ResponseContentLengthMismatchError)
119
+ this.name = 'ResponseContentLengthMismatchError'
120
+ this.message = message || 'Response body length does not match content-length header'
121
+ this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
122
+ }
123
+ }
124
+
125
+ class ClientDestroyedError extends UndiciError {
126
+ constructor (message) {
127
+ super(message)
128
+ Error.captureStackTrace(this, ClientDestroyedError)
129
+ this.name = 'ClientDestroyedError'
130
+ this.message = message || 'The client is destroyed'
131
+ this.code = 'UND_ERR_DESTROYED'
132
+ }
133
+ }
134
+
135
+ class ClientClosedError extends UndiciError {
136
+ constructor (message) {
137
+ super(message)
138
+ Error.captureStackTrace(this, ClientClosedError)
139
+ this.name = 'ClientClosedError'
140
+ this.message = message || 'The client is closed'
141
+ this.code = 'UND_ERR_CLOSED'
142
+ }
143
+ }
144
+
145
+ class SocketError extends UndiciError {
146
+ constructor (message, socket) {
147
+ super(message)
148
+ Error.captureStackTrace(this, SocketError)
149
+ this.name = 'SocketError'
150
+ this.message = message || 'Socket error'
151
+ this.code = 'UND_ERR_SOCKET'
152
+ this.socket = socket
153
+ }
154
+ }
155
+
156
+ class NotSupportedError extends UndiciError {
157
+ constructor (message) {
158
+ super(message)
159
+ Error.captureStackTrace(this, NotSupportedError)
160
+ this.name = 'NotSupportedError'
161
+ this.message = message || 'Not supported error'
162
+ this.code = 'UND_ERR_NOT_SUPPORTED'
163
+ }
164
+ }
165
+
166
+ class BalancedPoolMissingUpstreamError extends UndiciError {
167
+ constructor (message) {
168
+ super(message)
169
+ Error.captureStackTrace(this, NotSupportedError)
170
+ this.name = 'MissingUpstreamError'
171
+ this.message = message || 'No upstream has been added to the BalancedPool'
172
+ this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
173
+ }
174
+ }
175
+
176
+ class HTTPParserError extends Error {
177
+ constructor (message, code, data) {
178
+ super(message)
179
+ Error.captureStackTrace(this, HTTPParserError)
180
+ this.name = 'HTTPParserError'
181
+ this.code = code ? `HPE_${code}` : undefined
182
+ this.data = data ? data.toString() : undefined
183
+ }
184
+ }
185
+
186
+ class ResponseExceededMaxSizeError extends UndiciError {
187
+ constructor (message) {
188
+ super(message)
189
+ Error.captureStackTrace(this, ResponseExceededMaxSizeError)
190
+ this.name = 'ResponseExceededMaxSizeError'
191
+ this.message = message || 'Response content exceeded max size'
192
+ this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
193
+ }
194
+ }
195
+
196
+ class RequestRetryError extends UndiciError {
197
+ constructor (message, code, { headers, data }) {
198
+ super(message)
199
+ Error.captureStackTrace(this, RequestRetryError)
200
+ this.name = 'RequestRetryError'
201
+ this.message = message || 'Request retry error'
202
+ this.code = 'UND_ERR_REQ_RETRY'
203
+ this.statusCode = code
204
+ this.data = data
205
+ this.headers = headers
206
+ }
207
+ }
208
+
209
+ module.exports = {
210
+ HTTPParserError,
211
+ UndiciError,
212
+ HeadersTimeoutError,
213
+ HeadersOverflowError,
214
+ BodyTimeoutError,
215
+ RequestContentLengthMismatchError,
216
+ ConnectTimeoutError,
217
+ ResponseStatusCodeError,
218
+ InvalidArgumentError,
219
+ InvalidReturnValueError,
220
+ RequestAbortedError,
221
+ ClientDestroyedError,
222
+ ClientClosedError,
223
+ InformationalError,
224
+ SocketError,
225
+ NotSupportedError,
226
+ ResponseContentLengthMismatchError,
227
+ BalancedPoolMissingUpstreamError,
228
+ ResponseExceededMaxSizeError,
229
+ RequestRetryError
230
+ }
worker/node_modules/undici/lib/core/request.js ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const {
4
+ InvalidArgumentError,
5
+ NotSupportedError
6
+ } = require('./errors')
7
+ const assert = require('assert')
8
+ const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = require('./symbols')
9
+ const util = require('./util')
10
+
11
+ // tokenRegExp and headerCharRegex have been lifted from
12
+ // https://github.com/nodejs/node/blob/main/lib/_http_common.js
13
+
14
+ /**
15
+ * Verifies that the given val is a valid HTTP token
16
+ * per the rules defined in RFC 7230
17
+ * See https://tools.ietf.org/html/rfc7230#section-3.2.6
18
+ */
19
+ const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
20
+
21
+ /**
22
+ * Matches if val contains an invalid field-vchar
23
+ * field-value = *( field-content / obs-fold )
24
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
25
+ * field-vchar = VCHAR / obs-text
26
+ */
27
+ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
28
+
29
+ // Verifies that a given path is valid does not contain control chars \x00 to \x20
30
+ const invalidPathRegex = /[^\u0021-\u00ff]/
31
+
32
+ const kHandler = Symbol('handler')
33
+
34
+ const channels = {}
35
+
36
+ let extractBody
37
+
38
+ try {
39
+ const diagnosticsChannel = require('diagnostics_channel')
40
+ channels.create = diagnosticsChannel.channel('undici:request:create')
41
+ channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
42
+ channels.headers = diagnosticsChannel.channel('undici:request:headers')
43
+ channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
44
+ channels.error = diagnosticsChannel.channel('undici:request:error')
45
+ } catch {
46
+ channels.create = { hasSubscribers: false }
47
+ channels.bodySent = { hasSubscribers: false }
48
+ channels.headers = { hasSubscribers: false }
49
+ channels.trailers = { hasSubscribers: false }
50
+ channels.error = { hasSubscribers: false }
51
+ }
52
+
53
+ class Request {
54
+ constructor (origin, {
55
+ path,
56
+ method,
57
+ body,
58
+ headers,
59
+ query,
60
+ idempotent,
61
+ blocking,
62
+ upgrade,
63
+ headersTimeout,
64
+ bodyTimeout,
65
+ reset,
66
+ throwOnError,
67
+ expectContinue
68
+ }, handler) {
69
+ if (typeof path !== 'string') {
70
+ throw new InvalidArgumentError('path must be a string')
71
+ } else if (
72
+ path[0] !== '/' &&
73
+ !(path.startsWith('http://') || path.startsWith('https://')) &&
74
+ method !== 'CONNECT'
75
+ ) {
76
+ throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
77
+ } else if (invalidPathRegex.exec(path) !== null) {
78
+ throw new InvalidArgumentError('invalid request path')
79
+ }
80
+
81
+ if (typeof method !== 'string') {
82
+ throw new InvalidArgumentError('method must be a string')
83
+ } else if (tokenRegExp.exec(method) === null) {
84
+ throw new InvalidArgumentError('invalid request method')
85
+ }
86
+
87
+ if (upgrade && typeof upgrade !== 'string') {
88
+ throw new InvalidArgumentError('upgrade must be a string')
89
+ }
90
+
91
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
92
+ throw new InvalidArgumentError('invalid headersTimeout')
93
+ }
94
+
95
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
96
+ throw new InvalidArgumentError('invalid bodyTimeout')
97
+ }
98
+
99
+ if (reset != null && typeof reset !== 'boolean') {
100
+ throw new InvalidArgumentError('invalid reset')
101
+ }
102
+
103
+ if (expectContinue != null && typeof expectContinue !== 'boolean') {
104
+ throw new InvalidArgumentError('invalid expectContinue')
105
+ }
106
+
107
+ this.headersTimeout = headersTimeout
108
+
109
+ this.bodyTimeout = bodyTimeout
110
+
111
+ this.throwOnError = throwOnError === true
112
+
113
+ this.method = method
114
+
115
+ this.abort = null
116
+
117
+ if (body == null) {
118
+ this.body = null
119
+ } else if (util.isStream(body)) {
120
+ this.body = body
121
+
122
+ const rState = this.body._readableState
123
+ if (!rState || !rState.autoDestroy) {
124
+ this.endHandler = function autoDestroy () {
125
+ util.destroy(this)
126
+ }
127
+ this.body.on('end', this.endHandler)
128
+ }
129
+
130
+ this.errorHandler = err => {
131
+ if (this.abort) {
132
+ this.abort(err)
133
+ } else {
134
+ this.error = err
135
+ }
136
+ }
137
+ this.body.on('error', this.errorHandler)
138
+ } else if (util.isBuffer(body)) {
139
+ this.body = body.byteLength ? body : null
140
+ } else if (ArrayBuffer.isView(body)) {
141
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
142
+ } else if (body instanceof ArrayBuffer) {
143
+ this.body = body.byteLength ? Buffer.from(body) : null
144
+ } else if (typeof body === 'string') {
145
+ this.body = body.length ? Buffer.from(body) : null
146
+ } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
147
+ this.body = body
148
+ } else {
149
+ throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
150
+ }
151
+
152
+ this.completed = false
153
+
154
+ this.aborted = false
155
+
156
+ this.upgrade = upgrade || null
157
+
158
+ this.path = query ? util.buildURL(path, query) : path
159
+
160
+ this.origin = origin
161
+
162
+ this.idempotent = idempotent == null
163
+ ? method === 'HEAD' || method === 'GET'
164
+ : idempotent
165
+
166
+ this.blocking = blocking == null ? false : blocking
167
+
168
+ this.reset = reset == null ? null : reset
169
+
170
+ this.host = null
171
+
172
+ this.contentLength = null
173
+
174
+ this.contentType = null
175
+
176
+ this.headers = ''
177
+
178
+ // Only for H2
179
+ this.expectContinue = expectContinue != null ? expectContinue : false
180
+
181
+ if (Array.isArray(headers)) {
182
+ if (headers.length % 2 !== 0) {
183
+ throw new InvalidArgumentError('headers array must be even')
184
+ }
185
+ for (let i = 0; i < headers.length; i += 2) {
186
+ processHeader(this, headers[i], headers[i + 1])
187
+ }
188
+ } else if (headers && typeof headers === 'object') {
189
+ const keys = Object.keys(headers)
190
+ for (let i = 0; i < keys.length; i++) {
191
+ const key = keys[i]
192
+ processHeader(this, key, headers[key])
193
+ }
194
+ } else if (headers != null) {
195
+ throw new InvalidArgumentError('headers must be an object or an array')
196
+ }
197
+
198
+ if (util.isFormDataLike(this.body)) {
199
+ if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
200
+ throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
201
+ }
202
+
203
+ if (!extractBody) {
204
+ extractBody = require('../fetch/body.js').extractBody
205
+ }
206
+
207
+ const [bodyStream, contentType] = extractBody(body)
208
+ if (this.contentType == null) {
209
+ this.contentType = contentType
210
+ this.headers += `content-type: ${contentType}\r\n`
211
+ }
212
+ this.body = bodyStream.stream
213
+ this.contentLength = bodyStream.length
214
+ } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
215
+ this.contentType = body.type
216
+ this.headers += `content-type: ${body.type}\r\n`
217
+ }
218
+
219
+ util.validateHandler(handler, method, upgrade)
220
+
221
+ this.servername = util.getServerName(this.host)
222
+
223
+ this[kHandler] = handler
224
+
225
+ if (channels.create.hasSubscribers) {
226
+ channels.create.publish({ request: this })
227
+ }
228
+ }
229
+
230
+ onBodySent (chunk) {
231
+ if (this[kHandler].onBodySent) {
232
+ try {
233
+ return this[kHandler].onBodySent(chunk)
234
+ } catch (err) {
235
+ this.abort(err)
236
+ }
237
+ }
238
+ }
239
+
240
+ onRequestSent () {
241
+ if (channels.bodySent.hasSubscribers) {
242
+ channels.bodySent.publish({ request: this })
243
+ }
244
+
245
+ if (this[kHandler].onRequestSent) {
246
+ try {
247
+ return this[kHandler].onRequestSent()
248
+ } catch (err) {
249
+ this.abort(err)
250
+ }
251
+ }
252
+ }
253
+
254
+ onConnect (abort) {
255
+ assert(!this.aborted)
256
+ assert(!this.completed)
257
+
258
+ if (this.error) {
259
+ abort(this.error)
260
+ } else {
261
+ this.abort = abort
262
+ return this[kHandler].onConnect(abort)
263
+ }
264
+ }
265
+
266
+ onHeaders (statusCode, headers, resume, statusText) {
267
+ assert(!this.aborted)
268
+ assert(!this.completed)
269
+
270
+ if (channels.headers.hasSubscribers) {
271
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
272
+ }
273
+
274
+ try {
275
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
276
+ } catch (err) {
277
+ this.abort(err)
278
+ }
279
+ }
280
+
281
+ onData (chunk) {
282
+ assert(!this.aborted)
283
+ assert(!this.completed)
284
+
285
+ try {
286
+ return this[kHandler].onData(chunk)
287
+ } catch (err) {
288
+ this.abort(err)
289
+ return false
290
+ }
291
+ }
292
+
293
+ onUpgrade (statusCode, headers, socket) {
294
+ assert(!this.aborted)
295
+ assert(!this.completed)
296
+
297
+ return this[kHandler].onUpgrade(statusCode, headers, socket)
298
+ }
299
+
300
+ onComplete (trailers) {
301
+ this.onFinally()
302
+
303
+ assert(!this.aborted)
304
+
305
+ this.completed = true
306
+ if (channels.trailers.hasSubscribers) {
307
+ channels.trailers.publish({ request: this, trailers })
308
+ }
309
+
310
+ try {
311
+ return this[kHandler].onComplete(trailers)
312
+ } catch (err) {
313
+ // TODO (fix): This might be a bad idea?
314
+ this.onError(err)
315
+ }
316
+ }
317
+
318
+ onError (error) {
319
+ this.onFinally()
320
+
321
+ if (channels.error.hasSubscribers) {
322
+ channels.error.publish({ request: this, error })
323
+ }
324
+
325
+ if (this.aborted) {
326
+ return
327
+ }
328
+ this.aborted = true
329
+
330
+ return this[kHandler].onError(error)
331
+ }
332
+
333
+ onFinally () {
334
+ if (this.errorHandler) {
335
+ this.body.off('error', this.errorHandler)
336
+ this.errorHandler = null
337
+ }
338
+
339
+ if (this.endHandler) {
340
+ this.body.off('end', this.endHandler)
341
+ this.endHandler = null
342
+ }
343
+ }
344
+
345
+ // TODO: adjust to support H2
346
+ addHeader (key, value) {
347
+ processHeader(this, key, value)
348
+ return this
349
+ }
350
+
351
+ static [kHTTP1BuildRequest] (origin, opts, handler) {
352
+ // TODO: Migrate header parsing here, to make Requests
353
+ // HTTP agnostic
354
+ return new Request(origin, opts, handler)
355
+ }
356
+
357
+ static [kHTTP2BuildRequest] (origin, opts, handler) {
358
+ const headers = opts.headers
359
+ opts = { ...opts, headers: null }
360
+
361
+ const request = new Request(origin, opts, handler)
362
+
363
+ request.headers = {}
364
+
365
+ if (Array.isArray(headers)) {
366
+ if (headers.length % 2 !== 0) {
367
+ throw new InvalidArgumentError('headers array must be even')
368
+ }
369
+ for (let i = 0; i < headers.length; i += 2) {
370
+ processHeader(request, headers[i], headers[i + 1], true)
371
+ }
372
+ } else if (headers && typeof headers === 'object') {
373
+ const keys = Object.keys(headers)
374
+ for (let i = 0; i < keys.length; i++) {
375
+ const key = keys[i]
376
+ processHeader(request, key, headers[key], true)
377
+ }
378
+ } else if (headers != null) {
379
+ throw new InvalidArgumentError('headers must be an object or an array')
380
+ }
381
+
382
+ return request
383
+ }
384
+
385
+ static [kHTTP2CopyHeaders] (raw) {
386
+ const rawHeaders = raw.split('\r\n')
387
+ const headers = {}
388
+
389
+ for (const header of rawHeaders) {
390
+ const [key, value] = header.split(': ')
391
+
392
+ if (value == null || value.length === 0) continue
393
+
394
+ if (headers[key]) headers[key] += `,${value}`
395
+ else headers[key] = value
396
+ }
397
+
398
+ return headers
399
+ }
400
+ }
401
+
402
+ function processHeaderValue (key, val, skipAppend) {
403
+ if (val && typeof val === 'object') {
404
+ throw new InvalidArgumentError(`invalid ${key} header`)
405
+ }
406
+
407
+ val = val != null ? `${val}` : ''
408
+
409
+ if (headerCharRegex.exec(val) !== null) {
410
+ throw new InvalidArgumentError(`invalid ${key} header`)
411
+ }
412
+
413
+ return skipAppend ? val : `${key}: ${val}\r\n`
414
+ }
415
+
416
+ function processHeader (request, key, val, skipAppend = false) {
417
+ if (val && (typeof val === 'object' && !Array.isArray(val))) {
418
+ throw new InvalidArgumentError(`invalid ${key} header`)
419
+ } else if (val === undefined) {
420
+ return
421
+ }
422
+
423
+ if (
424
+ request.host === null &&
425
+ key.length === 4 &&
426
+ key.toLowerCase() === 'host'
427
+ ) {
428
+ if (headerCharRegex.exec(val) !== null) {
429
+ throw new InvalidArgumentError(`invalid ${key} header`)
430
+ }
431
+ // Consumed by Client
432
+ request.host = val
433
+ } else if (
434
+ request.contentLength === null &&
435
+ key.length === 14 &&
436
+ key.toLowerCase() === 'content-length'
437
+ ) {
438
+ request.contentLength = parseInt(val, 10)
439
+ if (!Number.isFinite(request.contentLength)) {
440
+ throw new InvalidArgumentError('invalid content-length header')
441
+ }
442
+ } else if (
443
+ request.contentType === null &&
444
+ key.length === 12 &&
445
+ key.toLowerCase() === 'content-type'
446
+ ) {
447
+ request.contentType = val
448
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
449
+ else request.headers += processHeaderValue(key, val)
450
+ } else if (
451
+ key.length === 17 &&
452
+ key.toLowerCase() === 'transfer-encoding'
453
+ ) {
454
+ throw new InvalidArgumentError('invalid transfer-encoding header')
455
+ } else if (
456
+ key.length === 10 &&
457
+ key.toLowerCase() === 'connection'
458
+ ) {
459
+ const value = typeof val === 'string' ? val.toLowerCase() : null
460
+ if (value !== 'close' && value !== 'keep-alive') {
461
+ throw new InvalidArgumentError('invalid connection header')
462
+ } else if (value === 'close') {
463
+ request.reset = true
464
+ }
465
+ } else if (
466
+ key.length === 10 &&
467
+ key.toLowerCase() === 'keep-alive'
468
+ ) {
469
+ throw new InvalidArgumentError('invalid keep-alive header')
470
+ } else if (
471
+ key.length === 7 &&
472
+ key.toLowerCase() === 'upgrade'
473
+ ) {
474
+ throw new InvalidArgumentError('invalid upgrade header')
475
+ } else if (
476
+ key.length === 6 &&
477
+ key.toLowerCase() === 'expect'
478
+ ) {
479
+ throw new NotSupportedError('expect header not supported')
480
+ } else if (tokenRegExp.exec(key) === null) {
481
+ throw new InvalidArgumentError('invalid header key')
482
+ } else {
483
+ if (Array.isArray(val)) {
484
+ for (let i = 0; i < val.length; i++) {
485
+ if (skipAppend) {
486
+ if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
487
+ else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
488
+ } else {
489
+ request.headers += processHeaderValue(key, val[i])
490
+ }
491
+ }
492
+ } else {
493
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
494
+ else request.headers += processHeaderValue(key, val)
495
+ }
496
+ }
497
+ }
498
+
499
+ module.exports = Request
worker/node_modules/undici/lib/core/symbols.js ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ kClose: Symbol('close'),
3
+ kDestroy: Symbol('destroy'),
4
+ kDispatch: Symbol('dispatch'),
5
+ kUrl: Symbol('url'),
6
+ kWriting: Symbol('writing'),
7
+ kResuming: Symbol('resuming'),
8
+ kQueue: Symbol('queue'),
9
+ kConnect: Symbol('connect'),
10
+ kConnecting: Symbol('connecting'),
11
+ kHeadersList: Symbol('headers list'),
12
+ kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
13
+ kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
14
+ kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
15
+ kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
16
+ kKeepAlive: Symbol('keep alive'),
17
+ kHeadersTimeout: Symbol('headers timeout'),
18
+ kBodyTimeout: Symbol('body timeout'),
19
+ kServerName: Symbol('server name'),
20
+ kLocalAddress: Symbol('local address'),
21
+ kHost: Symbol('host'),
22
+ kNoRef: Symbol('no ref'),
23
+ kBodyUsed: Symbol('used'),
24
+ kRunning: Symbol('running'),
25
+ kBlocking: Symbol('blocking'),
26
+ kPending: Symbol('pending'),
27
+ kSize: Symbol('size'),
28
+ kBusy: Symbol('busy'),
29
+ kQueued: Symbol('queued'),
30
+ kFree: Symbol('free'),
31
+ kConnected: Symbol('connected'),
32
+ kClosed: Symbol('closed'),
33
+ kNeedDrain: Symbol('need drain'),
34
+ kReset: Symbol('reset'),
35
+ kDestroyed: Symbol.for('nodejs.stream.destroyed'),
36
+ kMaxHeadersSize: Symbol('max headers size'),
37
+ kRunningIdx: Symbol('running index'),
38
+ kPendingIdx: Symbol('pending index'),
39
+ kError: Symbol('error'),
40
+ kClients: Symbol('clients'),
41
+ kClient: Symbol('client'),
42
+ kParser: Symbol('parser'),
43
+ kOnDestroyed: Symbol('destroy callbacks'),
44
+ kPipelining: Symbol('pipelining'),
45
+ kSocket: Symbol('socket'),
46
+ kHostHeader: Symbol('host header'),
47
+ kConnector: Symbol('connector'),
48
+ kStrictContentLength: Symbol('strict content length'),
49
+ kMaxRedirections: Symbol('maxRedirections'),
50
+ kMaxRequests: Symbol('maxRequestsPerClient'),
51
+ kProxy: Symbol('proxy agent options'),
52
+ kCounter: Symbol('socket request counter'),
53
+ kInterceptors: Symbol('dispatch interceptors'),
54
+ kMaxResponseSize: Symbol('max response size'),
55
+ kHTTP2Session: Symbol('http2Session'),
56
+ kHTTP2SessionState: Symbol('http2Session state'),
57
+ kHTTP2BuildRequest: Symbol('http2 build request'),
58
+ kHTTP1BuildRequest: Symbol('http1 build request'),
59
+ kHTTP2CopyHeaders: Symbol('http2 copy headers'),
60
+ kHTTPConnVersion: Symbol('http connection version'),
61
+ kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
62
+ kConstruct: Symbol('constructable')
63
+ }
worker/node_modules/undici/lib/core/util.js ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const assert = require('assert')
4
+ const { kDestroyed, kBodyUsed } = require('./symbols')
5
+ const { IncomingMessage } = require('http')
6
+ const stream = require('stream')
7
+ const net = require('net')
8
+ const { InvalidArgumentError } = require('./errors')
9
+ const { Blob } = require('buffer')
10
+ const nodeUtil = require('util')
11
+ const { stringify } = require('querystring')
12
+ const { headerNameLowerCasedRecord } = require('./constants')
13
+
14
+ const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
15
+
16
+ function nop () {}
17
+
18
+ function isStream (obj) {
19
+ return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
20
+ }
21
+
22
+ // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
23
+ function isBlobLike (object) {
24
+ return (Blob && object instanceof Blob) || (
25
+ object &&
26
+ typeof object === 'object' &&
27
+ (typeof object.stream === 'function' ||
28
+ typeof object.arrayBuffer === 'function') &&
29
+ /^(Blob|File)$/.test(object[Symbol.toStringTag])
30
+ )
31
+ }
32
+
33
+ function buildURL (url, queryParams) {
34
+ if (url.includes('?') || url.includes('#')) {
35
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".')
36
+ }
37
+
38
+ const stringified = stringify(queryParams)
39
+
40
+ if (stringified) {
41
+ url += '?' + stringified
42
+ }
43
+
44
+ return url
45
+ }
46
+
47
+ function parseURL (url) {
48
+ if (typeof url === 'string') {
49
+ url = new URL(url)
50
+
51
+ if (!/^https?:/.test(url.origin || url.protocol)) {
52
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
53
+ }
54
+
55
+ return url
56
+ }
57
+
58
+ if (!url || typeof url !== 'object') {
59
+ throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
60
+ }
61
+
62
+ if (!/^https?:/.test(url.origin || url.protocol)) {
63
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
64
+ }
65
+
66
+ if (!(url instanceof URL)) {
67
+ if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
68
+ throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
69
+ }
70
+
71
+ if (url.path != null && typeof url.path !== 'string') {
72
+ throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
73
+ }
74
+
75
+ if (url.pathname != null && typeof url.pathname !== 'string') {
76
+ throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
77
+ }
78
+
79
+ if (url.hostname != null && typeof url.hostname !== 'string') {
80
+ throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
81
+ }
82
+
83
+ if (url.origin != null && typeof url.origin !== 'string') {
84
+ throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
85
+ }
86
+
87
+ const port = url.port != null
88
+ ? url.port
89
+ : (url.protocol === 'https:' ? 443 : 80)
90
+ let origin = url.origin != null
91
+ ? url.origin
92
+ : `${url.protocol}//${url.hostname}:${port}`
93
+ let path = url.path != null
94
+ ? url.path
95
+ : `${url.pathname || ''}${url.search || ''}`
96
+
97
+ if (origin.endsWith('/')) {
98
+ origin = origin.substring(0, origin.length - 1)
99
+ }
100
+
101
+ if (path && !path.startsWith('/')) {
102
+ path = `/${path}`
103
+ }
104
+ // new URL(path, origin) is unsafe when `path` contains an absolute URL
105
+ // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
106
+ // If first parameter is a relative URL, second param is required, and will be used as the base URL.
107
+ // If first parameter is an absolute URL, a given second param will be ignored.
108
+ url = new URL(origin + path)
109
+ }
110
+
111
+ return url
112
+ }
113
+
114
+ function parseOrigin (url) {
115
+ url = parseURL(url)
116
+
117
+ if (url.pathname !== '/' || url.search || url.hash) {
118
+ throw new InvalidArgumentError('invalid url')
119
+ }
120
+
121
+ return url
122
+ }
123
+
124
+ function getHostname (host) {
125
+ if (host[0] === '[') {
126
+ const idx = host.indexOf(']')
127
+
128
+ assert(idx !== -1)
129
+ return host.substring(1, idx)
130
+ }
131
+
132
+ const idx = host.indexOf(':')
133
+ if (idx === -1) return host
134
+
135
+ return host.substring(0, idx)
136
+ }
137
+
138
+ // IP addresses are not valid server names per RFC6066
139
+ // > Currently, the only server names supported are DNS hostnames
140
+ function getServerName (host) {
141
+ if (!host) {
142
+ return null
143
+ }
144
+
145
+ assert.strictEqual(typeof host, 'string')
146
+
147
+ const servername = getHostname(host)
148
+ if (net.isIP(servername)) {
149
+ return ''
150
+ }
151
+
152
+ return servername
153
+ }
154
+
155
+ function deepClone (obj) {
156
+ return JSON.parse(JSON.stringify(obj))
157
+ }
158
+
159
+ function isAsyncIterable (obj) {
160
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
161
+ }
162
+
163
+ function isIterable (obj) {
164
+ return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
165
+ }
166
+
167
+ function bodyLength (body) {
168
+ if (body == null) {
169
+ return 0
170
+ } else if (isStream(body)) {
171
+ const state = body._readableState
172
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
173
+ ? state.length
174
+ : null
175
+ } else if (isBlobLike(body)) {
176
+ return body.size != null ? body.size : null
177
+ } else if (isBuffer(body)) {
178
+ return body.byteLength
179
+ }
180
+
181
+ return null
182
+ }
183
+
184
+ function isDestroyed (stream) {
185
+ return !stream || !!(stream.destroyed || stream[kDestroyed])
186
+ }
187
+
188
+ function isReadableAborted (stream) {
189
+ const state = stream && stream._readableState
190
+ return isDestroyed(stream) && state && !state.endEmitted
191
+ }
192
+
193
+ function destroy (stream, err) {
194
+ if (stream == null || !isStream(stream) || isDestroyed(stream)) {
195
+ return
196
+ }
197
+
198
+ if (typeof stream.destroy === 'function') {
199
+ if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
200
+ // See: https://github.com/nodejs/node/pull/38505/files
201
+ stream.socket = null
202
+ }
203
+
204
+ stream.destroy(err)
205
+ } else if (err) {
206
+ process.nextTick((stream, err) => {
207
+ stream.emit('error', err)
208
+ }, stream, err)
209
+ }
210
+
211
+ if (stream.destroyed !== true) {
212
+ stream[kDestroyed] = true
213
+ }
214
+ }
215
+
216
+ const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
217
+ function parseKeepAliveTimeout (val) {
218
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
219
+ return m ? parseInt(m[1], 10) * 1000 : null
220
+ }
221
+
222
+ /**
223
+ * Retrieves a header name and returns its lowercase value.
224
+ * @param {string | Buffer} value Header name
225
+ * @returns {string}
226
+ */
227
+ function headerNameToString (value) {
228
+ return headerNameLowerCasedRecord[value] || value.toLowerCase()
229
+ }
230
+
231
+ function parseHeaders (headers, obj = {}) {
232
+ // For H2 support
233
+ if (!Array.isArray(headers)) return headers
234
+
235
+ for (let i = 0; i < headers.length; i += 2) {
236
+ const key = headers[i].toString().toLowerCase()
237
+ let val = obj[key]
238
+
239
+ if (!val) {
240
+ if (Array.isArray(headers[i + 1])) {
241
+ obj[key] = headers[i + 1].map(x => x.toString('utf8'))
242
+ } else {
243
+ obj[key] = headers[i + 1].toString('utf8')
244
+ }
245
+ } else {
246
+ if (!Array.isArray(val)) {
247
+ val = [val]
248
+ obj[key] = val
249
+ }
250
+ val.push(headers[i + 1].toString('utf8'))
251
+ }
252
+ }
253
+
254
+ // See https://github.com/nodejs/node/pull/46528
255
+ if ('content-length' in obj && 'content-disposition' in obj) {
256
+ obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
257
+ }
258
+
259
+ return obj
260
+ }
261
+
262
+ function parseRawHeaders (headers) {
263
+ const ret = []
264
+ let hasContentLength = false
265
+ let contentDispositionIdx = -1
266
+
267
+ for (let n = 0; n < headers.length; n += 2) {
268
+ const key = headers[n + 0].toString()
269
+ const val = headers[n + 1].toString('utf8')
270
+
271
+ if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
272
+ ret.push(key, val)
273
+ hasContentLength = true
274
+ } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
275
+ contentDispositionIdx = ret.push(key, val) - 1
276
+ } else {
277
+ ret.push(key, val)
278
+ }
279
+ }
280
+
281
+ // See https://github.com/nodejs/node/pull/46528
282
+ if (hasContentLength && contentDispositionIdx !== -1) {
283
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
284
+ }
285
+
286
+ return ret
287
+ }
288
+
289
+ function isBuffer (buffer) {
290
+ // See, https://github.com/mcollina/undici/pull/319
291
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
292
+ }
293
+
294
+ function validateHandler (handler, method, upgrade) {
295
+ if (!handler || typeof handler !== 'object') {
296
+ throw new InvalidArgumentError('handler must be an object')
297
+ }
298
+
299
+ if (typeof handler.onConnect !== 'function') {
300
+ throw new InvalidArgumentError('invalid onConnect method')
301
+ }
302
+
303
+ if (typeof handler.onError !== 'function') {
304
+ throw new InvalidArgumentError('invalid onError method')
305
+ }
306
+
307
+ if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
308
+ throw new InvalidArgumentError('invalid onBodySent method')
309
+ }
310
+
311
+ if (upgrade || method === 'CONNECT') {
312
+ if (typeof handler.onUpgrade !== 'function') {
313
+ throw new InvalidArgumentError('invalid onUpgrade method')
314
+ }
315
+ } else {
316
+ if (typeof handler.onHeaders !== 'function') {
317
+ throw new InvalidArgumentError('invalid onHeaders method')
318
+ }
319
+
320
+ if (typeof handler.onData !== 'function') {
321
+ throw new InvalidArgumentError('invalid onData method')
322
+ }
323
+
324
+ if (typeof handler.onComplete !== 'function') {
325
+ throw new InvalidArgumentError('invalid onComplete method')
326
+ }
327
+ }
328
+ }
329
+
330
+ // A body is disturbed if it has been read from and it cannot
331
+ // be re-used without losing state or data.
332
+ function isDisturbed (body) {
333
+ return !!(body && (
334
+ stream.isDisturbed
335
+ ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
336
+ : body[kBodyUsed] ||
337
+ body.readableDidRead ||
338
+ (body._readableState && body._readableState.dataEmitted) ||
339
+ isReadableAborted(body)
340
+ ))
341
+ }
342
+
343
+ function isErrored (body) {
344
+ return !!(body && (
345
+ stream.isErrored
346
+ ? stream.isErrored(body)
347
+ : /state: 'errored'/.test(nodeUtil.inspect(body)
348
+ )))
349
+ }
350
+
351
+ function isReadable (body) {
352
+ return !!(body && (
353
+ stream.isReadable
354
+ ? stream.isReadable(body)
355
+ : /state: 'readable'/.test(nodeUtil.inspect(body)
356
+ )))
357
+ }
358
+
359
+ function getSocketInfo (socket) {
360
+ return {
361
+ localAddress: socket.localAddress,
362
+ localPort: socket.localPort,
363
+ remoteAddress: socket.remoteAddress,
364
+ remotePort: socket.remotePort,
365
+ remoteFamily: socket.remoteFamily,
366
+ timeout: socket.timeout,
367
+ bytesWritten: socket.bytesWritten,
368
+ bytesRead: socket.bytesRead
369
+ }
370
+ }
371
+
372
+ async function * convertIterableToBuffer (iterable) {
373
+ for await (const chunk of iterable) {
374
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
375
+ }
376
+ }
377
+
378
+ let ReadableStream
379
+ function ReadableStreamFrom (iterable) {
380
+ if (!ReadableStream) {
381
+ ReadableStream = require('stream/web').ReadableStream
382
+ }
383
+
384
+ if (ReadableStream.from) {
385
+ return ReadableStream.from(convertIterableToBuffer(iterable))
386
+ }
387
+
388
+ let iterator
389
+ return new ReadableStream(
390
+ {
391
+ async start () {
392
+ iterator = iterable[Symbol.asyncIterator]()
393
+ },
394
+ async pull (controller) {
395
+ const { done, value } = await iterator.next()
396
+ if (done) {
397
+ queueMicrotask(() => {
398
+ controller.close()
399
+ })
400
+ } else {
401
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
402
+ controller.enqueue(new Uint8Array(buf))
403
+ }
404
+ return controller.desiredSize > 0
405
+ },
406
+ async cancel (reason) {
407
+ await iterator.return()
408
+ }
409
+ },
410
+ 0
411
+ )
412
+ }
413
+
414
+ // The chunk should be a FormData instance and contains
415
+ // all the required methods.
416
+ function isFormDataLike (object) {
417
+ return (
418
+ object &&
419
+ typeof object === 'object' &&
420
+ typeof object.append === 'function' &&
421
+ typeof object.delete === 'function' &&
422
+ typeof object.get === 'function' &&
423
+ typeof object.getAll === 'function' &&
424
+ typeof object.has === 'function' &&
425
+ typeof object.set === 'function' &&
426
+ object[Symbol.toStringTag] === 'FormData'
427
+ )
428
+ }
429
+
430
+ function throwIfAborted (signal) {
431
+ if (!signal) { return }
432
+ if (typeof signal.throwIfAborted === 'function') {
433
+ signal.throwIfAborted()
434
+ } else {
435
+ if (signal.aborted) {
436
+ // DOMException not available < v17.0.0
437
+ const err = new Error('The operation was aborted')
438
+ err.name = 'AbortError'
439
+ throw err
440
+ }
441
+ }
442
+ }
443
+
444
+ function addAbortListener (signal, listener) {
445
+ if ('addEventListener' in signal) {
446
+ signal.addEventListener('abort', listener, { once: true })
447
+ return () => signal.removeEventListener('abort', listener)
448
+ }
449
+ signal.addListener('abort', listener)
450
+ return () => signal.removeListener('abort', listener)
451
+ }
452
+
453
+ const hasToWellFormed = !!String.prototype.toWellFormed
454
+
455
+ /**
456
+ * @param {string} val
457
+ */
458
+ function toUSVString (val) {
459
+ if (hasToWellFormed) {
460
+ return `${val}`.toWellFormed()
461
+ } else if (nodeUtil.toUSVString) {
462
+ return nodeUtil.toUSVString(val)
463
+ }
464
+
465
+ return `${val}`
466
+ }
467
+
468
+ // Parsed accordingly to RFC 9110
469
+ // https://www.rfc-editor.org/rfc/rfc9110#field.content-range
470
+ function parseRangeHeader (range) {
471
+ if (range == null || range === '') return { start: 0, end: null, size: null }
472
+
473
+ const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
474
+ return m
475
+ ? {
476
+ start: parseInt(m[1]),
477
+ end: m[2] ? parseInt(m[2]) : null,
478
+ size: m[3] ? parseInt(m[3]) : null
479
+ }
480
+ : null
481
+ }
482
+
483
+ const kEnumerableProperty = Object.create(null)
484
+ kEnumerableProperty.enumerable = true
485
+
486
+ module.exports = {
487
+ kEnumerableProperty,
488
+ nop,
489
+ isDisturbed,
490
+ isErrored,
491
+ isReadable,
492
+ toUSVString,
493
+ isReadableAborted,
494
+ isBlobLike,
495
+ parseOrigin,
496
+ parseURL,
497
+ getServerName,
498
+ isStream,
499
+ isIterable,
500
+ isAsyncIterable,
501
+ isDestroyed,
502
+ headerNameToString,
503
+ parseRawHeaders,
504
+ parseHeaders,
505
+ parseKeepAliveTimeout,
506
+ destroy,
507
+ bodyLength,
508
+ deepClone,
509
+ ReadableStreamFrom,
510
+ isBuffer,
511
+ validateHandler,
512
+ getSocketInfo,
513
+ isFormDataLike,
514
+ buildURL,
515
+ throwIfAborted,
516
+ addAbortListener,
517
+ parseRangeHeader,
518
+ nodeMajor,
519
+ nodeMinor,
520
+ nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
521
+ safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
522
+ }
worker/node_modules/undici/lib/dispatcher-base.js ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const Dispatcher = require('./dispatcher')
4
+ const {
5
+ ClientDestroyedError,
6
+ ClientClosedError,
7
+ InvalidArgumentError
8
+ } = require('./core/errors')
9
+ const { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols')
10
+
11
+ const kDestroyed = Symbol('destroyed')
12
+ const kClosed = Symbol('closed')
13
+ const kOnDestroyed = Symbol('onDestroyed')
14
+ const kOnClosed = Symbol('onClosed')
15
+ const kInterceptedDispatch = Symbol('Intercepted Dispatch')
16
+
17
+ class DispatcherBase extends Dispatcher {
18
+ constructor () {
19
+ super()
20
+
21
+ this[kDestroyed] = false
22
+ this[kOnDestroyed] = null
23
+ this[kClosed] = false
24
+ this[kOnClosed] = []
25
+ }
26
+
27
+ get destroyed () {
28
+ return this[kDestroyed]
29
+ }
30
+
31
+ get closed () {
32
+ return this[kClosed]
33
+ }
34
+
35
+ get interceptors () {
36
+ return this[kInterceptors]
37
+ }
38
+
39
+ set interceptors (newInterceptors) {
40
+ if (newInterceptors) {
41
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
42
+ const interceptor = this[kInterceptors][i]
43
+ if (typeof interceptor !== 'function') {
44
+ throw new InvalidArgumentError('interceptor must be an function')
45
+ }
46
+ }
47
+ }
48
+
49
+ this[kInterceptors] = newInterceptors
50
+ }
51
+
52
+ close (callback) {
53
+ if (callback === undefined) {
54
+ return new Promise((resolve, reject) => {
55
+ this.close((err, data) => {
56
+ return err ? reject(err) : resolve(data)
57
+ })
58
+ })
59
+ }
60
+
61
+ if (typeof callback !== 'function') {
62
+ throw new InvalidArgumentError('invalid callback')
63
+ }
64
+
65
+ if (this[kDestroyed]) {
66
+ queueMicrotask(() => callback(new ClientDestroyedError(), null))
67
+ return
68
+ }
69
+
70
+ if (this[kClosed]) {
71
+ if (this[kOnClosed]) {
72
+ this[kOnClosed].push(callback)
73
+ } else {
74
+ queueMicrotask(() => callback(null, null))
75
+ }
76
+ return
77
+ }
78
+
79
+ this[kClosed] = true
80
+ this[kOnClosed].push(callback)
81
+
82
+ const onClosed = () => {
83
+ const callbacks = this[kOnClosed]
84
+ this[kOnClosed] = null
85
+ for (let i = 0; i < callbacks.length; i++) {
86
+ callbacks[i](null, null)
87
+ }
88
+ }
89
+
90
+ // Should not error.
91
+ this[kClose]()
92
+ .then(() => this.destroy())
93
+ .then(() => {
94
+ queueMicrotask(onClosed)
95
+ })
96
+ }
97
+
98
+ destroy (err, callback) {
99
+ if (typeof err === 'function') {
100
+ callback = err
101
+ err = null
102
+ }
103
+
104
+ if (callback === undefined) {
105
+ return new Promise((resolve, reject) => {
106
+ this.destroy(err, (err, data) => {
107
+ return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
108
+ })
109
+ })
110
+ }
111
+
112
+ if (typeof callback !== 'function') {
113
+ throw new InvalidArgumentError('invalid callback')
114
+ }
115
+
116
+ if (this[kDestroyed]) {
117
+ if (this[kOnDestroyed]) {
118
+ this[kOnDestroyed].push(callback)
119
+ } else {
120
+ queueMicrotask(() => callback(null, null))
121
+ }
122
+ return
123
+ }
124
+
125
+ if (!err) {
126
+ err = new ClientDestroyedError()
127
+ }
128
+
129
+ this[kDestroyed] = true
130
+ this[kOnDestroyed] = this[kOnDestroyed] || []
131
+ this[kOnDestroyed].push(callback)
132
+
133
+ const onDestroyed = () => {
134
+ const callbacks = this[kOnDestroyed]
135
+ this[kOnDestroyed] = null
136
+ for (let i = 0; i < callbacks.length; i++) {
137
+ callbacks[i](null, null)
138
+ }
139
+ }
140
+
141
+ // Should not error.
142
+ this[kDestroy](err).then(() => {
143
+ queueMicrotask(onDestroyed)
144
+ })
145
+ }
146
+
147
+ [kInterceptedDispatch] (opts, handler) {
148
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
149
+ this[kInterceptedDispatch] = this[kDispatch]
150
+ return this[kDispatch](opts, handler)
151
+ }
152
+
153
+ let dispatch = this[kDispatch].bind(this)
154
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
155
+ dispatch = this[kInterceptors][i](dispatch)
156
+ }
157
+ this[kInterceptedDispatch] = dispatch
158
+ return dispatch(opts, handler)
159
+ }
160
+
161
+ dispatch (opts, handler) {
162
+ if (!handler || typeof handler !== 'object') {
163
+ throw new InvalidArgumentError('handler must be an object')
164
+ }
165
+
166
+ try {
167
+ if (!opts || typeof opts !== 'object') {
168
+ throw new InvalidArgumentError('opts must be an object.')
169
+ }
170
+
171
+ if (this[kDestroyed] || this[kOnDestroyed]) {
172
+ throw new ClientDestroyedError()
173
+ }
174
+
175
+ if (this[kClosed]) {
176
+ throw new ClientClosedError()
177
+ }
178
+
179
+ return this[kInterceptedDispatch](opts, handler)
180
+ } catch (err) {
181
+ if (typeof handler.onError !== 'function') {
182
+ throw new InvalidArgumentError('invalid onError method')
183
+ }
184
+
185
+ handler.onError(err)
186
+
187
+ return false
188
+ }
189
+ }
190
+ }
191
+
192
+ module.exports = DispatcherBase
worker/node_modules/undici/lib/dispatcher.js ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const EventEmitter = require('events')
4
+
5
+ class Dispatcher extends EventEmitter {
6
+ dispatch () {
7
+ throw new Error('not implemented')
8
+ }
9
+
10
+ close () {
11
+ throw new Error('not implemented')
12
+ }
13
+
14
+ destroy () {
15
+ throw new Error('not implemented')
16
+ }
17
+ }
18
+
19
+ module.exports = Dispatcher
worker/node_modules/undici/lib/fetch/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Ethan Arrowood
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
worker/node_modules/undici/lib/fetch/body.js ADDED
@@ -0,0 +1,613 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const Busboy = require('@fastify/busboy')
4
+ const util = require('../core/util')
5
+ const {
6
+ ReadableStreamFrom,
7
+ isBlobLike,
8
+ isReadableStreamLike,
9
+ readableStreamClose,
10
+ createDeferredPromise,
11
+ fullyReadBody
12
+ } = require('./util')
13
+ const { FormData } = require('./formdata')
14
+ const { kState } = require('./symbols')
15
+ const { webidl } = require('./webidl')
16
+ const { DOMException, structuredClone } = require('./constants')
17
+ const { Blob, File: NativeFile } = require('buffer')
18
+ const { kBodyUsed } = require('../core/symbols')
19
+ const assert = require('assert')
20
+ const { isErrored } = require('../core/util')
21
+ const { isUint8Array, isArrayBuffer } = require('util/types')
22
+ const { File: UndiciFile } = require('./file')
23
+ const { parseMIMEType, serializeAMimeType } = require('./dataURL')
24
+
25
+ let random
26
+ try {
27
+ const crypto = require('node:crypto')
28
+ random = (max) => crypto.randomInt(0, max)
29
+ } catch {
30
+ random = (max) => Math.floor(Math.random(max))
31
+ }
32
+
33
+ let ReadableStream = globalThis.ReadableStream
34
+
35
+ /** @type {globalThis['File']} */
36
+ const File = NativeFile ?? UndiciFile
37
+ const textEncoder = new TextEncoder()
38
+ const textDecoder = new TextDecoder()
39
+
40
+ // https://fetch.spec.whatwg.org/#concept-bodyinit-extract
41
+ function extractBody (object, keepalive = false) {
42
+ if (!ReadableStream) {
43
+ ReadableStream = require('stream/web').ReadableStream
44
+ }
45
+
46
+ // 1. Let stream be null.
47
+ let stream = null
48
+
49
+ // 2. If object is a ReadableStream object, then set stream to object.
50
+ if (object instanceof ReadableStream) {
51
+ stream = object
52
+ } else if (isBlobLike(object)) {
53
+ // 3. Otherwise, if object is a Blob object, set stream to the
54
+ // result of running object’s get stream.
55
+ stream = object.stream()
56
+ } else {
57
+ // 4. Otherwise, set stream to a new ReadableStream object, and set
58
+ // up stream.
59
+ stream = new ReadableStream({
60
+ async pull (controller) {
61
+ controller.enqueue(
62
+ typeof source === 'string' ? textEncoder.encode(source) : source
63
+ )
64
+ queueMicrotask(() => readableStreamClose(controller))
65
+ },
66
+ start () {},
67
+ type: undefined
68
+ })
69
+ }
70
+
71
+ // 5. Assert: stream is a ReadableStream object.
72
+ assert(isReadableStreamLike(stream))
73
+
74
+ // 6. Let action be null.
75
+ let action = null
76
+
77
+ // 7. Let source be null.
78
+ let source = null
79
+
80
+ // 8. Let length be null.
81
+ let length = null
82
+
83
+ // 9. Let type be null.
84
+ let type = null
85
+
86
+ // 10. Switch on object:
87
+ if (typeof object === 'string') {
88
+ // Set source to the UTF-8 encoding of object.
89
+ // Note: setting source to a Uint8Array here breaks some mocking assumptions.
90
+ source = object
91
+
92
+ // Set type to `text/plain;charset=UTF-8`.
93
+ type = 'text/plain;charset=UTF-8'
94
+ } else if (object instanceof URLSearchParams) {
95
+ // URLSearchParams
96
+
97
+ // spec says to run application/x-www-form-urlencoded on body.list
98
+ // this is implemented in Node.js as apart of an URLSearchParams instance toString method
99
+ // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
100
+ // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
101
+
102
+ // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
103
+ source = object.toString()
104
+
105
+ // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
106
+ type = 'application/x-www-form-urlencoded;charset=UTF-8'
107
+ } else if (isArrayBuffer(object)) {
108
+ // BufferSource/ArrayBuffer
109
+
110
+ // Set source to a copy of the bytes held by object.
111
+ source = new Uint8Array(object.slice())
112
+ } else if (ArrayBuffer.isView(object)) {
113
+ // BufferSource/ArrayBufferView
114
+
115
+ // Set source to a copy of the bytes held by object.
116
+ source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
117
+ } else if (util.isFormDataLike(object)) {
118
+ const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`
119
+ const prefix = `--${boundary}\r\nContent-Disposition: form-data`
120
+
121
+ /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
122
+ const escape = (str) =>
123
+ str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
124
+ const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
125
+
126
+ // Set action to this step: run the multipart/form-data
127
+ // encoding algorithm, with object’s entry list and UTF-8.
128
+ // - This ensures that the body is immutable and can't be changed afterwords
129
+ // - That the content-length is calculated in advance.
130
+ // - And that all parts are pre-encoded and ready to be sent.
131
+
132
+ const blobParts = []
133
+ const rn = new Uint8Array([13, 10]) // '\r\n'
134
+ length = 0
135
+ let hasUnknownSizeValue = false
136
+
137
+ for (const [name, value] of object) {
138
+ if (typeof value === 'string') {
139
+ const chunk = textEncoder.encode(prefix +
140
+ `; name="${escape(normalizeLinefeeds(name))}"` +
141
+ `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
142
+ blobParts.push(chunk)
143
+ length += chunk.byteLength
144
+ } else {
145
+ const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
146
+ (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
147
+ `Content-Type: ${
148
+ value.type || 'application/octet-stream'
149
+ }\r\n\r\n`)
150
+ blobParts.push(chunk, value, rn)
151
+ if (typeof value.size === 'number') {
152
+ length += chunk.byteLength + value.size + rn.byteLength
153
+ } else {
154
+ hasUnknownSizeValue = true
155
+ }
156
+ }
157
+ }
158
+
159
+ const chunk = textEncoder.encode(`--${boundary}--`)
160
+ blobParts.push(chunk)
161
+ length += chunk.byteLength
162
+ if (hasUnknownSizeValue) {
163
+ length = null
164
+ }
165
+
166
+ // Set source to object.
167
+ source = object
168
+
169
+ action = async function * () {
170
+ for (const part of blobParts) {
171
+ if (part.stream) {
172
+ yield * part.stream()
173
+ } else {
174
+ yield part
175
+ }
176
+ }
177
+ }
178
+
179
+ // Set type to `multipart/form-data; boundary=`,
180
+ // followed by the multipart/form-data boundary string generated
181
+ // by the multipart/form-data encoding algorithm.
182
+ type = 'multipart/form-data; boundary=' + boundary
183
+ } else if (isBlobLike(object)) {
184
+ // Blob
185
+
186
+ // Set source to object.
187
+ source = object
188
+
189
+ // Set length to object’s size.
190
+ length = object.size
191
+
192
+ // If object’s type attribute is not the empty byte sequence, set
193
+ // type to its value.
194
+ if (object.type) {
195
+ type = object.type
196
+ }
197
+ } else if (typeof object[Symbol.asyncIterator] === 'function') {
198
+ // If keepalive is true, then throw a TypeError.
199
+ if (keepalive) {
200
+ throw new TypeError('keepalive')
201
+ }
202
+
203
+ // If object is disturbed or locked, then throw a TypeError.
204
+ if (util.isDisturbed(object) || object.locked) {
205
+ throw new TypeError(
206
+ 'Response body object should not be disturbed or locked'
207
+ )
208
+ }
209
+
210
+ stream =
211
+ object instanceof ReadableStream ? object : ReadableStreamFrom(object)
212
+ }
213
+
214
+ // 11. If source is a byte sequence, then set action to a
215
+ // step that returns source and length to source’s length.
216
+ if (typeof source === 'string' || util.isBuffer(source)) {
217
+ length = Buffer.byteLength(source)
218
+ }
219
+
220
+ // 12. If action is non-null, then run these steps in in parallel:
221
+ if (action != null) {
222
+ // Run action.
223
+ let iterator
224
+ stream = new ReadableStream({
225
+ async start () {
226
+ iterator = action(object)[Symbol.asyncIterator]()
227
+ },
228
+ async pull (controller) {
229
+ const { value, done } = await iterator.next()
230
+ if (done) {
231
+ // When running action is done, close stream.
232
+ queueMicrotask(() => {
233
+ controller.close()
234
+ })
235
+ } else {
236
+ // Whenever one or more bytes are available and stream is not errored,
237
+ // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
238
+ // bytes into stream.
239
+ if (!isErrored(stream)) {
240
+ controller.enqueue(new Uint8Array(value))
241
+ }
242
+ }
243
+ return controller.desiredSize > 0
244
+ },
245
+ async cancel (reason) {
246
+ await iterator.return()
247
+ },
248
+ type: undefined
249
+ })
250
+ }
251
+
252
+ // 13. Let body be a body whose stream is stream, source is source,
253
+ // and length is length.
254
+ const body = { stream, source, length }
255
+
256
+ // 14. Return (body, type).
257
+ return [body, type]
258
+ }
259
+
260
+ // https://fetch.spec.whatwg.org/#bodyinit-safely-extract
261
+ function safelyExtractBody (object, keepalive = false) {
262
+ if (!ReadableStream) {
263
+ // istanbul ignore next
264
+ ReadableStream = require('stream/web').ReadableStream
265
+ }
266
+
267
+ // To safely extract a body and a `Content-Type` value from
268
+ // a byte sequence or BodyInit object object, run these steps:
269
+
270
+ // 1. If object is a ReadableStream object, then:
271
+ if (object instanceof ReadableStream) {
272
+ // Assert: object is neither disturbed nor locked.
273
+ // istanbul ignore next
274
+ assert(!util.isDisturbed(object), 'The body has already been consumed.')
275
+ // istanbul ignore next
276
+ assert(!object.locked, 'The stream is locked.')
277
+ }
278
+
279
+ // 2. Return the results of extracting object.
280
+ return extractBody(object, keepalive)
281
+ }
282
+
283
+ function cloneBody (body) {
284
+ // To clone a body body, run these steps:
285
+
286
+ // https://fetch.spec.whatwg.org/#concept-body-clone
287
+
288
+ // 1. Let « out1, out2 » be the result of teeing body’s stream.
289
+ const [out1, out2] = body.stream.tee()
290
+ const out2Clone = structuredClone(out2, { transfer: [out2] })
291
+ // This, for whatever reasons, unrefs out2Clone which allows
292
+ // the process to exit by itself.
293
+ const [, finalClone] = out2Clone.tee()
294
+
295
+ // 2. Set body’s stream to out1.
296
+ body.stream = out1
297
+
298
+ // 3. Return a body whose stream is out2 and other members are copied from body.
299
+ return {
300
+ stream: finalClone,
301
+ length: body.length,
302
+ source: body.source
303
+ }
304
+ }
305
+
306
+ async function * consumeBody (body) {
307
+ if (body) {
308
+ if (isUint8Array(body)) {
309
+ yield body
310
+ } else {
311
+ const stream = body.stream
312
+
313
+ if (util.isDisturbed(stream)) {
314
+ throw new TypeError('The body has already been consumed.')
315
+ }
316
+
317
+ if (stream.locked) {
318
+ throw new TypeError('The stream is locked.')
319
+ }
320
+
321
+ // Compat.
322
+ stream[kBodyUsed] = true
323
+
324
+ yield * stream
325
+ }
326
+ }
327
+ }
328
+
329
+ function throwIfAborted (state) {
330
+ if (state.aborted) {
331
+ throw new DOMException('The operation was aborted.', 'AbortError')
332
+ }
333
+ }
334
+
335
+ function bodyMixinMethods (instance) {
336
+ const methods = {
337
+ blob () {
338
+ // The blob() method steps are to return the result of
339
+ // running consume body with this and the following step
340
+ // given a byte sequence bytes: return a Blob whose
341
+ // contents are bytes and whose type attribute is this’s
342
+ // MIME type.
343
+ return specConsumeBody(this, (bytes) => {
344
+ let mimeType = bodyMimeType(this)
345
+
346
+ if (mimeType === 'failure') {
347
+ mimeType = ''
348
+ } else if (mimeType) {
349
+ mimeType = serializeAMimeType(mimeType)
350
+ }
351
+
352
+ // Return a Blob whose contents are bytes and type attribute
353
+ // is mimeType.
354
+ return new Blob([bytes], { type: mimeType })
355
+ }, instance)
356
+ },
357
+
358
+ arrayBuffer () {
359
+ // The arrayBuffer() method steps are to return the result
360
+ // of running consume body with this and the following step
361
+ // given a byte sequence bytes: return a new ArrayBuffer
362
+ // whose contents are bytes.
363
+ return specConsumeBody(this, (bytes) => {
364
+ return new Uint8Array(bytes).buffer
365
+ }, instance)
366
+ },
367
+
368
+ text () {
369
+ // The text() method steps are to return the result of running
370
+ // consume body with this and UTF-8 decode.
371
+ return specConsumeBody(this, utf8DecodeBytes, instance)
372
+ },
373
+
374
+ json () {
375
+ // The json() method steps are to return the result of running
376
+ // consume body with this and parse JSON from bytes.
377
+ return specConsumeBody(this, parseJSONFromBytes, instance)
378
+ },
379
+
380
+ async formData () {
381
+ webidl.brandCheck(this, instance)
382
+
383
+ throwIfAborted(this[kState])
384
+
385
+ const contentType = this.headers.get('Content-Type')
386
+
387
+ // If mimeType’s essence is "multipart/form-data", then:
388
+ if (/multipart\/form-data/.test(contentType)) {
389
+ const headers = {}
390
+ for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
391
+
392
+ const responseFormData = new FormData()
393
+
394
+ let busboy
395
+
396
+ try {
397
+ busboy = new Busboy({
398
+ headers,
399
+ preservePath: true
400
+ })
401
+ } catch (err) {
402
+ throw new DOMException(`${err}`, 'AbortError')
403
+ }
404
+
405
+ busboy.on('field', (name, value) => {
406
+ responseFormData.append(name, value)
407
+ })
408
+ busboy.on('file', (name, value, filename, encoding, mimeType) => {
409
+ const chunks = []
410
+
411
+ if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
412
+ let base64chunk = ''
413
+
414
+ value.on('data', (chunk) => {
415
+ base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
416
+
417
+ const end = base64chunk.length - base64chunk.length % 4
418
+ chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
419
+
420
+ base64chunk = base64chunk.slice(end)
421
+ })
422
+ value.on('end', () => {
423
+ chunks.push(Buffer.from(base64chunk, 'base64'))
424
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
425
+ })
426
+ } else {
427
+ value.on('data', (chunk) => {
428
+ chunks.push(chunk)
429
+ })
430
+ value.on('end', () => {
431
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
432
+ })
433
+ }
434
+ })
435
+
436
+ const busboyResolve = new Promise((resolve, reject) => {
437
+ busboy.on('finish', resolve)
438
+ busboy.on('error', (err) => reject(new TypeError(err)))
439
+ })
440
+
441
+ if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
442
+ busboy.end()
443
+ await busboyResolve
444
+
445
+ return responseFormData
446
+ } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
447
+ // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
448
+
449
+ // 1. Let entries be the result of parsing bytes.
450
+ let entries
451
+ try {
452
+ let text = ''
453
+ // application/x-www-form-urlencoded parser will keep the BOM.
454
+ // https://url.spec.whatwg.org/#concept-urlencoded-parser
455
+ // Note that streaming decoder is stateful and cannot be reused
456
+ const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
457
+
458
+ for await (const chunk of consumeBody(this[kState].body)) {
459
+ if (!isUint8Array(chunk)) {
460
+ throw new TypeError('Expected Uint8Array chunk')
461
+ }
462
+ text += streamingDecoder.decode(chunk, { stream: true })
463
+ }
464
+ text += streamingDecoder.decode()
465
+ entries = new URLSearchParams(text)
466
+ } catch (err) {
467
+ // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
468
+ // 2. If entries is failure, then throw a TypeError.
469
+ throw Object.assign(new TypeError(), { cause: err })
470
+ }
471
+
472
+ // 3. Return a new FormData object whose entries are entries.
473
+ const formData = new FormData()
474
+ for (const [name, value] of entries) {
475
+ formData.append(name, value)
476
+ }
477
+ return formData
478
+ } else {
479
+ // Wait a tick before checking if the request has been aborted.
480
+ // Otherwise, a TypeError can be thrown when an AbortError should.
481
+ await Promise.resolve()
482
+
483
+ throwIfAborted(this[kState])
484
+
485
+ // Otherwise, throw a TypeError.
486
+ throw webidl.errors.exception({
487
+ header: `${instance.name}.formData`,
488
+ message: 'Could not parse content as FormData.'
489
+ })
490
+ }
491
+ }
492
+ }
493
+
494
+ return methods
495
+ }
496
+
497
+ function mixinBody (prototype) {
498
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype))
499
+ }
500
+
501
+ /**
502
+ * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
503
+ * @param {Response|Request} object
504
+ * @param {(value: unknown) => unknown} convertBytesToJSValue
505
+ * @param {Response|Request} instance
506
+ */
507
+ async function specConsumeBody (object, convertBytesToJSValue, instance) {
508
+ webidl.brandCheck(object, instance)
509
+
510
+ throwIfAborted(object[kState])
511
+
512
+ // 1. If object is unusable, then return a promise rejected
513
+ // with a TypeError.
514
+ if (bodyUnusable(object[kState].body)) {
515
+ throw new TypeError('Body is unusable')
516
+ }
517
+
518
+ // 2. Let promise be a new promise.
519
+ const promise = createDeferredPromise()
520
+
521
+ // 3. Let errorSteps given error be to reject promise with error.
522
+ const errorSteps = (error) => promise.reject(error)
523
+
524
+ // 4. Let successSteps given a byte sequence data be to resolve
525
+ // promise with the result of running convertBytesToJSValue
526
+ // with data. If that threw an exception, then run errorSteps
527
+ // with that exception.
528
+ const successSteps = (data) => {
529
+ try {
530
+ promise.resolve(convertBytesToJSValue(data))
531
+ } catch (e) {
532
+ errorSteps(e)
533
+ }
534
+ }
535
+
536
+ // 5. If object’s body is null, then run successSteps with an
537
+ // empty byte sequence.
538
+ if (object[kState].body == null) {
539
+ successSteps(new Uint8Array())
540
+ return promise.promise
541
+ }
542
+
543
+ // 6. Otherwise, fully read object’s body given successSteps,
544
+ // errorSteps, and object’s relevant global object.
545
+ await fullyReadBody(object[kState].body, successSteps, errorSteps)
546
+
547
+ // 7. Return promise.
548
+ return promise.promise
549
+ }
550
+
551
+ // https://fetch.spec.whatwg.org/#body-unusable
552
+ function bodyUnusable (body) {
553
+ // An object including the Body interface mixin is
554
+ // said to be unusable if its body is non-null and
555
+ // its body’s stream is disturbed or locked.
556
+ return body != null && (body.stream.locked || util.isDisturbed(body.stream))
557
+ }
558
+
559
+ /**
560
+ * @see https://encoding.spec.whatwg.org/#utf-8-decode
561
+ * @param {Buffer} buffer
562
+ */
563
+ function utf8DecodeBytes (buffer) {
564
+ if (buffer.length === 0) {
565
+ return ''
566
+ }
567
+
568
+ // 1. Let buffer be the result of peeking three bytes from
569
+ // ioQueue, converted to a byte sequence.
570
+
571
+ // 2. If buffer is 0xEF 0xBB 0xBF, then read three
572
+ // bytes from ioQueue. (Do nothing with those bytes.)
573
+ if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
574
+ buffer = buffer.subarray(3)
575
+ }
576
+
577
+ // 3. Process a queue with an instance of UTF-8’s
578
+ // decoder, ioQueue, output, and "replacement".
579
+ const output = textDecoder.decode(buffer)
580
+
581
+ // 4. Return output.
582
+ return output
583
+ }
584
+
585
+ /**
586
+ * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
587
+ * @param {Uint8Array} bytes
588
+ */
589
+ function parseJSONFromBytes (bytes) {
590
+ return JSON.parse(utf8DecodeBytes(bytes))
591
+ }
592
+
593
+ /**
594
+ * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
595
+ * @param {import('./response').Response|import('./request').Request} object
596
+ */
597
+ function bodyMimeType (object) {
598
+ const { headersList } = object[kState]
599
+ const contentType = headersList.get('content-type')
600
+
601
+ if (contentType === null) {
602
+ return 'failure'
603
+ }
604
+
605
+ return parseMIMEType(contentType)
606
+ }
607
+
608
+ module.exports = {
609
+ extractBody,
610
+ safelyExtractBody,
611
+ cloneBody,
612
+ mixinBody
613
+ }
worker/node_modules/undici/lib/fetch/constants.js ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { MessageChannel, receiveMessageOnPort } = require('worker_threads')
4
+
5
+ const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
6
+ const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
7
+
8
+ const nullBodyStatus = [101, 204, 205, 304]
9
+
10
+ const redirectStatus = [301, 302, 303, 307, 308]
11
+ const redirectStatusSet = new Set(redirectStatus)
12
+
13
+ // https://fetch.spec.whatwg.org/#block-bad-port
14
+ const badPorts = [
15
+ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
16
+ '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
17
+ '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
18
+ '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
19
+ '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
20
+ '10080'
21
+ ]
22
+
23
+ const badPortsSet = new Set(badPorts)
24
+
25
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
26
+ const referrerPolicy = [
27
+ '',
28
+ 'no-referrer',
29
+ 'no-referrer-when-downgrade',
30
+ 'same-origin',
31
+ 'origin',
32
+ 'strict-origin',
33
+ 'origin-when-cross-origin',
34
+ 'strict-origin-when-cross-origin',
35
+ 'unsafe-url'
36
+ ]
37
+ const referrerPolicySet = new Set(referrerPolicy)
38
+
39
+ const requestRedirect = ['follow', 'manual', 'error']
40
+
41
+ const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
42
+ const safeMethodsSet = new Set(safeMethods)
43
+
44
+ const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
45
+
46
+ const requestCredentials = ['omit', 'same-origin', 'include']
47
+
48
+ const requestCache = [
49
+ 'default',
50
+ 'no-store',
51
+ 'reload',
52
+ 'no-cache',
53
+ 'force-cache',
54
+ 'only-if-cached'
55
+ ]
56
+
57
+ // https://fetch.spec.whatwg.org/#request-body-header-name
58
+ const requestBodyHeader = [
59
+ 'content-encoding',
60
+ 'content-language',
61
+ 'content-location',
62
+ 'content-type',
63
+ // See https://github.com/nodejs/undici/issues/2021
64
+ // 'Content-Length' is a forbidden header name, which is typically
65
+ // removed in the Headers implementation. However, undici doesn't
66
+ // filter out headers, so we add it here.
67
+ 'content-length'
68
+ ]
69
+
70
+ // https://fetch.spec.whatwg.org/#enumdef-requestduplex
71
+ const requestDuplex = [
72
+ 'half'
73
+ ]
74
+
75
+ // http://fetch.spec.whatwg.org/#forbidden-method
76
+ const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
77
+ const forbiddenMethodsSet = new Set(forbiddenMethods)
78
+
79
+ const subresource = [
80
+ 'audio',
81
+ 'audioworklet',
82
+ 'font',
83
+ 'image',
84
+ 'manifest',
85
+ 'paintworklet',
86
+ 'script',
87
+ 'style',
88
+ 'track',
89
+ 'video',
90
+ 'xslt',
91
+ ''
92
+ ]
93
+ const subresourceSet = new Set(subresource)
94
+
95
+ /** @type {globalThis['DOMException']} */
96
+ const DOMException = globalThis.DOMException ?? (() => {
97
+ // DOMException was only made a global in Node v17.0.0,
98
+ // but fetch supports >= v16.8.
99
+ try {
100
+ atob('~')
101
+ } catch (err) {
102
+ return Object.getPrototypeOf(err).constructor
103
+ }
104
+ })()
105
+
106
+ let channel
107
+
108
+ /** @type {globalThis['structuredClone']} */
109
+ const structuredClone =
110
+ globalThis.structuredClone ??
111
+ // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
112
+ // structuredClone was added in v17.0.0, but fetch supports v16.8
113
+ function structuredClone (value, options = undefined) {
114
+ if (arguments.length === 0) {
115
+ throw new TypeError('missing argument')
116
+ }
117
+
118
+ if (!channel) {
119
+ channel = new MessageChannel()
120
+ }
121
+ channel.port1.unref()
122
+ channel.port2.unref()
123
+ channel.port1.postMessage(value, options?.transfer)
124
+ return receiveMessageOnPort(channel.port2).message
125
+ }
126
+
127
+ module.exports = {
128
+ DOMException,
129
+ structuredClone,
130
+ subresource,
131
+ forbiddenMethods,
132
+ requestBodyHeader,
133
+ referrerPolicy,
134
+ requestRedirect,
135
+ requestMode,
136
+ requestCredentials,
137
+ requestCache,
138
+ redirectStatus,
139
+ corsSafeListedMethods,
140
+ nullBodyStatus,
141
+ safeMethods,
142
+ badPorts,
143
+ requestDuplex,
144
+ subresourceSet,
145
+ badPortsSet,
146
+ redirectStatusSet,
147
+ corsSafeListedMethodsSet,
148
+ safeMethodsSet,
149
+ forbiddenMethodsSet,
150
+ referrerPolicySet
151
+ }
worker/node_modules/undici/lib/fetch/dataURL.js ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const assert = require('assert')
2
+ const { atob } = require('buffer')
3
+ const { isomorphicDecode } = require('./util')
4
+
5
+ const encoder = new TextEncoder()
6
+
7
+ /**
8
+ * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
9
+ */
10
+ const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
11
+ const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
12
+ /**
13
+ * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
14
+ */
15
+ const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
16
+
17
+ // https://fetch.spec.whatwg.org/#data-url-processor
18
+ /** @param {URL} dataURL */
19
+ function dataURLProcessor (dataURL) {
20
+ // 1. Assert: dataURL’s scheme is "data".
21
+ assert(dataURL.protocol === 'data:')
22
+
23
+ // 2. Let input be the result of running the URL
24
+ // serializer on dataURL with exclude fragment
25
+ // set to true.
26
+ let input = URLSerializer(dataURL, true)
27
+
28
+ // 3. Remove the leading "data:" string from input.
29
+ input = input.slice(5)
30
+
31
+ // 4. Let position point at the start of input.
32
+ const position = { position: 0 }
33
+
34
+ // 5. Let mimeType be the result of collecting a
35
+ // sequence of code points that are not equal
36
+ // to U+002C (,), given position.
37
+ let mimeType = collectASequenceOfCodePointsFast(
38
+ ',',
39
+ input,
40
+ position
41
+ )
42
+
43
+ // 6. Strip leading and trailing ASCII whitespace
44
+ // from mimeType.
45
+ // Undici implementation note: we need to store the
46
+ // length because if the mimetype has spaces removed,
47
+ // the wrong amount will be sliced from the input in
48
+ // step #9
49
+ const mimeTypeLength = mimeType.length
50
+ mimeType = removeASCIIWhitespace(mimeType, true, true)
51
+
52
+ // 7. If position is past the end of input, then
53
+ // return failure
54
+ if (position.position >= input.length) {
55
+ return 'failure'
56
+ }
57
+
58
+ // 8. Advance position by 1.
59
+ position.position++
60
+
61
+ // 9. Let encodedBody be the remainder of input.
62
+ const encodedBody = input.slice(mimeTypeLength + 1)
63
+
64
+ // 10. Let body be the percent-decoding of encodedBody.
65
+ let body = stringPercentDecode(encodedBody)
66
+
67
+ // 11. If mimeType ends with U+003B (;), followed by
68
+ // zero or more U+0020 SPACE, followed by an ASCII
69
+ // case-insensitive match for "base64", then:
70
+ if (/;(\u0020){0,}base64$/i.test(mimeType)) {
71
+ // 1. Let stringBody be the isomorphic decode of body.
72
+ const stringBody = isomorphicDecode(body)
73
+
74
+ // 2. Set body to the forgiving-base64 decode of
75
+ // stringBody.
76
+ body = forgivingBase64(stringBody)
77
+
78
+ // 3. If body is failure, then return failure.
79
+ if (body === 'failure') {
80
+ return 'failure'
81
+ }
82
+
83
+ // 4. Remove the last 6 code points from mimeType.
84
+ mimeType = mimeType.slice(0, -6)
85
+
86
+ // 5. Remove trailing U+0020 SPACE code points from mimeType,
87
+ // if any.
88
+ mimeType = mimeType.replace(/(\u0020)+$/, '')
89
+
90
+ // 6. Remove the last U+003B (;) code point from mimeType.
91
+ mimeType = mimeType.slice(0, -1)
92
+ }
93
+
94
+ // 12. If mimeType starts with U+003B (;), then prepend
95
+ // "text/plain" to mimeType.
96
+ if (mimeType.startsWith(';')) {
97
+ mimeType = 'text/plain' + mimeType
98
+ }
99
+
100
+ // 13. Let mimeTypeRecord be the result of parsing
101
+ // mimeType.
102
+ let mimeTypeRecord = parseMIMEType(mimeType)
103
+
104
+ // 14. If mimeTypeRecord is failure, then set
105
+ // mimeTypeRecord to text/plain;charset=US-ASCII.
106
+ if (mimeTypeRecord === 'failure') {
107
+ mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
108
+ }
109
+
110
+ // 15. Return a new data: URL struct whose MIME
111
+ // type is mimeTypeRecord and body is body.
112
+ // https://fetch.spec.whatwg.org/#data-url-struct
113
+ return { mimeType: mimeTypeRecord, body }
114
+ }
115
+
116
+ // https://url.spec.whatwg.org/#concept-url-serializer
117
+ /**
118
+ * @param {URL} url
119
+ * @param {boolean} excludeFragment
120
+ */
121
+ function URLSerializer (url, excludeFragment = false) {
122
+ if (!excludeFragment) {
123
+ return url.href
124
+ }
125
+
126
+ const href = url.href
127
+ const hashLength = url.hash.length
128
+
129
+ return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
130
+ }
131
+
132
+ // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
133
+ /**
134
+ * @param {(char: string) => boolean} condition
135
+ * @param {string} input
136
+ * @param {{ position: number }} position
137
+ */
138
+ function collectASequenceOfCodePoints (condition, input, position) {
139
+ // 1. Let result be the empty string.
140
+ let result = ''
141
+
142
+ // 2. While position doesn’t point past the end of input and the
143
+ // code point at position within input meets the condition condition:
144
+ while (position.position < input.length && condition(input[position.position])) {
145
+ // 1. Append that code point to the end of result.
146
+ result += input[position.position]
147
+
148
+ // 2. Advance position by 1.
149
+ position.position++
150
+ }
151
+
152
+ // 3. Return result.
153
+ return result
154
+ }
155
+
156
+ /**
157
+ * A faster collectASequenceOfCodePoints that only works when comparing a single character.
158
+ * @param {string} char
159
+ * @param {string} input
160
+ * @param {{ position: number }} position
161
+ */
162
+ function collectASequenceOfCodePointsFast (char, input, position) {
163
+ const idx = input.indexOf(char, position.position)
164
+ const start = position.position
165
+
166
+ if (idx === -1) {
167
+ position.position = input.length
168
+ return input.slice(start)
169
+ }
170
+
171
+ position.position = idx
172
+ return input.slice(start, position.position)
173
+ }
174
+
175
+ // https://url.spec.whatwg.org/#string-percent-decode
176
+ /** @param {string} input */
177
+ function stringPercentDecode (input) {
178
+ // 1. Let bytes be the UTF-8 encoding of input.
179
+ const bytes = encoder.encode(input)
180
+
181
+ // 2. Return the percent-decoding of bytes.
182
+ return percentDecode(bytes)
183
+ }
184
+
185
+ // https://url.spec.whatwg.org/#percent-decode
186
+ /** @param {Uint8Array} input */
187
+ function percentDecode (input) {
188
+ // 1. Let output be an empty byte sequence.
189
+ /** @type {number[]} */
190
+ const output = []
191
+
192
+ // 2. For each byte byte in input:
193
+ for (let i = 0; i < input.length; i++) {
194
+ const byte = input[i]
195
+
196
+ // 1. If byte is not 0x25 (%), then append byte to output.
197
+ if (byte !== 0x25) {
198
+ output.push(byte)
199
+
200
+ // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
201
+ // after byte in input are not in the ranges
202
+ // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
203
+ // and 0x61 (a) to 0x66 (f), all inclusive, append byte
204
+ // to output.
205
+ } else if (
206
+ byte === 0x25 &&
207
+ !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
208
+ ) {
209
+ output.push(0x25)
210
+
211
+ // 3. Otherwise:
212
+ } else {
213
+ // 1. Let bytePoint be the two bytes after byte in input,
214
+ // decoded, and then interpreted as hexadecimal number.
215
+ const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
216
+ const bytePoint = Number.parseInt(nextTwoBytes, 16)
217
+
218
+ // 2. Append a byte whose value is bytePoint to output.
219
+ output.push(bytePoint)
220
+
221
+ // 3. Skip the next two bytes in input.
222
+ i += 2
223
+ }
224
+ }
225
+
226
+ // 3. Return output.
227
+ return Uint8Array.from(output)
228
+ }
229
+
230
+ // https://mimesniff.spec.whatwg.org/#parse-a-mime-type
231
+ /** @param {string} input */
232
+ function parseMIMEType (input) {
233
+ // 1. Remove any leading and trailing HTTP whitespace
234
+ // from input.
235
+ input = removeHTTPWhitespace(input, true, true)
236
+
237
+ // 2. Let position be a position variable for input,
238
+ // initially pointing at the start of input.
239
+ const position = { position: 0 }
240
+
241
+ // 3. Let type be the result of collecting a sequence
242
+ // of code points that are not U+002F (/) from
243
+ // input, given position.
244
+ const type = collectASequenceOfCodePointsFast(
245
+ '/',
246
+ input,
247
+ position
248
+ )
249
+
250
+ // 4. If type is the empty string or does not solely
251
+ // contain HTTP token code points, then return failure.
252
+ // https://mimesniff.spec.whatwg.org/#http-token-code-point
253
+ if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
254
+ return 'failure'
255
+ }
256
+
257
+ // 5. If position is past the end of input, then return
258
+ // failure
259
+ if (position.position > input.length) {
260
+ return 'failure'
261
+ }
262
+
263
+ // 6. Advance position by 1. (This skips past U+002F (/).)
264
+ position.position++
265
+
266
+ // 7. Let subtype be the result of collecting a sequence of
267
+ // code points that are not U+003B (;) from input, given
268
+ // position.
269
+ let subtype = collectASequenceOfCodePointsFast(
270
+ ';',
271
+ input,
272
+ position
273
+ )
274
+
275
+ // 8. Remove any trailing HTTP whitespace from subtype.
276
+ subtype = removeHTTPWhitespace(subtype, false, true)
277
+
278
+ // 9. If subtype is the empty string or does not solely
279
+ // contain HTTP token code points, then return failure.
280
+ if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
281
+ return 'failure'
282
+ }
283
+
284
+ const typeLowercase = type.toLowerCase()
285
+ const subtypeLowercase = subtype.toLowerCase()
286
+
287
+ // 10. Let mimeType be a new MIME type record whose type
288
+ // is type, in ASCII lowercase, and subtype is subtype,
289
+ // in ASCII lowercase.
290
+ // https://mimesniff.spec.whatwg.org/#mime-type
291
+ const mimeType = {
292
+ type: typeLowercase,
293
+ subtype: subtypeLowercase,
294
+ /** @type {Map<string, string>} */
295
+ parameters: new Map(),
296
+ // https://mimesniff.spec.whatwg.org/#mime-type-essence
297
+ essence: `${typeLowercase}/${subtypeLowercase}`
298
+ }
299
+
300
+ // 11. While position is not past the end of input:
301
+ while (position.position < input.length) {
302
+ // 1. Advance position by 1. (This skips past U+003B (;).)
303
+ position.position++
304
+
305
+ // 2. Collect a sequence of code points that are HTTP
306
+ // whitespace from input given position.
307
+ collectASequenceOfCodePoints(
308
+ // https://fetch.spec.whatwg.org/#http-whitespace
309
+ char => HTTP_WHITESPACE_REGEX.test(char),
310
+ input,
311
+ position
312
+ )
313
+
314
+ // 3. Let parameterName be the result of collecting a
315
+ // sequence of code points that are not U+003B (;)
316
+ // or U+003D (=) from input, given position.
317
+ let parameterName = collectASequenceOfCodePoints(
318
+ (char) => char !== ';' && char !== '=',
319
+ input,
320
+ position
321
+ )
322
+
323
+ // 4. Set parameterName to parameterName, in ASCII
324
+ // lowercase.
325
+ parameterName = parameterName.toLowerCase()
326
+
327
+ // 5. If position is not past the end of input, then:
328
+ if (position.position < input.length) {
329
+ // 1. If the code point at position within input is
330
+ // U+003B (;), then continue.
331
+ if (input[position.position] === ';') {
332
+ continue
333
+ }
334
+
335
+ // 2. Advance position by 1. (This skips past U+003D (=).)
336
+ position.position++
337
+ }
338
+
339
+ // 6. If position is past the end of input, then break.
340
+ if (position.position > input.length) {
341
+ break
342
+ }
343
+
344
+ // 7. Let parameterValue be null.
345
+ let parameterValue = null
346
+
347
+ // 8. If the code point at position within input is
348
+ // U+0022 ("), then:
349
+ if (input[position.position] === '"') {
350
+ // 1. Set parameterValue to the result of collecting
351
+ // an HTTP quoted string from input, given position
352
+ // and the extract-value flag.
353
+ parameterValue = collectAnHTTPQuotedString(input, position, true)
354
+
355
+ // 2. Collect a sequence of code points that are not
356
+ // U+003B (;) from input, given position.
357
+ collectASequenceOfCodePointsFast(
358
+ ';',
359
+ input,
360
+ position
361
+ )
362
+
363
+ // 9. Otherwise:
364
+ } else {
365
+ // 1. Set parameterValue to the result of collecting
366
+ // a sequence of code points that are not U+003B (;)
367
+ // from input, given position.
368
+ parameterValue = collectASequenceOfCodePointsFast(
369
+ ';',
370
+ input,
371
+ position
372
+ )
373
+
374
+ // 2. Remove any trailing HTTP whitespace from parameterValue.
375
+ parameterValue = removeHTTPWhitespace(parameterValue, false, true)
376
+
377
+ // 3. If parameterValue is the empty string, then continue.
378
+ if (parameterValue.length === 0) {
379
+ continue
380
+ }
381
+ }
382
+
383
+ // 10. If all of the following are true
384
+ // - parameterName is not the empty string
385
+ // - parameterName solely contains HTTP token code points
386
+ // - parameterValue solely contains HTTP quoted-string token code points
387
+ // - mimeType’s parameters[parameterName] does not exist
388
+ // then set mimeType’s parameters[parameterName] to parameterValue.
389
+ if (
390
+ parameterName.length !== 0 &&
391
+ HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
392
+ (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
393
+ !mimeType.parameters.has(parameterName)
394
+ ) {
395
+ mimeType.parameters.set(parameterName, parameterValue)
396
+ }
397
+ }
398
+
399
+ // 12. Return mimeType.
400
+ return mimeType
401
+ }
402
+
403
+ // https://infra.spec.whatwg.org/#forgiving-base64-decode
404
+ /** @param {string} data */
405
+ function forgivingBase64 (data) {
406
+ // 1. Remove all ASCII whitespace from data.
407
+ data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
408
+
409
+ // 2. If data’s code point length divides by 4 leaving
410
+ // no remainder, then:
411
+ if (data.length % 4 === 0) {
412
+ // 1. If data ends with one or two U+003D (=) code points,
413
+ // then remove them from data.
414
+ data = data.replace(/=?=$/, '')
415
+ }
416
+
417
+ // 3. If data’s code point length divides by 4 leaving
418
+ // a remainder of 1, then return failure.
419
+ if (data.length % 4 === 1) {
420
+ return 'failure'
421
+ }
422
+
423
+ // 4. If data contains a code point that is not one of
424
+ // U+002B (+)
425
+ // U+002F (/)
426
+ // ASCII alphanumeric
427
+ // then return failure.
428
+ if (/[^+/0-9A-Za-z]/.test(data)) {
429
+ return 'failure'
430
+ }
431
+
432
+ const binary = atob(data)
433
+ const bytes = new Uint8Array(binary.length)
434
+
435
+ for (let byte = 0; byte < binary.length; byte++) {
436
+ bytes[byte] = binary.charCodeAt(byte)
437
+ }
438
+
439
+ return bytes
440
+ }
441
+
442
+ // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
443
+ // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
444
+ /**
445
+ * @param {string} input
446
+ * @param {{ position: number }} position
447
+ * @param {boolean?} extractValue
448
+ */
449
+ function collectAnHTTPQuotedString (input, position, extractValue) {
450
+ // 1. Let positionStart be position.
451
+ const positionStart = position.position
452
+
453
+ // 2. Let value be the empty string.
454
+ let value = ''
455
+
456
+ // 3. Assert: the code point at position within input
457
+ // is U+0022 (").
458
+ assert(input[position.position] === '"')
459
+
460
+ // 4. Advance position by 1.
461
+ position.position++
462
+
463
+ // 5. While true:
464
+ while (true) {
465
+ // 1. Append the result of collecting a sequence of code points
466
+ // that are not U+0022 (") or U+005C (\) from input, given
467
+ // position, to value.
468
+ value += collectASequenceOfCodePoints(
469
+ (char) => char !== '"' && char !== '\\',
470
+ input,
471
+ position
472
+ )
473
+
474
+ // 2. If position is past the end of input, then break.
475
+ if (position.position >= input.length) {
476
+ break
477
+ }
478
+
479
+ // 3. Let quoteOrBackslash be the code point at position within
480
+ // input.
481
+ const quoteOrBackslash = input[position.position]
482
+
483
+ // 4. Advance position by 1.
484
+ position.position++
485
+
486
+ // 5. If quoteOrBackslash is U+005C (\), then:
487
+ if (quoteOrBackslash === '\\') {
488
+ // 1. If position is past the end of input, then append
489
+ // U+005C (\) to value and break.
490
+ if (position.position >= input.length) {
491
+ value += '\\'
492
+ break
493
+ }
494
+
495
+ // 2. Append the code point at position within input to value.
496
+ value += input[position.position]
497
+
498
+ // 3. Advance position by 1.
499
+ position.position++
500
+
501
+ // 6. Otherwise:
502
+ } else {
503
+ // 1. Assert: quoteOrBackslash is U+0022 (").
504
+ assert(quoteOrBackslash === '"')
505
+
506
+ // 2. Break.
507
+ break
508
+ }
509
+ }
510
+
511
+ // 6. If the extract-value flag is set, then return value.
512
+ if (extractValue) {
513
+ return value
514
+ }
515
+
516
+ // 7. Return the code points from positionStart to position,
517
+ // inclusive, within input.
518
+ return input.slice(positionStart, position.position)
519
+ }
520
+
521
+ /**
522
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
523
+ */
524
+ function serializeAMimeType (mimeType) {
525
+ assert(mimeType !== 'failure')
526
+ const { parameters, essence } = mimeType
527
+
528
+ // 1. Let serialization be the concatenation of mimeType’s
529
+ // type, U+002F (/), and mimeType’s subtype.
530
+ let serialization = essence
531
+
532
+ // 2. For each name → value of mimeType’s parameters:
533
+ for (let [name, value] of parameters.entries()) {
534
+ // 1. Append U+003B (;) to serialization.
535
+ serialization += ';'
536
+
537
+ // 2. Append name to serialization.
538
+ serialization += name
539
+
540
+ // 3. Append U+003D (=) to serialization.
541
+ serialization += '='
542
+
543
+ // 4. If value does not solely contain HTTP token code
544
+ // points or value is the empty string, then:
545
+ if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
546
+ // 1. Precede each occurence of U+0022 (") or
547
+ // U+005C (\) in value with U+005C (\).
548
+ value = value.replace(/(\\|")/g, '\\$1')
549
+
550
+ // 2. Prepend U+0022 (") to value.
551
+ value = '"' + value
552
+
553
+ // 3. Append U+0022 (") to value.
554
+ value += '"'
555
+ }
556
+
557
+ // 5. Append value to serialization.
558
+ serialization += value
559
+ }
560
+
561
+ // 3. Return serialization.
562
+ return serialization
563
+ }
564
+
565
+ /**
566
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
567
+ * @param {string} char
568
+ */
569
+ function isHTTPWhiteSpace (char) {
570
+ return char === '\r' || char === '\n' || char === '\t' || char === ' '
571
+ }
572
+
573
+ /**
574
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
575
+ * @param {string} str
576
+ */
577
+ function removeHTTPWhitespace (str, leading = true, trailing = true) {
578
+ let lead = 0
579
+ let trail = str.length - 1
580
+
581
+ if (leading) {
582
+ for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
583
+ }
584
+
585
+ if (trailing) {
586
+ for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
587
+ }
588
+
589
+ return str.slice(lead, trail + 1)
590
+ }
591
+
592
+ /**
593
+ * @see https://infra.spec.whatwg.org/#ascii-whitespace
594
+ * @param {string} char
595
+ */
596
+ function isASCIIWhitespace (char) {
597
+ return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
598
+ }
599
+
600
+ /**
601
+ * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
602
+ */
603
+ function removeASCIIWhitespace (str, leading = true, trailing = true) {
604
+ let lead = 0
605
+ let trail = str.length - 1
606
+
607
+ if (leading) {
608
+ for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
609
+ }
610
+
611
+ if (trailing) {
612
+ for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
613
+ }
614
+
615
+ return str.slice(lead, trail + 1)
616
+ }
617
+
618
+ module.exports = {
619
+ dataURLProcessor,
620
+ URLSerializer,
621
+ collectASequenceOfCodePoints,
622
+ collectASequenceOfCodePointsFast,
623
+ stringPercentDecode,
624
+ parseMIMEType,
625
+ collectAnHTTPQuotedString,
626
+ serializeAMimeType
627
+ }
worker/node_modules/undici/lib/fetch/file.js ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { Blob, File: NativeFile } = require('buffer')
4
+ const { types } = require('util')
5
+ const { kState } = require('./symbols')
6
+ const { isBlobLike } = require('./util')
7
+ const { webidl } = require('./webidl')
8
+ const { parseMIMEType, serializeAMimeType } = require('./dataURL')
9
+ const { kEnumerableProperty } = require('../core/util')
10
+ const encoder = new TextEncoder()
11
+
12
+ class File extends Blob {
13
+ constructor (fileBits, fileName, options = {}) {
14
+ // The File constructor is invoked with two or three parameters, depending
15
+ // on whether the optional dictionary parameter is used. When the File()
16
+ // constructor is invoked, user agents must run the following steps:
17
+ webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
18
+
19
+ fileBits = webidl.converters['sequence<BlobPart>'](fileBits)
20
+ fileName = webidl.converters.USVString(fileName)
21
+ options = webidl.converters.FilePropertyBag(options)
22
+
23
+ // 1. Let bytes be the result of processing blob parts given fileBits and
24
+ // options.
25
+ // Note: Blob handles this for us
26
+
27
+ // 2. Let n be the fileName argument to the constructor.
28
+ const n = fileName
29
+
30
+ // 3. Process FilePropertyBag dictionary argument by running the following
31
+ // substeps:
32
+
33
+ // 1. If the type member is provided and is not the empty string, let t
34
+ // be set to the type dictionary member. If t contains any characters
35
+ // outside the range U+0020 to U+007E, then set t to the empty string
36
+ // and return from these substeps.
37
+ // 2. Convert every character in t to ASCII lowercase.
38
+ let t = options.type
39
+ let d
40
+
41
+ // eslint-disable-next-line no-labels
42
+ substep: {
43
+ if (t) {
44
+ t = parseMIMEType(t)
45
+
46
+ if (t === 'failure') {
47
+ t = ''
48
+ // eslint-disable-next-line no-labels
49
+ break substep
50
+ }
51
+
52
+ t = serializeAMimeType(t).toLowerCase()
53
+ }
54
+
55
+ // 3. If the lastModified member is provided, let d be set to the
56
+ // lastModified dictionary member. If it is not provided, set d to the
57
+ // current date and time represented as the number of milliseconds since
58
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
59
+ d = options.lastModified
60
+ }
61
+
62
+ // 4. Return a new File object F such that:
63
+ // F refers to the bytes byte sequence.
64
+ // F.size is set to the number of total bytes in bytes.
65
+ // F.name is set to n.
66
+ // F.type is set to t.
67
+ // F.lastModified is set to d.
68
+
69
+ super(processBlobParts(fileBits, options), { type: t })
70
+ this[kState] = {
71
+ name: n,
72
+ lastModified: d,
73
+ type: t
74
+ }
75
+ }
76
+
77
+ get name () {
78
+ webidl.brandCheck(this, File)
79
+
80
+ return this[kState].name
81
+ }
82
+
83
+ get lastModified () {
84
+ webidl.brandCheck(this, File)
85
+
86
+ return this[kState].lastModified
87
+ }
88
+
89
+ get type () {
90
+ webidl.brandCheck(this, File)
91
+
92
+ return this[kState].type
93
+ }
94
+ }
95
+
96
+ class FileLike {
97
+ constructor (blobLike, fileName, options = {}) {
98
+ // TODO: argument idl type check
99
+
100
+ // The File constructor is invoked with two or three parameters, depending
101
+ // on whether the optional dictionary parameter is used. When the File()
102
+ // constructor is invoked, user agents must run the following steps:
103
+
104
+ // 1. Let bytes be the result of processing blob parts given fileBits and
105
+ // options.
106
+
107
+ // 2. Let n be the fileName argument to the constructor.
108
+ const n = fileName
109
+
110
+ // 3. Process FilePropertyBag dictionary argument by running the following
111
+ // substeps:
112
+
113
+ // 1. If the type member is provided and is not the empty string, let t
114
+ // be set to the type dictionary member. If t contains any characters
115
+ // outside the range U+0020 to U+007E, then set t to the empty string
116
+ // and return from these substeps.
117
+ // TODO
118
+ const t = options.type
119
+
120
+ // 2. Convert every character in t to ASCII lowercase.
121
+ // TODO
122
+
123
+ // 3. If the lastModified member is provided, let d be set to the
124
+ // lastModified dictionary member. If it is not provided, set d to the
125
+ // current date and time represented as the number of milliseconds since
126
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
127
+ const d = options.lastModified ?? Date.now()
128
+
129
+ // 4. Return a new File object F such that:
130
+ // F refers to the bytes byte sequence.
131
+ // F.size is set to the number of total bytes in bytes.
132
+ // F.name is set to n.
133
+ // F.type is set to t.
134
+ // F.lastModified is set to d.
135
+
136
+ this[kState] = {
137
+ blobLike,
138
+ name: n,
139
+ type: t,
140
+ lastModified: d
141
+ }
142
+ }
143
+
144
+ stream (...args) {
145
+ webidl.brandCheck(this, FileLike)
146
+
147
+ return this[kState].blobLike.stream(...args)
148
+ }
149
+
150
+ arrayBuffer (...args) {
151
+ webidl.brandCheck(this, FileLike)
152
+
153
+ return this[kState].blobLike.arrayBuffer(...args)
154
+ }
155
+
156
+ slice (...args) {
157
+ webidl.brandCheck(this, FileLike)
158
+
159
+ return this[kState].blobLike.slice(...args)
160
+ }
161
+
162
+ text (...args) {
163
+ webidl.brandCheck(this, FileLike)
164
+
165
+ return this[kState].blobLike.text(...args)
166
+ }
167
+
168
+ get size () {
169
+ webidl.brandCheck(this, FileLike)
170
+
171
+ return this[kState].blobLike.size
172
+ }
173
+
174
+ get type () {
175
+ webidl.brandCheck(this, FileLike)
176
+
177
+ return this[kState].blobLike.type
178
+ }
179
+
180
+ get name () {
181
+ webidl.brandCheck(this, FileLike)
182
+
183
+ return this[kState].name
184
+ }
185
+
186
+ get lastModified () {
187
+ webidl.brandCheck(this, FileLike)
188
+
189
+ return this[kState].lastModified
190
+ }
191
+
192
+ get [Symbol.toStringTag] () {
193
+ return 'File'
194
+ }
195
+ }
196
+
197
+ Object.defineProperties(File.prototype, {
198
+ [Symbol.toStringTag]: {
199
+ value: 'File',
200
+ configurable: true
201
+ },
202
+ name: kEnumerableProperty,
203
+ lastModified: kEnumerableProperty
204
+ })
205
+
206
+ webidl.converters.Blob = webidl.interfaceConverter(Blob)
207
+
208
+ webidl.converters.BlobPart = function (V, opts) {
209
+ if (webidl.util.Type(V) === 'Object') {
210
+ if (isBlobLike(V)) {
211
+ return webidl.converters.Blob(V, { strict: false })
212
+ }
213
+
214
+ if (
215
+ ArrayBuffer.isView(V) ||
216
+ types.isAnyArrayBuffer(V)
217
+ ) {
218
+ return webidl.converters.BufferSource(V, opts)
219
+ }
220
+ }
221
+
222
+ return webidl.converters.USVString(V, opts)
223
+ }
224
+
225
+ webidl.converters['sequence<BlobPart>'] = webidl.sequenceConverter(
226
+ webidl.converters.BlobPart
227
+ )
228
+
229
+ // https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
230
+ webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
231
+ {
232
+ key: 'lastModified',
233
+ converter: webidl.converters['long long'],
234
+ get defaultValue () {
235
+ return Date.now()
236
+ }
237
+ },
238
+ {
239
+ key: 'type',
240
+ converter: webidl.converters.DOMString,
241
+ defaultValue: ''
242
+ },
243
+ {
244
+ key: 'endings',
245
+ converter: (value) => {
246
+ value = webidl.converters.DOMString(value)
247
+ value = value.toLowerCase()
248
+
249
+ if (value !== 'native') {
250
+ value = 'transparent'
251
+ }
252
+
253
+ return value
254
+ },
255
+ defaultValue: 'transparent'
256
+ }
257
+ ])
258
+
259
+ /**
260
+ * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
261
+ * @param {(NodeJS.TypedArray|Blob|string)[]} parts
262
+ * @param {{ type: string, endings: string }} options
263
+ */
264
+ function processBlobParts (parts, options) {
265
+ // 1. Let bytes be an empty sequence of bytes.
266
+ /** @type {NodeJS.TypedArray[]} */
267
+ const bytes = []
268
+
269
+ // 2. For each element in parts:
270
+ for (const element of parts) {
271
+ // 1. If element is a USVString, run the following substeps:
272
+ if (typeof element === 'string') {
273
+ // 1. Let s be element.
274
+ let s = element
275
+
276
+ // 2. If the endings member of options is "native", set s
277
+ // to the result of converting line endings to native
278
+ // of element.
279
+ if (options.endings === 'native') {
280
+ s = convertLineEndingsNative(s)
281
+ }
282
+
283
+ // 3. Append the result of UTF-8 encoding s to bytes.
284
+ bytes.push(encoder.encode(s))
285
+ } else if (
286
+ types.isAnyArrayBuffer(element) ||
287
+ types.isTypedArray(element)
288
+ ) {
289
+ // 2. If element is a BufferSource, get a copy of the
290
+ // bytes held by the buffer source, and append those
291
+ // bytes to bytes.
292
+ if (!element.buffer) { // ArrayBuffer
293
+ bytes.push(new Uint8Array(element))
294
+ } else {
295
+ bytes.push(
296
+ new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
297
+ )
298
+ }
299
+ } else if (isBlobLike(element)) {
300
+ // 3. If element is a Blob, append the bytes it represents
301
+ // to bytes.
302
+ bytes.push(element)
303
+ }
304
+ }
305
+
306
+ // 3. Return bytes.
307
+ return bytes
308
+ }
309
+
310
+ /**
311
+ * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
312
+ * @param {string} s
313
+ */
314
+ function convertLineEndingsNative (s) {
315
+ // 1. Let native line ending be be the code point U+000A LF.
316
+ let nativeLineEnding = '\n'
317
+
318
+ // 2. If the underlying platform’s conventions are to
319
+ // represent newlines as a carriage return and line feed
320
+ // sequence, set native line ending to the code point
321
+ // U+000D CR followed by the code point U+000A LF.
322
+ if (process.platform === 'win32') {
323
+ nativeLineEnding = '\r\n'
324
+ }
325
+
326
+ return s.replace(/\r?\n/g, nativeLineEnding)
327
+ }
328
+
329
+ // If this function is moved to ./util.js, some tools (such as
330
+ // rollup) will warn about circular dependencies. See:
331
+ // https://github.com/nodejs/undici/issues/1629
332
+ function isFileLike (object) {
333
+ return (
334
+ (NativeFile && object instanceof NativeFile) ||
335
+ object instanceof File || (
336
+ object &&
337
+ (typeof object.stream === 'function' ||
338
+ typeof object.arrayBuffer === 'function') &&
339
+ object[Symbol.toStringTag] === 'File'
340
+ )
341
+ )
342
+ }
343
+
344
+ module.exports = { File, FileLike, isFileLike }
worker/node_modules/undici/lib/fetch/formdata.js ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { isBlobLike, toUSVString, makeIterator } = require('./util')
4
+ const { kState } = require('./symbols')
5
+ const { File: UndiciFile, FileLike, isFileLike } = require('./file')
6
+ const { webidl } = require('./webidl')
7
+ const { Blob, File: NativeFile } = require('buffer')
8
+
9
+ /** @type {globalThis['File']} */
10
+ const File = NativeFile ?? UndiciFile
11
+
12
+ // https://xhr.spec.whatwg.org/#formdata
13
+ class FormData {
14
+ constructor (form) {
15
+ if (form !== undefined) {
16
+ throw webidl.errors.conversionFailed({
17
+ prefix: 'FormData constructor',
18
+ argument: 'Argument 1',
19
+ types: ['undefined']
20
+ })
21
+ }
22
+
23
+ this[kState] = []
24
+ }
25
+
26
+ append (name, value, filename = undefined) {
27
+ webidl.brandCheck(this, FormData)
28
+
29
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
30
+
31
+ if (arguments.length === 3 && !isBlobLike(value)) {
32
+ throw new TypeError(
33
+ "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
34
+ )
35
+ }
36
+
37
+ // 1. Let value be value if given; otherwise blobValue.
38
+
39
+ name = webidl.converters.USVString(name)
40
+ value = isBlobLike(value)
41
+ ? webidl.converters.Blob(value, { strict: false })
42
+ : webidl.converters.USVString(value)
43
+ filename = arguments.length === 3
44
+ ? webidl.converters.USVString(filename)
45
+ : undefined
46
+
47
+ // 2. Let entry be the result of creating an entry with
48
+ // name, value, and filename if given.
49
+ const entry = makeEntry(name, value, filename)
50
+
51
+ // 3. Append entry to this’s entry list.
52
+ this[kState].push(entry)
53
+ }
54
+
55
+ delete (name) {
56
+ webidl.brandCheck(this, FormData)
57
+
58
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
59
+
60
+ name = webidl.converters.USVString(name)
61
+
62
+ // The delete(name) method steps are to remove all entries whose name
63
+ // is name from this’s entry list.
64
+ this[kState] = this[kState].filter(entry => entry.name !== name)
65
+ }
66
+
67
+ get (name) {
68
+ webidl.brandCheck(this, FormData)
69
+
70
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
71
+
72
+ name = webidl.converters.USVString(name)
73
+
74
+ // 1. If there is no entry whose name is name in this’s entry list,
75
+ // then return null.
76
+ const idx = this[kState].findIndex((entry) => entry.name === name)
77
+ if (idx === -1) {
78
+ return null
79
+ }
80
+
81
+ // 2. Return the value of the first entry whose name is name from
82
+ // this’s entry list.
83
+ return this[kState][idx].value
84
+ }
85
+
86
+ getAll (name) {
87
+ webidl.brandCheck(this, FormData)
88
+
89
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
90
+
91
+ name = webidl.converters.USVString(name)
92
+
93
+ // 1. If there is no entry whose name is name in this’s entry list,
94
+ // then return the empty list.
95
+ // 2. Return the values of all entries whose name is name, in order,
96
+ // from this’s entry list.
97
+ return this[kState]
98
+ .filter((entry) => entry.name === name)
99
+ .map((entry) => entry.value)
100
+ }
101
+
102
+ has (name) {
103
+ webidl.brandCheck(this, FormData)
104
+
105
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
106
+
107
+ name = webidl.converters.USVString(name)
108
+
109
+ // The has(name) method steps are to return true if there is an entry
110
+ // whose name is name in this’s entry list; otherwise false.
111
+ return this[kState].findIndex((entry) => entry.name === name) !== -1
112
+ }
113
+
114
+ set (name, value, filename = undefined) {
115
+ webidl.brandCheck(this, FormData)
116
+
117
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
118
+
119
+ if (arguments.length === 3 && !isBlobLike(value)) {
120
+ throw new TypeError(
121
+ "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
122
+ )
123
+ }
124
+
125
+ // The set(name, value) and set(name, blobValue, filename) method steps
126
+ // are:
127
+
128
+ // 1. Let value be value if given; otherwise blobValue.
129
+
130
+ name = webidl.converters.USVString(name)
131
+ value = isBlobLike(value)
132
+ ? webidl.converters.Blob(value, { strict: false })
133
+ : webidl.converters.USVString(value)
134
+ filename = arguments.length === 3
135
+ ? toUSVString(filename)
136
+ : undefined
137
+
138
+ // 2. Let entry be the result of creating an entry with name, value, and
139
+ // filename if given.
140
+ const entry = makeEntry(name, value, filename)
141
+
142
+ // 3. If there are entries in this’s entry list whose name is name, then
143
+ // replace the first such entry with entry and remove the others.
144
+ const idx = this[kState].findIndex((entry) => entry.name === name)
145
+ if (idx !== -1) {
146
+ this[kState] = [
147
+ ...this[kState].slice(0, idx),
148
+ entry,
149
+ ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
150
+ ]
151
+ } else {
152
+ // 4. Otherwise, append entry to this’s entry list.
153
+ this[kState].push(entry)
154
+ }
155
+ }
156
+
157
+ entries () {
158
+ webidl.brandCheck(this, FormData)
159
+
160
+ return makeIterator(
161
+ () => this[kState].map(pair => [pair.name, pair.value]),
162
+ 'FormData',
163
+ 'key+value'
164
+ )
165
+ }
166
+
167
+ keys () {
168
+ webidl.brandCheck(this, FormData)
169
+
170
+ return makeIterator(
171
+ () => this[kState].map(pair => [pair.name, pair.value]),
172
+ 'FormData',
173
+ 'key'
174
+ )
175
+ }
176
+
177
+ values () {
178
+ webidl.brandCheck(this, FormData)
179
+
180
+ return makeIterator(
181
+ () => this[kState].map(pair => [pair.name, pair.value]),
182
+ 'FormData',
183
+ 'value'
184
+ )
185
+ }
186
+
187
+ /**
188
+ * @param {(value: string, key: string, self: FormData) => void} callbackFn
189
+ * @param {unknown} thisArg
190
+ */
191
+ forEach (callbackFn, thisArg = globalThis) {
192
+ webidl.brandCheck(this, FormData)
193
+
194
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
195
+
196
+ if (typeof callbackFn !== 'function') {
197
+ throw new TypeError(
198
+ "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
199
+ )
200
+ }
201
+
202
+ for (const [key, value] of this) {
203
+ callbackFn.apply(thisArg, [value, key, this])
204
+ }
205
+ }
206
+ }
207
+
208
+ FormData.prototype[Symbol.iterator] = FormData.prototype.entries
209
+
210
+ Object.defineProperties(FormData.prototype, {
211
+ [Symbol.toStringTag]: {
212
+ value: 'FormData',
213
+ configurable: true
214
+ }
215
+ })
216
+
217
+ /**
218
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
219
+ * @param {string} name
220
+ * @param {string|Blob} value
221
+ * @param {?string} filename
222
+ * @returns
223
+ */
224
+ function makeEntry (name, value, filename) {
225
+ // 1. Set name to the result of converting name into a scalar value string.
226
+ // "To convert a string into a scalar value string, replace any surrogates
227
+ // with U+FFFD."
228
+ // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
229
+ name = Buffer.from(name).toString('utf8')
230
+
231
+ // 2. If value is a string, then set value to the result of converting
232
+ // value into a scalar value string.
233
+ if (typeof value === 'string') {
234
+ value = Buffer.from(value).toString('utf8')
235
+ } else {
236
+ // 3. Otherwise:
237
+
238
+ // 1. If value is not a File object, then set value to a new File object,
239
+ // representing the same bytes, whose name attribute value is "blob"
240
+ if (!isFileLike(value)) {
241
+ value = value instanceof Blob
242
+ ? new File([value], 'blob', { type: value.type })
243
+ : new FileLike(value, 'blob', { type: value.type })
244
+ }
245
+
246
+ // 2. If filename is given, then set value to a new File object,
247
+ // representing the same bytes, whose name attribute is filename.
248
+ if (filename !== undefined) {
249
+ /** @type {FilePropertyBag} */
250
+ const options = {
251
+ type: value.type,
252
+ lastModified: value.lastModified
253
+ }
254
+
255
+ value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
256
+ ? new File([value], filename, options)
257
+ : new FileLike(value, filename, options)
258
+ }
259
+ }
260
+
261
+ // 4. Return an entry whose name is name and whose value is value.
262
+ return { name, value }
263
+ }
264
+
265
+ module.exports = { FormData }
worker/node_modules/undici/lib/fetch/global.js ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ // In case of breaking changes, increase the version
4
+ // number to avoid conflicts.
5
+ const globalOrigin = Symbol.for('undici.globalOrigin.1')
6
+
7
+ function getGlobalOrigin () {
8
+ return globalThis[globalOrigin]
9
+ }
10
+
11
+ function setGlobalOrigin (newOrigin) {
12
+ if (newOrigin === undefined) {
13
+ Object.defineProperty(globalThis, globalOrigin, {
14
+ value: undefined,
15
+ writable: true,
16
+ enumerable: false,
17
+ configurable: false
18
+ })
19
+
20
+ return
21
+ }
22
+
23
+ const parsedURL = new URL(newOrigin)
24
+
25
+ if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
26
+ throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
27
+ }
28
+
29
+ Object.defineProperty(globalThis, globalOrigin, {
30
+ value: parsedURL,
31
+ writable: true,
32
+ enumerable: false,
33
+ configurable: false
34
+ })
35
+ }
36
+
37
+ module.exports = {
38
+ getGlobalOrigin,
39
+ setGlobalOrigin
40
+ }
worker/node_modules/undici/lib/fetch/headers.js ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // https://github.com/Ethan-Arrowood/undici-fetch
2
+
3
+ 'use strict'
4
+
5
+ const { kHeadersList, kConstruct } = require('../core/symbols')
6
+ const { kGuard } = require('./symbols')
7
+ const { kEnumerableProperty } = require('../core/util')
8
+ const {
9
+ makeIterator,
10
+ isValidHeaderName,
11
+ isValidHeaderValue
12
+ } = require('./util')
13
+ const util = require('util')
14
+ const { webidl } = require('./webidl')
15
+ const assert = require('assert')
16
+
17
+ const kHeadersMap = Symbol('headers map')
18
+ const kHeadersSortedMap = Symbol('headers map sorted')
19
+
20
+ /**
21
+ * @param {number} code
22
+ */
23
+ function isHTTPWhiteSpaceCharCode (code) {
24
+ return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
25
+ }
26
+
27
+ /**
28
+ * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
29
+ * @param {string} potentialValue
30
+ */
31
+ function headerValueNormalize (potentialValue) {
32
+ // To normalize a byte sequence potentialValue, remove
33
+ // any leading and trailing HTTP whitespace bytes from
34
+ // potentialValue.
35
+ let i = 0; let j = potentialValue.length
36
+
37
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
38
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
39
+
40
+ return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
41
+ }
42
+
43
+ function fill (headers, object) {
44
+ // To fill a Headers object headers with a given object object, run these steps:
45
+
46
+ // 1. If object is a sequence, then for each header in object:
47
+ // Note: webidl conversion to array has already been done.
48
+ if (Array.isArray(object)) {
49
+ for (let i = 0; i < object.length; ++i) {
50
+ const header = object[i]
51
+ // 1. If header does not contain exactly two items, then throw a TypeError.
52
+ if (header.length !== 2) {
53
+ throw webidl.errors.exception({
54
+ header: 'Headers constructor',
55
+ message: `expected name/value pair to be length 2, found ${header.length}.`
56
+ })
57
+ }
58
+
59
+ // 2. Append (header’s first item, header’s second item) to headers.
60
+ appendHeader(headers, header[0], header[1])
61
+ }
62
+ } else if (typeof object === 'object' && object !== null) {
63
+ // Note: null should throw
64
+
65
+ // 2. Otherwise, object is a record, then for each key → value in object,
66
+ // append (key, value) to headers
67
+ const keys = Object.keys(object)
68
+ for (let i = 0; i < keys.length; ++i) {
69
+ appendHeader(headers, keys[i], object[keys[i]])
70
+ }
71
+ } else {
72
+ throw webidl.errors.conversionFailed({
73
+ prefix: 'Headers constructor',
74
+ argument: 'Argument 1',
75
+ types: ['sequence<sequence<ByteString>>', 'record<ByteString, ByteString>']
76
+ })
77
+ }
78
+ }
79
+
80
+ /**
81
+ * @see https://fetch.spec.whatwg.org/#concept-headers-append
82
+ */
83
+ function appendHeader (headers, name, value) {
84
+ // 1. Normalize value.
85
+ value = headerValueNormalize(value)
86
+
87
+ // 2. If name is not a header name or value is not a
88
+ // header value, then throw a TypeError.
89
+ if (!isValidHeaderName(name)) {
90
+ throw webidl.errors.invalidArgument({
91
+ prefix: 'Headers.append',
92
+ value: name,
93
+ type: 'header name'
94
+ })
95
+ } else if (!isValidHeaderValue(value)) {
96
+ throw webidl.errors.invalidArgument({
97
+ prefix: 'Headers.append',
98
+ value,
99
+ type: 'header value'
100
+ })
101
+ }
102
+
103
+ // 3. If headers’s guard is "immutable", then throw a TypeError.
104
+ // 4. Otherwise, if headers’s guard is "request" and name is a
105
+ // forbidden header name, return.
106
+ // Note: undici does not implement forbidden header names
107
+ if (headers[kGuard] === 'immutable') {
108
+ throw new TypeError('immutable')
109
+ } else if (headers[kGuard] === 'request-no-cors') {
110
+ // 5. Otherwise, if headers’s guard is "request-no-cors":
111
+ // TODO
112
+ }
113
+
114
+ // 6. Otherwise, if headers’s guard is "response" and name is a
115
+ // forbidden response-header name, return.
116
+
117
+ // 7. Append (name, value) to headers’s header list.
118
+ return headers[kHeadersList].append(name, value)
119
+
120
+ // 8. If headers’s guard is "request-no-cors", then remove
121
+ // privileged no-CORS request headers from headers
122
+ }
123
+
124
+ class HeadersList {
125
+ /** @type {[string, string][]|null} */
126
+ cookies = null
127
+
128
+ constructor (init) {
129
+ if (init instanceof HeadersList) {
130
+ this[kHeadersMap] = new Map(init[kHeadersMap])
131
+ this[kHeadersSortedMap] = init[kHeadersSortedMap]
132
+ this.cookies = init.cookies === null ? null : [...init.cookies]
133
+ } else {
134
+ this[kHeadersMap] = new Map(init)
135
+ this[kHeadersSortedMap] = null
136
+ }
137
+ }
138
+
139
+ // https://fetch.spec.whatwg.org/#header-list-contains
140
+ contains (name) {
141
+ // A header list list contains a header name name if list
142
+ // contains a header whose name is a byte-case-insensitive
143
+ // match for name.
144
+ name = name.toLowerCase()
145
+
146
+ return this[kHeadersMap].has(name)
147
+ }
148
+
149
+ clear () {
150
+ this[kHeadersMap].clear()
151
+ this[kHeadersSortedMap] = null
152
+ this.cookies = null
153
+ }
154
+
155
+ // https://fetch.spec.whatwg.org/#concept-header-list-append
156
+ append (name, value) {
157
+ this[kHeadersSortedMap] = null
158
+
159
+ // 1. If list contains name, then set name to the first such
160
+ // header’s name.
161
+ const lowercaseName = name.toLowerCase()
162
+ const exists = this[kHeadersMap].get(lowercaseName)
163
+
164
+ // 2. Append (name, value) to list.
165
+ if (exists) {
166
+ const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
167
+ this[kHeadersMap].set(lowercaseName, {
168
+ name: exists.name,
169
+ value: `${exists.value}${delimiter}${value}`
170
+ })
171
+ } else {
172
+ this[kHeadersMap].set(lowercaseName, { name, value })
173
+ }
174
+
175
+ if (lowercaseName === 'set-cookie') {
176
+ this.cookies ??= []
177
+ this.cookies.push(value)
178
+ }
179
+ }
180
+
181
+ // https://fetch.spec.whatwg.org/#concept-header-list-set
182
+ set (name, value) {
183
+ this[kHeadersSortedMap] = null
184
+ const lowercaseName = name.toLowerCase()
185
+
186
+ if (lowercaseName === 'set-cookie') {
187
+ this.cookies = [value]
188
+ }
189
+
190
+ // 1. If list contains name, then set the value of
191
+ // the first such header to value and remove the
192
+ // others.
193
+ // 2. Otherwise, append header (name, value) to list.
194
+ this[kHeadersMap].set(lowercaseName, { name, value })
195
+ }
196
+
197
+ // https://fetch.spec.whatwg.org/#concept-header-list-delete
198
+ delete (name) {
199
+ this[kHeadersSortedMap] = null
200
+
201
+ name = name.toLowerCase()
202
+
203
+ if (name === 'set-cookie') {
204
+ this.cookies = null
205
+ }
206
+
207
+ this[kHeadersMap].delete(name)
208
+ }
209
+
210
+ // https://fetch.spec.whatwg.org/#concept-header-list-get
211
+ get (name) {
212
+ const value = this[kHeadersMap].get(name.toLowerCase())
213
+
214
+ // 1. If list does not contain name, then return null.
215
+ // 2. Return the values of all headers in list whose name
216
+ // is a byte-case-insensitive match for name,
217
+ // separated from each other by 0x2C 0x20, in order.
218
+ return value === undefined ? null : value.value
219
+ }
220
+
221
+ * [Symbol.iterator] () {
222
+ // use the lowercased name
223
+ for (const [name, { value }] of this[kHeadersMap]) {
224
+ yield [name, value]
225
+ }
226
+ }
227
+
228
+ get entries () {
229
+ const headers = {}
230
+
231
+ if (this[kHeadersMap].size) {
232
+ for (const { name, value } of this[kHeadersMap].values()) {
233
+ headers[name] = value
234
+ }
235
+ }
236
+
237
+ return headers
238
+ }
239
+ }
240
+
241
+ // https://fetch.spec.whatwg.org/#headers-class
242
+ class Headers {
243
+ constructor (init = undefined) {
244
+ if (init === kConstruct) {
245
+ return
246
+ }
247
+ this[kHeadersList] = new HeadersList()
248
+
249
+ // The new Headers(init) constructor steps are:
250
+
251
+ // 1. Set this’s guard to "none".
252
+ this[kGuard] = 'none'
253
+
254
+ // 2. If init is given, then fill this with init.
255
+ if (init !== undefined) {
256
+ init = webidl.converters.HeadersInit(init)
257
+ fill(this, init)
258
+ }
259
+ }
260
+
261
+ // https://fetch.spec.whatwg.org/#dom-headers-append
262
+ append (name, value) {
263
+ webidl.brandCheck(this, Headers)
264
+
265
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
266
+
267
+ name = webidl.converters.ByteString(name)
268
+ value = webidl.converters.ByteString(value)
269
+
270
+ return appendHeader(this, name, value)
271
+ }
272
+
273
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
274
+ delete (name) {
275
+ webidl.brandCheck(this, Headers)
276
+
277
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
278
+
279
+ name = webidl.converters.ByteString(name)
280
+
281
+ // 1. If name is not a header name, then throw a TypeError.
282
+ if (!isValidHeaderName(name)) {
283
+ throw webidl.errors.invalidArgument({
284
+ prefix: 'Headers.delete',
285
+ value: name,
286
+ type: 'header name'
287
+ })
288
+ }
289
+
290
+ // 2. If this’s guard is "immutable", then throw a TypeError.
291
+ // 3. Otherwise, if this’s guard is "request" and name is a
292
+ // forbidden header name, return.
293
+ // 4. Otherwise, if this’s guard is "request-no-cors", name
294
+ // is not a no-CORS-safelisted request-header name, and
295
+ // name is not a privileged no-CORS request-header name,
296
+ // return.
297
+ // 5. Otherwise, if this’s guard is "response" and name is
298
+ // a forbidden response-header name, return.
299
+ // Note: undici does not implement forbidden header names
300
+ if (this[kGuard] === 'immutable') {
301
+ throw new TypeError('immutable')
302
+ } else if (this[kGuard] === 'request-no-cors') {
303
+ // TODO
304
+ }
305
+
306
+ // 6. If this’s header list does not contain name, then
307
+ // return.
308
+ if (!this[kHeadersList].contains(name)) {
309
+ return
310
+ }
311
+
312
+ // 7. Delete name from this’s header list.
313
+ // 8. If this’s guard is "request-no-cors", then remove
314
+ // privileged no-CORS request headers from this.
315
+ this[kHeadersList].delete(name)
316
+ }
317
+
318
+ // https://fetch.spec.whatwg.org/#dom-headers-get
319
+ get (name) {
320
+ webidl.brandCheck(this, Headers)
321
+
322
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
323
+
324
+ name = webidl.converters.ByteString(name)
325
+
326
+ // 1. If name is not a header name, then throw a TypeError.
327
+ if (!isValidHeaderName(name)) {
328
+ throw webidl.errors.invalidArgument({
329
+ prefix: 'Headers.get',
330
+ value: name,
331
+ type: 'header name'
332
+ })
333
+ }
334
+
335
+ // 2. Return the result of getting name from this’s header
336
+ // list.
337
+ return this[kHeadersList].get(name)
338
+ }
339
+
340
+ // https://fetch.spec.whatwg.org/#dom-headers-has
341
+ has (name) {
342
+ webidl.brandCheck(this, Headers)
343
+
344
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
345
+
346
+ name = webidl.converters.ByteString(name)
347
+
348
+ // 1. If name is not a header name, then throw a TypeError.
349
+ if (!isValidHeaderName(name)) {
350
+ throw webidl.errors.invalidArgument({
351
+ prefix: 'Headers.has',
352
+ value: name,
353
+ type: 'header name'
354
+ })
355
+ }
356
+
357
+ // 2. Return true if this’s header list contains name;
358
+ // otherwise false.
359
+ return this[kHeadersList].contains(name)
360
+ }
361
+
362
+ // https://fetch.spec.whatwg.org/#dom-headers-set
363
+ set (name, value) {
364
+ webidl.brandCheck(this, Headers)
365
+
366
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
367
+
368
+ name = webidl.converters.ByteString(name)
369
+ value = webidl.converters.ByteString(value)
370
+
371
+ // 1. Normalize value.
372
+ value = headerValueNormalize(value)
373
+
374
+ // 2. If name is not a header name or value is not a
375
+ // header value, then throw a TypeError.
376
+ if (!isValidHeaderName(name)) {
377
+ throw webidl.errors.invalidArgument({
378
+ prefix: 'Headers.set',
379
+ value: name,
380
+ type: 'header name'
381
+ })
382
+ } else if (!isValidHeaderValue(value)) {
383
+ throw webidl.errors.invalidArgument({
384
+ prefix: 'Headers.set',
385
+ value,
386
+ type: 'header value'
387
+ })
388
+ }
389
+
390
+ // 3. If this’s guard is "immutable", then throw a TypeError.
391
+ // 4. Otherwise, if this’s guard is "request" and name is a
392
+ // forbidden header name, return.
393
+ // 5. Otherwise, if this’s guard is "request-no-cors" and
394
+ // name/value is not a no-CORS-safelisted request-header,
395
+ // return.
396
+ // 6. Otherwise, if this’s guard is "response" and name is a
397
+ // forbidden response-header name, return.
398
+ // Note: undici does not implement forbidden header names
399
+ if (this[kGuard] === 'immutable') {
400
+ throw new TypeError('immutable')
401
+ } else if (this[kGuard] === 'request-no-cors') {
402
+ // TODO
403
+ }
404
+
405
+ // 7. Set (name, value) in this’s header list.
406
+ // 8. If this’s guard is "request-no-cors", then remove
407
+ // privileged no-CORS request headers from this
408
+ this[kHeadersList].set(name, value)
409
+ }
410
+
411
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
412
+ getSetCookie () {
413
+ webidl.brandCheck(this, Headers)
414
+
415
+ // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
416
+ // 2. Return the values of all headers in this’s header list whose name is
417
+ // a byte-case-insensitive match for `Set-Cookie`, in order.
418
+
419
+ const list = this[kHeadersList].cookies
420
+
421
+ if (list) {
422
+ return [...list]
423
+ }
424
+
425
+ return []
426
+ }
427
+
428
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
429
+ get [kHeadersSortedMap] () {
430
+ if (this[kHeadersList][kHeadersSortedMap]) {
431
+ return this[kHeadersList][kHeadersSortedMap]
432
+ }
433
+
434
+ // 1. Let headers be an empty list of headers with the key being the name
435
+ // and value the value.
436
+ const headers = []
437
+
438
+ // 2. Let names be the result of convert header names to a sorted-lowercase
439
+ // set with all the names of the headers in list.
440
+ const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
441
+ const cookies = this[kHeadersList].cookies
442
+
443
+ // 3. For each name of names:
444
+ for (let i = 0; i < names.length; ++i) {
445
+ const [name, value] = names[i]
446
+ // 1. If name is `set-cookie`, then:
447
+ if (name === 'set-cookie') {
448
+ // 1. Let values be a list of all values of headers in list whose name
449
+ // is a byte-case-insensitive match for name, in order.
450
+
451
+ // 2. For each value of values:
452
+ // 1. Append (name, value) to headers.
453
+ for (let j = 0; j < cookies.length; ++j) {
454
+ headers.push([name, cookies[j]])
455
+ }
456
+ } else {
457
+ // 2. Otherwise:
458
+
459
+ // 1. Let value be the result of getting name from list.
460
+
461
+ // 2. Assert: value is non-null.
462
+ assert(value !== null)
463
+
464
+ // 3. Append (name, value) to headers.
465
+ headers.push([name, value])
466
+ }
467
+ }
468
+
469
+ this[kHeadersList][kHeadersSortedMap] = headers
470
+
471
+ // 4. Return headers.
472
+ return headers
473
+ }
474
+
475
+ keys () {
476
+ webidl.brandCheck(this, Headers)
477
+
478
+ if (this[kGuard] === 'immutable') {
479
+ const value = this[kHeadersSortedMap]
480
+ return makeIterator(() => value, 'Headers',
481
+ 'key')
482
+ }
483
+
484
+ return makeIterator(
485
+ () => [...this[kHeadersSortedMap].values()],
486
+ 'Headers',
487
+ 'key'
488
+ )
489
+ }
490
+
491
+ values () {
492
+ webidl.brandCheck(this, Headers)
493
+
494
+ if (this[kGuard] === 'immutable') {
495
+ const value = this[kHeadersSortedMap]
496
+ return makeIterator(() => value, 'Headers',
497
+ 'value')
498
+ }
499
+
500
+ return makeIterator(
501
+ () => [...this[kHeadersSortedMap].values()],
502
+ 'Headers',
503
+ 'value'
504
+ )
505
+ }
506
+
507
+ entries () {
508
+ webidl.brandCheck(this, Headers)
509
+
510
+ if (this[kGuard] === 'immutable') {
511
+ const value = this[kHeadersSortedMap]
512
+ return makeIterator(() => value, 'Headers',
513
+ 'key+value')
514
+ }
515
+
516
+ return makeIterator(
517
+ () => [...this[kHeadersSortedMap].values()],
518
+ 'Headers',
519
+ 'key+value'
520
+ )
521
+ }
522
+
523
+ /**
524
+ * @param {(value: string, key: string, self: Headers) => void} callbackFn
525
+ * @param {unknown} thisArg
526
+ */
527
+ forEach (callbackFn, thisArg = globalThis) {
528
+ webidl.brandCheck(this, Headers)
529
+
530
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
531
+
532
+ if (typeof callbackFn !== 'function') {
533
+ throw new TypeError(
534
+ "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
535
+ )
536
+ }
537
+
538
+ for (const [key, value] of this) {
539
+ callbackFn.apply(thisArg, [value, key, this])
540
+ }
541
+ }
542
+
543
+ [Symbol.for('nodejs.util.inspect.custom')] () {
544
+ webidl.brandCheck(this, Headers)
545
+
546
+ return this[kHeadersList]
547
+ }
548
+ }
549
+
550
+ Headers.prototype[Symbol.iterator] = Headers.prototype.entries
551
+
552
+ Object.defineProperties(Headers.prototype, {
553
+ append: kEnumerableProperty,
554
+ delete: kEnumerableProperty,
555
+ get: kEnumerableProperty,
556
+ has: kEnumerableProperty,
557
+ set: kEnumerableProperty,
558
+ getSetCookie: kEnumerableProperty,
559
+ keys: kEnumerableProperty,
560
+ values: kEnumerableProperty,
561
+ entries: kEnumerableProperty,
562
+ forEach: kEnumerableProperty,
563
+ [Symbol.iterator]: { enumerable: false },
564
+ [Symbol.toStringTag]: {
565
+ value: 'Headers',
566
+ configurable: true
567
+ },
568
+ [util.inspect.custom]: {
569
+ enumerable: false
570
+ }
571
+ })
572
+
573
+ webidl.converters.HeadersInit = function (V) {
574
+ if (webidl.util.Type(V) === 'Object') {
575
+ if (V[Symbol.iterator]) {
576
+ return webidl.converters['sequence<sequence<ByteString>>'](V)
577
+ }
578
+
579
+ return webidl.converters['record<ByteString, ByteString>'](V)
580
+ }
581
+
582
+ throw webidl.errors.conversionFailed({
583
+ prefix: 'Headers constructor',
584
+ argument: 'Argument 1',
585
+ types: ['sequence<sequence<ByteString>>', 'record<ByteString, ByteString>']
586
+ })
587
+ }
588
+
589
+ module.exports = {
590
+ fill,
591
+ Headers,
592
+ HeadersList
593
+ }
worker/node_modules/undici/lib/fetch/index.js ADDED
@@ -0,0 +1,2148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // https://github.com/Ethan-Arrowood/undici-fetch
2
+
3
+ 'use strict'
4
+
5
+ const {
6
+ Response,
7
+ makeNetworkError,
8
+ makeAppropriateNetworkError,
9
+ filterResponse,
10
+ makeResponse
11
+ } = require('./response')
12
+ const { Headers } = require('./headers')
13
+ const { Request, makeRequest } = require('./request')
14
+ const zlib = require('zlib')
15
+ const {
16
+ bytesMatch,
17
+ makePolicyContainer,
18
+ clonePolicyContainer,
19
+ requestBadPort,
20
+ TAOCheck,
21
+ appendRequestOriginHeader,
22
+ responseLocationURL,
23
+ requestCurrentURL,
24
+ setRequestReferrerPolicyOnRedirect,
25
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
26
+ createOpaqueTimingInfo,
27
+ appendFetchMetadata,
28
+ corsCheck,
29
+ crossOriginResourcePolicyCheck,
30
+ determineRequestsReferrer,
31
+ coarsenedSharedCurrentTime,
32
+ createDeferredPromise,
33
+ isBlobLike,
34
+ sameOrigin,
35
+ isCancelled,
36
+ isAborted,
37
+ isErrorLike,
38
+ fullyReadBody,
39
+ readableStreamClose,
40
+ isomorphicEncode,
41
+ urlIsLocal,
42
+ urlIsHttpHttpsScheme,
43
+ urlHasHttpsScheme
44
+ } = require('./util')
45
+ const { kState, kHeaders, kGuard, kRealm } = require('./symbols')
46
+ const assert = require('assert')
47
+ const { safelyExtractBody } = require('./body')
48
+ const {
49
+ redirectStatusSet,
50
+ nullBodyStatus,
51
+ safeMethodsSet,
52
+ requestBodyHeader,
53
+ subresourceSet,
54
+ DOMException
55
+ } = require('./constants')
56
+ const { kHeadersList } = require('../core/symbols')
57
+ const EE = require('events')
58
+ const { Readable, pipeline } = require('stream')
59
+ const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util')
60
+ const { dataURLProcessor, serializeAMimeType } = require('./dataURL')
61
+ const { TransformStream } = require('stream/web')
62
+ const { getGlobalDispatcher } = require('../global')
63
+ const { webidl } = require('./webidl')
64
+ const { STATUS_CODES } = require('http')
65
+ const GET_OR_HEAD = ['GET', 'HEAD']
66
+
67
+ /** @type {import('buffer').resolveObjectURL} */
68
+ let resolveObjectURL
69
+ let ReadableStream = globalThis.ReadableStream
70
+
71
+ class Fetch extends EE {
72
+ constructor (dispatcher) {
73
+ super()
74
+
75
+ this.dispatcher = dispatcher
76
+ this.connection = null
77
+ this.dump = false
78
+ this.state = 'ongoing'
79
+ // 2 terminated listeners get added per request,
80
+ // but only 1 gets removed. If there are 20 redirects,
81
+ // 21 listeners will be added.
82
+ // See https://github.com/nodejs/undici/issues/1711
83
+ // TODO (fix): Find and fix root cause for leaked listener.
84
+ this.setMaxListeners(21)
85
+ }
86
+
87
+ terminate (reason) {
88
+ if (this.state !== 'ongoing') {
89
+ return
90
+ }
91
+
92
+ this.state = 'terminated'
93
+ this.connection?.destroy(reason)
94
+ this.emit('terminated', reason)
95
+ }
96
+
97
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
98
+ abort (error) {
99
+ if (this.state !== 'ongoing') {
100
+ return
101
+ }
102
+
103
+ // 1. Set controller’s state to "aborted".
104
+ this.state = 'aborted'
105
+
106
+ // 2. Let fallbackError be an "AbortError" DOMException.
107
+ // 3. Set error to fallbackError if it is not given.
108
+ if (!error) {
109
+ error = new DOMException('The operation was aborted.', 'AbortError')
110
+ }
111
+
112
+ // 4. Let serializedError be StructuredSerialize(error).
113
+ // If that threw an exception, catch it, and let
114
+ // serializedError be StructuredSerialize(fallbackError).
115
+
116
+ // 5. Set controller’s serialized abort reason to serializedError.
117
+ this.serializedAbortReason = error
118
+
119
+ this.connection?.destroy(error)
120
+ this.emit('terminated', error)
121
+ }
122
+ }
123
+
124
+ // https://fetch.spec.whatwg.org/#fetch-method
125
+ function fetch (input, init = {}) {
126
+ webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
127
+
128
+ // 1. Let p be a new promise.
129
+ const p = createDeferredPromise()
130
+
131
+ // 2. Let requestObject be the result of invoking the initial value of
132
+ // Request as constructor with input and init as arguments. If this throws
133
+ // an exception, reject p with it and return p.
134
+ let requestObject
135
+
136
+ try {
137
+ requestObject = new Request(input, init)
138
+ } catch (e) {
139
+ p.reject(e)
140
+ return p.promise
141
+ }
142
+
143
+ // 3. Let request be requestObject’s request.
144
+ const request = requestObject[kState]
145
+
146
+ // 4. If requestObject’s signal’s aborted flag is set, then:
147
+ if (requestObject.signal.aborted) {
148
+ // 1. Abort the fetch() call with p, request, null, and
149
+ // requestObject’s signal’s abort reason.
150
+ abortFetch(p, request, null, requestObject.signal.reason)
151
+
152
+ // 2. Return p.
153
+ return p.promise
154
+ }
155
+
156
+ // 5. Let globalObject be request’s client’s global object.
157
+ const globalObject = request.client.globalObject
158
+
159
+ // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
160
+ // request’s service-workers mode to "none".
161
+ if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
162
+ request.serviceWorkers = 'none'
163
+ }
164
+
165
+ // 7. Let responseObject be null.
166
+ let responseObject = null
167
+
168
+ // 8. Let relevantRealm be this’s relevant Realm.
169
+ const relevantRealm = null
170
+
171
+ // 9. Let locallyAborted be false.
172
+ let locallyAborted = false
173
+
174
+ // 10. Let controller be null.
175
+ let controller = null
176
+
177
+ // 11. Add the following abort steps to requestObject’s signal:
178
+ addAbortListener(
179
+ requestObject.signal,
180
+ () => {
181
+ // 1. Set locallyAborted to true.
182
+ locallyAborted = true
183
+
184
+ // 2. Assert: controller is non-null.
185
+ assert(controller != null)
186
+
187
+ // 3. Abort controller with requestObject’s signal’s abort reason.
188
+ controller.abort(requestObject.signal.reason)
189
+
190
+ // 4. Abort the fetch() call with p, request, responseObject,
191
+ // and requestObject’s signal’s abort reason.
192
+ abortFetch(p, request, responseObject, requestObject.signal.reason)
193
+ }
194
+ )
195
+
196
+ // 12. Let handleFetchDone given response response be to finalize and
197
+ // report timing with response, globalObject, and "fetch".
198
+ const handleFetchDone = (response) =>
199
+ finalizeAndReportTiming(response, 'fetch')
200
+
201
+ // 13. Set controller to the result of calling fetch given request,
202
+ // with processResponseEndOfBody set to handleFetchDone, and processResponse
203
+ // given response being these substeps:
204
+
205
+ const processResponse = (response) => {
206
+ // 1. If locallyAborted is true, terminate these substeps.
207
+ if (locallyAborted) {
208
+ return Promise.resolve()
209
+ }
210
+
211
+ // 2. If response’s aborted flag is set, then:
212
+ if (response.aborted) {
213
+ // 1. Let deserializedError be the result of deserialize a serialized
214
+ // abort reason given controller’s serialized abort reason and
215
+ // relevantRealm.
216
+
217
+ // 2. Abort the fetch() call with p, request, responseObject, and
218
+ // deserializedError.
219
+
220
+ abortFetch(p, request, responseObject, controller.serializedAbortReason)
221
+ return Promise.resolve()
222
+ }
223
+
224
+ // 3. If response is a network error, then reject p with a TypeError
225
+ // and terminate these substeps.
226
+ if (response.type === 'error') {
227
+ p.reject(
228
+ Object.assign(new TypeError('fetch failed'), { cause: response.error })
229
+ )
230
+ return Promise.resolve()
231
+ }
232
+
233
+ // 4. Set responseObject to the result of creating a Response object,
234
+ // given response, "immutable", and relevantRealm.
235
+ responseObject = new Response()
236
+ responseObject[kState] = response
237
+ responseObject[kRealm] = relevantRealm
238
+ responseObject[kHeaders][kHeadersList] = response.headersList
239
+ responseObject[kHeaders][kGuard] = 'immutable'
240
+ responseObject[kHeaders][kRealm] = relevantRealm
241
+
242
+ // 5. Resolve p with responseObject.
243
+ p.resolve(responseObject)
244
+ }
245
+
246
+ controller = fetching({
247
+ request,
248
+ processResponseEndOfBody: handleFetchDone,
249
+ processResponse,
250
+ dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
251
+ })
252
+
253
+ // 14. Return p.
254
+ return p.promise
255
+ }
256
+
257
+ // https://fetch.spec.whatwg.org/#finalize-and-report-timing
258
+ function finalizeAndReportTiming (response, initiatorType = 'other') {
259
+ // 1. If response is an aborted network error, then return.
260
+ if (response.type === 'error' && response.aborted) {
261
+ return
262
+ }
263
+
264
+ // 2. If response’s URL list is null or empty, then return.
265
+ if (!response.urlList?.length) {
266
+ return
267
+ }
268
+
269
+ // 3. Let originalURL be response’s URL list[0].
270
+ const originalURL = response.urlList[0]
271
+
272
+ // 4. Let timingInfo be response’s timing info.
273
+ let timingInfo = response.timingInfo
274
+
275
+ // 5. Let cacheState be response’s cache state.
276
+ let cacheState = response.cacheState
277
+
278
+ // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
279
+ if (!urlIsHttpHttpsScheme(originalURL)) {
280
+ return
281
+ }
282
+
283
+ // 7. If timingInfo is null, then return.
284
+ if (timingInfo === null) {
285
+ return
286
+ }
287
+
288
+ // 8. If response’s timing allow passed flag is not set, then:
289
+ if (!response.timingAllowPassed) {
290
+ // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
291
+ timingInfo = createOpaqueTimingInfo({
292
+ startTime: timingInfo.startTime
293
+ })
294
+
295
+ // 2. Set cacheState to the empty string.
296
+ cacheState = ''
297
+ }
298
+
299
+ // 9. Set timingInfo’s end time to the coarsened shared current time
300
+ // given global’s relevant settings object’s cross-origin isolated
301
+ // capability.
302
+ // TODO: given global’s relevant settings object’s cross-origin isolated
303
+ // capability?
304
+ timingInfo.endTime = coarsenedSharedCurrentTime()
305
+
306
+ // 10. Set response’s timing info to timingInfo.
307
+ response.timingInfo = timingInfo
308
+
309
+ // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
310
+ // global, and cacheState.
311
+ markResourceTiming(
312
+ timingInfo,
313
+ originalURL,
314
+ initiatorType,
315
+ globalThis,
316
+ cacheState
317
+ )
318
+ }
319
+
320
+ // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
321
+ function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
322
+ if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
323
+ performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
324
+ }
325
+ }
326
+
327
+ // https://fetch.spec.whatwg.org/#abort-fetch
328
+ function abortFetch (p, request, responseObject, error) {
329
+ // Note: AbortSignal.reason was added in node v17.2.0
330
+ // which would give us an undefined error to reject with.
331
+ // Remove this once node v16 is no longer supported.
332
+ if (!error) {
333
+ error = new DOMException('The operation was aborted.', 'AbortError')
334
+ }
335
+
336
+ // 1. Reject promise with error.
337
+ p.reject(error)
338
+
339
+ // 2. If request’s body is not null and is readable, then cancel request’s
340
+ // body with error.
341
+ if (request.body != null && isReadable(request.body?.stream)) {
342
+ request.body.stream.cancel(error).catch((err) => {
343
+ if (err.code === 'ERR_INVALID_STATE') {
344
+ // Node bug?
345
+ return
346
+ }
347
+ throw err
348
+ })
349
+ }
350
+
351
+ // 3. If responseObject is null, then return.
352
+ if (responseObject == null) {
353
+ return
354
+ }
355
+
356
+ // 4. Let response be responseObject’s response.
357
+ const response = responseObject[kState]
358
+
359
+ // 5. If response’s body is not null and is readable, then error response’s
360
+ // body with error.
361
+ if (response.body != null && isReadable(response.body?.stream)) {
362
+ response.body.stream.cancel(error).catch((err) => {
363
+ if (err.code === 'ERR_INVALID_STATE') {
364
+ // Node bug?
365
+ return
366
+ }
367
+ throw err
368
+ })
369
+ }
370
+ }
371
+
372
+ // https://fetch.spec.whatwg.org/#fetching
373
+ function fetching ({
374
+ request,
375
+ processRequestBodyChunkLength,
376
+ processRequestEndOfBody,
377
+ processResponse,
378
+ processResponseEndOfBody,
379
+ processResponseConsumeBody,
380
+ useParallelQueue = false,
381
+ dispatcher // undici
382
+ }) {
383
+ // 1. Let taskDestination be null.
384
+ let taskDestination = null
385
+
386
+ // 2. Let crossOriginIsolatedCapability be false.
387
+ let crossOriginIsolatedCapability = false
388
+
389
+ // 3. If request’s client is non-null, then:
390
+ if (request.client != null) {
391
+ // 1. Set taskDestination to request’s client’s global object.
392
+ taskDestination = request.client.globalObject
393
+
394
+ // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
395
+ // isolated capability.
396
+ crossOriginIsolatedCapability =
397
+ request.client.crossOriginIsolatedCapability
398
+ }
399
+
400
+ // 4. If useParallelQueue is true, then set taskDestination to the result of
401
+ // starting a new parallel queue.
402
+ // TODO
403
+
404
+ // 5. Let timingInfo be a new fetch timing info whose start time and
405
+ // post-redirect start time are the coarsened shared current time given
406
+ // crossOriginIsolatedCapability.
407
+ const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
408
+ const timingInfo = createOpaqueTimingInfo({
409
+ startTime: currenTime
410
+ })
411
+
412
+ // 6. Let fetchParams be a new fetch params whose
413
+ // request is request,
414
+ // timing info is timingInfo,
415
+ // process request body chunk length is processRequestBodyChunkLength,
416
+ // process request end-of-body is processRequestEndOfBody,
417
+ // process response is processResponse,
418
+ // process response consume body is processResponseConsumeBody,
419
+ // process response end-of-body is processResponseEndOfBody,
420
+ // task destination is taskDestination,
421
+ // and cross-origin isolated capability is crossOriginIsolatedCapability.
422
+ const fetchParams = {
423
+ controller: new Fetch(dispatcher),
424
+ request,
425
+ timingInfo,
426
+ processRequestBodyChunkLength,
427
+ processRequestEndOfBody,
428
+ processResponse,
429
+ processResponseConsumeBody,
430
+ processResponseEndOfBody,
431
+ taskDestination,
432
+ crossOriginIsolatedCapability
433
+ }
434
+
435
+ // 7. If request’s body is a byte sequence, then set request’s body to
436
+ // request’s body as a body.
437
+ // NOTE: Since fetching is only called from fetch, body should already be
438
+ // extracted.
439
+ assert(!request.body || request.body.stream)
440
+
441
+ // 8. If request’s window is "client", then set request’s window to request’s
442
+ // client, if request’s client’s global object is a Window object; otherwise
443
+ // "no-window".
444
+ if (request.window === 'client') {
445
+ // TODO: What if request.client is null?
446
+ request.window =
447
+ request.client?.globalObject?.constructor?.name === 'Window'
448
+ ? request.client
449
+ : 'no-window'
450
+ }
451
+
452
+ // 9. If request’s origin is "client", then set request’s origin to request’s
453
+ // client’s origin.
454
+ if (request.origin === 'client') {
455
+ // TODO: What if request.client is null?
456
+ request.origin = request.client?.origin
457
+ }
458
+
459
+ // 10. If all of the following conditions are true:
460
+ // TODO
461
+
462
+ // 11. If request’s policy container is "client", then:
463
+ if (request.policyContainer === 'client') {
464
+ // 1. If request’s client is non-null, then set request’s policy
465
+ // container to a clone of request’s client’s policy container. [HTML]
466
+ if (request.client != null) {
467
+ request.policyContainer = clonePolicyContainer(
468
+ request.client.policyContainer
469
+ )
470
+ } else {
471
+ // 2. Otherwise, set request’s policy container to a new policy
472
+ // container.
473
+ request.policyContainer = makePolicyContainer()
474
+ }
475
+ }
476
+
477
+ // 12. If request’s header list does not contain `Accept`, then:
478
+ if (!request.headersList.contains('accept')) {
479
+ // 1. Let value be `*/*`.
480
+ const value = '*/*'
481
+
482
+ // 2. A user agent should set value to the first matching statement, if
483
+ // any, switching on request’s destination:
484
+ // "document"
485
+ // "frame"
486
+ // "iframe"
487
+ // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
488
+ // "image"
489
+ // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
490
+ // "style"
491
+ // `text/css,*/*;q=0.1`
492
+ // TODO
493
+
494
+ // 3. Append `Accept`/value to request’s header list.
495
+ request.headersList.append('accept', value)
496
+ }
497
+
498
+ // 13. If request’s header list does not contain `Accept-Language`, then
499
+ // user agents should append `Accept-Language`/an appropriate value to
500
+ // request’s header list.
501
+ if (!request.headersList.contains('accept-language')) {
502
+ request.headersList.append('accept-language', '*')
503
+ }
504
+
505
+ // 14. If request’s priority is null, then use request’s initiator and
506
+ // destination appropriately in setting request’s priority to a
507
+ // user-agent-defined object.
508
+ if (request.priority === null) {
509
+ // TODO
510
+ }
511
+
512
+ // 15. If request is a subresource request, then:
513
+ if (subresourceSet.has(request.destination)) {
514
+ // TODO
515
+ }
516
+
517
+ // 16. Run main fetch given fetchParams.
518
+ mainFetch(fetchParams)
519
+ .catch(err => {
520
+ fetchParams.controller.terminate(err)
521
+ })
522
+
523
+ // 17. Return fetchParam's controller
524
+ return fetchParams.controller
525
+ }
526
+
527
+ // https://fetch.spec.whatwg.org/#concept-main-fetch
528
+ async function mainFetch (fetchParams, recursive = false) {
529
+ // 1. Let request be fetchParams’s request.
530
+ const request = fetchParams.request
531
+
532
+ // 2. Let response be null.
533
+ let response = null
534
+
535
+ // 3. If request’s local-URLs-only flag is set and request’s current URL is
536
+ // not local, then set response to a network error.
537
+ if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
538
+ response = makeNetworkError('local URLs only')
539
+ }
540
+
541
+ // 4. Run report Content Security Policy violations for request.
542
+ // TODO
543
+
544
+ // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
545
+ tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
546
+
547
+ // 6. If should request be blocked due to a bad port, should fetching request
548
+ // be blocked as mixed content, or should request be blocked by Content
549
+ // Security Policy returns blocked, then set response to a network error.
550
+ if (requestBadPort(request) === 'blocked') {
551
+ response = makeNetworkError('bad port')
552
+ }
553
+ // TODO: should fetching request be blocked as mixed content?
554
+ // TODO: should request be blocked by Content Security Policy?
555
+
556
+ // 7. If request’s referrer policy is the empty string, then set request’s
557
+ // referrer policy to request’s policy container’s referrer policy.
558
+ if (request.referrerPolicy === '') {
559
+ request.referrerPolicy = request.policyContainer.referrerPolicy
560
+ }
561
+
562
+ // 8. If request’s referrer is not "no-referrer", then set request’s
563
+ // referrer to the result of invoking determine request’s referrer.
564
+ if (request.referrer !== 'no-referrer') {
565
+ request.referrer = determineRequestsReferrer(request)
566
+ }
567
+
568
+ // 9. Set request’s current URL’s scheme to "https" if all of the following
569
+ // conditions are true:
570
+ // - request’s current URL’s scheme is "http"
571
+ // - request’s current URL’s host is a domain
572
+ // - Matching request’s current URL’s host per Known HSTS Host Domain Name
573
+ // Matching results in either a superdomain match with an asserted
574
+ // includeSubDomains directive or a congruent match (with or without an
575
+ // asserted includeSubDomains directive). [HSTS]
576
+ // TODO
577
+
578
+ // 10. If recursive is false, then run the remaining steps in parallel.
579
+ // TODO
580
+
581
+ // 11. If response is null, then set response to the result of running
582
+ // the steps corresponding to the first matching statement:
583
+ if (response === null) {
584
+ response = await (async () => {
585
+ const currentURL = requestCurrentURL(request)
586
+
587
+ if (
588
+ // - request’s current URL’s origin is same origin with request’s origin,
589
+ // and request’s response tainting is "basic"
590
+ (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
591
+ // request’s current URL’s scheme is "data"
592
+ (currentURL.protocol === 'data:') ||
593
+ // - request’s mode is "navigate" or "websocket"
594
+ (request.mode === 'navigate' || request.mode === 'websocket')
595
+ ) {
596
+ // 1. Set request’s response tainting to "basic".
597
+ request.responseTainting = 'basic'
598
+
599
+ // 2. Return the result of running scheme fetch given fetchParams.
600
+ return await schemeFetch(fetchParams)
601
+ }
602
+
603
+ // request’s mode is "same-origin"
604
+ if (request.mode === 'same-origin') {
605
+ // 1. Return a network error.
606
+ return makeNetworkError('request mode cannot be "same-origin"')
607
+ }
608
+
609
+ // request’s mode is "no-cors"
610
+ if (request.mode === 'no-cors') {
611
+ // 1. If request’s redirect mode is not "follow", then return a network
612
+ // error.
613
+ if (request.redirect !== 'follow') {
614
+ return makeNetworkError(
615
+ 'redirect mode cannot be "follow" for "no-cors" request'
616
+ )
617
+ }
618
+
619
+ // 2. Set request’s response tainting to "opaque".
620
+ request.responseTainting = 'opaque'
621
+
622
+ // 3. Return the result of running scheme fetch given fetchParams.
623
+ return await schemeFetch(fetchParams)
624
+ }
625
+
626
+ // request’s current URL’s scheme is not an HTTP(S) scheme
627
+ if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
628
+ // Return a network error.
629
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
630
+ }
631
+
632
+ // - request’s use-CORS-preflight flag is set
633
+ // - request’s unsafe-request flag is set and either request’s method is
634
+ // not a CORS-safelisted method or CORS-unsafe request-header names with
635
+ // request’s header list is not empty
636
+ // 1. Set request’s response tainting to "cors".
637
+ // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
638
+ // given fetchParams and true.
639
+ // 3. If corsWithPreflightResponse is a network error, then clear cache
640
+ // entries using request.
641
+ // 4. Return corsWithPreflightResponse.
642
+ // TODO
643
+
644
+ // Otherwise
645
+ // 1. Set request’s response tainting to "cors".
646
+ request.responseTainting = 'cors'
647
+
648
+ // 2. Return the result of running HTTP fetch given fetchParams.
649
+ return await httpFetch(fetchParams)
650
+ })()
651
+ }
652
+
653
+ // 12. If recursive is true, then return response.
654
+ if (recursive) {
655
+ return response
656
+ }
657
+
658
+ // 13. If response is not a network error and response is not a filtered
659
+ // response, then:
660
+ if (response.status !== 0 && !response.internalResponse) {
661
+ // If request’s response tainting is "cors", then:
662
+ if (request.responseTainting === 'cors') {
663
+ // 1. Let headerNames be the result of extracting header list values
664
+ // given `Access-Control-Expose-Headers` and response’s header list.
665
+ // TODO
666
+ // 2. If request’s credentials mode is not "include" and headerNames
667
+ // contains `*`, then set response’s CORS-exposed header-name list to
668
+ // all unique header names in response’s header list.
669
+ // TODO
670
+ // 3. Otherwise, if headerNames is not null or failure, then set
671
+ // response’s CORS-exposed header-name list to headerNames.
672
+ // TODO
673
+ }
674
+
675
+ // Set response to the following filtered response with response as its
676
+ // internal response, depending on request’s response tainting:
677
+ if (request.responseTainting === 'basic') {
678
+ response = filterResponse(response, 'basic')
679
+ } else if (request.responseTainting === 'cors') {
680
+ response = filterResponse(response, 'cors')
681
+ } else if (request.responseTainting === 'opaque') {
682
+ response = filterResponse(response, 'opaque')
683
+ } else {
684
+ assert(false)
685
+ }
686
+ }
687
+
688
+ // 14. Let internalResponse be response, if response is a network error,
689
+ // and response’s internal response otherwise.
690
+ let internalResponse =
691
+ response.status === 0 ? response : response.internalResponse
692
+
693
+ // 15. If internalResponse’s URL list is empty, then set it to a clone of
694
+ // request’s URL list.
695
+ if (internalResponse.urlList.length === 0) {
696
+ internalResponse.urlList.push(...request.urlList)
697
+ }
698
+
699
+ // 16. If request’s timing allow failed flag is unset, then set
700
+ // internalResponse’s timing allow passed flag.
701
+ if (!request.timingAllowFailed) {
702
+ response.timingAllowPassed = true
703
+ }
704
+
705
+ // 17. If response is not a network error and any of the following returns
706
+ // blocked
707
+ // - should internalResponse to request be blocked as mixed content
708
+ // - should internalResponse to request be blocked by Content Security Policy
709
+ // - should internalResponse to request be blocked due to its MIME type
710
+ // - should internalResponse to request be blocked due to nosniff
711
+ // TODO
712
+
713
+ // 18. If response’s type is "opaque", internalResponse’s status is 206,
714
+ // internalResponse’s range-requested flag is set, and request’s header
715
+ // list does not contain `Range`, then set response and internalResponse
716
+ // to a network error.
717
+ if (
718
+ response.type === 'opaque' &&
719
+ internalResponse.status === 206 &&
720
+ internalResponse.rangeRequested &&
721
+ !request.headers.contains('range')
722
+ ) {
723
+ response = internalResponse = makeNetworkError()
724
+ }
725
+
726
+ // 19. If response is not a network error and either request’s method is
727
+ // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
728
+ // set internalResponse’s body to null and disregard any enqueuing toward
729
+ // it (if any).
730
+ if (
731
+ response.status !== 0 &&
732
+ (request.method === 'HEAD' ||
733
+ request.method === 'CONNECT' ||
734
+ nullBodyStatus.includes(internalResponse.status))
735
+ ) {
736
+ internalResponse.body = null
737
+ fetchParams.controller.dump = true
738
+ }
739
+
740
+ // 20. If request’s integrity metadata is not the empty string, then:
741
+ if (request.integrity) {
742
+ // 1. Let processBodyError be this step: run fetch finale given fetchParams
743
+ // and a network error.
744
+ const processBodyError = (reason) =>
745
+ fetchFinale(fetchParams, makeNetworkError(reason))
746
+
747
+ // 2. If request’s response tainting is "opaque", or response’s body is null,
748
+ // then run processBodyError and abort these steps.
749
+ if (request.responseTainting === 'opaque' || response.body == null) {
750
+ processBodyError(response.error)
751
+ return
752
+ }
753
+
754
+ // 3. Let processBody given bytes be these steps:
755
+ const processBody = (bytes) => {
756
+ // 1. If bytes do not match request’s integrity metadata,
757
+ // then run processBodyError and abort these steps. [SRI]
758
+ if (!bytesMatch(bytes, request.integrity)) {
759
+ processBodyError('integrity mismatch')
760
+ return
761
+ }
762
+
763
+ // 2. Set response’s body to bytes as a body.
764
+ response.body = safelyExtractBody(bytes)[0]
765
+
766
+ // 3. Run fetch finale given fetchParams and response.
767
+ fetchFinale(fetchParams, response)
768
+ }
769
+
770
+ // 4. Fully read response’s body given processBody and processBodyError.
771
+ await fullyReadBody(response.body, processBody, processBodyError)
772
+ } else {
773
+ // 21. Otherwise, run fetch finale given fetchParams and response.
774
+ fetchFinale(fetchParams, response)
775
+ }
776
+ }
777
+
778
+ // https://fetch.spec.whatwg.org/#concept-scheme-fetch
779
+ // given a fetch params fetchParams
780
+ function schemeFetch (fetchParams) {
781
+ // Note: since the connection is destroyed on redirect, which sets fetchParams to a
782
+ // cancelled state, we do not want this condition to trigger *unless* there have been
783
+ // no redirects. See https://github.com/nodejs/undici/issues/1776
784
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
785
+ if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
786
+ return Promise.resolve(makeAppropriateNetworkError(fetchParams))
787
+ }
788
+
789
+ // 2. Let request be fetchParams’s request.
790
+ const { request } = fetchParams
791
+
792
+ const { protocol: scheme } = requestCurrentURL(request)
793
+
794
+ // 3. Switch on request’s current URL’s scheme and run the associated steps:
795
+ switch (scheme) {
796
+ case 'about:': {
797
+ // If request’s current URL’s path is the string "blank", then return a new response
798
+ // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
799
+ // and body is the empty byte sequence as a body.
800
+
801
+ // Otherwise, return a network error.
802
+ return Promise.resolve(makeNetworkError('about scheme is not supported'))
803
+ }
804
+ case 'blob:': {
805
+ if (!resolveObjectURL) {
806
+ resolveObjectURL = require('buffer').resolveObjectURL
807
+ }
808
+
809
+ // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
810
+ const blobURLEntry = requestCurrentURL(request)
811
+
812
+ // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
813
+ // Buffer.resolveObjectURL does not ignore URL queries.
814
+ if (blobURLEntry.search.length !== 0) {
815
+ return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
816
+ }
817
+
818
+ const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
819
+
820
+ // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
821
+ // object is not a Blob object, then return a network error.
822
+ if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
823
+ return Promise.resolve(makeNetworkError('invalid method'))
824
+ }
825
+
826
+ // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
827
+ const bodyWithType = safelyExtractBody(blobURLEntryObject)
828
+
829
+ // 4. Let body be bodyWithType’s body.
830
+ const body = bodyWithType[0]
831
+
832
+ // 5. Let length be body’s length, serialized and isomorphic encoded.
833
+ const length = isomorphicEncode(`${body.length}`)
834
+
835
+ // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
836
+ const type = bodyWithType[1] ?? ''
837
+
838
+ // 7. Return a new response whose status message is `OK`, header list is
839
+ // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
840
+ const response = makeResponse({
841
+ statusText: 'OK',
842
+ headersList: [
843
+ ['content-length', { name: 'Content-Length', value: length }],
844
+ ['content-type', { name: 'Content-Type', value: type }]
845
+ ]
846
+ })
847
+
848
+ response.body = body
849
+
850
+ return Promise.resolve(response)
851
+ }
852
+ case 'data:': {
853
+ // 1. Let dataURLStruct be the result of running the
854
+ // data: URL processor on request’s current URL.
855
+ const currentURL = requestCurrentURL(request)
856
+ const dataURLStruct = dataURLProcessor(currentURL)
857
+
858
+ // 2. If dataURLStruct is failure, then return a
859
+ // network error.
860
+ if (dataURLStruct === 'failure') {
861
+ return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
862
+ }
863
+
864
+ // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
865
+ const mimeType = serializeAMimeType(dataURLStruct.mimeType)
866
+
867
+ // 4. Return a response whose status message is `OK`,
868
+ // header list is « (`Content-Type`, mimeType) »,
869
+ // and body is dataURLStruct’s body as a body.
870
+ return Promise.resolve(makeResponse({
871
+ statusText: 'OK',
872
+ headersList: [
873
+ ['content-type', { name: 'Content-Type', value: mimeType }]
874
+ ],
875
+ body: safelyExtractBody(dataURLStruct.body)[0]
876
+ }))
877
+ }
878
+ case 'file:': {
879
+ // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
880
+ // When in doubt, return a network error.
881
+ return Promise.resolve(makeNetworkError('not implemented... yet...'))
882
+ }
883
+ case 'http:':
884
+ case 'https:': {
885
+ // Return the result of running HTTP fetch given fetchParams.
886
+
887
+ return httpFetch(fetchParams)
888
+ .catch((err) => makeNetworkError(err))
889
+ }
890
+ default: {
891
+ return Promise.resolve(makeNetworkError('unknown scheme'))
892
+ }
893
+ }
894
+ }
895
+
896
+ // https://fetch.spec.whatwg.org/#finalize-response
897
+ function finalizeResponse (fetchParams, response) {
898
+ // 1. Set fetchParams’s request’s done flag.
899
+ fetchParams.request.done = true
900
+
901
+ // 2, If fetchParams’s process response done is not null, then queue a fetch
902
+ // task to run fetchParams’s process response done given response, with
903
+ // fetchParams’s task destination.
904
+ if (fetchParams.processResponseDone != null) {
905
+ queueMicrotask(() => fetchParams.processResponseDone(response))
906
+ }
907
+ }
908
+
909
+ // https://fetch.spec.whatwg.org/#fetch-finale
910
+ function fetchFinale (fetchParams, response) {
911
+ // 1. If response is a network error, then:
912
+ if (response.type === 'error') {
913
+ // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
914
+ response.urlList = [fetchParams.request.urlList[0]]
915
+
916
+ // 2. Set response’s timing info to the result of creating an opaque timing
917
+ // info for fetchParams’s timing info.
918
+ response.timingInfo = createOpaqueTimingInfo({
919
+ startTime: fetchParams.timingInfo.startTime
920
+ })
921
+ }
922
+
923
+ // 2. Let processResponseEndOfBody be the following steps:
924
+ const processResponseEndOfBody = () => {
925
+ // 1. Set fetchParams’s request’s done flag.
926
+ fetchParams.request.done = true
927
+
928
+ // If fetchParams’s process response end-of-body is not null,
929
+ // then queue a fetch task to run fetchParams’s process response
930
+ // end-of-body given response with fetchParams’s task destination.
931
+ if (fetchParams.processResponseEndOfBody != null) {
932
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
933
+ }
934
+ }
935
+
936
+ // 3. If fetchParams’s process response is non-null, then queue a fetch task
937
+ // to run fetchParams’s process response given response, with fetchParams’s
938
+ // task destination.
939
+ if (fetchParams.processResponse != null) {
940
+ queueMicrotask(() => fetchParams.processResponse(response))
941
+ }
942
+
943
+ // 4. If response’s body is null, then run processResponseEndOfBody.
944
+ if (response.body == null) {
945
+ processResponseEndOfBody()
946
+ } else {
947
+ // 5. Otherwise:
948
+
949
+ // 1. Let transformStream be a new a TransformStream.
950
+
951
+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
952
+ // enqueues chunk in transformStream.
953
+ const identityTransformAlgorithm = (chunk, controller) => {
954
+ controller.enqueue(chunk)
955
+ }
956
+
957
+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
958
+ // and flushAlgorithm set to processResponseEndOfBody.
959
+ const transformStream = new TransformStream({
960
+ start () {},
961
+ transform: identityTransformAlgorithm,
962
+ flush: processResponseEndOfBody
963
+ }, {
964
+ size () {
965
+ return 1
966
+ }
967
+ }, {
968
+ size () {
969
+ return 1
970
+ }
971
+ })
972
+
973
+ // 4. Set response’s body to the result of piping response’s body through transformStream.
974
+ response.body = { stream: response.body.stream.pipeThrough(transformStream) }
975
+ }
976
+
977
+ // 6. If fetchParams’s process response consume body is non-null, then:
978
+ if (fetchParams.processResponseConsumeBody != null) {
979
+ // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
980
+ // process response consume body given response and nullOrBytes.
981
+ const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
982
+
983
+ // 2. Let processBodyError be this step: run fetchParams’s process
984
+ // response consume body given response and failure.
985
+ const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
986
+
987
+ // 3. If response’s body is null, then queue a fetch task to run processBody
988
+ // given null, with fetchParams’s task destination.
989
+ if (response.body == null) {
990
+ queueMicrotask(() => processBody(null))
991
+ } else {
992
+ // 4. Otherwise, fully read response’s body given processBody, processBodyError,
993
+ // and fetchParams’s task destination.
994
+ return fullyReadBody(response.body, processBody, processBodyError)
995
+ }
996
+ return Promise.resolve()
997
+ }
998
+ }
999
+
1000
+ // https://fetch.spec.whatwg.org/#http-fetch
1001
+ async function httpFetch (fetchParams) {
1002
+ // 1. Let request be fetchParams’s request.
1003
+ const request = fetchParams.request
1004
+
1005
+ // 2. Let response be null.
1006
+ let response = null
1007
+
1008
+ // 3. Let actualResponse be null.
1009
+ let actualResponse = null
1010
+
1011
+ // 4. Let timingInfo be fetchParams’s timing info.
1012
+ const timingInfo = fetchParams.timingInfo
1013
+
1014
+ // 5. If request’s service-workers mode is "all", then:
1015
+ if (request.serviceWorkers === 'all') {
1016
+ // TODO
1017
+ }
1018
+
1019
+ // 6. If response is null, then:
1020
+ if (response === null) {
1021
+ // 1. If makeCORSPreflight is true and one of these conditions is true:
1022
+ // TODO
1023
+
1024
+ // 2. If request’s redirect mode is "follow", then set request’s
1025
+ // service-workers mode to "none".
1026
+ if (request.redirect === 'follow') {
1027
+ request.serviceWorkers = 'none'
1028
+ }
1029
+
1030
+ // 3. Set response and actualResponse to the result of running
1031
+ // HTTP-network-or-cache fetch given fetchParams.
1032
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
1033
+
1034
+ // 4. If request’s response tainting is "cors" and a CORS check
1035
+ // for request and response returns failure, then return a network error.
1036
+ if (
1037
+ request.responseTainting === 'cors' &&
1038
+ corsCheck(request, response) === 'failure'
1039
+ ) {
1040
+ return makeNetworkError('cors failure')
1041
+ }
1042
+
1043
+ // 5. If the TAO check for request and response returns failure, then set
1044
+ // request’s timing allow failed flag.
1045
+ if (TAOCheck(request, response) === 'failure') {
1046
+ request.timingAllowFailed = true
1047
+ }
1048
+ }
1049
+
1050
+ // 7. If either request’s response tainting or response’s type
1051
+ // is "opaque", and the cross-origin resource policy check with
1052
+ // request’s origin, request’s client, request’s destination,
1053
+ // and actualResponse returns blocked, then return a network error.
1054
+ if (
1055
+ (request.responseTainting === 'opaque' || response.type === 'opaque') &&
1056
+ crossOriginResourcePolicyCheck(
1057
+ request.origin,
1058
+ request.client,
1059
+ request.destination,
1060
+ actualResponse
1061
+ ) === 'blocked'
1062
+ ) {
1063
+ return makeNetworkError('blocked')
1064
+ }
1065
+
1066
+ // 8. If actualResponse’s status is a redirect status, then:
1067
+ if (redirectStatusSet.has(actualResponse.status)) {
1068
+ // 1. If actualResponse’s status is not 303, request’s body is not null,
1069
+ // and the connection uses HTTP/2, then user agents may, and are even
1070
+ // encouraged to, transmit an RST_STREAM frame.
1071
+ // See, https://github.com/whatwg/fetch/issues/1288
1072
+ if (request.redirect !== 'manual') {
1073
+ fetchParams.controller.connection.destroy()
1074
+ }
1075
+
1076
+ // 2. Switch on request’s redirect mode:
1077
+ if (request.redirect === 'error') {
1078
+ // Set response to a network error.
1079
+ response = makeNetworkError('unexpected redirect')
1080
+ } else if (request.redirect === 'manual') {
1081
+ // Set response to an opaque-redirect filtered response whose internal
1082
+ // response is actualResponse.
1083
+ // NOTE(spec): On the web this would return an `opaqueredirect` response,
1084
+ // but that doesn't make sense server side.
1085
+ // See https://github.com/nodejs/undici/issues/1193.
1086
+ response = actualResponse
1087
+ } else if (request.redirect === 'follow') {
1088
+ // Set response to the result of running HTTP-redirect fetch given
1089
+ // fetchParams and response.
1090
+ response = await httpRedirectFetch(fetchParams, response)
1091
+ } else {
1092
+ assert(false)
1093
+ }
1094
+ }
1095
+
1096
+ // 9. Set response’s timing info to timingInfo.
1097
+ response.timingInfo = timingInfo
1098
+
1099
+ // 10. Return response.
1100
+ return response
1101
+ }
1102
+
1103
+ // https://fetch.spec.whatwg.org/#http-redirect-fetch
1104
+ function httpRedirectFetch (fetchParams, response) {
1105
+ // 1. Let request be fetchParams’s request.
1106
+ const request = fetchParams.request
1107
+
1108
+ // 2. Let actualResponse be response, if response is not a filtered response,
1109
+ // and response’s internal response otherwise.
1110
+ const actualResponse = response.internalResponse
1111
+ ? response.internalResponse
1112
+ : response
1113
+
1114
+ // 3. Let locationURL be actualResponse’s location URL given request’s current
1115
+ // URL’s fragment.
1116
+ let locationURL
1117
+
1118
+ try {
1119
+ locationURL = responseLocationURL(
1120
+ actualResponse,
1121
+ requestCurrentURL(request).hash
1122
+ )
1123
+
1124
+ // 4. If locationURL is null, then return response.
1125
+ if (locationURL == null) {
1126
+ return response
1127
+ }
1128
+ } catch (err) {
1129
+ // 5. If locationURL is failure, then return a network error.
1130
+ return Promise.resolve(makeNetworkError(err))
1131
+ }
1132
+
1133
+ // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
1134
+ // error.
1135
+ if (!urlIsHttpHttpsScheme(locationURL)) {
1136
+ return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
1137
+ }
1138
+
1139
+ // 7. If request’s redirect count is 20, then return a network error.
1140
+ if (request.redirectCount === 20) {
1141
+ return Promise.resolve(makeNetworkError('redirect count exceeded'))
1142
+ }
1143
+
1144
+ // 8. Increase request’s redirect count by 1.
1145
+ request.redirectCount += 1
1146
+
1147
+ // 9. If request’s mode is "cors", locationURL includes credentials, and
1148
+ // request’s origin is not same origin with locationURL’s origin, then return
1149
+ // a network error.
1150
+ if (
1151
+ request.mode === 'cors' &&
1152
+ (locationURL.username || locationURL.password) &&
1153
+ !sameOrigin(request, locationURL)
1154
+ ) {
1155
+ return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
1156
+ }
1157
+
1158
+ // 10. If request’s response tainting is "cors" and locationURL includes
1159
+ // credentials, then return a network error.
1160
+ if (
1161
+ request.responseTainting === 'cors' &&
1162
+ (locationURL.username || locationURL.password)
1163
+ ) {
1164
+ return Promise.resolve(makeNetworkError(
1165
+ 'URL cannot contain credentials for request mode "cors"'
1166
+ ))
1167
+ }
1168
+
1169
+ // 11. If actualResponse’s status is not 303, request’s body is non-null,
1170
+ // and request’s body’s source is null, then return a network error.
1171
+ if (
1172
+ actualResponse.status !== 303 &&
1173
+ request.body != null &&
1174
+ request.body.source == null
1175
+ ) {
1176
+ return Promise.resolve(makeNetworkError())
1177
+ }
1178
+
1179
+ // 12. If one of the following is true
1180
+ // - actualResponse’s status is 301 or 302 and request’s method is `POST`
1181
+ // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
1182
+ if (
1183
+ ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
1184
+ (actualResponse.status === 303 &&
1185
+ !GET_OR_HEAD.includes(request.method))
1186
+ ) {
1187
+ // then:
1188
+ // 1. Set request’s method to `GET` and request’s body to null.
1189
+ request.method = 'GET'
1190
+ request.body = null
1191
+
1192
+ // 2. For each headerName of request-body-header name, delete headerName from
1193
+ // request’s header list.
1194
+ for (const headerName of requestBodyHeader) {
1195
+ request.headersList.delete(headerName)
1196
+ }
1197
+ }
1198
+
1199
+ // 13. If request’s current URL’s origin is not same origin with locationURL’s
1200
+ // origin, then for each headerName of CORS non-wildcard request-header name,
1201
+ // delete headerName from request’s header list.
1202
+ if (!sameOrigin(requestCurrentURL(request), locationURL)) {
1203
+ // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
1204
+ request.headersList.delete('authorization')
1205
+
1206
+ // https://fetch.spec.whatwg.org/#authentication-entries
1207
+ request.headersList.delete('proxy-authorization', true)
1208
+
1209
+ // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
1210
+ request.headersList.delete('cookie')
1211
+ request.headersList.delete('host')
1212
+ }
1213
+
1214
+ // 14. If request’s body is non-null, then set request’s body to the first return
1215
+ // value of safely extracting request’s body’s source.
1216
+ if (request.body != null) {
1217
+ assert(request.body.source != null)
1218
+ request.body = safelyExtractBody(request.body.source)[0]
1219
+ }
1220
+
1221
+ // 15. Let timingInfo be fetchParams’s timing info.
1222
+ const timingInfo = fetchParams.timingInfo
1223
+
1224
+ // 16. Set timingInfo’s redirect end time and post-redirect start time to the
1225
+ // coarsened shared current time given fetchParams’s cross-origin isolated
1226
+ // capability.
1227
+ timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
1228
+ coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
1229
+
1230
+ // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
1231
+ // redirect start time to timingInfo’s start time.
1232
+ if (timingInfo.redirectStartTime === 0) {
1233
+ timingInfo.redirectStartTime = timingInfo.startTime
1234
+ }
1235
+
1236
+ // 18. Append locationURL to request’s URL list.
1237
+ request.urlList.push(locationURL)
1238
+
1239
+ // 19. Invoke set request’s referrer policy on redirect on request and
1240
+ // actualResponse.
1241
+ setRequestReferrerPolicyOnRedirect(request, actualResponse)
1242
+
1243
+ // 20. Return the result of running main fetch given fetchParams and true.
1244
+ return mainFetch(fetchParams, true)
1245
+ }
1246
+
1247
+ // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
1248
+ async function httpNetworkOrCacheFetch (
1249
+ fetchParams,
1250
+ isAuthenticationFetch = false,
1251
+ isNewConnectionFetch = false
1252
+ ) {
1253
+ // 1. Let request be fetchParams’s request.
1254
+ const request = fetchParams.request
1255
+
1256
+ // 2. Let httpFetchParams be null.
1257
+ let httpFetchParams = null
1258
+
1259
+ // 3. Let httpRequest be null.
1260
+ let httpRequest = null
1261
+
1262
+ // 4. Let response be null.
1263
+ let response = null
1264
+
1265
+ // 5. Let storedResponse be null.
1266
+ // TODO: cache
1267
+
1268
+ // 6. Let httpCache be null.
1269
+ const httpCache = null
1270
+
1271
+ // 7. Let the revalidatingFlag be unset.
1272
+ const revalidatingFlag = false
1273
+
1274
+ // 8. Run these steps, but abort when the ongoing fetch is terminated:
1275
+
1276
+ // 1. If request’s window is "no-window" and request’s redirect mode is
1277
+ // "error", then set httpFetchParams to fetchParams and httpRequest to
1278
+ // request.
1279
+ if (request.window === 'no-window' && request.redirect === 'error') {
1280
+ httpFetchParams = fetchParams
1281
+ httpRequest = request
1282
+ } else {
1283
+ // Otherwise:
1284
+
1285
+ // 1. Set httpRequest to a clone of request.
1286
+ httpRequest = makeRequest(request)
1287
+
1288
+ // 2. Set httpFetchParams to a copy of fetchParams.
1289
+ httpFetchParams = { ...fetchParams }
1290
+
1291
+ // 3. Set httpFetchParams’s request to httpRequest.
1292
+ httpFetchParams.request = httpRequest
1293
+ }
1294
+
1295
+ // 3. Let includeCredentials be true if one of
1296
+ const includeCredentials =
1297
+ request.credentials === 'include' ||
1298
+ (request.credentials === 'same-origin' &&
1299
+ request.responseTainting === 'basic')
1300
+
1301
+ // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
1302
+ // body is non-null; otherwise null.
1303
+ const contentLength = httpRequest.body ? httpRequest.body.length : null
1304
+
1305
+ // 5. Let contentLengthHeaderValue be null.
1306
+ let contentLengthHeaderValue = null
1307
+
1308
+ // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
1309
+ // `PUT`, then set contentLengthHeaderValue to `0`.
1310
+ if (
1311
+ httpRequest.body == null &&
1312
+ ['POST', 'PUT'].includes(httpRequest.method)
1313
+ ) {
1314
+ contentLengthHeaderValue = '0'
1315
+ }
1316
+
1317
+ // 7. If contentLength is non-null, then set contentLengthHeaderValue to
1318
+ // contentLength, serialized and isomorphic encoded.
1319
+ if (contentLength != null) {
1320
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
1321
+ }
1322
+
1323
+ // 8. If contentLengthHeaderValue is non-null, then append
1324
+ // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
1325
+ // list.
1326
+ if (contentLengthHeaderValue != null) {
1327
+ httpRequest.headersList.append('content-length', contentLengthHeaderValue)
1328
+ }
1329
+
1330
+ // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
1331
+ // contentLengthHeaderValue) to httpRequest’s header list.
1332
+
1333
+ // 10. If contentLength is non-null and httpRequest’s keepalive is true,
1334
+ // then:
1335
+ if (contentLength != null && httpRequest.keepalive) {
1336
+ // NOTE: keepalive is a noop outside of browser context.
1337
+ }
1338
+
1339
+ // 11. If httpRequest’s referrer is a URL, then append
1340
+ // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
1341
+ // to httpRequest’s header list.
1342
+ if (httpRequest.referrer instanceof URL) {
1343
+ httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
1344
+ }
1345
+
1346
+ // 12. Append a request `Origin` header for httpRequest.
1347
+ appendRequestOriginHeader(httpRequest)
1348
+
1349
+ // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
1350
+ appendFetchMetadata(httpRequest)
1351
+
1352
+ // 14. If httpRequest’s header list does not contain `User-Agent`, then
1353
+ // user agents should append `User-Agent`/default `User-Agent` value to
1354
+ // httpRequest’s header list.
1355
+ if (!httpRequest.headersList.contains('user-agent')) {
1356
+ httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
1357
+ }
1358
+
1359
+ // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
1360
+ // list contains `If-Modified-Since`, `If-None-Match`,
1361
+ // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
1362
+ // httpRequest’s cache mode to "no-store".
1363
+ if (
1364
+ httpRequest.cache === 'default' &&
1365
+ (httpRequest.headersList.contains('if-modified-since') ||
1366
+ httpRequest.headersList.contains('if-none-match') ||
1367
+ httpRequest.headersList.contains('if-unmodified-since') ||
1368
+ httpRequest.headersList.contains('if-match') ||
1369
+ httpRequest.headersList.contains('if-range'))
1370
+ ) {
1371
+ httpRequest.cache = 'no-store'
1372
+ }
1373
+
1374
+ // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
1375
+ // no-cache cache-control header modification flag is unset, and
1376
+ // httpRequest’s header list does not contain `Cache-Control`, then append
1377
+ // `Cache-Control`/`max-age=0` to httpRequest’s header list.
1378
+ if (
1379
+ httpRequest.cache === 'no-cache' &&
1380
+ !httpRequest.preventNoCacheCacheControlHeaderModification &&
1381
+ !httpRequest.headersList.contains('cache-control')
1382
+ ) {
1383
+ httpRequest.headersList.append('cache-control', 'max-age=0')
1384
+ }
1385
+
1386
+ // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
1387
+ if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
1388
+ // 1. If httpRequest’s header list does not contain `Pragma`, then append
1389
+ // `Pragma`/`no-cache` to httpRequest’s header list.
1390
+ if (!httpRequest.headersList.contains('pragma')) {
1391
+ httpRequest.headersList.append('pragma', 'no-cache')
1392
+ }
1393
+
1394
+ // 2. If httpRequest’s header list does not contain `Cache-Control`,
1395
+ // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
1396
+ if (!httpRequest.headersList.contains('cache-control')) {
1397
+ httpRequest.headersList.append('cache-control', 'no-cache')
1398
+ }
1399
+ }
1400
+
1401
+ // 18. If httpRequest’s header list contains `Range`, then append
1402
+ // `Accept-Encoding`/`identity` to httpRequest’s header list.
1403
+ if (httpRequest.headersList.contains('range')) {
1404
+ httpRequest.headersList.append('accept-encoding', 'identity')
1405
+ }
1406
+
1407
+ // 19. Modify httpRequest’s header list per HTTP. Do not append a given
1408
+ // header if httpRequest’s header list contains that header’s name.
1409
+ // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
1410
+ if (!httpRequest.headersList.contains('accept-encoding')) {
1411
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
1412
+ httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
1413
+ } else {
1414
+ httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
1415
+ }
1416
+ }
1417
+
1418
+ httpRequest.headersList.delete('host')
1419
+
1420
+ // 20. If includeCredentials is true, then:
1421
+ if (includeCredentials) {
1422
+ // 1. If the user agent is not configured to block cookies for httpRequest
1423
+ // (see section 7 of [COOKIES]), then:
1424
+ // TODO: credentials
1425
+ // 2. If httpRequest’s header list does not contain `Authorization`, then:
1426
+ // TODO: credentials
1427
+ }
1428
+
1429
+ // 21. If there’s a proxy-authentication entry, use it as appropriate.
1430
+ // TODO: proxy-authentication
1431
+
1432
+ // 22. Set httpCache to the result of determining the HTTP cache
1433
+ // partition, given httpRequest.
1434
+ // TODO: cache
1435
+
1436
+ // 23. If httpCache is null, then set httpRequest’s cache mode to
1437
+ // "no-store".
1438
+ if (httpCache == null) {
1439
+ httpRequest.cache = 'no-store'
1440
+ }
1441
+
1442
+ // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
1443
+ // then:
1444
+ if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
1445
+ // TODO: cache
1446
+ }
1447
+
1448
+ // 9. If aborted, then return the appropriate network error for fetchParams.
1449
+ // TODO
1450
+
1451
+ // 10. If response is null, then:
1452
+ if (response == null) {
1453
+ // 1. If httpRequest’s cache mode is "only-if-cached", then return a
1454
+ // network error.
1455
+ if (httpRequest.mode === 'only-if-cached') {
1456
+ return makeNetworkError('only if cached')
1457
+ }
1458
+
1459
+ // 2. Let forwardResponse be the result of running HTTP-network fetch
1460
+ // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
1461
+ const forwardResponse = await httpNetworkFetch(
1462
+ httpFetchParams,
1463
+ includeCredentials,
1464
+ isNewConnectionFetch
1465
+ )
1466
+
1467
+ // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
1468
+ // in the range 200 to 399, inclusive, invalidate appropriate stored
1469
+ // responses in httpCache, as per the "Invalidation" chapter of HTTP
1470
+ // Caching, and set storedResponse to null. [HTTP-CACHING]
1471
+ if (
1472
+ !safeMethodsSet.has(httpRequest.method) &&
1473
+ forwardResponse.status >= 200 &&
1474
+ forwardResponse.status <= 399
1475
+ ) {
1476
+ // TODO: cache
1477
+ }
1478
+
1479
+ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
1480
+ // then:
1481
+ if (revalidatingFlag && forwardResponse.status === 304) {
1482
+ // TODO: cache
1483
+ }
1484
+
1485
+ // 5. If response is null, then:
1486
+ if (response == null) {
1487
+ // 1. Set response to forwardResponse.
1488
+ response = forwardResponse
1489
+
1490
+ // 2. Store httpRequest and forwardResponse in httpCache, as per the
1491
+ // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
1492
+ // TODO: cache
1493
+ }
1494
+ }
1495
+
1496
+ // 11. Set response’s URL list to a clone of httpRequest’s URL list.
1497
+ response.urlList = [...httpRequest.urlList]
1498
+
1499
+ // 12. If httpRequest’s header list contains `Range`, then set response’s
1500
+ // range-requested flag.
1501
+ if (httpRequest.headersList.contains('range')) {
1502
+ response.rangeRequested = true
1503
+ }
1504
+
1505
+ // 13. Set response’s request-includes-credentials to includeCredentials.
1506
+ response.requestIncludesCredentials = includeCredentials
1507
+
1508
+ // 14. If response’s status is 401, httpRequest’s response tainting is not
1509
+ // "cors", includeCredentials is true, and request’s window is an environment
1510
+ // settings object, then:
1511
+ // TODO
1512
+
1513
+ // 15. If response’s status is 407, then:
1514
+ if (response.status === 407) {
1515
+ // 1. If request’s window is "no-window", then return a network error.
1516
+ if (request.window === 'no-window') {
1517
+ return makeNetworkError()
1518
+ }
1519
+
1520
+ // 2. ???
1521
+
1522
+ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
1523
+ if (isCancelled(fetchParams)) {
1524
+ return makeAppropriateNetworkError(fetchParams)
1525
+ }
1526
+
1527
+ // 4. Prompt the end user as appropriate in request’s window and store
1528
+ // the result as a proxy-authentication entry. [HTTP-AUTH]
1529
+ // TODO: Invoke some kind of callback?
1530
+
1531
+ // 5. Set response to the result of running HTTP-network-or-cache fetch given
1532
+ // fetchParams.
1533
+ // TODO
1534
+ return makeNetworkError('proxy authentication required')
1535
+ }
1536
+
1537
+ // 16. If all of the following are true
1538
+ if (
1539
+ // response’s status is 421
1540
+ response.status === 421 &&
1541
+ // isNewConnectionFetch is false
1542
+ !isNewConnectionFetch &&
1543
+ // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
1544
+ (request.body == null || request.body.source != null)
1545
+ ) {
1546
+ // then:
1547
+
1548
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
1549
+ if (isCancelled(fetchParams)) {
1550
+ return makeAppropriateNetworkError(fetchParams)
1551
+ }
1552
+
1553
+ // 2. Set response to the result of running HTTP-network-or-cache
1554
+ // fetch given fetchParams, isAuthenticationFetch, and true.
1555
+
1556
+ // TODO (spec): The spec doesn't specify this but we need to cancel
1557
+ // the active response before we can start a new one.
1558
+ // https://github.com/whatwg/fetch/issues/1293
1559
+ fetchParams.controller.connection.destroy()
1560
+
1561
+ response = await httpNetworkOrCacheFetch(
1562
+ fetchParams,
1563
+ isAuthenticationFetch,
1564
+ true
1565
+ )
1566
+ }
1567
+
1568
+ // 17. If isAuthenticationFetch is true, then create an authentication entry
1569
+ if (isAuthenticationFetch) {
1570
+ // TODO
1571
+ }
1572
+
1573
+ // 18. Return response.
1574
+ return response
1575
+ }
1576
+
1577
+ // https://fetch.spec.whatwg.org/#http-network-fetch
1578
+ async function httpNetworkFetch (
1579
+ fetchParams,
1580
+ includeCredentials = false,
1581
+ forceNewConnection = false
1582
+ ) {
1583
+ assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
1584
+
1585
+ fetchParams.controller.connection = {
1586
+ abort: null,
1587
+ destroyed: false,
1588
+ destroy (err) {
1589
+ if (!this.destroyed) {
1590
+ this.destroyed = true
1591
+ this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
1592
+ }
1593
+ }
1594
+ }
1595
+
1596
+ // 1. Let request be fetchParams’s request.
1597
+ const request = fetchParams.request
1598
+
1599
+ // 2. Let response be null.
1600
+ let response = null
1601
+
1602
+ // 3. Let timingInfo be fetchParams’s timing info.
1603
+ const timingInfo = fetchParams.timingInfo
1604
+
1605
+ // 4. Let httpCache be the result of determining the HTTP cache partition,
1606
+ // given request.
1607
+ // TODO: cache
1608
+ const httpCache = null
1609
+
1610
+ // 5. If httpCache is null, then set request’s cache mode to "no-store".
1611
+ if (httpCache == null) {
1612
+ request.cache = 'no-store'
1613
+ }
1614
+
1615
+ // 6. Let networkPartitionKey be the result of determining the network
1616
+ // partition key given request.
1617
+ // TODO
1618
+
1619
+ // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
1620
+ // "no".
1621
+ const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
1622
+
1623
+ // 8. Switch on request’s mode:
1624
+ if (request.mode === 'websocket') {
1625
+ // Let connection be the result of obtaining a WebSocket connection,
1626
+ // given request’s current URL.
1627
+ // TODO
1628
+ } else {
1629
+ // Let connection be the result of obtaining a connection, given
1630
+ // networkPartitionKey, request’s current URL’s origin,
1631
+ // includeCredentials, and forceNewConnection.
1632
+ // TODO
1633
+ }
1634
+
1635
+ // 9. Run these steps, but abort when the ongoing fetch is terminated:
1636
+
1637
+ // 1. If connection is failure, then return a network error.
1638
+
1639
+ // 2. Set timingInfo’s final connection timing info to the result of
1640
+ // calling clamp and coarsen connection timing info with connection’s
1641
+ // timing info, timingInfo’s post-redirect start time, and fetchParams’s
1642
+ // cross-origin isolated capability.
1643
+
1644
+ // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
1645
+ // and request’s body’s source is null, then append (`Transfer-Encoding`,
1646
+ // `chunked`) to request’s header list.
1647
+
1648
+ // 4. Set timingInfo’s final network-request start time to the coarsened
1649
+ // shared current time given fetchParams’s cross-origin isolated
1650
+ // capability.
1651
+
1652
+ // 5. Set response to the result of making an HTTP request over connection
1653
+ // using request with the following caveats:
1654
+
1655
+ // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
1656
+ // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
1657
+
1658
+ // - If request’s body is non-null, and request’s body’s source is null,
1659
+ // then the user agent may have a buffer of up to 64 kibibytes and store
1660
+ // a part of request’s body in that buffer. If the user agent reads from
1661
+ // request’s body beyond that buffer’s size and the user agent needs to
1662
+ // resend request, then instead return a network error.
1663
+
1664
+ // - Set timingInfo’s final network-response start time to the coarsened
1665
+ // shared current time given fetchParams’s cross-origin isolated capability,
1666
+ // immediately after the user agent’s HTTP parser receives the first byte
1667
+ // of the response (e.g., frame header bytes for HTTP/2 or response status
1668
+ // line for HTTP/1.x).
1669
+
1670
+ // - Wait until all the headers are transmitted.
1671
+
1672
+ // - Any responses whose status is in the range 100 to 199, inclusive,
1673
+ // and is not 101, are to be ignored, except for the purposes of setting
1674
+ // timingInfo’s final network-response start time above.
1675
+
1676
+ // - If request’s header list contains `Transfer-Encoding`/`chunked` and
1677
+ // response is transferred via HTTP/1.0 or older, then return a network
1678
+ // error.
1679
+
1680
+ // - If the HTTP request results in a TLS client certificate dialog, then:
1681
+
1682
+ // 1. If request’s window is an environment settings object, make the
1683
+ // dialog available in request’s window.
1684
+
1685
+ // 2. Otherwise, return a network error.
1686
+
1687
+ // To transmit request’s body body, run these steps:
1688
+ let requestBody = null
1689
+ // 1. If body is null and fetchParams’s process request end-of-body is
1690
+ // non-null, then queue a fetch task given fetchParams’s process request
1691
+ // end-of-body and fetchParams’s task destination.
1692
+ if (request.body == null && fetchParams.processRequestEndOfBody) {
1693
+ queueMicrotask(() => fetchParams.processRequestEndOfBody())
1694
+ } else if (request.body != null) {
1695
+ // 2. Otherwise, if body is non-null:
1696
+
1697
+ // 1. Let processBodyChunk given bytes be these steps:
1698
+ const processBodyChunk = async function * (bytes) {
1699
+ // 1. If the ongoing fetch is terminated, then abort these steps.
1700
+ if (isCancelled(fetchParams)) {
1701
+ return
1702
+ }
1703
+
1704
+ // 2. Run this step in parallel: transmit bytes.
1705
+ yield bytes
1706
+
1707
+ // 3. If fetchParams’s process request body is non-null, then run
1708
+ // fetchParams’s process request body given bytes’s length.
1709
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
1710
+ }
1711
+
1712
+ // 2. Let processEndOfBody be these steps:
1713
+ const processEndOfBody = () => {
1714
+ // 1. If fetchParams is canceled, then abort these steps.
1715
+ if (isCancelled(fetchParams)) {
1716
+ return
1717
+ }
1718
+
1719
+ // 2. If fetchParams’s process request end-of-body is non-null,
1720
+ // then run fetchParams’s process request end-of-body.
1721
+ if (fetchParams.processRequestEndOfBody) {
1722
+ fetchParams.processRequestEndOfBody()
1723
+ }
1724
+ }
1725
+
1726
+ // 3. Let processBodyError given e be these steps:
1727
+ const processBodyError = (e) => {
1728
+ // 1. If fetchParams is canceled, then abort these steps.
1729
+ if (isCancelled(fetchParams)) {
1730
+ return
1731
+ }
1732
+
1733
+ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
1734
+ if (e.name === 'AbortError') {
1735
+ fetchParams.controller.abort()
1736
+ } else {
1737
+ fetchParams.controller.terminate(e)
1738
+ }
1739
+ }
1740
+
1741
+ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
1742
+ // processBodyError, and fetchParams’s task destination.
1743
+ requestBody = (async function * () {
1744
+ try {
1745
+ for await (const bytes of request.body.stream) {
1746
+ yield * processBodyChunk(bytes)
1747
+ }
1748
+ processEndOfBody()
1749
+ } catch (err) {
1750
+ processBodyError(err)
1751
+ }
1752
+ })()
1753
+ }
1754
+
1755
+ try {
1756
+ // socket is only provided for websockets
1757
+ const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
1758
+
1759
+ if (socket) {
1760
+ response = makeResponse({ status, statusText, headersList, socket })
1761
+ } else {
1762
+ const iterator = body[Symbol.asyncIterator]()
1763
+ fetchParams.controller.next = () => iterator.next()
1764
+
1765
+ response = makeResponse({ status, statusText, headersList })
1766
+ }
1767
+ } catch (err) {
1768
+ // 10. If aborted, then:
1769
+ if (err.name === 'AbortError') {
1770
+ // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
1771
+ fetchParams.controller.connection.destroy()
1772
+
1773
+ // 2. Return the appropriate network error for fetchParams.
1774
+ return makeAppropriateNetworkError(fetchParams, err)
1775
+ }
1776
+
1777
+ return makeNetworkError(err)
1778
+ }
1779
+
1780
+ // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
1781
+ // if it is suspended.
1782
+ const pullAlgorithm = () => {
1783
+ fetchParams.controller.resume()
1784
+ }
1785
+
1786
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
1787
+ // controller with reason, given reason.
1788
+ const cancelAlgorithm = (reason) => {
1789
+ fetchParams.controller.abort(reason)
1790
+ }
1791
+
1792
+ // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
1793
+ // the user agent.
1794
+ // TODO
1795
+
1796
+ // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
1797
+ // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
1798
+ // TODO
1799
+
1800
+ // 15. Let stream be a new ReadableStream.
1801
+ // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
1802
+ // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
1803
+ // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
1804
+ if (!ReadableStream) {
1805
+ ReadableStream = require('stream/web').ReadableStream
1806
+ }
1807
+
1808
+ const stream = new ReadableStream(
1809
+ {
1810
+ async start (controller) {
1811
+ fetchParams.controller.controller = controller
1812
+ },
1813
+ async pull (controller) {
1814
+ await pullAlgorithm(controller)
1815
+ },
1816
+ async cancel (reason) {
1817
+ await cancelAlgorithm(reason)
1818
+ }
1819
+ },
1820
+ {
1821
+ highWaterMark: 0,
1822
+ size () {
1823
+ return 1
1824
+ }
1825
+ }
1826
+ )
1827
+
1828
+ // 17. Run these steps, but abort when the ongoing fetch is terminated:
1829
+
1830
+ // 1. Set response’s body to a new body whose stream is stream.
1831
+ response.body = { stream }
1832
+
1833
+ // 2. If response is not a network error and request’s cache mode is
1834
+ // not "no-store", then update response in httpCache for request.
1835
+ // TODO
1836
+
1837
+ // 3. If includeCredentials is true and the user agent is not configured
1838
+ // to block cookies for request (see section 7 of [COOKIES]), then run the
1839
+ // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
1840
+ // the value of each header whose name is a byte-case-insensitive match for
1841
+ // `Set-Cookie` in response’s header list, if any, and request’s current URL.
1842
+ // TODO
1843
+
1844
+ // 18. If aborted, then:
1845
+ // TODO
1846
+
1847
+ // 19. Run these steps in parallel:
1848
+
1849
+ // 1. Run these steps, but abort when fetchParams is canceled:
1850
+ fetchParams.controller.on('terminated', onAborted)
1851
+ fetchParams.controller.resume = async () => {
1852
+ // 1. While true
1853
+ while (true) {
1854
+ // 1-3. See onData...
1855
+
1856
+ // 4. Set bytes to the result of handling content codings given
1857
+ // codings and bytes.
1858
+ let bytes
1859
+ let isFailure
1860
+ try {
1861
+ const { done, value } = await fetchParams.controller.next()
1862
+
1863
+ if (isAborted(fetchParams)) {
1864
+ break
1865
+ }
1866
+
1867
+ bytes = done ? undefined : value
1868
+ } catch (err) {
1869
+ if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
1870
+ // zlib doesn't like empty streams.
1871
+ bytes = undefined
1872
+ } else {
1873
+ bytes = err
1874
+
1875
+ // err may be propagated from the result of calling readablestream.cancel,
1876
+ // which might not be an error. https://github.com/nodejs/undici/issues/2009
1877
+ isFailure = true
1878
+ }
1879
+ }
1880
+
1881
+ if (bytes === undefined) {
1882
+ // 2. Otherwise, if the bytes transmission for response’s message
1883
+ // body is done normally and stream is readable, then close
1884
+ // stream, finalize response for fetchParams and response, and
1885
+ // abort these in-parallel steps.
1886
+ readableStreamClose(fetchParams.controller.controller)
1887
+
1888
+ finalizeResponse(fetchParams, response)
1889
+
1890
+ return
1891
+ }
1892
+
1893
+ // 5. Increase timingInfo’s decoded body size by bytes’s length.
1894
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0
1895
+
1896
+ // 6. If bytes is failure, then terminate fetchParams’s controller.
1897
+ if (isFailure) {
1898
+ fetchParams.controller.terminate(bytes)
1899
+ return
1900
+ }
1901
+
1902
+ // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
1903
+ // into stream.
1904
+ fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
1905
+
1906
+ // 8. If stream is errored, then terminate the ongoing fetch.
1907
+ if (isErrored(stream)) {
1908
+ fetchParams.controller.terminate()
1909
+ return
1910
+ }
1911
+
1912
+ // 9. If stream doesn’t need more data ask the user agent to suspend
1913
+ // the ongoing fetch.
1914
+ if (!fetchParams.controller.controller.desiredSize) {
1915
+ return
1916
+ }
1917
+ }
1918
+ }
1919
+
1920
+ // 2. If aborted, then:
1921
+ function onAborted (reason) {
1922
+ // 2. If fetchParams is aborted, then:
1923
+ if (isAborted(fetchParams)) {
1924
+ // 1. Set response’s aborted flag.
1925
+ response.aborted = true
1926
+
1927
+ // 2. If stream is readable, then error stream with the result of
1928
+ // deserialize a serialized abort reason given fetchParams’s
1929
+ // controller’s serialized abort reason and an
1930
+ // implementation-defined realm.
1931
+ if (isReadable(stream)) {
1932
+ fetchParams.controller.controller.error(
1933
+ fetchParams.controller.serializedAbortReason
1934
+ )
1935
+ }
1936
+ } else {
1937
+ // 3. Otherwise, if stream is readable, error stream with a TypeError.
1938
+ if (isReadable(stream)) {
1939
+ fetchParams.controller.controller.error(new TypeError('terminated', {
1940
+ cause: isErrorLike(reason) ? reason : undefined
1941
+ }))
1942
+ }
1943
+ }
1944
+
1945
+ // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
1946
+ // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
1947
+ fetchParams.controller.connection.destroy()
1948
+ }
1949
+
1950
+ // 20. Return response.
1951
+ return response
1952
+
1953
+ async function dispatch ({ body }) {
1954
+ const url = requestCurrentURL(request)
1955
+ /** @type {import('../..').Agent} */
1956
+ const agent = fetchParams.controller.dispatcher
1957
+
1958
+ return new Promise((resolve, reject) => agent.dispatch(
1959
+ {
1960
+ path: url.pathname + url.search,
1961
+ origin: url.origin,
1962
+ method: request.method,
1963
+ body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
1964
+ headers: request.headersList.entries,
1965
+ maxRedirections: 0,
1966
+ upgrade: request.mode === 'websocket' ? 'websocket' : undefined
1967
+ },
1968
+ {
1969
+ body: null,
1970
+ abort: null,
1971
+
1972
+ onConnect (abort) {
1973
+ // TODO (fix): Do we need connection here?
1974
+ const { connection } = fetchParams.controller
1975
+
1976
+ if (connection.destroyed) {
1977
+ abort(new DOMException('The operation was aborted.', 'AbortError'))
1978
+ } else {
1979
+ fetchParams.controller.on('terminated', abort)
1980
+ this.abort = connection.abort = abort
1981
+ }
1982
+ },
1983
+
1984
+ onHeaders (status, headersList, resume, statusText) {
1985
+ if (status < 200) {
1986
+ return
1987
+ }
1988
+
1989
+ let codings = []
1990
+ let location = ''
1991
+
1992
+ const headers = new Headers()
1993
+
1994
+ // For H2, the headers are a plain JS object
1995
+ // We distinguish between them and iterate accordingly
1996
+ if (Array.isArray(headersList)) {
1997
+ for (let n = 0; n < headersList.length; n += 2) {
1998
+ const key = headersList[n + 0].toString('latin1')
1999
+ const val = headersList[n + 1].toString('latin1')
2000
+ if (key.toLowerCase() === 'content-encoding') {
2001
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
2002
+ // "All content-coding values are case-insensitive..."
2003
+ codings = val.toLowerCase().split(',').map((x) => x.trim())
2004
+ } else if (key.toLowerCase() === 'location') {
2005
+ location = val
2006
+ }
2007
+
2008
+ headers[kHeadersList].append(key, val)
2009
+ }
2010
+ } else {
2011
+ const keys = Object.keys(headersList)
2012
+ for (const key of keys) {
2013
+ const val = headersList[key]
2014
+ if (key.toLowerCase() === 'content-encoding') {
2015
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
2016
+ // "All content-coding values are case-insensitive..."
2017
+ codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
2018
+ } else if (key.toLowerCase() === 'location') {
2019
+ location = val
2020
+ }
2021
+
2022
+ headers[kHeadersList].append(key, val)
2023
+ }
2024
+ }
2025
+
2026
+ this.body = new Readable({ read: resume })
2027
+
2028
+ const decoders = []
2029
+
2030
+ const willFollow = request.redirect === 'follow' &&
2031
+ location &&
2032
+ redirectStatusSet.has(status)
2033
+
2034
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
2035
+ if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
2036
+ for (const coding of codings) {
2037
+ // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
2038
+ if (coding === 'x-gzip' || coding === 'gzip') {
2039
+ decoders.push(zlib.createGunzip({
2040
+ // Be less strict when decoding compressed responses, since sometimes
2041
+ // servers send slightly invalid responses that are still accepted
2042
+ // by common browsers.
2043
+ // Always using Z_SYNC_FLUSH is what cURL does.
2044
+ flush: zlib.constants.Z_SYNC_FLUSH,
2045
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
2046
+ }))
2047
+ } else if (coding === 'deflate') {
2048
+ decoders.push(zlib.createInflate())
2049
+ } else if (coding === 'br') {
2050
+ decoders.push(zlib.createBrotliDecompress())
2051
+ } else {
2052
+ decoders.length = 0
2053
+ break
2054
+ }
2055
+ }
2056
+ }
2057
+
2058
+ resolve({
2059
+ status,
2060
+ statusText,
2061
+ headersList: headers[kHeadersList],
2062
+ body: decoders.length
2063
+ ? pipeline(this.body, ...decoders, () => { })
2064
+ : this.body.on('error', () => {})
2065
+ })
2066
+
2067
+ return true
2068
+ },
2069
+
2070
+ onData (chunk) {
2071
+ if (fetchParams.controller.dump) {
2072
+ return
2073
+ }
2074
+
2075
+ // 1. If one or more bytes have been transmitted from response’s
2076
+ // message body, then:
2077
+
2078
+ // 1. Let bytes be the transmitted bytes.
2079
+ const bytes = chunk
2080
+
2081
+ // 2. Let codings be the result of extracting header list values
2082
+ // given `Content-Encoding` and response’s header list.
2083
+ // See pullAlgorithm.
2084
+
2085
+ // 3. Increase timingInfo’s encoded body size by bytes’s length.
2086
+ timingInfo.encodedBodySize += bytes.byteLength
2087
+
2088
+ // 4. See pullAlgorithm...
2089
+
2090
+ return this.body.push(bytes)
2091
+ },
2092
+
2093
+ onComplete () {
2094
+ if (this.abort) {
2095
+ fetchParams.controller.off('terminated', this.abort)
2096
+ }
2097
+
2098
+ fetchParams.controller.ended = true
2099
+
2100
+ this.body.push(null)
2101
+ },
2102
+
2103
+ onError (error) {
2104
+ if (this.abort) {
2105
+ fetchParams.controller.off('terminated', this.abort)
2106
+ }
2107
+
2108
+ this.body?.destroy(error)
2109
+
2110
+ fetchParams.controller.terminate(error)
2111
+
2112
+ reject(error)
2113
+ },
2114
+
2115
+ onUpgrade (status, headersList, socket) {
2116
+ if (status !== 101) {
2117
+ return
2118
+ }
2119
+
2120
+ const headers = new Headers()
2121
+
2122
+ for (let n = 0; n < headersList.length; n += 2) {
2123
+ const key = headersList[n + 0].toString('latin1')
2124
+ const val = headersList[n + 1].toString('latin1')
2125
+
2126
+ headers[kHeadersList].append(key, val)
2127
+ }
2128
+
2129
+ resolve({
2130
+ status,
2131
+ statusText: STATUS_CODES[status],
2132
+ headersList: headers[kHeadersList],
2133
+ socket
2134
+ })
2135
+
2136
+ return true
2137
+ }
2138
+ }
2139
+ ))
2140
+ }
2141
+ }
2142
+
2143
+ module.exports = {
2144
+ fetch,
2145
+ Fetch,
2146
+ fetching,
2147
+ finalizeAndReportTiming
2148
+ }
worker/node_modules/undici/lib/fetch/request.js ADDED
@@ -0,0 +1,946 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* globals AbortController */
2
+
3
+ 'use strict'
4
+
5
+ const { extractBody, mixinBody, cloneBody } = require('./body')
6
+ const { Headers, fill: fillHeaders, HeadersList } = require('./headers')
7
+ const { FinalizationRegistry } = require('../compat/dispatcher-weakref')()
8
+ const util = require('../core/util')
9
+ const {
10
+ isValidHTTPToken,
11
+ sameOrigin,
12
+ normalizeMethod,
13
+ makePolicyContainer,
14
+ normalizeMethodRecord
15
+ } = require('./util')
16
+ const {
17
+ forbiddenMethodsSet,
18
+ corsSafeListedMethodsSet,
19
+ referrerPolicy,
20
+ requestRedirect,
21
+ requestMode,
22
+ requestCredentials,
23
+ requestCache,
24
+ requestDuplex
25
+ } = require('./constants')
26
+ const { kEnumerableProperty } = util
27
+ const { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols')
28
+ const { webidl } = require('./webidl')
29
+ const { getGlobalOrigin } = require('./global')
30
+ const { URLSerializer } = require('./dataURL')
31
+ const { kHeadersList, kConstruct } = require('../core/symbols')
32
+ const assert = require('assert')
33
+ const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('events')
34
+
35
+ let TransformStream = globalThis.TransformStream
36
+
37
+ const kAbortController = Symbol('abortController')
38
+
39
+ const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
40
+ signal.removeEventListener('abort', abort)
41
+ })
42
+
43
+ // https://fetch.spec.whatwg.org/#request-class
44
+ class Request {
45
+ // https://fetch.spec.whatwg.org/#dom-request
46
+ constructor (input, init = {}) {
47
+ if (input === kConstruct) {
48
+ return
49
+ }
50
+
51
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
52
+
53
+ input = webidl.converters.RequestInfo(input)
54
+ init = webidl.converters.RequestInit(init)
55
+
56
+ // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
57
+ this[kRealm] = {
58
+ settingsObject: {
59
+ baseUrl: getGlobalOrigin(),
60
+ get origin () {
61
+ return this.baseUrl?.origin
62
+ },
63
+ policyContainer: makePolicyContainer()
64
+ }
65
+ }
66
+
67
+ // 1. Let request be null.
68
+ let request = null
69
+
70
+ // 2. Let fallbackMode be null.
71
+ let fallbackMode = null
72
+
73
+ // 3. Let baseURL be this’s relevant settings object’s API base URL.
74
+ const baseUrl = this[kRealm].settingsObject.baseUrl
75
+
76
+ // 4. Let signal be null.
77
+ let signal = null
78
+
79
+ // 5. If input is a string, then:
80
+ if (typeof input === 'string') {
81
+ // 1. Let parsedURL be the result of parsing input with baseURL.
82
+ // 2. If parsedURL is failure, then throw a TypeError.
83
+ let parsedURL
84
+ try {
85
+ parsedURL = new URL(input, baseUrl)
86
+ } catch (err) {
87
+ throw new TypeError('Failed to parse URL from ' + input, { cause: err })
88
+ }
89
+
90
+ // 3. If parsedURL includes credentials, then throw a TypeError.
91
+ if (parsedURL.username || parsedURL.password) {
92
+ throw new TypeError(
93
+ 'Request cannot be constructed from a URL that includes credentials: ' +
94
+ input
95
+ )
96
+ }
97
+
98
+ // 4. Set request to a new request whose URL is parsedURL.
99
+ request = makeRequest({ urlList: [parsedURL] })
100
+
101
+ // 5. Set fallbackMode to "cors".
102
+ fallbackMode = 'cors'
103
+ } else {
104
+ // 6. Otherwise:
105
+
106
+ // 7. Assert: input is a Request object.
107
+ assert(input instanceof Request)
108
+
109
+ // 8. Set request to input’s request.
110
+ request = input[kState]
111
+
112
+ // 9. Set signal to input’s signal.
113
+ signal = input[kSignal]
114
+ }
115
+
116
+ // 7. Let origin be this’s relevant settings object’s origin.
117
+ const origin = this[kRealm].settingsObject.origin
118
+
119
+ // 8. Let window be "client".
120
+ let window = 'client'
121
+
122
+ // 9. If request’s window is an environment settings object and its origin
123
+ // is same origin with origin, then set window to request’s window.
124
+ if (
125
+ request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
126
+ sameOrigin(request.window, origin)
127
+ ) {
128
+ window = request.window
129
+ }
130
+
131
+ // 10. If init["window"] exists and is non-null, then throw a TypeError.
132
+ if (init.window != null) {
133
+ throw new TypeError(`'window' option '${window}' must be null`)
134
+ }
135
+
136
+ // 11. If init["window"] exists, then set window to "no-window".
137
+ if ('window' in init) {
138
+ window = 'no-window'
139
+ }
140
+
141
+ // 12. Set request to a new request with the following properties:
142
+ request = makeRequest({
143
+ // URL request’s URL.
144
+ // undici implementation note: this is set as the first item in request's urlList in makeRequest
145
+ // method request’s method.
146
+ method: request.method,
147
+ // header list A copy of request’s header list.
148
+ // undici implementation note: headersList is cloned in makeRequest
149
+ headersList: request.headersList,
150
+ // unsafe-request flag Set.
151
+ unsafeRequest: request.unsafeRequest,
152
+ // client This’s relevant settings object.
153
+ client: this[kRealm].settingsObject,
154
+ // window window.
155
+ window,
156
+ // priority request’s priority.
157
+ priority: request.priority,
158
+ // origin request’s origin. The propagation of the origin is only significant for navigation requests
159
+ // being handled by a service worker. In this scenario a request can have an origin that is different
160
+ // from the current client.
161
+ origin: request.origin,
162
+ // referrer request’s referrer.
163
+ referrer: request.referrer,
164
+ // referrer policy request’s referrer policy.
165
+ referrerPolicy: request.referrerPolicy,
166
+ // mode request’s mode.
167
+ mode: request.mode,
168
+ // credentials mode request’s credentials mode.
169
+ credentials: request.credentials,
170
+ // cache mode request’s cache mode.
171
+ cache: request.cache,
172
+ // redirect mode request’s redirect mode.
173
+ redirect: request.redirect,
174
+ // integrity metadata request’s integrity metadata.
175
+ integrity: request.integrity,
176
+ // keepalive request’s keepalive.
177
+ keepalive: request.keepalive,
178
+ // reload-navigation flag request’s reload-navigation flag.
179
+ reloadNavigation: request.reloadNavigation,
180
+ // history-navigation flag request’s history-navigation flag.
181
+ historyNavigation: request.historyNavigation,
182
+ // URL list A clone of request’s URL list.
183
+ urlList: [...request.urlList]
184
+ })
185
+
186
+ const initHasKey = Object.keys(init).length !== 0
187
+
188
+ // 13. If init is not empty, then:
189
+ if (initHasKey) {
190
+ // 1. If request’s mode is "navigate", then set it to "same-origin".
191
+ if (request.mode === 'navigate') {
192
+ request.mode = 'same-origin'
193
+ }
194
+
195
+ // 2. Unset request’s reload-navigation flag.
196
+ request.reloadNavigation = false
197
+
198
+ // 3. Unset request’s history-navigation flag.
199
+ request.historyNavigation = false
200
+
201
+ // 4. Set request’s origin to "client".
202
+ request.origin = 'client'
203
+
204
+ // 5. Set request’s referrer to "client"
205
+ request.referrer = 'client'
206
+
207
+ // 6. Set request’s referrer policy to the empty string.
208
+ request.referrerPolicy = ''
209
+
210
+ // 7. Set request’s URL to request’s current URL.
211
+ request.url = request.urlList[request.urlList.length - 1]
212
+
213
+ // 8. Set request’s URL list to « request’s URL ».
214
+ request.urlList = [request.url]
215
+ }
216
+
217
+ // 14. If init["referrer"] exists, then:
218
+ if (init.referrer !== undefined) {
219
+ // 1. Let referrer be init["referrer"].
220
+ const referrer = init.referrer
221
+
222
+ // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
223
+ if (referrer === '') {
224
+ request.referrer = 'no-referrer'
225
+ } else {
226
+ // 1. Let parsedReferrer be the result of parsing referrer with
227
+ // baseURL.
228
+ // 2. If parsedReferrer is failure, then throw a TypeError.
229
+ let parsedReferrer
230
+ try {
231
+ parsedReferrer = new URL(referrer, baseUrl)
232
+ } catch (err) {
233
+ throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
234
+ }
235
+
236
+ // 3. If one of the following is true
237
+ // - parsedReferrer’s scheme is "about" and path is the string "client"
238
+ // - parsedReferrer’s origin is not same origin with origin
239
+ // then set request’s referrer to "client".
240
+ if (
241
+ (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
242
+ (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
243
+ ) {
244
+ request.referrer = 'client'
245
+ } else {
246
+ // 4. Otherwise, set request’s referrer to parsedReferrer.
247
+ request.referrer = parsedReferrer
248
+ }
249
+ }
250
+ }
251
+
252
+ // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
253
+ // to it.
254
+ if (init.referrerPolicy !== undefined) {
255
+ request.referrerPolicy = init.referrerPolicy
256
+ }
257
+
258
+ // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
259
+ let mode
260
+ if (init.mode !== undefined) {
261
+ mode = init.mode
262
+ } else {
263
+ mode = fallbackMode
264
+ }
265
+
266
+ // 17. If mode is "navigate", then throw a TypeError.
267
+ if (mode === 'navigate') {
268
+ throw webidl.errors.exception({
269
+ header: 'Request constructor',
270
+ message: 'invalid request mode navigate.'
271
+ })
272
+ }
273
+
274
+ // 18. If mode is non-null, set request’s mode to mode.
275
+ if (mode != null) {
276
+ request.mode = mode
277
+ }
278
+
279
+ // 19. If init["credentials"] exists, then set request’s credentials mode
280
+ // to it.
281
+ if (init.credentials !== undefined) {
282
+ request.credentials = init.credentials
283
+ }
284
+
285
+ // 18. If init["cache"] exists, then set request’s cache mode to it.
286
+ if (init.cache !== undefined) {
287
+ request.cache = init.cache
288
+ }
289
+
290
+ // 21. If request’s cache mode is "only-if-cached" and request’s mode is
291
+ // not "same-origin", then throw a TypeError.
292
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
293
+ throw new TypeError(
294
+ "'only-if-cached' can be set only with 'same-origin' mode"
295
+ )
296
+ }
297
+
298
+ // 22. If init["redirect"] exists, then set request’s redirect mode to it.
299
+ if (init.redirect !== undefined) {
300
+ request.redirect = init.redirect
301
+ }
302
+
303
+ // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
304
+ if (init.integrity != null) {
305
+ request.integrity = String(init.integrity)
306
+ }
307
+
308
+ // 24. If init["keepalive"] exists, then set request’s keepalive to it.
309
+ if (init.keepalive !== undefined) {
310
+ request.keepalive = Boolean(init.keepalive)
311
+ }
312
+
313
+ // 25. If init["method"] exists, then:
314
+ if (init.method !== undefined) {
315
+ // 1. Let method be init["method"].
316
+ let method = init.method
317
+
318
+ // 2. If method is not a method or method is a forbidden method, then
319
+ // throw a TypeError.
320
+ if (!isValidHTTPToken(method)) {
321
+ throw new TypeError(`'${method}' is not a valid HTTP method.`)
322
+ }
323
+
324
+ if (forbiddenMethodsSet.has(method.toUpperCase())) {
325
+ throw new TypeError(`'${method}' HTTP method is unsupported.`)
326
+ }
327
+
328
+ // 3. Normalize method.
329
+ method = normalizeMethodRecord[method] ?? normalizeMethod(method)
330
+
331
+ // 4. Set request’s method to method.
332
+ request.method = method
333
+ }
334
+
335
+ // 26. If init["signal"] exists, then set signal to it.
336
+ if (init.signal !== undefined) {
337
+ signal = init.signal
338
+ }
339
+
340
+ // 27. Set this’s request to request.
341
+ this[kState] = request
342
+
343
+ // 28. Set this’s signal to a new AbortSignal object with this’s relevant
344
+ // Realm.
345
+ // TODO: could this be simplified with AbortSignal.any
346
+ // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
347
+ const ac = new AbortController()
348
+ this[kSignal] = ac.signal
349
+ this[kSignal][kRealm] = this[kRealm]
350
+
351
+ // 29. If signal is not null, then make this’s signal follow signal.
352
+ if (signal != null) {
353
+ if (
354
+ !signal ||
355
+ typeof signal.aborted !== 'boolean' ||
356
+ typeof signal.addEventListener !== 'function'
357
+ ) {
358
+ throw new TypeError(
359
+ "Failed to construct 'Request': member signal is not of type AbortSignal."
360
+ )
361
+ }
362
+
363
+ if (signal.aborted) {
364
+ ac.abort(signal.reason)
365
+ } else {
366
+ // Keep a strong ref to ac while request object
367
+ // is alive. This is needed to prevent AbortController
368
+ // from being prematurely garbage collected.
369
+ // See, https://github.com/nodejs/undici/issues/1926.
370
+ this[kAbortController] = ac
371
+
372
+ const acRef = new WeakRef(ac)
373
+ const abort = function () {
374
+ const ac = acRef.deref()
375
+ if (ac !== undefined) {
376
+ ac.abort(this.reason)
377
+ }
378
+ }
379
+
380
+ // Third-party AbortControllers may not work with these.
381
+ // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
382
+ try {
383
+ // If the max amount of listeners is equal to the default, increase it
384
+ // This is only available in node >= v19.9.0
385
+ if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
386
+ setMaxListeners(100, signal)
387
+ } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
388
+ setMaxListeners(100, signal)
389
+ }
390
+ } catch {}
391
+
392
+ util.addAbortListener(signal, abort)
393
+ requestFinalizer.register(ac, { signal, abort })
394
+ }
395
+ }
396
+
397
+ // 30. Set this’s headers to a new Headers object with this’s relevant
398
+ // Realm, whose header list is request’s header list and guard is
399
+ // "request".
400
+ this[kHeaders] = new Headers(kConstruct)
401
+ this[kHeaders][kHeadersList] = request.headersList
402
+ this[kHeaders][kGuard] = 'request'
403
+ this[kHeaders][kRealm] = this[kRealm]
404
+
405
+ // 31. If this’s request’s mode is "no-cors", then:
406
+ if (mode === 'no-cors') {
407
+ // 1. If this’s request’s method is not a CORS-safelisted method,
408
+ // then throw a TypeError.
409
+ if (!corsSafeListedMethodsSet.has(request.method)) {
410
+ throw new TypeError(
411
+ `'${request.method} is unsupported in no-cors mode.`
412
+ )
413
+ }
414
+
415
+ // 2. Set this’s headers’s guard to "request-no-cors".
416
+ this[kHeaders][kGuard] = 'request-no-cors'
417
+ }
418
+
419
+ // 32. If init is not empty, then:
420
+ if (initHasKey) {
421
+ /** @type {HeadersList} */
422
+ const headersList = this[kHeaders][kHeadersList]
423
+ // 1. Let headers be a copy of this’s headers and its associated header
424
+ // list.
425
+ // 2. If init["headers"] exists, then set headers to init["headers"].
426
+ const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
427
+
428
+ // 3. Empty this’s headers’s header list.
429
+ headersList.clear()
430
+
431
+ // 4. If headers is a Headers object, then for each header in its header
432
+ // list, append header’s name/header’s value to this’s headers.
433
+ if (headers instanceof HeadersList) {
434
+ for (const [key, val] of headers) {
435
+ headersList.append(key, val)
436
+ }
437
+ // Note: Copy the `set-cookie` meta-data.
438
+ headersList.cookies = headers.cookies
439
+ } else {
440
+ // 5. Otherwise, fill this’s headers with headers.
441
+ fillHeaders(this[kHeaders], headers)
442
+ }
443
+ }
444
+
445
+ // 33. Let inputBody be input’s request’s body if input is a Request
446
+ // object; otherwise null.
447
+ const inputBody = input instanceof Request ? input[kState].body : null
448
+
449
+ // 34. If either init["body"] exists and is non-null or inputBody is
450
+ // non-null, and request’s method is `GET` or `HEAD`, then throw a
451
+ // TypeError.
452
+ if (
453
+ (init.body != null || inputBody != null) &&
454
+ (request.method === 'GET' || request.method === 'HEAD')
455
+ ) {
456
+ throw new TypeError('Request with GET/HEAD method cannot have body.')
457
+ }
458
+
459
+ // 35. Let initBody be null.
460
+ let initBody = null
461
+
462
+ // 36. If init["body"] exists and is non-null, then:
463
+ if (init.body != null) {
464
+ // 1. Let Content-Type be null.
465
+ // 2. Set initBody and Content-Type to the result of extracting
466
+ // init["body"], with keepalive set to request’s keepalive.
467
+ const [extractedBody, contentType] = extractBody(
468
+ init.body,
469
+ request.keepalive
470
+ )
471
+ initBody = extractedBody
472
+
473
+ // 3, If Content-Type is non-null and this’s headers’s header list does
474
+ // not contain `Content-Type`, then append `Content-Type`/Content-Type to
475
+ // this’s headers.
476
+ if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
477
+ this[kHeaders].append('content-type', contentType)
478
+ }
479
+ }
480
+
481
+ // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
482
+ // inputBody.
483
+ const inputOrInitBody = initBody ?? inputBody
484
+
485
+ // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
486
+ // null, then:
487
+ if (inputOrInitBody != null && inputOrInitBody.source == null) {
488
+ // 1. If initBody is non-null and init["duplex"] does not exist,
489
+ // then throw a TypeError.
490
+ if (initBody != null && init.duplex == null) {
491
+ throw new TypeError('RequestInit: duplex option is required when sending a body.')
492
+ }
493
+
494
+ // 2. If this’s request’s mode is neither "same-origin" nor "cors",
495
+ // then throw a TypeError.
496
+ if (request.mode !== 'same-origin' && request.mode !== 'cors') {
497
+ throw new TypeError(
498
+ 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
499
+ )
500
+ }
501
+
502
+ // 3. Set this’s request’s use-CORS-preflight flag.
503
+ request.useCORSPreflightFlag = true
504
+ }
505
+
506
+ // 39. Let finalBody be inputOrInitBody.
507
+ let finalBody = inputOrInitBody
508
+
509
+ // 40. If initBody is null and inputBody is non-null, then:
510
+ if (initBody == null && inputBody != null) {
511
+ // 1. If input is unusable, then throw a TypeError.
512
+ if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
513
+ throw new TypeError(
514
+ 'Cannot construct a Request with a Request object that has already been used.'
515
+ )
516
+ }
517
+
518
+ // 2. Set finalBody to the result of creating a proxy for inputBody.
519
+ if (!TransformStream) {
520
+ TransformStream = require('stream/web').TransformStream
521
+ }
522
+
523
+ // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
524
+ const identityTransform = new TransformStream()
525
+ inputBody.stream.pipeThrough(identityTransform)
526
+ finalBody = {
527
+ source: inputBody.source,
528
+ length: inputBody.length,
529
+ stream: identityTransform.readable
530
+ }
531
+ }
532
+
533
+ // 41. Set this’s request’s body to finalBody.
534
+ this[kState].body = finalBody
535
+ }
536
+
537
+ // Returns request’s HTTP method, which is "GET" by default.
538
+ get method () {
539
+ webidl.brandCheck(this, Request)
540
+
541
+ // The method getter steps are to return this’s request’s method.
542
+ return this[kState].method
543
+ }
544
+
545
+ // Returns the URL of request as a string.
546
+ get url () {
547
+ webidl.brandCheck(this, Request)
548
+
549
+ // The url getter steps are to return this’s request’s URL, serialized.
550
+ return URLSerializer(this[kState].url)
551
+ }
552
+
553
+ // Returns a Headers object consisting of the headers associated with request.
554
+ // Note that headers added in the network layer by the user agent will not
555
+ // be accounted for in this object, e.g., the "Host" header.
556
+ get headers () {
557
+ webidl.brandCheck(this, Request)
558
+
559
+ // The headers getter steps are to return this’s headers.
560
+ return this[kHeaders]
561
+ }
562
+
563
+ // Returns the kind of resource requested by request, e.g., "document"
564
+ // or "script".
565
+ get destination () {
566
+ webidl.brandCheck(this, Request)
567
+
568
+ // The destination getter are to return this’s request’s destination.
569
+ return this[kState].destination
570
+ }
571
+
572
+ // Returns the referrer of request. Its value can be a same-origin URL if
573
+ // explicitly set in init, the empty string to indicate no referrer, and
574
+ // "about:client" when defaulting to the global’s default. This is used
575
+ // during fetching to determine the value of the `Referer` header of the
576
+ // request being made.
577
+ get referrer () {
578
+ webidl.brandCheck(this, Request)
579
+
580
+ // 1. If this’s request’s referrer is "no-referrer", then return the
581
+ // empty string.
582
+ if (this[kState].referrer === 'no-referrer') {
583
+ return ''
584
+ }
585
+
586
+ // 2. If this’s request’s referrer is "client", then return
587
+ // "about:client".
588
+ if (this[kState].referrer === 'client') {
589
+ return 'about:client'
590
+ }
591
+
592
+ // Return this’s request’s referrer, serialized.
593
+ return this[kState].referrer.toString()
594
+ }
595
+
596
+ // Returns the referrer policy associated with request.
597
+ // This is used during fetching to compute the value of the request’s
598
+ // referrer.
599
+ get referrerPolicy () {
600
+ webidl.brandCheck(this, Request)
601
+
602
+ // The referrerPolicy getter steps are to return this’s request’s referrer policy.
603
+ return this[kState].referrerPolicy
604
+ }
605
+
606
+ // Returns the mode associated with request, which is a string indicating
607
+ // whether the request will use CORS, or will be restricted to same-origin
608
+ // URLs.
609
+ get mode () {
610
+ webidl.brandCheck(this, Request)
611
+
612
+ // The mode getter steps are to return this’s request’s mode.
613
+ return this[kState].mode
614
+ }
615
+
616
+ // Returns the credentials mode associated with request,
617
+ // which is a string indicating whether credentials will be sent with the
618
+ // request always, never, or only when sent to a same-origin URL.
619
+ get credentials () {
620
+ // The credentials getter steps are to return this’s request’s credentials mode.
621
+ return this[kState].credentials
622
+ }
623
+
624
+ // Returns the cache mode associated with request,
625
+ // which is a string indicating how the request will
626
+ // interact with the browser’s cache when fetching.
627
+ get cache () {
628
+ webidl.brandCheck(this, Request)
629
+
630
+ // The cache getter steps are to return this’s request’s cache mode.
631
+ return this[kState].cache
632
+ }
633
+
634
+ // Returns the redirect mode associated with request,
635
+ // which is a string indicating how redirects for the
636
+ // request will be handled during fetching. A request
637
+ // will follow redirects by default.
638
+ get redirect () {
639
+ webidl.brandCheck(this, Request)
640
+
641
+ // The redirect getter steps are to return this’s request’s redirect mode.
642
+ return this[kState].redirect
643
+ }
644
+
645
+ // Returns request’s subresource integrity metadata, which is a
646
+ // cryptographic hash of the resource being fetched. Its value
647
+ // consists of multiple hashes separated by whitespace. [SRI]
648
+ get integrity () {
649
+ webidl.brandCheck(this, Request)
650
+
651
+ // The integrity getter steps are to return this’s request’s integrity
652
+ // metadata.
653
+ return this[kState].integrity
654
+ }
655
+
656
+ // Returns a boolean indicating whether or not request can outlive the
657
+ // global in which it was created.
658
+ get keepalive () {
659
+ webidl.brandCheck(this, Request)
660
+
661
+ // The keepalive getter steps are to return this’s request’s keepalive.
662
+ return this[kState].keepalive
663
+ }
664
+
665
+ // Returns a boolean indicating whether or not request is for a reload
666
+ // navigation.
667
+ get isReloadNavigation () {
668
+ webidl.brandCheck(this, Request)
669
+
670
+ // The isReloadNavigation getter steps are to return true if this’s
671
+ // request’s reload-navigation flag is set; otherwise false.
672
+ return this[kState].reloadNavigation
673
+ }
674
+
675
+ // Returns a boolean indicating whether or not request is for a history
676
+ // navigation (a.k.a. back-foward navigation).
677
+ get isHistoryNavigation () {
678
+ webidl.brandCheck(this, Request)
679
+
680
+ // The isHistoryNavigation getter steps are to return true if this’s request’s
681
+ // history-navigation flag is set; otherwise false.
682
+ return this[kState].historyNavigation
683
+ }
684
+
685
+ // Returns the signal associated with request, which is an AbortSignal
686
+ // object indicating whether or not request has been aborted, and its
687
+ // abort event handler.
688
+ get signal () {
689
+ webidl.brandCheck(this, Request)
690
+
691
+ // The signal getter steps are to return this’s signal.
692
+ return this[kSignal]
693
+ }
694
+
695
+ get body () {
696
+ webidl.brandCheck(this, Request)
697
+
698
+ return this[kState].body ? this[kState].body.stream : null
699
+ }
700
+
701
+ get bodyUsed () {
702
+ webidl.brandCheck(this, Request)
703
+
704
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
705
+ }
706
+
707
+ get duplex () {
708
+ webidl.brandCheck(this, Request)
709
+
710
+ return 'half'
711
+ }
712
+
713
+ // Returns a clone of request.
714
+ clone () {
715
+ webidl.brandCheck(this, Request)
716
+
717
+ // 1. If this is unusable, then throw a TypeError.
718
+ if (this.bodyUsed || this.body?.locked) {
719
+ throw new TypeError('unusable')
720
+ }
721
+
722
+ // 2. Let clonedRequest be the result of cloning this’s request.
723
+ const clonedRequest = cloneRequest(this[kState])
724
+
725
+ // 3. Let clonedRequestObject be the result of creating a Request object,
726
+ // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
727
+ const clonedRequestObject = new Request(kConstruct)
728
+ clonedRequestObject[kState] = clonedRequest
729
+ clonedRequestObject[kRealm] = this[kRealm]
730
+ clonedRequestObject[kHeaders] = new Headers(kConstruct)
731
+ clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
732
+ clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
733
+ clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
734
+
735
+ // 4. Make clonedRequestObject’s signal follow this’s signal.
736
+ const ac = new AbortController()
737
+ if (this.signal.aborted) {
738
+ ac.abort(this.signal.reason)
739
+ } else {
740
+ util.addAbortListener(
741
+ this.signal,
742
+ () => {
743
+ ac.abort(this.signal.reason)
744
+ }
745
+ )
746
+ }
747
+ clonedRequestObject[kSignal] = ac.signal
748
+
749
+ // 4. Return clonedRequestObject.
750
+ return clonedRequestObject
751
+ }
752
+ }
753
+
754
+ mixinBody(Request)
755
+
756
+ function makeRequest (init) {
757
+ // https://fetch.spec.whatwg.org/#requests
758
+ const request = {
759
+ method: 'GET',
760
+ localURLsOnly: false,
761
+ unsafeRequest: false,
762
+ body: null,
763
+ client: null,
764
+ reservedClient: null,
765
+ replacesClientId: '',
766
+ window: 'client',
767
+ keepalive: false,
768
+ serviceWorkers: 'all',
769
+ initiator: '',
770
+ destination: '',
771
+ priority: null,
772
+ origin: 'client',
773
+ policyContainer: 'client',
774
+ referrer: 'client',
775
+ referrerPolicy: '',
776
+ mode: 'no-cors',
777
+ useCORSPreflightFlag: false,
778
+ credentials: 'same-origin',
779
+ useCredentials: false,
780
+ cache: 'default',
781
+ redirect: 'follow',
782
+ integrity: '',
783
+ cryptoGraphicsNonceMetadata: '',
784
+ parserMetadata: '',
785
+ reloadNavigation: false,
786
+ historyNavigation: false,
787
+ userActivation: false,
788
+ taintedOrigin: false,
789
+ redirectCount: 0,
790
+ responseTainting: 'basic',
791
+ preventNoCacheCacheControlHeaderModification: false,
792
+ done: false,
793
+ timingAllowFailed: false,
794
+ ...init,
795
+ headersList: init.headersList
796
+ ? new HeadersList(init.headersList)
797
+ : new HeadersList()
798
+ }
799
+ request.url = request.urlList[0]
800
+ return request
801
+ }
802
+
803
+ // https://fetch.spec.whatwg.org/#concept-request-clone
804
+ function cloneRequest (request) {
805
+ // To clone a request request, run these steps:
806
+
807
+ // 1. Let newRequest be a copy of request, except for its body.
808
+ const newRequest = makeRequest({ ...request, body: null })
809
+
810
+ // 2. If request’s body is non-null, set newRequest’s body to the
811
+ // result of cloning request’s body.
812
+ if (request.body != null) {
813
+ newRequest.body = cloneBody(request.body)
814
+ }
815
+
816
+ // 3. Return newRequest.
817
+ return newRequest
818
+ }
819
+
820
+ Object.defineProperties(Request.prototype, {
821
+ method: kEnumerableProperty,
822
+ url: kEnumerableProperty,
823
+ headers: kEnumerableProperty,
824
+ redirect: kEnumerableProperty,
825
+ clone: kEnumerableProperty,
826
+ signal: kEnumerableProperty,
827
+ duplex: kEnumerableProperty,
828
+ destination: kEnumerableProperty,
829
+ body: kEnumerableProperty,
830
+ bodyUsed: kEnumerableProperty,
831
+ isHistoryNavigation: kEnumerableProperty,
832
+ isReloadNavigation: kEnumerableProperty,
833
+ keepalive: kEnumerableProperty,
834
+ integrity: kEnumerableProperty,
835
+ cache: kEnumerableProperty,
836
+ credentials: kEnumerableProperty,
837
+ attribute: kEnumerableProperty,
838
+ referrerPolicy: kEnumerableProperty,
839
+ referrer: kEnumerableProperty,
840
+ mode: kEnumerableProperty,
841
+ [Symbol.toStringTag]: {
842
+ value: 'Request',
843
+ configurable: true
844
+ }
845
+ })
846
+
847
+ webidl.converters.Request = webidl.interfaceConverter(
848
+ Request
849
+ )
850
+
851
+ // https://fetch.spec.whatwg.org/#requestinfo
852
+ webidl.converters.RequestInfo = function (V) {
853
+ if (typeof V === 'string') {
854
+ return webidl.converters.USVString(V)
855
+ }
856
+
857
+ if (V instanceof Request) {
858
+ return webidl.converters.Request(V)
859
+ }
860
+
861
+ return webidl.converters.USVString(V)
862
+ }
863
+
864
+ webidl.converters.AbortSignal = webidl.interfaceConverter(
865
+ AbortSignal
866
+ )
867
+
868
+ // https://fetch.spec.whatwg.org/#requestinit
869
+ webidl.converters.RequestInit = webidl.dictionaryConverter([
870
+ {
871
+ key: 'method',
872
+ converter: webidl.converters.ByteString
873
+ },
874
+ {
875
+ key: 'headers',
876
+ converter: webidl.converters.HeadersInit
877
+ },
878
+ {
879
+ key: 'body',
880
+ converter: webidl.nullableConverter(
881
+ webidl.converters.BodyInit
882
+ )
883
+ },
884
+ {
885
+ key: 'referrer',
886
+ converter: webidl.converters.USVString
887
+ },
888
+ {
889
+ key: 'referrerPolicy',
890
+ converter: webidl.converters.DOMString,
891
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
892
+ allowedValues: referrerPolicy
893
+ },
894
+ {
895
+ key: 'mode',
896
+ converter: webidl.converters.DOMString,
897
+ // https://fetch.spec.whatwg.org/#concept-request-mode
898
+ allowedValues: requestMode
899
+ },
900
+ {
901
+ key: 'credentials',
902
+ converter: webidl.converters.DOMString,
903
+ // https://fetch.spec.whatwg.org/#requestcredentials
904
+ allowedValues: requestCredentials
905
+ },
906
+ {
907
+ key: 'cache',
908
+ converter: webidl.converters.DOMString,
909
+ // https://fetch.spec.whatwg.org/#requestcache
910
+ allowedValues: requestCache
911
+ },
912
+ {
913
+ key: 'redirect',
914
+ converter: webidl.converters.DOMString,
915
+ // https://fetch.spec.whatwg.org/#requestredirect
916
+ allowedValues: requestRedirect
917
+ },
918
+ {
919
+ key: 'integrity',
920
+ converter: webidl.converters.DOMString
921
+ },
922
+ {
923
+ key: 'keepalive',
924
+ converter: webidl.converters.boolean
925
+ },
926
+ {
927
+ key: 'signal',
928
+ converter: webidl.nullableConverter(
929
+ (signal) => webidl.converters.AbortSignal(
930
+ signal,
931
+ { strict: false }
932
+ )
933
+ )
934
+ },
935
+ {
936
+ key: 'window',
937
+ converter: webidl.converters.any
938
+ },
939
+ {
940
+ key: 'duplex',
941
+ converter: webidl.converters.DOMString,
942
+ allowedValues: requestDuplex
943
+ }
944
+ ])
945
+
946
+ module.exports = { Request, makeRequest }
worker/node_modules/undici/lib/fetch/response.js ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { Headers, HeadersList, fill } = require('./headers')
4
+ const { extractBody, cloneBody, mixinBody } = require('./body')
5
+ const util = require('../core/util')
6
+ const { kEnumerableProperty } = util
7
+ const {
8
+ isValidReasonPhrase,
9
+ isCancelled,
10
+ isAborted,
11
+ isBlobLike,
12
+ serializeJavascriptValueToJSONString,
13
+ isErrorLike,
14
+ isomorphicEncode
15
+ } = require('./util')
16
+ const {
17
+ redirectStatusSet,
18
+ nullBodyStatus,
19
+ DOMException
20
+ } = require('./constants')
21
+ const { kState, kHeaders, kGuard, kRealm } = require('./symbols')
22
+ const { webidl } = require('./webidl')
23
+ const { FormData } = require('./formdata')
24
+ const { getGlobalOrigin } = require('./global')
25
+ const { URLSerializer } = require('./dataURL')
26
+ const { kHeadersList, kConstruct } = require('../core/symbols')
27
+ const assert = require('assert')
28
+ const { types } = require('util')
29
+
30
+ const ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream
31
+ const textEncoder = new TextEncoder('utf-8')
32
+
33
+ // https://fetch.spec.whatwg.org/#response-class
34
+ class Response {
35
+ // Creates network error Response.
36
+ static error () {
37
+ // TODO
38
+ const relevantRealm = { settingsObject: {} }
39
+
40
+ // The static error() method steps are to return the result of creating a
41
+ // Response object, given a new network error, "immutable", and this’s
42
+ // relevant Realm.
43
+ const responseObject = new Response()
44
+ responseObject[kState] = makeNetworkError()
45
+ responseObject[kRealm] = relevantRealm
46
+ responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
47
+ responseObject[kHeaders][kGuard] = 'immutable'
48
+ responseObject[kHeaders][kRealm] = relevantRealm
49
+ return responseObject
50
+ }
51
+
52
+ // https://fetch.spec.whatwg.org/#dom-response-json
53
+ static json (data, init = {}) {
54
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
55
+
56
+ if (init !== null) {
57
+ init = webidl.converters.ResponseInit(init)
58
+ }
59
+
60
+ // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
61
+ const bytes = textEncoder.encode(
62
+ serializeJavascriptValueToJSONString(data)
63
+ )
64
+
65
+ // 2. Let body be the result of extracting bytes.
66
+ const body = extractBody(bytes)
67
+
68
+ // 3. Let responseObject be the result of creating a Response object, given a new response,
69
+ // "response", and this’s relevant Realm.
70
+ const relevantRealm = { settingsObject: {} }
71
+ const responseObject = new Response()
72
+ responseObject[kRealm] = relevantRealm
73
+ responseObject[kHeaders][kGuard] = 'response'
74
+ responseObject[kHeaders][kRealm] = relevantRealm
75
+
76
+ // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
77
+ initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
78
+
79
+ // 5. Return responseObject.
80
+ return responseObject
81
+ }
82
+
83
+ // Creates a redirect Response that redirects to url with status status.
84
+ static redirect (url, status = 302) {
85
+ const relevantRealm = { settingsObject: {} }
86
+
87
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
88
+
89
+ url = webidl.converters.USVString(url)
90
+ status = webidl.converters['unsigned short'](status)
91
+
92
+ // 1. Let parsedURL be the result of parsing url with current settings
93
+ // object’s API base URL.
94
+ // 2. If parsedURL is failure, then throw a TypeError.
95
+ // TODO: base-URL?
96
+ let parsedURL
97
+ try {
98
+ parsedURL = new URL(url, getGlobalOrigin())
99
+ } catch (err) {
100
+ throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
101
+ cause: err
102
+ })
103
+ }
104
+
105
+ // 3. If status is not a redirect status, then throw a RangeError.
106
+ if (!redirectStatusSet.has(status)) {
107
+ throw new RangeError('Invalid status code ' + status)
108
+ }
109
+
110
+ // 4. Let responseObject be the result of creating a Response object,
111
+ // given a new response, "immutable", and this’s relevant Realm.
112
+ const responseObject = new Response()
113
+ responseObject[kRealm] = relevantRealm
114
+ responseObject[kHeaders][kGuard] = 'immutable'
115
+ responseObject[kHeaders][kRealm] = relevantRealm
116
+
117
+ // 5. Set responseObject’s response’s status to status.
118
+ responseObject[kState].status = status
119
+
120
+ // 6. Let value be parsedURL, serialized and isomorphic encoded.
121
+ const value = isomorphicEncode(URLSerializer(parsedURL))
122
+
123
+ // 7. Append `Location`/value to responseObject’s response’s header list.
124
+ responseObject[kState].headersList.append('location', value)
125
+
126
+ // 8. Return responseObject.
127
+ return responseObject
128
+ }
129
+
130
+ // https://fetch.spec.whatwg.org/#dom-response
131
+ constructor (body = null, init = {}) {
132
+ if (body !== null) {
133
+ body = webidl.converters.BodyInit(body)
134
+ }
135
+
136
+ init = webidl.converters.ResponseInit(init)
137
+
138
+ // TODO
139
+ this[kRealm] = { settingsObject: {} }
140
+
141
+ // 1. Set this’s response to a new response.
142
+ this[kState] = makeResponse({})
143
+
144
+ // 2. Set this’s headers to a new Headers object with this’s relevant
145
+ // Realm, whose header list is this’s response’s header list and guard
146
+ // is "response".
147
+ this[kHeaders] = new Headers(kConstruct)
148
+ this[kHeaders][kGuard] = 'response'
149
+ this[kHeaders][kHeadersList] = this[kState].headersList
150
+ this[kHeaders][kRealm] = this[kRealm]
151
+
152
+ // 3. Let bodyWithType be null.
153
+ let bodyWithType = null
154
+
155
+ // 4. If body is non-null, then set bodyWithType to the result of extracting body.
156
+ if (body != null) {
157
+ const [extractedBody, type] = extractBody(body)
158
+ bodyWithType = { body: extractedBody, type }
159
+ }
160
+
161
+ // 5. Perform initialize a response given this, init, and bodyWithType.
162
+ initializeResponse(this, init, bodyWithType)
163
+ }
164
+
165
+ // Returns response’s type, e.g., "cors".
166
+ get type () {
167
+ webidl.brandCheck(this, Response)
168
+
169
+ // The type getter steps are to return this’s response’s type.
170
+ return this[kState].type
171
+ }
172
+
173
+ // Returns response’s URL, if it has one; otherwise the empty string.
174
+ get url () {
175
+ webidl.brandCheck(this, Response)
176
+
177
+ const urlList = this[kState].urlList
178
+
179
+ // The url getter steps are to return the empty string if this’s
180
+ // response’s URL is null; otherwise this’s response’s URL,
181
+ // serialized with exclude fragment set to true.
182
+ const url = urlList[urlList.length - 1] ?? null
183
+
184
+ if (url === null) {
185
+ return ''
186
+ }
187
+
188
+ return URLSerializer(url, true)
189
+ }
190
+
191
+ // Returns whether response was obtained through a redirect.
192
+ get redirected () {
193
+ webidl.brandCheck(this, Response)
194
+
195
+ // The redirected getter steps are to return true if this’s response’s URL
196
+ // list has more than one item; otherwise false.
197
+ return this[kState].urlList.length > 1
198
+ }
199
+
200
+ // Returns response’s status.
201
+ get status () {
202
+ webidl.brandCheck(this, Response)
203
+
204
+ // The status getter steps are to return this’s response’s status.
205
+ return this[kState].status
206
+ }
207
+
208
+ // Returns whether response’s status is an ok status.
209
+ get ok () {
210
+ webidl.brandCheck(this, Response)
211
+
212
+ // The ok getter steps are to return true if this’s response’s status is an
213
+ // ok status; otherwise false.
214
+ return this[kState].status >= 200 && this[kState].status <= 299
215
+ }
216
+
217
+ // Returns response’s status message.
218
+ get statusText () {
219
+ webidl.brandCheck(this, Response)
220
+
221
+ // The statusText getter steps are to return this’s response’s status
222
+ // message.
223
+ return this[kState].statusText
224
+ }
225
+
226
+ // Returns response’s headers as Headers.
227
+ get headers () {
228
+ webidl.brandCheck(this, Response)
229
+
230
+ // The headers getter steps are to return this’s headers.
231
+ return this[kHeaders]
232
+ }
233
+
234
+ get body () {
235
+ webidl.brandCheck(this, Response)
236
+
237
+ return this[kState].body ? this[kState].body.stream : null
238
+ }
239
+
240
+ get bodyUsed () {
241
+ webidl.brandCheck(this, Response)
242
+
243
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
244
+ }
245
+
246
+ // Returns a clone of response.
247
+ clone () {
248
+ webidl.brandCheck(this, Response)
249
+
250
+ // 1. If this is unusable, then throw a TypeError.
251
+ if (this.bodyUsed || (this.body && this.body.locked)) {
252
+ throw webidl.errors.exception({
253
+ header: 'Response.clone',
254
+ message: 'Body has already been consumed.'
255
+ })
256
+ }
257
+
258
+ // 2. Let clonedResponse be the result of cloning this’s response.
259
+ const clonedResponse = cloneResponse(this[kState])
260
+
261
+ // 3. Return the result of creating a Response object, given
262
+ // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
263
+ const clonedResponseObject = new Response()
264
+ clonedResponseObject[kState] = clonedResponse
265
+ clonedResponseObject[kRealm] = this[kRealm]
266
+ clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
267
+ clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
268
+ clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
269
+
270
+ return clonedResponseObject
271
+ }
272
+ }
273
+
274
+ mixinBody(Response)
275
+
276
+ Object.defineProperties(Response.prototype, {
277
+ type: kEnumerableProperty,
278
+ url: kEnumerableProperty,
279
+ status: kEnumerableProperty,
280
+ ok: kEnumerableProperty,
281
+ redirected: kEnumerableProperty,
282
+ statusText: kEnumerableProperty,
283
+ headers: kEnumerableProperty,
284
+ clone: kEnumerableProperty,
285
+ body: kEnumerableProperty,
286
+ bodyUsed: kEnumerableProperty,
287
+ [Symbol.toStringTag]: {
288
+ value: 'Response',
289
+ configurable: true
290
+ }
291
+ })
292
+
293
+ Object.defineProperties(Response, {
294
+ json: kEnumerableProperty,
295
+ redirect: kEnumerableProperty,
296
+ error: kEnumerableProperty
297
+ })
298
+
299
+ // https://fetch.spec.whatwg.org/#concept-response-clone
300
+ function cloneResponse (response) {
301
+ // To clone a response response, run these steps:
302
+
303
+ // 1. If response is a filtered response, then return a new identical
304
+ // filtered response whose internal response is a clone of response’s
305
+ // internal response.
306
+ if (response.internalResponse) {
307
+ return filterResponse(
308
+ cloneResponse(response.internalResponse),
309
+ response.type
310
+ )
311
+ }
312
+
313
+ // 2. Let newResponse be a copy of response, except for its body.
314
+ const newResponse = makeResponse({ ...response, body: null })
315
+
316
+ // 3. If response’s body is non-null, then set newResponse’s body to the
317
+ // result of cloning response’s body.
318
+ if (response.body != null) {
319
+ newResponse.body = cloneBody(response.body)
320
+ }
321
+
322
+ // 4. Return newResponse.
323
+ return newResponse
324
+ }
325
+
326
+ function makeResponse (init) {
327
+ return {
328
+ aborted: false,
329
+ rangeRequested: false,
330
+ timingAllowPassed: false,
331
+ requestIncludesCredentials: false,
332
+ type: 'default',
333
+ status: 200,
334
+ timingInfo: null,
335
+ cacheState: '',
336
+ statusText: '',
337
+ ...init,
338
+ headersList: init.headersList
339
+ ? new HeadersList(init.headersList)
340
+ : new HeadersList(),
341
+ urlList: init.urlList ? [...init.urlList] : []
342
+ }
343
+ }
344
+
345
+ function makeNetworkError (reason) {
346
+ const isError = isErrorLike(reason)
347
+ return makeResponse({
348
+ type: 'error',
349
+ status: 0,
350
+ error: isError
351
+ ? reason
352
+ : new Error(reason ? String(reason) : reason),
353
+ aborted: reason && reason.name === 'AbortError'
354
+ })
355
+ }
356
+
357
+ function makeFilteredResponse (response, state) {
358
+ state = {
359
+ internalResponse: response,
360
+ ...state
361
+ }
362
+
363
+ return new Proxy(response, {
364
+ get (target, p) {
365
+ return p in state ? state[p] : target[p]
366
+ },
367
+ set (target, p, value) {
368
+ assert(!(p in state))
369
+ target[p] = value
370
+ return true
371
+ }
372
+ })
373
+ }
374
+
375
+ // https://fetch.spec.whatwg.org/#concept-filtered-response
376
+ function filterResponse (response, type) {
377
+ // Set response to the following filtered response with response as its
378
+ // internal response, depending on request’s response tainting:
379
+ if (type === 'basic') {
380
+ // A basic filtered response is a filtered response whose type is "basic"
381
+ // and header list excludes any headers in internal response’s header list
382
+ // whose name is a forbidden response-header name.
383
+
384
+ // Note: undici does not implement forbidden response-header names
385
+ return makeFilteredResponse(response, {
386
+ type: 'basic',
387
+ headersList: response.headersList
388
+ })
389
+ } else if (type === 'cors') {
390
+ // A CORS filtered response is a filtered response whose type is "cors"
391
+ // and header list excludes any headers in internal response’s header
392
+ // list whose name is not a CORS-safelisted response-header name, given
393
+ // internal response’s CORS-exposed header-name list.
394
+
395
+ // Note: undici does not implement CORS-safelisted response-header names
396
+ return makeFilteredResponse(response, {
397
+ type: 'cors',
398
+ headersList: response.headersList
399
+ })
400
+ } else if (type === 'opaque') {
401
+ // An opaque filtered response is a filtered response whose type is
402
+ // "opaque", URL list is the empty list, status is 0, status message
403
+ // is the empty byte sequence, header list is empty, and body is null.
404
+
405
+ return makeFilteredResponse(response, {
406
+ type: 'opaque',
407
+ urlList: Object.freeze([]),
408
+ status: 0,
409
+ statusText: '',
410
+ body: null
411
+ })
412
+ } else if (type === 'opaqueredirect') {
413
+ // An opaque-redirect filtered response is a filtered response whose type
414
+ // is "opaqueredirect", status is 0, status message is the empty byte
415
+ // sequence, header list is empty, and body is null.
416
+
417
+ return makeFilteredResponse(response, {
418
+ type: 'opaqueredirect',
419
+ status: 0,
420
+ statusText: '',
421
+ headersList: [],
422
+ body: null
423
+ })
424
+ } else {
425
+ assert(false)
426
+ }
427
+ }
428
+
429
+ // https://fetch.spec.whatwg.org/#appropriate-network-error
430
+ function makeAppropriateNetworkError (fetchParams, err = null) {
431
+ // 1. Assert: fetchParams is canceled.
432
+ assert(isCancelled(fetchParams))
433
+
434
+ // 2. Return an aborted network error if fetchParams is aborted;
435
+ // otherwise return a network error.
436
+ return isAborted(fetchParams)
437
+ ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
438
+ : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
439
+ }
440
+
441
+ // https://whatpr.org/fetch/1392.html#initialize-a-response
442
+ function initializeResponse (response, init, body) {
443
+ // 1. If init["status"] is not in the range 200 to 599, inclusive, then
444
+ // throw a RangeError.
445
+ if (init.status !== null && (init.status < 200 || init.status > 599)) {
446
+ throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
447
+ }
448
+
449
+ // 2. If init["statusText"] does not match the reason-phrase token production,
450
+ // then throw a TypeError.
451
+ if ('statusText' in init && init.statusText != null) {
452
+ // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
453
+ // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
454
+ if (!isValidReasonPhrase(String(init.statusText))) {
455
+ throw new TypeError('Invalid statusText')
456
+ }
457
+ }
458
+
459
+ // 3. Set response’s response’s status to init["status"].
460
+ if ('status' in init && init.status != null) {
461
+ response[kState].status = init.status
462
+ }
463
+
464
+ // 4. Set response’s response’s status message to init["statusText"].
465
+ if ('statusText' in init && init.statusText != null) {
466
+ response[kState].statusText = init.statusText
467
+ }
468
+
469
+ // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
470
+ if ('headers' in init && init.headers != null) {
471
+ fill(response[kHeaders], init.headers)
472
+ }
473
+
474
+ // 6. If body was given, then:
475
+ if (body) {
476
+ // 1. If response's status is a null body status, then throw a TypeError.
477
+ if (nullBodyStatus.includes(response.status)) {
478
+ throw webidl.errors.exception({
479
+ header: 'Response constructor',
480
+ message: 'Invalid response status code ' + response.status
481
+ })
482
+ }
483
+
484
+ // 2. Set response's body to body's body.
485
+ response[kState].body = body.body
486
+
487
+ // 3. If body's type is non-null and response's header list does not contain
488
+ // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
489
+ if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
490
+ response[kState].headersList.append('content-type', body.type)
491
+ }
492
+ }
493
+ }
494
+
495
+ webidl.converters.ReadableStream = webidl.interfaceConverter(
496
+ ReadableStream
497
+ )
498
+
499
+ webidl.converters.FormData = webidl.interfaceConverter(
500
+ FormData
501
+ )
502
+
503
+ webidl.converters.URLSearchParams = webidl.interfaceConverter(
504
+ URLSearchParams
505
+ )
506
+
507
+ // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
508
+ webidl.converters.XMLHttpRequestBodyInit = function (V) {
509
+ if (typeof V === 'string') {
510
+ return webidl.converters.USVString(V)
511
+ }
512
+
513
+ if (isBlobLike(V)) {
514
+ return webidl.converters.Blob(V, { strict: false })
515
+ }
516
+
517
+ if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
518
+ return webidl.converters.BufferSource(V)
519
+ }
520
+
521
+ if (util.isFormDataLike(V)) {
522
+ return webidl.converters.FormData(V, { strict: false })
523
+ }
524
+
525
+ if (V instanceof URLSearchParams) {
526
+ return webidl.converters.URLSearchParams(V)
527
+ }
528
+
529
+ return webidl.converters.DOMString(V)
530
+ }
531
+
532
+ // https://fetch.spec.whatwg.org/#bodyinit
533
+ webidl.converters.BodyInit = function (V) {
534
+ if (V instanceof ReadableStream) {
535
+ return webidl.converters.ReadableStream(V)
536
+ }
537
+
538
+ // Note: the spec doesn't include async iterables,
539
+ // this is an undici extension.
540
+ if (V?.[Symbol.asyncIterator]) {
541
+ return V
542
+ }
543
+
544
+ return webidl.converters.XMLHttpRequestBodyInit(V)
545
+ }
546
+
547
+ webidl.converters.ResponseInit = webidl.dictionaryConverter([
548
+ {
549
+ key: 'status',
550
+ converter: webidl.converters['unsigned short'],
551
+ defaultValue: 200
552
+ },
553
+ {
554
+ key: 'statusText',
555
+ converter: webidl.converters.ByteString,
556
+ defaultValue: ''
557
+ },
558
+ {
559
+ key: 'headers',
560
+ converter: webidl.converters.HeadersInit
561
+ }
562
+ ])
563
+
564
+ module.exports = {
565
+ makeNetworkError,
566
+ makeResponse,
567
+ makeAppropriateNetworkError,
568
+ filterResponse,
569
+ Response,
570
+ cloneResponse
571
+ }
worker/node_modules/undici/lib/fetch/symbols.js ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ module.exports = {
4
+ kUrl: Symbol('url'),
5
+ kHeaders: Symbol('headers'),
6
+ kSignal: Symbol('signal'),
7
+ kState: Symbol('state'),
8
+ kGuard: Symbol('guard'),
9
+ kRealm: Symbol('realm')
10
+ }
worker/node_modules/undici/lib/fetch/util.js ADDED
@@ -0,0 +1,1144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants')
4
+ const { getGlobalOrigin } = require('./global')
5
+ const { performance } = require('perf_hooks')
6
+ const { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util')
7
+ const assert = require('assert')
8
+ const { isUint8Array } = require('util/types')
9
+
10
+ let supportedHashes = []
11
+
12
+ // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
13
+ /** @type {import('crypto')|undefined} */
14
+ let crypto
15
+
16
+ try {
17
+ crypto = require('crypto')
18
+ const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
19
+ supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
20
+ /* c8 ignore next 3 */
21
+ } catch {
22
+ }
23
+
24
+ function responseURL (response) {
25
+ // https://fetch.spec.whatwg.org/#responses
26
+ // A response has an associated URL. It is a pointer to the last URL
27
+ // in response’s URL list and null if response’s URL list is empty.
28
+ const urlList = response.urlList
29
+ const length = urlList.length
30
+ return length === 0 ? null : urlList[length - 1].toString()
31
+ }
32
+
33
+ // https://fetch.spec.whatwg.org/#concept-response-location-url
34
+ function responseLocationURL (response, requestFragment) {
35
+ // 1. If response’s status is not a redirect status, then return null.
36
+ if (!redirectStatusSet.has(response.status)) {
37
+ return null
38
+ }
39
+
40
+ // 2. Let location be the result of extracting header list values given
41
+ // `Location` and response’s header list.
42
+ let location = response.headersList.get('location')
43
+
44
+ // 3. If location is a header value, then set location to the result of
45
+ // parsing location with response’s URL.
46
+ if (location !== null && isValidHeaderValue(location)) {
47
+ location = new URL(location, responseURL(response))
48
+ }
49
+
50
+ // 4. If location is a URL whose fragment is null, then set location’s
51
+ // fragment to requestFragment.
52
+ if (location && !location.hash) {
53
+ location.hash = requestFragment
54
+ }
55
+
56
+ // 5. Return location.
57
+ return location
58
+ }
59
+
60
+ /** @returns {URL} */
61
+ function requestCurrentURL (request) {
62
+ return request.urlList[request.urlList.length - 1]
63
+ }
64
+
65
+ function requestBadPort (request) {
66
+ // 1. Let url be request’s current URL.
67
+ const url = requestCurrentURL(request)
68
+
69
+ // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
70
+ // then return blocked.
71
+ if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
72
+ return 'blocked'
73
+ }
74
+
75
+ // 3. Return allowed.
76
+ return 'allowed'
77
+ }
78
+
79
+ function isErrorLike (object) {
80
+ return object instanceof Error || (
81
+ object?.constructor?.name === 'Error' ||
82
+ object?.constructor?.name === 'DOMException'
83
+ )
84
+ }
85
+
86
+ // Check whether |statusText| is a ByteString and
87
+ // matches the Reason-Phrase token production.
88
+ // RFC 2616: https://tools.ietf.org/html/rfc2616
89
+ // RFC 7230: https://tools.ietf.org/html/rfc7230
90
+ // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
91
+ // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
92
+ function isValidReasonPhrase (statusText) {
93
+ for (let i = 0; i < statusText.length; ++i) {
94
+ const c = statusText.charCodeAt(i)
95
+ if (
96
+ !(
97
+ (
98
+ c === 0x09 || // HTAB
99
+ (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
100
+ (c >= 0x80 && c <= 0xff)
101
+ ) // obs-text
102
+ )
103
+ ) {
104
+ return false
105
+ }
106
+ }
107
+ return true
108
+ }
109
+
110
+ /**
111
+ * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
112
+ * @param {number} c
113
+ */
114
+ function isTokenCharCode (c) {
115
+ switch (c) {
116
+ case 0x22:
117
+ case 0x28:
118
+ case 0x29:
119
+ case 0x2c:
120
+ case 0x2f:
121
+ case 0x3a:
122
+ case 0x3b:
123
+ case 0x3c:
124
+ case 0x3d:
125
+ case 0x3e:
126
+ case 0x3f:
127
+ case 0x40:
128
+ case 0x5b:
129
+ case 0x5c:
130
+ case 0x5d:
131
+ case 0x7b:
132
+ case 0x7d:
133
+ // DQUOTE and "(),/:;<=>?@[\]{}"
134
+ return false
135
+ default:
136
+ // VCHAR %x21-7E
137
+ return c >= 0x21 && c <= 0x7e
138
+ }
139
+ }
140
+
141
+ /**
142
+ * @param {string} characters
143
+ */
144
+ function isValidHTTPToken (characters) {
145
+ if (characters.length === 0) {
146
+ return false
147
+ }
148
+ for (let i = 0; i < characters.length; ++i) {
149
+ if (!isTokenCharCode(characters.charCodeAt(i))) {
150
+ return false
151
+ }
152
+ }
153
+ return true
154
+ }
155
+
156
+ /**
157
+ * @see https://fetch.spec.whatwg.org/#header-name
158
+ * @param {string} potentialValue
159
+ */
160
+ function isValidHeaderName (potentialValue) {
161
+ return isValidHTTPToken(potentialValue)
162
+ }
163
+
164
+ /**
165
+ * @see https://fetch.spec.whatwg.org/#header-value
166
+ * @param {string} potentialValue
167
+ */
168
+ function isValidHeaderValue (potentialValue) {
169
+ // - Has no leading or trailing HTTP tab or space bytes.
170
+ // - Contains no 0x00 (NUL) or HTTP newline bytes.
171
+ if (
172
+ potentialValue.startsWith('\t') ||
173
+ potentialValue.startsWith(' ') ||
174
+ potentialValue.endsWith('\t') ||
175
+ potentialValue.endsWith(' ')
176
+ ) {
177
+ return false
178
+ }
179
+
180
+ if (
181
+ potentialValue.includes('\0') ||
182
+ potentialValue.includes('\r') ||
183
+ potentialValue.includes('\n')
184
+ ) {
185
+ return false
186
+ }
187
+
188
+ return true
189
+ }
190
+
191
+ // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
192
+ function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
193
+ // Given a request request and a response actualResponse, this algorithm
194
+ // updates request’s referrer policy according to the Referrer-Policy
195
+ // header (if any) in actualResponse.
196
+
197
+ // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
198
+ // from a Referrer-Policy header on actualResponse.
199
+
200
+ // 8.1 Parse a referrer policy from a Referrer-Policy header
201
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
202
+ const { headersList } = actualResponse
203
+ // 2. Let policy be the empty string.
204
+ // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
205
+ // 4. Return policy.
206
+ const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
207
+
208
+ // Note: As the referrer-policy can contain multiple policies
209
+ // separated by comma, we need to loop through all of them
210
+ // and pick the first valid one.
211
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
212
+ let policy = ''
213
+ if (policyHeader.length > 0) {
214
+ // The right-most policy takes precedence.
215
+ // The left-most policy is the fallback.
216
+ for (let i = policyHeader.length; i !== 0; i--) {
217
+ const token = policyHeader[i - 1].trim()
218
+ if (referrerPolicyTokens.has(token)) {
219
+ policy = token
220
+ break
221
+ }
222
+ }
223
+ }
224
+
225
+ // 2. If policy is not the empty string, then set request’s referrer policy to policy.
226
+ if (policy !== '') {
227
+ request.referrerPolicy = policy
228
+ }
229
+ }
230
+
231
+ // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
232
+ function crossOriginResourcePolicyCheck () {
233
+ // TODO
234
+ return 'allowed'
235
+ }
236
+
237
+ // https://fetch.spec.whatwg.org/#concept-cors-check
238
+ function corsCheck () {
239
+ // TODO
240
+ return 'success'
241
+ }
242
+
243
+ // https://fetch.spec.whatwg.org/#concept-tao-check
244
+ function TAOCheck () {
245
+ // TODO
246
+ return 'success'
247
+ }
248
+
249
+ function appendFetchMetadata (httpRequest) {
250
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
251
+ // TODO
252
+
253
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
254
+
255
+ // 1. Assert: r’s url is a potentially trustworthy URL.
256
+ // TODO
257
+
258
+ // 2. Let header be a Structured Header whose value is a token.
259
+ let header = null
260
+
261
+ // 3. Set header’s value to r’s mode.
262
+ header = httpRequest.mode
263
+
264
+ // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
265
+ httpRequest.headersList.set('sec-fetch-mode', header)
266
+
267
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
268
+ // TODO
269
+
270
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
271
+ // TODO
272
+ }
273
+
274
+ // https://fetch.spec.whatwg.org/#append-a-request-origin-header
275
+ function appendRequestOriginHeader (request) {
276
+ // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
277
+ let serializedOrigin = request.origin
278
+
279
+ // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
280
+ if (request.responseTainting === 'cors' || request.mode === 'websocket') {
281
+ if (serializedOrigin) {
282
+ request.headersList.append('origin', serializedOrigin)
283
+ }
284
+
285
+ // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
286
+ } else if (request.method !== 'GET' && request.method !== 'HEAD') {
287
+ // 1. Switch on request’s referrer policy:
288
+ switch (request.referrerPolicy) {
289
+ case 'no-referrer':
290
+ // Set serializedOrigin to `null`.
291
+ serializedOrigin = null
292
+ break
293
+ case 'no-referrer-when-downgrade':
294
+ case 'strict-origin':
295
+ case 'strict-origin-when-cross-origin':
296
+ // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
297
+ if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
298
+ serializedOrigin = null
299
+ }
300
+ break
301
+ case 'same-origin':
302
+ // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.
303
+ if (!sameOrigin(request, requestCurrentURL(request))) {
304
+ serializedOrigin = null
305
+ }
306
+ break
307
+ default:
308
+ // Do nothing.
309
+ }
310
+
311
+ if (serializedOrigin) {
312
+ // 2. Append (`Origin`, serializedOrigin) to request’s header list.
313
+ request.headersList.append('origin', serializedOrigin)
314
+ }
315
+ }
316
+ }
317
+
318
+ function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
319
+ // TODO
320
+ return performance.now()
321
+ }
322
+
323
+ // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
324
+ function createOpaqueTimingInfo (timingInfo) {
325
+ return {
326
+ startTime: timingInfo.startTime ?? 0,
327
+ redirectStartTime: 0,
328
+ redirectEndTime: 0,
329
+ postRedirectStartTime: timingInfo.startTime ?? 0,
330
+ finalServiceWorkerStartTime: 0,
331
+ finalNetworkResponseStartTime: 0,
332
+ finalNetworkRequestStartTime: 0,
333
+ endTime: 0,
334
+ encodedBodySize: 0,
335
+ decodedBodySize: 0,
336
+ finalConnectionTimingInfo: null
337
+ }
338
+ }
339
+
340
+ // https://html.spec.whatwg.org/multipage/origin.html#policy-container
341
+ function makePolicyContainer () {
342
+ // Note: the fetch spec doesn't make use of embedder policy or CSP list
343
+ return {
344
+ referrerPolicy: 'strict-origin-when-cross-origin'
345
+ }
346
+ }
347
+
348
+ // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
349
+ function clonePolicyContainer (policyContainer) {
350
+ return {
351
+ referrerPolicy: policyContainer.referrerPolicy
352
+ }
353
+ }
354
+
355
+ // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
356
+ function determineRequestsReferrer (request) {
357
+ // 1. Let policy be request's referrer policy.
358
+ const policy = request.referrerPolicy
359
+
360
+ // Note: policy cannot (shouldn't) be null or an empty string.
361
+ assert(policy)
362
+
363
+ // 2. Let environment be request’s client.
364
+
365
+ let referrerSource = null
366
+
367
+ // 3. Switch on request’s referrer:
368
+ if (request.referrer === 'client') {
369
+ // Note: node isn't a browser and doesn't implement document/iframes,
370
+ // so we bypass this step and replace it with our own.
371
+
372
+ const globalOrigin = getGlobalOrigin()
373
+
374
+ if (!globalOrigin || globalOrigin.origin === 'null') {
375
+ return 'no-referrer'
376
+ }
377
+
378
+ // note: we need to clone it as it's mutated
379
+ referrerSource = new URL(globalOrigin)
380
+ } else if (request.referrer instanceof URL) {
381
+ // Let referrerSource be request’s referrer.
382
+ referrerSource = request.referrer
383
+ }
384
+
385
+ // 4. Let request’s referrerURL be the result of stripping referrerSource for
386
+ // use as a referrer.
387
+ let referrerURL = stripURLForReferrer(referrerSource)
388
+
389
+ // 5. Let referrerOrigin be the result of stripping referrerSource for use as
390
+ // a referrer, with the origin-only flag set to true.
391
+ const referrerOrigin = stripURLForReferrer(referrerSource, true)
392
+
393
+ // 6. If the result of serializing referrerURL is a string whose length is
394
+ // greater than 4096, set referrerURL to referrerOrigin.
395
+ if (referrerURL.toString().length > 4096) {
396
+ referrerURL = referrerOrigin
397
+ }
398
+
399
+ const areSameOrigin = sameOrigin(request, referrerURL)
400
+ const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
401
+ !isURLPotentiallyTrustworthy(request.url)
402
+
403
+ // 8. Execute the switch statements corresponding to the value of policy:
404
+ switch (policy) {
405
+ case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
406
+ case 'unsafe-url': return referrerURL
407
+ case 'same-origin':
408
+ return areSameOrigin ? referrerOrigin : 'no-referrer'
409
+ case 'origin-when-cross-origin':
410
+ return areSameOrigin ? referrerURL : referrerOrigin
411
+ case 'strict-origin-when-cross-origin': {
412
+ const currentURL = requestCurrentURL(request)
413
+
414
+ // 1. If the origin of referrerURL and the origin of request’s current
415
+ // URL are the same, then return referrerURL.
416
+ if (sameOrigin(referrerURL, currentURL)) {
417
+ return referrerURL
418
+ }
419
+
420
+ // 2. If referrerURL is a potentially trustworthy URL and request’s
421
+ // current URL is not a potentially trustworthy URL, then return no
422
+ // referrer.
423
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
424
+ return 'no-referrer'
425
+ }
426
+
427
+ // 3. Return referrerOrigin.
428
+ return referrerOrigin
429
+ }
430
+ case 'strict-origin': // eslint-disable-line
431
+ /**
432
+ * 1. If referrerURL is a potentially trustworthy URL and
433
+ * request’s current URL is not a potentially trustworthy URL,
434
+ * then return no referrer.
435
+ * 2. Return referrerOrigin
436
+ */
437
+ case 'no-referrer-when-downgrade': // eslint-disable-line
438
+ /**
439
+ * 1. If referrerURL is a potentially trustworthy URL and
440
+ * request’s current URL is not a potentially trustworthy URL,
441
+ * then return no referrer.
442
+ * 2. Return referrerOrigin
443
+ */
444
+
445
+ default: // eslint-disable-line
446
+ return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
447
+ }
448
+ }
449
+
450
+ /**
451
+ * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
452
+ * @param {URL} url
453
+ * @param {boolean|undefined} originOnly
454
+ */
455
+ function stripURLForReferrer (url, originOnly) {
456
+ // 1. Assert: url is a URL.
457
+ assert(url instanceof URL)
458
+
459
+ // 2. If url’s scheme is a local scheme, then return no referrer.
460
+ if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
461
+ return 'no-referrer'
462
+ }
463
+
464
+ // 3. Set url’s username to the empty string.
465
+ url.username = ''
466
+
467
+ // 4. Set url’s password to the empty string.
468
+ url.password = ''
469
+
470
+ // 5. Set url’s fragment to null.
471
+ url.hash = ''
472
+
473
+ // 6. If the origin-only flag is true, then:
474
+ if (originOnly) {
475
+ // 1. Set url’s path to « the empty string ».
476
+ url.pathname = ''
477
+
478
+ // 2. Set url’s query to null.
479
+ url.search = ''
480
+ }
481
+
482
+ // 7. Return url.
483
+ return url
484
+ }
485
+
486
+ function isURLPotentiallyTrustworthy (url) {
487
+ if (!(url instanceof URL)) {
488
+ return false
489
+ }
490
+
491
+ // If child of about, return true
492
+ if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
493
+ return true
494
+ }
495
+
496
+ // If scheme is data, return true
497
+ if (url.protocol === 'data:') return true
498
+
499
+ // If file, return true
500
+ if (url.protocol === 'file:') return true
501
+
502
+ return isOriginPotentiallyTrustworthy(url.origin)
503
+
504
+ function isOriginPotentiallyTrustworthy (origin) {
505
+ // If origin is explicitly null, return false
506
+ if (origin == null || origin === 'null') return false
507
+
508
+ const originAsURL = new URL(origin)
509
+
510
+ // If secure, return true
511
+ if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
512
+ return true
513
+ }
514
+
515
+ // If localhost or variants, return true
516
+ if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
517
+ (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
518
+ (originAsURL.hostname.endsWith('.localhost'))) {
519
+ return true
520
+ }
521
+
522
+ // If any other, return false
523
+ return false
524
+ }
525
+ }
526
+
527
+ /**
528
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
529
+ * @param {Uint8Array} bytes
530
+ * @param {string} metadataList
531
+ */
532
+ function bytesMatch (bytes, metadataList) {
533
+ // If node is not built with OpenSSL support, we cannot check
534
+ // a request's integrity, so allow it by default (the spec will
535
+ // allow requests if an invalid hash is given, as precedence).
536
+ /* istanbul ignore if: only if node is built with --without-ssl */
537
+ if (crypto === undefined) {
538
+ return true
539
+ }
540
+
541
+ // 1. Let parsedMetadata be the result of parsing metadataList.
542
+ const parsedMetadata = parseMetadata(metadataList)
543
+
544
+ // 2. If parsedMetadata is no metadata, return true.
545
+ if (parsedMetadata === 'no metadata') {
546
+ return true
547
+ }
548
+
549
+ // 3. If response is not eligible for integrity validation, return false.
550
+ // TODO
551
+
552
+ // 4. If parsedMetadata is the empty set, return true.
553
+ if (parsedMetadata.length === 0) {
554
+ return true
555
+ }
556
+
557
+ // 5. Let metadata be the result of getting the strongest
558
+ // metadata from parsedMetadata.
559
+ const strongest = getStrongestMetadata(parsedMetadata)
560
+ const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
561
+
562
+ // 6. For each item in metadata:
563
+ for (const item of metadata) {
564
+ // 1. Let algorithm be the alg component of item.
565
+ const algorithm = item.algo
566
+
567
+ // 2. Let expectedValue be the val component of item.
568
+ const expectedValue = item.hash
569
+
570
+ // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
571
+ // "be liberal with padding". This is annoying, and it's not even in the spec.
572
+
573
+ // 3. Let actualValue be the result of applying algorithm to bytes.
574
+ let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
575
+
576
+ if (actualValue[actualValue.length - 1] === '=') {
577
+ if (actualValue[actualValue.length - 2] === '=') {
578
+ actualValue = actualValue.slice(0, -2)
579
+ } else {
580
+ actualValue = actualValue.slice(0, -1)
581
+ }
582
+ }
583
+
584
+ // 4. If actualValue is a case-sensitive match for expectedValue,
585
+ // return true.
586
+ if (compareBase64Mixed(actualValue, expectedValue)) {
587
+ return true
588
+ }
589
+ }
590
+
591
+ // 7. Return false.
592
+ return false
593
+ }
594
+
595
+ // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
596
+ // https://www.w3.org/TR/CSP2/#source-list-syntax
597
+ // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
598
+ const parseHashWithOptions = /(?<algo>sha256|sha384|sha512)-((?<hash>[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
599
+
600
+ /**
601
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
602
+ * @param {string} metadata
603
+ */
604
+ function parseMetadata (metadata) {
605
+ // 1. Let result be the empty set.
606
+ /** @type {{ algo: string, hash: string }[]} */
607
+ const result = []
608
+
609
+ // 2. Let empty be equal to true.
610
+ let empty = true
611
+
612
+ // 3. For each token returned by splitting metadata on spaces:
613
+ for (const token of metadata.split(' ')) {
614
+ // 1. Set empty to false.
615
+ empty = false
616
+
617
+ // 2. Parse token as a hash-with-options.
618
+ const parsedToken = parseHashWithOptions.exec(token)
619
+
620
+ // 3. If token does not parse, continue to the next token.
621
+ if (
622
+ parsedToken === null ||
623
+ parsedToken.groups === undefined ||
624
+ parsedToken.groups.algo === undefined
625
+ ) {
626
+ // Note: Chromium blocks the request at this point, but Firefox
627
+ // gives a warning that an invalid integrity was given. The
628
+ // correct behavior is to ignore these, and subsequently not
629
+ // check the integrity of the resource.
630
+ continue
631
+ }
632
+
633
+ // 4. Let algorithm be the hash-algo component of token.
634
+ const algorithm = parsedToken.groups.algo.toLowerCase()
635
+
636
+ // 5. If algorithm is a hash function recognized by the user
637
+ // agent, add the parsed token to result.
638
+ if (supportedHashes.includes(algorithm)) {
639
+ result.push(parsedToken.groups)
640
+ }
641
+ }
642
+
643
+ // 4. Return no metadata if empty is true, otherwise return result.
644
+ if (empty === true) {
645
+ return 'no metadata'
646
+ }
647
+
648
+ return result
649
+ }
650
+
651
+ /**
652
+ * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
653
+ */
654
+ function getStrongestMetadata (metadataList) {
655
+ // Let algorithm be the algo component of the first item in metadataList.
656
+ // Can be sha256
657
+ let algorithm = metadataList[0].algo
658
+ // If the algorithm is sha512, then it is the strongest
659
+ // and we can return immediately
660
+ if (algorithm[3] === '5') {
661
+ return algorithm
662
+ }
663
+
664
+ for (let i = 1; i < metadataList.length; ++i) {
665
+ const metadata = metadataList[i]
666
+ // If the algorithm is sha512, then it is the strongest
667
+ // and we can break the loop immediately
668
+ if (metadata.algo[3] === '5') {
669
+ algorithm = 'sha512'
670
+ break
671
+ // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
672
+ } else if (algorithm[3] === '3') {
673
+ continue
674
+ // algorithm is sha256, check if algorithm is sha384 and if so, set it as
675
+ // the strongest
676
+ } else if (metadata.algo[3] === '3') {
677
+ algorithm = 'sha384'
678
+ }
679
+ }
680
+ return algorithm
681
+ }
682
+
683
+ function filterMetadataListByAlgorithm (metadataList, algorithm) {
684
+ if (metadataList.length === 1) {
685
+ return metadataList
686
+ }
687
+
688
+ let pos = 0
689
+ for (let i = 0; i < metadataList.length; ++i) {
690
+ if (metadataList[i].algo === algorithm) {
691
+ metadataList[pos++] = metadataList[i]
692
+ }
693
+ }
694
+
695
+ metadataList.length = pos
696
+
697
+ return metadataList
698
+ }
699
+
700
+ /**
701
+ * Compares two base64 strings, allowing for base64url
702
+ * in the second string.
703
+ *
704
+ * @param {string} actualValue always base64
705
+ * @param {string} expectedValue base64 or base64url
706
+ * @returns {boolean}
707
+ */
708
+ function compareBase64Mixed (actualValue, expectedValue) {
709
+ if (actualValue.length !== expectedValue.length) {
710
+ return false
711
+ }
712
+ for (let i = 0; i < actualValue.length; ++i) {
713
+ if (actualValue[i] !== expectedValue[i]) {
714
+ if (
715
+ (actualValue[i] === '+' && expectedValue[i] === '-') ||
716
+ (actualValue[i] === '/' && expectedValue[i] === '_')
717
+ ) {
718
+ continue
719
+ }
720
+ return false
721
+ }
722
+ }
723
+
724
+ return true
725
+ }
726
+
727
+ // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
728
+ function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
729
+ // TODO
730
+ }
731
+
732
+ /**
733
+ * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
734
+ * @param {URL} A
735
+ * @param {URL} B
736
+ */
737
+ function sameOrigin (A, B) {
738
+ // 1. If A and B are the same opaque origin, then return true.
739
+ if (A.origin === B.origin && A.origin === 'null') {
740
+ return true
741
+ }
742
+
743
+ // 2. If A and B are both tuple origins and their schemes,
744
+ // hosts, and port are identical, then return true.
745
+ if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
746
+ return true
747
+ }
748
+
749
+ // 3. Return false.
750
+ return false
751
+ }
752
+
753
+ function createDeferredPromise () {
754
+ let res
755
+ let rej
756
+ const promise = new Promise((resolve, reject) => {
757
+ res = resolve
758
+ rej = reject
759
+ })
760
+
761
+ return { promise, resolve: res, reject: rej }
762
+ }
763
+
764
+ function isAborted (fetchParams) {
765
+ return fetchParams.controller.state === 'aborted'
766
+ }
767
+
768
+ function isCancelled (fetchParams) {
769
+ return fetchParams.controller.state === 'aborted' ||
770
+ fetchParams.controller.state === 'terminated'
771
+ }
772
+
773
+ const normalizeMethodRecord = {
774
+ delete: 'DELETE',
775
+ DELETE: 'DELETE',
776
+ get: 'GET',
777
+ GET: 'GET',
778
+ head: 'HEAD',
779
+ HEAD: 'HEAD',
780
+ options: 'OPTIONS',
781
+ OPTIONS: 'OPTIONS',
782
+ post: 'POST',
783
+ POST: 'POST',
784
+ put: 'PUT',
785
+ PUT: 'PUT'
786
+ }
787
+
788
+ // Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
789
+ Object.setPrototypeOf(normalizeMethodRecord, null)
790
+
791
+ /**
792
+ * @see https://fetch.spec.whatwg.org/#concept-method-normalize
793
+ * @param {string} method
794
+ */
795
+ function normalizeMethod (method) {
796
+ return normalizeMethodRecord[method.toLowerCase()] ?? method
797
+ }
798
+
799
+ // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
800
+ function serializeJavascriptValueToJSONString (value) {
801
+ // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
802
+ const result = JSON.stringify(value)
803
+
804
+ // 2. If result is undefined, then throw a TypeError.
805
+ if (result === undefined) {
806
+ throw new TypeError('Value is not JSON serializable')
807
+ }
808
+
809
+ // 3. Assert: result is a string.
810
+ assert(typeof result === 'string')
811
+
812
+ // 4. Return result.
813
+ return result
814
+ }
815
+
816
+ // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
817
+ const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
818
+
819
+ /**
820
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
821
+ * @param {() => unknown[]} iterator
822
+ * @param {string} name name of the instance
823
+ * @param {'key'|'value'|'key+value'} kind
824
+ */
825
+ function makeIterator (iterator, name, kind) {
826
+ const object = {
827
+ index: 0,
828
+ kind,
829
+ target: iterator
830
+ }
831
+
832
+ const i = {
833
+ next () {
834
+ // 1. Let interface be the interface for which the iterator prototype object exists.
835
+
836
+ // 2. Let thisValue be the this value.
837
+
838
+ // 3. Let object be ? ToObject(thisValue).
839
+
840
+ // 4. If object is a platform object, then perform a security
841
+ // check, passing:
842
+
843
+ // 5. If object is not a default iterator object for interface,
844
+ // then throw a TypeError.
845
+ if (Object.getPrototypeOf(this) !== i) {
846
+ throw new TypeError(
847
+ `'next' called on an object that does not implement interface ${name} Iterator.`
848
+ )
849
+ }
850
+
851
+ // 6. Let index be object’s index.
852
+ // 7. Let kind be object’s kind.
853
+ // 8. Let values be object’s target's value pairs to iterate over.
854
+ const { index, kind, target } = object
855
+ const values = target()
856
+
857
+ // 9. Let len be the length of values.
858
+ const len = values.length
859
+
860
+ // 10. If index is greater than or equal to len, then return
861
+ // CreateIterResultObject(undefined, true).
862
+ if (index >= len) {
863
+ return { value: undefined, done: true }
864
+ }
865
+
866
+ // 11. Let pair be the entry in values at index index.
867
+ const pair = values[index]
868
+
869
+ // 12. Set object’s index to index + 1.
870
+ object.index = index + 1
871
+
872
+ // 13. Return the iterator result for pair and kind.
873
+ return iteratorResult(pair, kind)
874
+ },
875
+ // The class string of an iterator prototype object for a given interface is the
876
+ // result of concatenating the identifier of the interface and the string " Iterator".
877
+ [Symbol.toStringTag]: `${name} Iterator`
878
+ }
879
+
880
+ // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
881
+ Object.setPrototypeOf(i, esIteratorPrototype)
882
+ // esIteratorPrototype needs to be the prototype of i
883
+ // which is the prototype of an empty object. Yes, it's confusing.
884
+ return Object.setPrototypeOf({}, i)
885
+ }
886
+
887
+ // https://webidl.spec.whatwg.org/#iterator-result
888
+ function iteratorResult (pair, kind) {
889
+ let result
890
+
891
+ // 1. Let result be a value determined by the value of kind:
892
+ switch (kind) {
893
+ case 'key': {
894
+ // 1. Let idlKey be pair’s key.
895
+ // 2. Let key be the result of converting idlKey to an
896
+ // ECMAScript value.
897
+ // 3. result is key.
898
+ result = pair[0]
899
+ break
900
+ }
901
+ case 'value': {
902
+ // 1. Let idlValue be pair’s value.
903
+ // 2. Let value be the result of converting idlValue to
904
+ // an ECMAScript value.
905
+ // 3. result is value.
906
+ result = pair[1]
907
+ break
908
+ }
909
+ case 'key+value': {
910
+ // 1. Let idlKey be pair’s key.
911
+ // 2. Let idlValue be pair’s value.
912
+ // 3. Let key be the result of converting idlKey to an
913
+ // ECMAScript value.
914
+ // 4. Let value be the result of converting idlValue to
915
+ // an ECMAScript value.
916
+ // 5. Let array be ! ArrayCreate(2).
917
+ // 6. Call ! CreateDataProperty(array, "0", key).
918
+ // 7. Call ! CreateDataProperty(array, "1", value).
919
+ // 8. result is array.
920
+ result = pair
921
+ break
922
+ }
923
+ }
924
+
925
+ // 2. Return CreateIterResultObject(result, false).
926
+ return { value: result, done: false }
927
+ }
928
+
929
+ /**
930
+ * @see https://fetch.spec.whatwg.org/#body-fully-read
931
+ */
932
+ async function fullyReadBody (body, processBody, processBodyError) {
933
+ // 1. If taskDestination is null, then set taskDestination to
934
+ // the result of starting a new parallel queue.
935
+
936
+ // 2. Let successSteps given a byte sequence bytes be to queue a
937
+ // fetch task to run processBody given bytes, with taskDestination.
938
+ const successSteps = processBody
939
+
940
+ // 3. Let errorSteps be to queue a fetch task to run processBodyError,
941
+ // with taskDestination.
942
+ const errorSteps = processBodyError
943
+
944
+ // 4. Let reader be the result of getting a reader for body’s stream.
945
+ // If that threw an exception, then run errorSteps with that
946
+ // exception and return.
947
+ let reader
948
+
949
+ try {
950
+ reader = body.stream.getReader()
951
+ } catch (e) {
952
+ errorSteps(e)
953
+ return
954
+ }
955
+
956
+ // 5. Read all bytes from reader, given successSteps and errorSteps.
957
+ try {
958
+ const result = await readAllBytes(reader)
959
+ successSteps(result)
960
+ } catch (e) {
961
+ errorSteps(e)
962
+ }
963
+ }
964
+
965
+ /** @type {ReadableStream} */
966
+ let ReadableStream = globalThis.ReadableStream
967
+
968
+ function isReadableStreamLike (stream) {
969
+ if (!ReadableStream) {
970
+ ReadableStream = require('stream/web').ReadableStream
971
+ }
972
+
973
+ return stream instanceof ReadableStream || (
974
+ stream[Symbol.toStringTag] === 'ReadableStream' &&
975
+ typeof stream.tee === 'function'
976
+ )
977
+ }
978
+
979
+ const MAXIMUM_ARGUMENT_LENGTH = 65535
980
+
981
+ /**
982
+ * @see https://infra.spec.whatwg.org/#isomorphic-decode
983
+ * @param {number[]|Uint8Array} input
984
+ */
985
+ function isomorphicDecode (input) {
986
+ // 1. To isomorphic decode a byte sequence input, return a string whose code point
987
+ // length is equal to input’s length and whose code points have the same values
988
+ // as the values of input’s bytes, in the same order.
989
+
990
+ if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
991
+ return String.fromCharCode(...input)
992
+ }
993
+
994
+ return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
995
+ }
996
+
997
+ /**
998
+ * @param {ReadableStreamController<Uint8Array>} controller
999
+ */
1000
+ function readableStreamClose (controller) {
1001
+ try {
1002
+ controller.close()
1003
+ } catch (err) {
1004
+ // TODO: add comment explaining why this error occurs.
1005
+ if (!err.message.includes('Controller is already closed')) {
1006
+ throw err
1007
+ }
1008
+ }
1009
+ }
1010
+
1011
+ /**
1012
+ * @see https://infra.spec.whatwg.org/#isomorphic-encode
1013
+ * @param {string} input
1014
+ */
1015
+ function isomorphicEncode (input) {
1016
+ // 1. Assert: input contains no code points greater than U+00FF.
1017
+ for (let i = 0; i < input.length; i++) {
1018
+ assert(input.charCodeAt(i) <= 0xFF)
1019
+ }
1020
+
1021
+ // 2. Return a byte sequence whose length is equal to input’s code
1022
+ // point length and whose bytes have the same values as the
1023
+ // values of input’s code points, in the same order
1024
+ return input
1025
+ }
1026
+
1027
+ /**
1028
+ * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
1029
+ * @see https://streams.spec.whatwg.org/#read-loop
1030
+ * @param {ReadableStreamDefaultReader} reader
1031
+ */
1032
+ async function readAllBytes (reader) {
1033
+ const bytes = []
1034
+ let byteLength = 0
1035
+
1036
+ while (true) {
1037
+ const { done, value: chunk } = await reader.read()
1038
+
1039
+ if (done) {
1040
+ // 1. Call successSteps with bytes.
1041
+ return Buffer.concat(bytes, byteLength)
1042
+ }
1043
+
1044
+ // 1. If chunk is not a Uint8Array object, call failureSteps
1045
+ // with a TypeError and abort these steps.
1046
+ if (!isUint8Array(chunk)) {
1047
+ throw new TypeError('Received non-Uint8Array chunk')
1048
+ }
1049
+
1050
+ // 2. Append the bytes represented by chunk to bytes.
1051
+ bytes.push(chunk)
1052
+ byteLength += chunk.length
1053
+
1054
+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * @see https://fetch.spec.whatwg.org/#is-local
1060
+ * @param {URL} url
1061
+ */
1062
+ function urlIsLocal (url) {
1063
+ assert('protocol' in url) // ensure it's a url object
1064
+
1065
+ const protocol = url.protocol
1066
+
1067
+ return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
1068
+ }
1069
+
1070
+ /**
1071
+ * @param {string|URL} url
1072
+ */
1073
+ function urlHasHttpsScheme (url) {
1074
+ if (typeof url === 'string') {
1075
+ return url.startsWith('https:')
1076
+ }
1077
+
1078
+ return url.protocol === 'https:'
1079
+ }
1080
+
1081
+ /**
1082
+ * @see https://fetch.spec.whatwg.org/#http-scheme
1083
+ * @param {URL} url
1084
+ */
1085
+ function urlIsHttpHttpsScheme (url) {
1086
+ assert('protocol' in url) // ensure it's a url object
1087
+
1088
+ const protocol = url.protocol
1089
+
1090
+ return protocol === 'http:' || protocol === 'https:'
1091
+ }
1092
+
1093
+ /**
1094
+ * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
1095
+ */
1096
+ const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
1097
+
1098
+ module.exports = {
1099
+ isAborted,
1100
+ isCancelled,
1101
+ createDeferredPromise,
1102
+ ReadableStreamFrom,
1103
+ toUSVString,
1104
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
1105
+ coarsenedSharedCurrentTime,
1106
+ determineRequestsReferrer,
1107
+ makePolicyContainer,
1108
+ clonePolicyContainer,
1109
+ appendFetchMetadata,
1110
+ appendRequestOriginHeader,
1111
+ TAOCheck,
1112
+ corsCheck,
1113
+ crossOriginResourcePolicyCheck,
1114
+ createOpaqueTimingInfo,
1115
+ setRequestReferrerPolicyOnRedirect,
1116
+ isValidHTTPToken,
1117
+ requestBadPort,
1118
+ requestCurrentURL,
1119
+ responseURL,
1120
+ responseLocationURL,
1121
+ isBlobLike,
1122
+ isURLPotentiallyTrustworthy,
1123
+ isValidReasonPhrase,
1124
+ sameOrigin,
1125
+ normalizeMethod,
1126
+ serializeJavascriptValueToJSONString,
1127
+ makeIterator,
1128
+ isValidHeaderName,
1129
+ isValidHeaderValue,
1130
+ hasOwn,
1131
+ isErrorLike,
1132
+ fullyReadBody,
1133
+ bytesMatch,
1134
+ isReadableStreamLike,
1135
+ readableStreamClose,
1136
+ isomorphicEncode,
1137
+ isomorphicDecode,
1138
+ urlIsLocal,
1139
+ urlHasHttpsScheme,
1140
+ urlIsHttpHttpsScheme,
1141
+ readAllBytes,
1142
+ normalizeMethodRecord,
1143
+ parseMetadata
1144
+ }
worker/node_modules/undici/lib/fetch/webidl.js ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { types } = require('util')
4
+ const { hasOwn, toUSVString } = require('./util')
5
+
6
+ /** @type {import('../../types/webidl').Webidl} */
7
+ const webidl = {}
8
+ webidl.converters = {}
9
+ webidl.util = {}
10
+ webidl.errors = {}
11
+
12
+ webidl.errors.exception = function (message) {
13
+ return new TypeError(`${message.header}: ${message.message}`)
14
+ }
15
+
16
+ webidl.errors.conversionFailed = function (context) {
17
+ const plural = context.types.length === 1 ? '' : ' one of'
18
+ const message =
19
+ `${context.argument} could not be converted to` +
20
+ `${plural}: ${context.types.join(', ')}.`
21
+
22
+ return webidl.errors.exception({
23
+ header: context.prefix,
24
+ message
25
+ })
26
+ }
27
+
28
+ webidl.errors.invalidArgument = function (context) {
29
+ return webidl.errors.exception({
30
+ header: context.prefix,
31
+ message: `"${context.value}" is an invalid ${context.type}.`
32
+ })
33
+ }
34
+
35
+ // https://webidl.spec.whatwg.org/#implements
36
+ webidl.brandCheck = function (V, I, opts = undefined) {
37
+ if (opts?.strict !== false && !(V instanceof I)) {
38
+ throw new TypeError('Illegal invocation')
39
+ } else {
40
+ return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
41
+ }
42
+ }
43
+
44
+ webidl.argumentLengthCheck = function ({ length }, min, ctx) {
45
+ if (length < min) {
46
+ throw webidl.errors.exception({
47
+ message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
48
+ `but${length ? ' only' : ''} ${length} found.`,
49
+ ...ctx
50
+ })
51
+ }
52
+ }
53
+
54
+ webidl.illegalConstructor = function () {
55
+ throw webidl.errors.exception({
56
+ header: 'TypeError',
57
+ message: 'Illegal constructor'
58
+ })
59
+ }
60
+
61
+ // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
62
+ webidl.util.Type = function (V) {
63
+ switch (typeof V) {
64
+ case 'undefined': return 'Undefined'
65
+ case 'boolean': return 'Boolean'
66
+ case 'string': return 'String'
67
+ case 'symbol': return 'Symbol'
68
+ case 'number': return 'Number'
69
+ case 'bigint': return 'BigInt'
70
+ case 'function':
71
+ case 'object': {
72
+ if (V === null) {
73
+ return 'Null'
74
+ }
75
+
76
+ return 'Object'
77
+ }
78
+ }
79
+ }
80
+
81
+ // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
82
+ webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
83
+ let upperBound
84
+ let lowerBound
85
+
86
+ // 1. If bitLength is 64, then:
87
+ if (bitLength === 64) {
88
+ // 1. Let upperBound be 2^53 − 1.
89
+ upperBound = Math.pow(2, 53) - 1
90
+
91
+ // 2. If signedness is "unsigned", then let lowerBound be 0.
92
+ if (signedness === 'unsigned') {
93
+ lowerBound = 0
94
+ } else {
95
+ // 3. Otherwise let lowerBound be −2^53 + 1.
96
+ lowerBound = Math.pow(-2, 53) + 1
97
+ }
98
+ } else if (signedness === 'unsigned') {
99
+ // 2. Otherwise, if signedness is "unsigned", then:
100
+
101
+ // 1. Let lowerBound be 0.
102
+ lowerBound = 0
103
+
104
+ // 2. Let upperBound be 2^bitLength − 1.
105
+ upperBound = Math.pow(2, bitLength) - 1
106
+ } else {
107
+ // 3. Otherwise:
108
+
109
+ // 1. Let lowerBound be -2^bitLength − 1.
110
+ lowerBound = Math.pow(-2, bitLength) - 1
111
+
112
+ // 2. Let upperBound be 2^bitLength − 1 − 1.
113
+ upperBound = Math.pow(2, bitLength - 1) - 1
114
+ }
115
+
116
+ // 4. Let x be ? ToNumber(V).
117
+ let x = Number(V)
118
+
119
+ // 5. If x is −0, then set x to +0.
120
+ if (x === 0) {
121
+ x = 0
122
+ }
123
+
124
+ // 6. If the conversion is to an IDL type associated
125
+ // with the [EnforceRange] extended attribute, then:
126
+ if (opts.enforceRange === true) {
127
+ // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
128
+ if (
129
+ Number.isNaN(x) ||
130
+ x === Number.POSITIVE_INFINITY ||
131
+ x === Number.NEGATIVE_INFINITY
132
+ ) {
133
+ throw webidl.errors.exception({
134
+ header: 'Integer conversion',
135
+ message: `Could not convert ${V} to an integer.`
136
+ })
137
+ }
138
+
139
+ // 2. Set x to IntegerPart(x).
140
+ x = webidl.util.IntegerPart(x)
141
+
142
+ // 3. If x < lowerBound or x > upperBound, then
143
+ // throw a TypeError.
144
+ if (x < lowerBound || x > upperBound) {
145
+ throw webidl.errors.exception({
146
+ header: 'Integer conversion',
147
+ message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
148
+ })
149
+ }
150
+
151
+ // 4. Return x.
152
+ return x
153
+ }
154
+
155
+ // 7. If x is not NaN and the conversion is to an IDL
156
+ // type associated with the [Clamp] extended
157
+ // attribute, then:
158
+ if (!Number.isNaN(x) && opts.clamp === true) {
159
+ // 1. Set x to min(max(x, lowerBound), upperBound).
160
+ x = Math.min(Math.max(x, lowerBound), upperBound)
161
+
162
+ // 2. Round x to the nearest integer, choosing the
163
+ // even integer if it lies halfway between two,
164
+ // and choosing +0 rather than −0.
165
+ if (Math.floor(x) % 2 === 0) {
166
+ x = Math.floor(x)
167
+ } else {
168
+ x = Math.ceil(x)
169
+ }
170
+
171
+ // 3. Return x.
172
+ return x
173
+ }
174
+
175
+ // 8. If x is NaN, +0, +∞, or −∞, then return +0.
176
+ if (
177
+ Number.isNaN(x) ||
178
+ (x === 0 && Object.is(0, x)) ||
179
+ x === Number.POSITIVE_INFINITY ||
180
+ x === Number.NEGATIVE_INFINITY
181
+ ) {
182
+ return 0
183
+ }
184
+
185
+ // 9. Set x to IntegerPart(x).
186
+ x = webidl.util.IntegerPart(x)
187
+
188
+ // 10. Set x to x modulo 2^bitLength.
189
+ x = x % Math.pow(2, bitLength)
190
+
191
+ // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
192
+ // then return x − 2^bitLength.
193
+ if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
194
+ return x - Math.pow(2, bitLength)
195
+ }
196
+
197
+ // 12. Otherwise, return x.
198
+ return x
199
+ }
200
+
201
+ // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
202
+ webidl.util.IntegerPart = function (n) {
203
+ // 1. Let r be floor(abs(n)).
204
+ const r = Math.floor(Math.abs(n))
205
+
206
+ // 2. If n < 0, then return -1 × r.
207
+ if (n < 0) {
208
+ return -1 * r
209
+ }
210
+
211
+ // 3. Otherwise, return r.
212
+ return r
213
+ }
214
+
215
+ // https://webidl.spec.whatwg.org/#es-sequence
216
+ webidl.sequenceConverter = function (converter) {
217
+ return (V) => {
218
+ // 1. If Type(V) is not Object, throw a TypeError.
219
+ if (webidl.util.Type(V) !== 'Object') {
220
+ throw webidl.errors.exception({
221
+ header: 'Sequence',
222
+ message: `Value of type ${webidl.util.Type(V)} is not an Object.`
223
+ })
224
+ }
225
+
226
+ // 2. Let method be ? GetMethod(V, @@iterator).
227
+ /** @type {Generator} */
228
+ const method = V?.[Symbol.iterator]?.()
229
+ const seq = []
230
+
231
+ // 3. If method is undefined, throw a TypeError.
232
+ if (
233
+ method === undefined ||
234
+ typeof method.next !== 'function'
235
+ ) {
236
+ throw webidl.errors.exception({
237
+ header: 'Sequence',
238
+ message: 'Object is not an iterator.'
239
+ })
240
+ }
241
+
242
+ // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
243
+ while (true) {
244
+ const { done, value } = method.next()
245
+
246
+ if (done) {
247
+ break
248
+ }
249
+
250
+ seq.push(converter(value))
251
+ }
252
+
253
+ return seq
254
+ }
255
+ }
256
+
257
+ // https://webidl.spec.whatwg.org/#es-to-record
258
+ webidl.recordConverter = function (keyConverter, valueConverter) {
259
+ return (O) => {
260
+ // 1. If Type(O) is not Object, throw a TypeError.
261
+ if (webidl.util.Type(O) !== 'Object') {
262
+ throw webidl.errors.exception({
263
+ header: 'Record',
264
+ message: `Value of type ${webidl.util.Type(O)} is not an Object.`
265
+ })
266
+ }
267
+
268
+ // 2. Let result be a new empty instance of record<K, V>.
269
+ const result = {}
270
+
271
+ if (!types.isProxy(O)) {
272
+ // Object.keys only returns enumerable properties
273
+ const keys = Object.keys(O)
274
+
275
+ for (const key of keys) {
276
+ // 1. Let typedKey be key converted to an IDL value of type K.
277
+ const typedKey = keyConverter(key)
278
+
279
+ // 2. Let value be ? Get(O, key).
280
+ // 3. Let typedValue be value converted to an IDL value of type V.
281
+ const typedValue = valueConverter(O[key])
282
+
283
+ // 4. Set result[typedKey] to typedValue.
284
+ result[typedKey] = typedValue
285
+ }
286
+
287
+ // 5. Return result.
288
+ return result
289
+ }
290
+
291
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
292
+ const keys = Reflect.ownKeys(O)
293
+
294
+ // 4. For each key of keys.
295
+ for (const key of keys) {
296
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
297
+ const desc = Reflect.getOwnPropertyDescriptor(O, key)
298
+
299
+ // 2. If desc is not undefined and desc.[[Enumerable]] is true:
300
+ if (desc?.enumerable) {
301
+ // 1. Let typedKey be key converted to an IDL value of type K.
302
+ const typedKey = keyConverter(key)
303
+
304
+ // 2. Let value be ? Get(O, key).
305
+ // 3. Let typedValue be value converted to an IDL value of type V.
306
+ const typedValue = valueConverter(O[key])
307
+
308
+ // 4. Set result[typedKey] to typedValue.
309
+ result[typedKey] = typedValue
310
+ }
311
+ }
312
+
313
+ // 5. Return result.
314
+ return result
315
+ }
316
+ }
317
+
318
+ webidl.interfaceConverter = function (i) {
319
+ return (V, opts = {}) => {
320
+ if (opts.strict !== false && !(V instanceof i)) {
321
+ throw webidl.errors.exception({
322
+ header: i.name,
323
+ message: `Expected ${V} to be an instance of ${i.name}.`
324
+ })
325
+ }
326
+
327
+ return V
328
+ }
329
+ }
330
+
331
+ webidl.dictionaryConverter = function (converters) {
332
+ return (dictionary) => {
333
+ const type = webidl.util.Type(dictionary)
334
+ const dict = {}
335
+
336
+ if (type === 'Null' || type === 'Undefined') {
337
+ return dict
338
+ } else if (type !== 'Object') {
339
+ throw webidl.errors.exception({
340
+ header: 'Dictionary',
341
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
342
+ })
343
+ }
344
+
345
+ for (const options of converters) {
346
+ const { key, defaultValue, required, converter } = options
347
+
348
+ if (required === true) {
349
+ if (!hasOwn(dictionary, key)) {
350
+ throw webidl.errors.exception({
351
+ header: 'Dictionary',
352
+ message: `Missing required key "${key}".`
353
+ })
354
+ }
355
+ }
356
+
357
+ let value = dictionary[key]
358
+ const hasDefault = hasOwn(options, 'defaultValue')
359
+
360
+ // Only use defaultValue if value is undefined and
361
+ // a defaultValue options was provided.
362
+ if (hasDefault && value !== null) {
363
+ value = value ?? defaultValue
364
+ }
365
+
366
+ // A key can be optional and have no default value.
367
+ // When this happens, do not perform a conversion,
368
+ // and do not assign the key a value.
369
+ if (required || hasDefault || value !== undefined) {
370
+ value = converter(value)
371
+
372
+ if (
373
+ options.allowedValues &&
374
+ !options.allowedValues.includes(value)
375
+ ) {
376
+ throw webidl.errors.exception({
377
+ header: 'Dictionary',
378
+ message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
379
+ })
380
+ }
381
+
382
+ dict[key] = value
383
+ }
384
+ }
385
+
386
+ return dict
387
+ }
388
+ }
389
+
390
+ webidl.nullableConverter = function (converter) {
391
+ return (V) => {
392
+ if (V === null) {
393
+ return V
394
+ }
395
+
396
+ return converter(V)
397
+ }
398
+ }
399
+
400
+ // https://webidl.spec.whatwg.org/#es-DOMString
401
+ webidl.converters.DOMString = function (V, opts = {}) {
402
+ // 1. If V is null and the conversion is to an IDL type
403
+ // associated with the [LegacyNullToEmptyString]
404
+ // extended attribute, then return the DOMString value
405
+ // that represents the empty string.
406
+ if (V === null && opts.legacyNullToEmptyString) {
407
+ return ''
408
+ }
409
+
410
+ // 2. Let x be ? ToString(V).
411
+ if (typeof V === 'symbol') {
412
+ throw new TypeError('Could not convert argument of type symbol to string.')
413
+ }
414
+
415
+ // 3. Return the IDL DOMString value that represents the
416
+ // same sequence of code units as the one the
417
+ // ECMAScript String value x represents.
418
+ return String(V)
419
+ }
420
+
421
+ // https://webidl.spec.whatwg.org/#es-ByteString
422
+ webidl.converters.ByteString = function (V) {
423
+ // 1. Let x be ? ToString(V).
424
+ // Note: DOMString converter perform ? ToString(V)
425
+ const x = webidl.converters.DOMString(V)
426
+
427
+ // 2. If the value of any element of x is greater than
428
+ // 255, then throw a TypeError.
429
+ for (let index = 0; index < x.length; index++) {
430
+ if (x.charCodeAt(index) > 255) {
431
+ throw new TypeError(
432
+ 'Cannot convert argument to a ByteString because the character at ' +
433
+ `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
434
+ )
435
+ }
436
+ }
437
+
438
+ // 3. Return an IDL ByteString value whose length is the
439
+ // length of x, and where the value of each element is
440
+ // the value of the corresponding element of x.
441
+ return x
442
+ }
443
+
444
+ // https://webidl.spec.whatwg.org/#es-USVString
445
+ webidl.converters.USVString = toUSVString
446
+
447
+ // https://webidl.spec.whatwg.org/#es-boolean
448
+ webidl.converters.boolean = function (V) {
449
+ // 1. Let x be the result of computing ToBoolean(V).
450
+ const x = Boolean(V)
451
+
452
+ // 2. Return the IDL boolean value that is the one that represents
453
+ // the same truth value as the ECMAScript Boolean value x.
454
+ return x
455
+ }
456
+
457
+ // https://webidl.spec.whatwg.org/#es-any
458
+ webidl.converters.any = function (V) {
459
+ return V
460
+ }
461
+
462
+ // https://webidl.spec.whatwg.org/#es-long-long
463
+ webidl.converters['long long'] = function (V) {
464
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
465
+ const x = webidl.util.ConvertToInt(V, 64, 'signed')
466
+
467
+ // 2. Return the IDL long long value that represents
468
+ // the same numeric value as x.
469
+ return x
470
+ }
471
+
472
+ // https://webidl.spec.whatwg.org/#es-unsigned-long-long
473
+ webidl.converters['unsigned long long'] = function (V) {
474
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
475
+ const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
476
+
477
+ // 2. Return the IDL unsigned long long value that
478
+ // represents the same numeric value as x.
479
+ return x
480
+ }
481
+
482
+ // https://webidl.spec.whatwg.org/#es-unsigned-long
483
+ webidl.converters['unsigned long'] = function (V) {
484
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
485
+ const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
486
+
487
+ // 2. Return the IDL unsigned long value that
488
+ // represents the same numeric value as x.
489
+ return x
490
+ }
491
+
492
+ // https://webidl.spec.whatwg.org/#es-unsigned-short
493
+ webidl.converters['unsigned short'] = function (V, opts) {
494
+ // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
495
+ const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
496
+
497
+ // 2. Return the IDL unsigned short value that represents
498
+ // the same numeric value as x.
499
+ return x
500
+ }
501
+
502
+ // https://webidl.spec.whatwg.org/#idl-ArrayBuffer
503
+ webidl.converters.ArrayBuffer = function (V, opts = {}) {
504
+ // 1. If Type(V) is not Object, or V does not have an
505
+ // [[ArrayBufferData]] internal slot, then throw a
506
+ // TypeError.
507
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
508
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
509
+ if (
510
+ webidl.util.Type(V) !== 'Object' ||
511
+ !types.isAnyArrayBuffer(V)
512
+ ) {
513
+ throw webidl.errors.conversionFailed({
514
+ prefix: `${V}`,
515
+ argument: `${V}`,
516
+ types: ['ArrayBuffer']
517
+ })
518
+ }
519
+
520
+ // 2. If the conversion is not to an IDL type associated
521
+ // with the [AllowShared] extended attribute, and
522
+ // IsSharedArrayBuffer(V) is true, then throw a
523
+ // TypeError.
524
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
525
+ throw webidl.errors.exception({
526
+ header: 'ArrayBuffer',
527
+ message: 'SharedArrayBuffer is not allowed.'
528
+ })
529
+ }
530
+
531
+ // 3. If the conversion is not to an IDL type associated
532
+ // with the [AllowResizable] extended attribute, and
533
+ // IsResizableArrayBuffer(V) is true, then throw a
534
+ // TypeError.
535
+ // Note: resizable ArrayBuffers are currently a proposal.
536
+
537
+ // 4. Return the IDL ArrayBuffer value that is a
538
+ // reference to the same object as V.
539
+ return V
540
+ }
541
+
542
+ webidl.converters.TypedArray = function (V, T, opts = {}) {
543
+ // 1. Let T be the IDL type V is being converted to.
544
+
545
+ // 2. If Type(V) is not Object, or V does not have a
546
+ // [[TypedArrayName]] internal slot with a value
547
+ // equal to T’s name, then throw a TypeError.
548
+ if (
549
+ webidl.util.Type(V) !== 'Object' ||
550
+ !types.isTypedArray(V) ||
551
+ V.constructor.name !== T.name
552
+ ) {
553
+ throw webidl.errors.conversionFailed({
554
+ prefix: `${T.name}`,
555
+ argument: `${V}`,
556
+ types: [T.name]
557
+ })
558
+ }
559
+
560
+ // 3. If the conversion is not to an IDL type associated
561
+ // with the [AllowShared] extended attribute, and
562
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
563
+ // true, then throw a TypeError.
564
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
565
+ throw webidl.errors.exception({
566
+ header: 'ArrayBuffer',
567
+ message: 'SharedArrayBuffer is not allowed.'
568
+ })
569
+ }
570
+
571
+ // 4. If the conversion is not to an IDL type associated
572
+ // with the [AllowResizable] extended attribute, and
573
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
574
+ // true, then throw a TypeError.
575
+ // Note: resizable array buffers are currently a proposal
576
+
577
+ // 5. Return the IDL value of type T that is a reference
578
+ // to the same object as V.
579
+ return V
580
+ }
581
+
582
+ webidl.converters.DataView = function (V, opts = {}) {
583
+ // 1. If Type(V) is not Object, or V does not have a
584
+ // [[DataView]] internal slot, then throw a TypeError.
585
+ if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
586
+ throw webidl.errors.exception({
587
+ header: 'DataView',
588
+ message: 'Object is not a DataView.'
589
+ })
590
+ }
591
+
592
+ // 2. If the conversion is not to an IDL type associated
593
+ // with the [AllowShared] extended attribute, and
594
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
595
+ // then throw a TypeError.
596
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
597
+ throw webidl.errors.exception({
598
+ header: 'ArrayBuffer',
599
+ message: 'SharedArrayBuffer is not allowed.'
600
+ })
601
+ }
602
+
603
+ // 3. If the conversion is not to an IDL type associated
604
+ // with the [AllowResizable] extended attribute, and
605
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
606
+ // true, then throw a TypeError.
607
+ // Note: resizable ArrayBuffers are currently a proposal
608
+
609
+ // 4. Return the IDL DataView value that is a reference
610
+ // to the same object as V.
611
+ return V
612
+ }
613
+
614
+ // https://webidl.spec.whatwg.org/#BufferSource
615
+ webidl.converters.BufferSource = function (V, opts = {}) {
616
+ if (types.isAnyArrayBuffer(V)) {
617
+ return webidl.converters.ArrayBuffer(V, opts)
618
+ }
619
+
620
+ if (types.isTypedArray(V)) {
621
+ return webidl.converters.TypedArray(V, V.constructor)
622
+ }
623
+
624
+ if (types.isDataView(V)) {
625
+ return webidl.converters.DataView(V, opts)
626
+ }
627
+
628
+ throw new TypeError(`Could not convert ${V} to a BufferSource.`)
629
+ }
630
+
631
+ webidl.converters['sequence<ByteString>'] = webidl.sequenceConverter(
632
+ webidl.converters.ByteString
633
+ )
634
+
635
+ webidl.converters['sequence<sequence<ByteString>>'] = webidl.sequenceConverter(
636
+ webidl.converters['sequence<ByteString>']
637
+ )
638
+
639
+ webidl.converters['record<ByteString, ByteString>'] = webidl.recordConverter(
640
+ webidl.converters.ByteString,
641
+ webidl.converters.ByteString
642
+ )
643
+
644
+ module.exports = {
645
+ webidl
646
+ }
worker/node_modules/undici/lib/fileapi/encoding.js ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ /**
4
+ * @see https://encoding.spec.whatwg.org/#concept-encoding-get
5
+ * @param {string|undefined} label
6
+ */
7
+ function getEncoding (label) {
8
+ if (!label) {
9
+ return 'failure'
10
+ }
11
+
12
+ // 1. Remove any leading and trailing ASCII whitespace from label.
13
+ // 2. If label is an ASCII case-insensitive match for any of the
14
+ // labels listed in the table below, then return the
15
+ // corresponding encoding; otherwise return failure.
16
+ switch (label.trim().toLowerCase()) {
17
+ case 'unicode-1-1-utf-8':
18
+ case 'unicode11utf8':
19
+ case 'unicode20utf8':
20
+ case 'utf-8':
21
+ case 'utf8':
22
+ case 'x-unicode20utf8':
23
+ return 'UTF-8'
24
+ case '866':
25
+ case 'cp866':
26
+ case 'csibm866':
27
+ case 'ibm866':
28
+ return 'IBM866'
29
+ case 'csisolatin2':
30
+ case 'iso-8859-2':
31
+ case 'iso-ir-101':
32
+ case 'iso8859-2':
33
+ case 'iso88592':
34
+ case 'iso_8859-2':
35
+ case 'iso_8859-2:1987':
36
+ case 'l2':
37
+ case 'latin2':
38
+ return 'ISO-8859-2'
39
+ case 'csisolatin3':
40
+ case 'iso-8859-3':
41
+ case 'iso-ir-109':
42
+ case 'iso8859-3':
43
+ case 'iso88593':
44
+ case 'iso_8859-3':
45
+ case 'iso_8859-3:1988':
46
+ case 'l3':
47
+ case 'latin3':
48
+ return 'ISO-8859-3'
49
+ case 'csisolatin4':
50
+ case 'iso-8859-4':
51
+ case 'iso-ir-110':
52
+ case 'iso8859-4':
53
+ case 'iso88594':
54
+ case 'iso_8859-4':
55
+ case 'iso_8859-4:1988':
56
+ case 'l4':
57
+ case 'latin4':
58
+ return 'ISO-8859-4'
59
+ case 'csisolatincyrillic':
60
+ case 'cyrillic':
61
+ case 'iso-8859-5':
62
+ case 'iso-ir-144':
63
+ case 'iso8859-5':
64
+ case 'iso88595':
65
+ case 'iso_8859-5':
66
+ case 'iso_8859-5:1988':
67
+ return 'ISO-8859-5'
68
+ case 'arabic':
69
+ case 'asmo-708':
70
+ case 'csiso88596e':
71
+ case 'csiso88596i':
72
+ case 'csisolatinarabic':
73
+ case 'ecma-114':
74
+ case 'iso-8859-6':
75
+ case 'iso-8859-6-e':
76
+ case 'iso-8859-6-i':
77
+ case 'iso-ir-127':
78
+ case 'iso8859-6':
79
+ case 'iso88596':
80
+ case 'iso_8859-6':
81
+ case 'iso_8859-6:1987':
82
+ return 'ISO-8859-6'
83
+ case 'csisolatingreek':
84
+ case 'ecma-118':
85
+ case 'elot_928':
86
+ case 'greek':
87
+ case 'greek8':
88
+ case 'iso-8859-7':
89
+ case 'iso-ir-126':
90
+ case 'iso8859-7':
91
+ case 'iso88597':
92
+ case 'iso_8859-7':
93
+ case 'iso_8859-7:1987':
94
+ case 'sun_eu_greek':
95
+ return 'ISO-8859-7'
96
+ case 'csiso88598e':
97
+ case 'csisolatinhebrew':
98
+ case 'hebrew':
99
+ case 'iso-8859-8':
100
+ case 'iso-8859-8-e':
101
+ case 'iso-ir-138':
102
+ case 'iso8859-8':
103
+ case 'iso88598':
104
+ case 'iso_8859-8':
105
+ case 'iso_8859-8:1988':
106
+ case 'visual':
107
+ return 'ISO-8859-8'
108
+ case 'csiso88598i':
109
+ case 'iso-8859-8-i':
110
+ case 'logical':
111
+ return 'ISO-8859-8-I'
112
+ case 'csisolatin6':
113
+ case 'iso-8859-10':
114
+ case 'iso-ir-157':
115
+ case 'iso8859-10':
116
+ case 'iso885910':
117
+ case 'l6':
118
+ case 'latin6':
119
+ return 'ISO-8859-10'
120
+ case 'iso-8859-13':
121
+ case 'iso8859-13':
122
+ case 'iso885913':
123
+ return 'ISO-8859-13'
124
+ case 'iso-8859-14':
125
+ case 'iso8859-14':
126
+ case 'iso885914':
127
+ return 'ISO-8859-14'
128
+ case 'csisolatin9':
129
+ case 'iso-8859-15':
130
+ case 'iso8859-15':
131
+ case 'iso885915':
132
+ case 'iso_8859-15':
133
+ case 'l9':
134
+ return 'ISO-8859-15'
135
+ case 'iso-8859-16':
136
+ return 'ISO-8859-16'
137
+ case 'cskoi8r':
138
+ case 'koi':
139
+ case 'koi8':
140
+ case 'koi8-r':
141
+ case 'koi8_r':
142
+ return 'KOI8-R'
143
+ case 'koi8-ru':
144
+ case 'koi8-u':
145
+ return 'KOI8-U'
146
+ case 'csmacintosh':
147
+ case 'mac':
148
+ case 'macintosh':
149
+ case 'x-mac-roman':
150
+ return 'macintosh'
151
+ case 'iso-8859-11':
152
+ case 'iso8859-11':
153
+ case 'iso885911':
154
+ case 'tis-620':
155
+ case 'windows-874':
156
+ return 'windows-874'
157
+ case 'cp1250':
158
+ case 'windows-1250':
159
+ case 'x-cp1250':
160
+ return 'windows-1250'
161
+ case 'cp1251':
162
+ case 'windows-1251':
163
+ case 'x-cp1251':
164
+ return 'windows-1251'
165
+ case 'ansi_x3.4-1968':
166
+ case 'ascii':
167
+ case 'cp1252':
168
+ case 'cp819':
169
+ case 'csisolatin1':
170
+ case 'ibm819':
171
+ case 'iso-8859-1':
172
+ case 'iso-ir-100':
173
+ case 'iso8859-1':
174
+ case 'iso88591':
175
+ case 'iso_8859-1':
176
+ case 'iso_8859-1:1987':
177
+ case 'l1':
178
+ case 'latin1':
179
+ case 'us-ascii':
180
+ case 'windows-1252':
181
+ case 'x-cp1252':
182
+ return 'windows-1252'
183
+ case 'cp1253':
184
+ case 'windows-1253':
185
+ case 'x-cp1253':
186
+ return 'windows-1253'
187
+ case 'cp1254':
188
+ case 'csisolatin5':
189
+ case 'iso-8859-9':
190
+ case 'iso-ir-148':
191
+ case 'iso8859-9':
192
+ case 'iso88599':
193
+ case 'iso_8859-9':
194
+ case 'iso_8859-9:1989':
195
+ case 'l5':
196
+ case 'latin5':
197
+ case 'windows-1254':
198
+ case 'x-cp1254':
199
+ return 'windows-1254'
200
+ case 'cp1255':
201
+ case 'windows-1255':
202
+ case 'x-cp1255':
203
+ return 'windows-1255'
204
+ case 'cp1256':
205
+ case 'windows-1256':
206
+ case 'x-cp1256':
207
+ return 'windows-1256'
208
+ case 'cp1257':
209
+ case 'windows-1257':
210
+ case 'x-cp1257':
211
+ return 'windows-1257'
212
+ case 'cp1258':
213
+ case 'windows-1258':
214
+ case 'x-cp1258':
215
+ return 'windows-1258'
216
+ case 'x-mac-cyrillic':
217
+ case 'x-mac-ukrainian':
218
+ return 'x-mac-cyrillic'
219
+ case 'chinese':
220
+ case 'csgb2312':
221
+ case 'csiso58gb231280':
222
+ case 'gb2312':
223
+ case 'gb_2312':
224
+ case 'gb_2312-80':
225
+ case 'gbk':
226
+ case 'iso-ir-58':
227
+ case 'x-gbk':
228
+ return 'GBK'
229
+ case 'gb18030':
230
+ return 'gb18030'
231
+ case 'big5':
232
+ case 'big5-hkscs':
233
+ case 'cn-big5':
234
+ case 'csbig5':
235
+ case 'x-x-big5':
236
+ return 'Big5'
237
+ case 'cseucpkdfmtjapanese':
238
+ case 'euc-jp':
239
+ case 'x-euc-jp':
240
+ return 'EUC-JP'
241
+ case 'csiso2022jp':
242
+ case 'iso-2022-jp':
243
+ return 'ISO-2022-JP'
244
+ case 'csshiftjis':
245
+ case 'ms932':
246
+ case 'ms_kanji':
247
+ case 'shift-jis':
248
+ case 'shift_jis':
249
+ case 'sjis':
250
+ case 'windows-31j':
251
+ case 'x-sjis':
252
+ return 'Shift_JIS'
253
+ case 'cseuckr':
254
+ case 'csksc56011987':
255
+ case 'euc-kr':
256
+ case 'iso-ir-149':
257
+ case 'korean':
258
+ case 'ks_c_5601-1987':
259
+ case 'ks_c_5601-1989':
260
+ case 'ksc5601':
261
+ case 'ksc_5601':
262
+ case 'windows-949':
263
+ return 'EUC-KR'
264
+ case 'csiso2022kr':
265
+ case 'hz-gb-2312':
266
+ case 'iso-2022-cn':
267
+ case 'iso-2022-cn-ext':
268
+ case 'iso-2022-kr':
269
+ case 'replacement':
270
+ return 'replacement'
271
+ case 'unicodefffe':
272
+ case 'utf-16be':
273
+ return 'UTF-16BE'
274
+ case 'csunicode':
275
+ case 'iso-10646-ucs-2':
276
+ case 'ucs-2':
277
+ case 'unicode':
278
+ case 'unicodefeff':
279
+ case 'utf-16':
280
+ case 'utf-16le':
281
+ return 'UTF-16LE'
282
+ case 'x-user-defined':
283
+ return 'x-user-defined'
284
+ default: return 'failure'
285
+ }
286
+ }
287
+
288
+ module.exports = {
289
+ getEncoding
290
+ }
worker/node_modules/undici/lib/fileapi/filereader.js ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const {
4
+ staticPropertyDescriptors,
5
+ readOperation,
6
+ fireAProgressEvent
7
+ } = require('./util')
8
+ const {
9
+ kState,
10
+ kError,
11
+ kResult,
12
+ kEvents,
13
+ kAborted
14
+ } = require('./symbols')
15
+ const { webidl } = require('../fetch/webidl')
16
+ const { kEnumerableProperty } = require('../core/util')
17
+
18
+ class FileReader extends EventTarget {
19
+ constructor () {
20
+ super()
21
+
22
+ this[kState] = 'empty'
23
+ this[kResult] = null
24
+ this[kError] = null
25
+ this[kEvents] = {
26
+ loadend: null,
27
+ error: null,
28
+ abort: null,
29
+ load: null,
30
+ progress: null,
31
+ loadstart: null
32
+ }
33
+ }
34
+
35
+ /**
36
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
37
+ * @param {import('buffer').Blob} blob
38
+ */
39
+ readAsArrayBuffer (blob) {
40
+ webidl.brandCheck(this, FileReader)
41
+
42
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
43
+
44
+ blob = webidl.converters.Blob(blob, { strict: false })
45
+
46
+ // The readAsArrayBuffer(blob) method, when invoked,
47
+ // must initiate a read operation for blob with ArrayBuffer.
48
+ readOperation(this, blob, 'ArrayBuffer')
49
+ }
50
+
51
+ /**
52
+ * @see https://w3c.github.io/FileAPI/#readAsBinaryString
53
+ * @param {import('buffer').Blob} blob
54
+ */
55
+ readAsBinaryString (blob) {
56
+ webidl.brandCheck(this, FileReader)
57
+
58
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
59
+
60
+ blob = webidl.converters.Blob(blob, { strict: false })
61
+
62
+ // The readAsBinaryString(blob) method, when invoked,
63
+ // must initiate a read operation for blob with BinaryString.
64
+ readOperation(this, blob, 'BinaryString')
65
+ }
66
+
67
+ /**
68
+ * @see https://w3c.github.io/FileAPI/#readAsDataText
69
+ * @param {import('buffer').Blob} blob
70
+ * @param {string?} encoding
71
+ */
72
+ readAsText (blob, encoding = undefined) {
73
+ webidl.brandCheck(this, FileReader)
74
+
75
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
76
+
77
+ blob = webidl.converters.Blob(blob, { strict: false })
78
+
79
+ if (encoding !== undefined) {
80
+ encoding = webidl.converters.DOMString(encoding)
81
+ }
82
+
83
+ // The readAsText(blob, encoding) method, when invoked,
84
+ // must initiate a read operation for blob with Text and encoding.
85
+ readOperation(this, blob, 'Text', encoding)
86
+ }
87
+
88
+ /**
89
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
90
+ * @param {import('buffer').Blob} blob
91
+ */
92
+ readAsDataURL (blob) {
93
+ webidl.brandCheck(this, FileReader)
94
+
95
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
96
+
97
+ blob = webidl.converters.Blob(blob, { strict: false })
98
+
99
+ // The readAsDataURL(blob) method, when invoked, must
100
+ // initiate a read operation for blob with DataURL.
101
+ readOperation(this, blob, 'DataURL')
102
+ }
103
+
104
+ /**
105
+ * @see https://w3c.github.io/FileAPI/#dfn-abort
106
+ */
107
+ abort () {
108
+ // 1. If this's state is "empty" or if this's state is
109
+ // "done" set this's result to null and terminate
110
+ // this algorithm.
111
+ if (this[kState] === 'empty' || this[kState] === 'done') {
112
+ this[kResult] = null
113
+ return
114
+ }
115
+
116
+ // 2. If this's state is "loading" set this's state to
117
+ // "done" and set this's result to null.
118
+ if (this[kState] === 'loading') {
119
+ this[kState] = 'done'
120
+ this[kResult] = null
121
+ }
122
+
123
+ // 3. If there are any tasks from this on the file reading
124
+ // task source in an affiliated task queue, then remove
125
+ // those tasks from that task queue.
126
+ this[kAborted] = true
127
+
128
+ // 4. Terminate the algorithm for the read method being processed.
129
+ // TODO
130
+
131
+ // 5. Fire a progress event called abort at this.
132
+ fireAProgressEvent('abort', this)
133
+
134
+ // 6. If this's state is not "loading", fire a progress
135
+ // event called loadend at this.
136
+ if (this[kState] !== 'loading') {
137
+ fireAProgressEvent('loadend', this)
138
+ }
139
+ }
140
+
141
+ /**
142
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
143
+ */
144
+ get readyState () {
145
+ webidl.brandCheck(this, FileReader)
146
+
147
+ switch (this[kState]) {
148
+ case 'empty': return this.EMPTY
149
+ case 'loading': return this.LOADING
150
+ case 'done': return this.DONE
151
+ }
152
+ }
153
+
154
+ /**
155
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-result
156
+ */
157
+ get result () {
158
+ webidl.brandCheck(this, FileReader)
159
+
160
+ // The result attribute’s getter, when invoked, must return
161
+ // this's result.
162
+ return this[kResult]
163
+ }
164
+
165
+ /**
166
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-error
167
+ */
168
+ get error () {
169
+ webidl.brandCheck(this, FileReader)
170
+
171
+ // The error attribute’s getter, when invoked, must return
172
+ // this's error.
173
+ return this[kError]
174
+ }
175
+
176
+ get onloadend () {
177
+ webidl.brandCheck(this, FileReader)
178
+
179
+ return this[kEvents].loadend
180
+ }
181
+
182
+ set onloadend (fn) {
183
+ webidl.brandCheck(this, FileReader)
184
+
185
+ if (this[kEvents].loadend) {
186
+ this.removeEventListener('loadend', this[kEvents].loadend)
187
+ }
188
+
189
+ if (typeof fn === 'function') {
190
+ this[kEvents].loadend = fn
191
+ this.addEventListener('loadend', fn)
192
+ } else {
193
+ this[kEvents].loadend = null
194
+ }
195
+ }
196
+
197
+ get onerror () {
198
+ webidl.brandCheck(this, FileReader)
199
+
200
+ return this[kEvents].error
201
+ }
202
+
203
+ set onerror (fn) {
204
+ webidl.brandCheck(this, FileReader)
205
+
206
+ if (this[kEvents].error) {
207
+ this.removeEventListener('error', this[kEvents].error)
208
+ }
209
+
210
+ if (typeof fn === 'function') {
211
+ this[kEvents].error = fn
212
+ this.addEventListener('error', fn)
213
+ } else {
214
+ this[kEvents].error = null
215
+ }
216
+ }
217
+
218
+ get onloadstart () {
219
+ webidl.brandCheck(this, FileReader)
220
+
221
+ return this[kEvents].loadstart
222
+ }
223
+
224
+ set onloadstart (fn) {
225
+ webidl.brandCheck(this, FileReader)
226
+
227
+ if (this[kEvents].loadstart) {
228
+ this.removeEventListener('loadstart', this[kEvents].loadstart)
229
+ }
230
+
231
+ if (typeof fn === 'function') {
232
+ this[kEvents].loadstart = fn
233
+ this.addEventListener('loadstart', fn)
234
+ } else {
235
+ this[kEvents].loadstart = null
236
+ }
237
+ }
238
+
239
+ get onprogress () {
240
+ webidl.brandCheck(this, FileReader)
241
+
242
+ return this[kEvents].progress
243
+ }
244
+
245
+ set onprogress (fn) {
246
+ webidl.brandCheck(this, FileReader)
247
+
248
+ if (this[kEvents].progress) {
249
+ this.removeEventListener('progress', this[kEvents].progress)
250
+ }
251
+
252
+ if (typeof fn === 'function') {
253
+ this[kEvents].progress = fn
254
+ this.addEventListener('progress', fn)
255
+ } else {
256
+ this[kEvents].progress = null
257
+ }
258
+ }
259
+
260
+ get onload () {
261
+ webidl.brandCheck(this, FileReader)
262
+
263
+ return this[kEvents].load
264
+ }
265
+
266
+ set onload (fn) {
267
+ webidl.brandCheck(this, FileReader)
268
+
269
+ if (this[kEvents].load) {
270
+ this.removeEventListener('load', this[kEvents].load)
271
+ }
272
+
273
+ if (typeof fn === 'function') {
274
+ this[kEvents].load = fn
275
+ this.addEventListener('load', fn)
276
+ } else {
277
+ this[kEvents].load = null
278
+ }
279
+ }
280
+
281
+ get onabort () {
282
+ webidl.brandCheck(this, FileReader)
283
+
284
+ return this[kEvents].abort
285
+ }
286
+
287
+ set onabort (fn) {
288
+ webidl.brandCheck(this, FileReader)
289
+
290
+ if (this[kEvents].abort) {
291
+ this.removeEventListener('abort', this[kEvents].abort)
292
+ }
293
+
294
+ if (typeof fn === 'function') {
295
+ this[kEvents].abort = fn
296
+ this.addEventListener('abort', fn)
297
+ } else {
298
+ this[kEvents].abort = null
299
+ }
300
+ }
301
+ }
302
+
303
+ // https://w3c.github.io/FileAPI/#dom-filereader-empty
304
+ FileReader.EMPTY = FileReader.prototype.EMPTY = 0
305
+ // https://w3c.github.io/FileAPI/#dom-filereader-loading
306
+ FileReader.LOADING = FileReader.prototype.LOADING = 1
307
+ // https://w3c.github.io/FileAPI/#dom-filereader-done
308
+ FileReader.DONE = FileReader.prototype.DONE = 2
309
+
310
+ Object.defineProperties(FileReader.prototype, {
311
+ EMPTY: staticPropertyDescriptors,
312
+ LOADING: staticPropertyDescriptors,
313
+ DONE: staticPropertyDescriptors,
314
+ readAsArrayBuffer: kEnumerableProperty,
315
+ readAsBinaryString: kEnumerableProperty,
316
+ readAsText: kEnumerableProperty,
317
+ readAsDataURL: kEnumerableProperty,
318
+ abort: kEnumerableProperty,
319
+ readyState: kEnumerableProperty,
320
+ result: kEnumerableProperty,
321
+ error: kEnumerableProperty,
322
+ onloadstart: kEnumerableProperty,
323
+ onprogress: kEnumerableProperty,
324
+ onload: kEnumerableProperty,
325
+ onabort: kEnumerableProperty,
326
+ onerror: kEnumerableProperty,
327
+ onloadend: kEnumerableProperty,
328
+ [Symbol.toStringTag]: {
329
+ value: 'FileReader',
330
+ writable: false,
331
+ enumerable: false,
332
+ configurable: true
333
+ }
334
+ })
335
+
336
+ Object.defineProperties(FileReader, {
337
+ EMPTY: staticPropertyDescriptors,
338
+ LOADING: staticPropertyDescriptors,
339
+ DONE: staticPropertyDescriptors
340
+ })
341
+
342
+ module.exports = {
343
+ FileReader
344
+ }
worker/node_modules/undici/lib/fileapi/progressevent.js ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const { webidl } = require('../fetch/webidl')
4
+
5
+ const kState = Symbol('ProgressEvent state')
6
+
7
+ /**
8
+ * @see https://xhr.spec.whatwg.org/#progressevent
9
+ */
10
+ class ProgressEvent extends Event {
11
+ constructor (type, eventInitDict = {}) {
12
+ type = webidl.converters.DOMString(type)
13
+ eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
14
+
15
+ super(type, eventInitDict)
16
+
17
+ this[kState] = {
18
+ lengthComputable: eventInitDict.lengthComputable,
19
+ loaded: eventInitDict.loaded,
20
+ total: eventInitDict.total
21
+ }
22
+ }
23
+
24
+ get lengthComputable () {
25
+ webidl.brandCheck(this, ProgressEvent)
26
+
27
+ return this[kState].lengthComputable
28
+ }
29
+
30
+ get loaded () {
31
+ webidl.brandCheck(this, ProgressEvent)
32
+
33
+ return this[kState].loaded
34
+ }
35
+
36
+ get total () {
37
+ webidl.brandCheck(this, ProgressEvent)
38
+
39
+ return this[kState].total
40
+ }
41
+ }
42
+
43
+ webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
44
+ {
45
+ key: 'lengthComputable',
46
+ converter: webidl.converters.boolean,
47
+ defaultValue: false
48
+ },
49
+ {
50
+ key: 'loaded',
51
+ converter: webidl.converters['unsigned long long'],
52
+ defaultValue: 0
53
+ },
54
+ {
55
+ key: 'total',
56
+ converter: webidl.converters['unsigned long long'],
57
+ defaultValue: 0
58
+ },
59
+ {
60
+ key: 'bubbles',
61
+ converter: webidl.converters.boolean,
62
+ defaultValue: false
63
+ },
64
+ {
65
+ key: 'cancelable',
66
+ converter: webidl.converters.boolean,
67
+ defaultValue: false
68
+ },
69
+ {
70
+ key: 'composed',
71
+ converter: webidl.converters.boolean,
72
+ defaultValue: false
73
+ }
74
+ ])
75
+
76
+ module.exports = {
77
+ ProgressEvent
78
+ }
worker/node_modules/undici/lib/fileapi/symbols.js ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ module.exports = {
4
+ kState: Symbol('FileReader state'),
5
+ kResult: Symbol('FileReader result'),
6
+ kError: Symbol('FileReader error'),
7
+ kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
8
+ kEvents: Symbol('FileReader events'),
9
+ kAborted: Symbol('FileReader aborted')
10
+ }
worker/node_modules/undici/lib/fileapi/util.js ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ const {
4
+ kState,
5
+ kError,
6
+ kResult,
7
+ kAborted,
8
+ kLastProgressEventFired
9
+ } = require('./symbols')
10
+ const { ProgressEvent } = require('./progressevent')
11
+ const { getEncoding } = require('./encoding')
12
+ const { DOMException } = require('../fetch/constants')
13
+ const { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL')
14
+ const { types } = require('util')
15
+ const { StringDecoder } = require('string_decoder')
16
+ const { btoa } = require('buffer')
17
+
18
+ /** @type {PropertyDescriptor} */
19
+ const staticPropertyDescriptors = {
20
+ enumerable: true,
21
+ writable: false,
22
+ configurable: false
23
+ }
24
+
25
+ /**
26
+ * @see https://w3c.github.io/FileAPI/#readOperation
27
+ * @param {import('./filereader').FileReader} fr
28
+ * @param {import('buffer').Blob} blob
29
+ * @param {string} type
30
+ * @param {string?} encodingName
31
+ */
32
+ function readOperation (fr, blob, type, encodingName) {
33
+ // 1. If fr’s state is "loading", throw an InvalidStateError
34
+ // DOMException.
35
+ if (fr[kState] === 'loading') {
36
+ throw new DOMException('Invalid state', 'InvalidStateError')
37
+ }
38
+
39
+ // 2. Set fr’s state to "loading".
40
+ fr[kState] = 'loading'
41
+
42
+ // 3. Set fr’s result to null.
43
+ fr[kResult] = null
44
+
45
+ // 4. Set fr’s error to null.
46
+ fr[kError] = null
47
+
48
+ // 5. Let stream be the result of calling get stream on blob.
49
+ /** @type {import('stream/web').ReadableStream} */
50
+ const stream = blob.stream()
51
+
52
+ // 6. Let reader be the result of getting a reader from stream.
53
+ const reader = stream.getReader()
54
+
55
+ // 7. Let bytes be an empty byte sequence.
56
+ /** @type {Uint8Array[]} */
57
+ const bytes = []
58
+
59
+ // 8. Let chunkPromise be the result of reading a chunk from
60
+ // stream with reader.
61
+ let chunkPromise = reader.read()
62
+
63
+ // 9. Let isFirstChunk be true.
64
+ let isFirstChunk = true
65
+
66
+ // 10. In parallel, while true:
67
+ // Note: "In parallel" just means non-blocking
68
+ // Note 2: readOperation itself cannot be async as double
69
+ // reading the body would then reject the promise, instead
70
+ // of throwing an error.
71
+ ;(async () => {
72
+ while (!fr[kAborted]) {
73
+ // 1. Wait for chunkPromise to be fulfilled or rejected.
74
+ try {
75
+ const { done, value } = await chunkPromise
76
+
77
+ // 2. If chunkPromise is fulfilled, and isFirstChunk is
78
+ // true, queue a task to fire a progress event called
79
+ // loadstart at fr.
80
+ if (isFirstChunk && !fr[kAborted]) {
81
+ queueMicrotask(() => {
82
+ fireAProgressEvent('loadstart', fr)
83
+ })
84
+ }
85
+
86
+ // 3. Set isFirstChunk to false.
87
+ isFirstChunk = false
88
+
89
+ // 4. If chunkPromise is fulfilled with an object whose
90
+ // done property is false and whose value property is
91
+ // a Uint8Array object, run these steps:
92
+ if (!done && types.isUint8Array(value)) {
93
+ // 1. Let bs be the byte sequence represented by the
94
+ // Uint8Array object.
95
+
96
+ // 2. Append bs to bytes.
97
+ bytes.push(value)
98
+
99
+ // 3. If roughly 50ms have passed since these steps
100
+ // were last invoked, queue a task to fire a
101
+ // progress event called progress at fr.
102
+ if (
103
+ (
104
+ fr[kLastProgressEventFired] === undefined ||
105
+ Date.now() - fr[kLastProgressEventFired] >= 50
106
+ ) &&
107
+ !fr[kAborted]
108
+ ) {
109
+ fr[kLastProgressEventFired] = Date.now()
110
+ queueMicrotask(() => {
111
+ fireAProgressEvent('progress', fr)
112
+ })
113
+ }
114
+
115
+ // 4. Set chunkPromise to the result of reading a
116
+ // chunk from stream with reader.
117
+ chunkPromise = reader.read()
118
+ } else if (done) {
119
+ // 5. Otherwise, if chunkPromise is fulfilled with an
120
+ // object whose done property is true, queue a task
121
+ // to run the following steps and abort this algorithm:
122
+ queueMicrotask(() => {
123
+ // 1. Set fr’s state to "done".
124
+ fr[kState] = 'done'
125
+
126
+ // 2. Let result be the result of package data given
127
+ // bytes, type, blob’s type, and encodingName.
128
+ try {
129
+ const result = packageData(bytes, type, blob.type, encodingName)
130
+
131
+ // 4. Else:
132
+
133
+ if (fr[kAborted]) {
134
+ return
135
+ }
136
+
137
+ // 1. Set fr’s result to result.
138
+ fr[kResult] = result
139
+
140
+ // 2. Fire a progress event called load at the fr.
141
+ fireAProgressEvent('load', fr)
142
+ } catch (error) {
143
+ // 3. If package data threw an exception error:
144
+
145
+ // 1. Set fr’s error to error.
146
+ fr[kError] = error
147
+
148
+ // 2. Fire a progress event called error at fr.
149
+ fireAProgressEvent('error', fr)
150
+ }
151
+
152
+ // 5. If fr’s state is not "loading", fire a progress
153
+ // event called loadend at the fr.
154
+ if (fr[kState] !== 'loading') {
155
+ fireAProgressEvent('loadend', fr)
156
+ }
157
+ })
158
+
159
+ break
160
+ }
161
+ } catch (error) {
162
+ if (fr[kAborted]) {
163
+ return
164
+ }
165
+
166
+ // 6. Otherwise, if chunkPromise is rejected with an
167
+ // error error, queue a task to run the following
168
+ // steps and abort this algorithm:
169
+ queueMicrotask(() => {
170
+ // 1. Set fr’s state to "done".
171
+ fr[kState] = 'done'
172
+
173
+ // 2. Set fr’s error to error.
174
+ fr[kError] = error
175
+
176
+ // 3. Fire a progress event called error at fr.
177
+ fireAProgressEvent('error', fr)
178
+
179
+ // 4. If fr’s state is not "loading", fire a progress
180
+ // event called loadend at fr.
181
+ if (fr[kState] !== 'loading') {
182
+ fireAProgressEvent('loadend', fr)
183
+ }
184
+ })
185
+
186
+ break
187
+ }
188
+ }
189
+ })()
190
+ }
191
+
192
+ /**
193
+ * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
194
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
195
+ * @param {string} e The name of the event
196
+ * @param {import('./filereader').FileReader} reader
197
+ */
198
+ function fireAProgressEvent (e, reader) {
199
+ // The progress event e does not bubble. e.bubbles must be false
200
+ // The progress event e is NOT cancelable. e.cancelable must be false
201
+ const event = new ProgressEvent(e, {
202
+ bubbles: false,
203
+ cancelable: false
204
+ })
205
+
206
+ reader.dispatchEvent(event)
207
+ }
208
+
209
+ /**
210
+ * @see https://w3c.github.io/FileAPI/#blob-package-data
211
+ * @param {Uint8Array[]} bytes
212
+ * @param {string} type
213
+ * @param {string?} mimeType
214
+ * @param {string?} encodingName
215
+ */
216
+ function packageData (bytes, type, mimeType, encodingName) {
217
+ // 1. A Blob has an associated package data algorithm, given
218
+ // bytes, a type, a optional mimeType, and a optional
219
+ // encodingName, which switches on type and runs the
220
+ // associated steps:
221
+
222
+ switch (type) {
223
+ case 'DataURL': {
224
+ // 1. Return bytes as a DataURL [RFC2397] subject to
225
+ // the considerations below:
226
+ // * Use mimeType as part of the Data URL if it is
227
+ // available in keeping with the Data URL
228
+ // specification [RFC2397].
229
+ // * If mimeType is not available return a Data URL
230
+ // without a media-type. [RFC2397].
231
+
232
+ // https://datatracker.ietf.org/doc/html/rfc2397#section-3
233
+ // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
234
+ // mediatype := [ type "/" subtype ] *( ";" parameter )
235
+ // data := *urlchar
236
+ // parameter := attribute "=" value
237
+ let dataURL = 'data:'
238
+
239
+ const parsed = parseMIMEType(mimeType || 'application/octet-stream')
240
+
241
+ if (parsed !== 'failure') {
242
+ dataURL += serializeAMimeType(parsed)
243
+ }
244
+
245
+ dataURL += ';base64,'
246
+
247
+ const decoder = new StringDecoder('latin1')
248
+
249
+ for (const chunk of bytes) {
250
+ dataURL += btoa(decoder.write(chunk))
251
+ }
252
+
253
+ dataURL += btoa(decoder.end())
254
+
255
+ return dataURL
256
+ }
257
+ case 'Text': {
258
+ // 1. Let encoding be failure
259
+ let encoding = 'failure'
260
+
261
+ // 2. If the encodingName is present, set encoding to the
262
+ // result of getting an encoding from encodingName.
263
+ if (encodingName) {
264
+ encoding = getEncoding(encodingName)
265
+ }
266
+
267
+ // 3. If encoding is failure, and mimeType is present:
268
+ if (encoding === 'failure' && mimeType) {
269
+ // 1. Let type be the result of parse a MIME type
270
+ // given mimeType.
271
+ const type = parseMIMEType(mimeType)
272
+
273
+ // 2. If type is not failure, set encoding to the result
274
+ // of getting an encoding from type’s parameters["charset"].
275
+ if (type !== 'failure') {
276
+ encoding = getEncoding(type.parameters.get('charset'))
277
+ }
278
+ }
279
+
280
+ // 4. If encoding is failure, then set encoding to UTF-8.
281
+ if (encoding === 'failure') {
282
+ encoding = 'UTF-8'
283
+ }
284
+
285
+ // 5. Decode bytes using fallback encoding encoding, and
286
+ // return the result.
287
+ return decode(bytes, encoding)
288
+ }
289
+ case 'ArrayBuffer': {
290
+ // Return a new ArrayBuffer whose contents are bytes.
291
+ const sequence = combineByteSequences(bytes)
292
+
293
+ return sequence.buffer
294
+ }
295
+ case 'BinaryString': {
296
+ // Return bytes as a binary string, in which every byte
297
+ // is represented by a code unit of equal value [0..255].
298
+ let binaryString = ''
299
+
300
+ const decoder = new StringDecoder('latin1')
301
+
302
+ for (const chunk of bytes) {
303
+ binaryString += decoder.write(chunk)
304
+ }
305
+
306
+ binaryString += decoder.end()
307
+
308
+ return binaryString
309
+ }
310
+ }
311
+ }
312
+
313
+ /**
314
+ * @see https://encoding.spec.whatwg.org/#decode
315
+ * @param {Uint8Array[]} ioQueue
316
+ * @param {string} encoding
317
+ */
318
+ function decode (ioQueue, encoding) {
319
+ const bytes = combineByteSequences(ioQueue)
320
+
321
+ // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
322
+ const BOMEncoding = BOMSniffing(bytes)
323
+
324
+ let slice = 0
325
+
326
+ // 2. If BOMEncoding is non-null:
327
+ if (BOMEncoding !== null) {
328
+ // 1. Set encoding to BOMEncoding.
329
+ encoding = BOMEncoding
330
+
331
+ // 2. Read three bytes from ioQueue, if BOMEncoding is
332
+ // UTF-8; otherwise read two bytes.
333
+ // (Do nothing with those bytes.)
334
+ slice = BOMEncoding === 'UTF-8' ? 3 : 2
335
+ }
336
+
337
+ // 3. Process a queue with an instance of encoding’s
338
+ // decoder, ioQueue, output, and "replacement".
339
+
340
+ // 4. Return output.
341
+
342
+ const sliced = bytes.slice(slice)
343
+ return new TextDecoder(encoding).decode(sliced)
344
+ }
345
+
346
+ /**
347
+ * @see https://encoding.spec.whatwg.org/#bom-sniff
348
+ * @param {Uint8Array} ioQueue
349
+ */
350
+ function BOMSniffing (ioQueue) {
351
+ // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
352
+ // converted to a byte sequence.
353
+ const [a, b, c] = ioQueue
354
+
355
+ // 2. For each of the rows in the table below, starting with
356
+ // the first one and going down, if BOM starts with the
357
+ // bytes given in the first column, then return the
358
+ // encoding given in the cell in the second column of that
359
+ // row. Otherwise, return null.
360
+ if (a === 0xEF && b === 0xBB && c === 0xBF) {
361
+ return 'UTF-8'
362
+ } else if (a === 0xFE && b === 0xFF) {
363
+ return 'UTF-16BE'
364
+ } else if (a === 0xFF && b === 0xFE) {
365
+ return 'UTF-16LE'
366
+ }
367
+
368
+ return null
369
+ }
370
+
371
+ /**
372
+ * @param {Uint8Array[]} sequences
373
+ */
374
+ function combineByteSequences (sequences) {
375
+ const size = sequences.reduce((a, b) => {
376
+ return a + b.byteLength
377
+ }, 0)
378
+
379
+ let offset = 0
380
+
381
+ return sequences.reduce((a, b) => {
382
+ a.set(b, offset)
383
+ offset += b.byteLength
384
+ return a
385
+ }, new Uint8Array(size))
386
+ }
387
+
388
+ module.exports = {
389
+ staticPropertyDescriptors,
390
+ readOperation,
391
+ fireAProgressEvent
392
+ }
worker/node_modules/undici/lib/global.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ // We include a version number for the Dispatcher API. In case of breaking changes,
4
+ // this version number must be increased to avoid conflicts.
5
+ const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
6
+ const { InvalidArgumentError } = require('./core/errors')
7
+ const Agent = require('./agent')
8
+
9
+ if (getGlobalDispatcher() === undefined) {
10
+ setGlobalDispatcher(new Agent())
11
+ }
12
+
13
+ function setGlobalDispatcher (agent) {
14
+ if (!agent || typeof agent.dispatch !== 'function') {
15
+ throw new InvalidArgumentError('Argument agent must implement Agent')
16
+ }
17
+ Object.defineProperty(globalThis, globalDispatcher, {
18
+ value: agent,
19
+ writable: true,
20
+ enumerable: false,
21
+ configurable: false
22
+ })
23
+ }
24
+
25
+ function getGlobalDispatcher () {
26
+ return globalThis[globalDispatcher]
27
+ }
28
+
29
+ module.exports = {
30
+ setGlobalDispatcher,
31
+ getGlobalDispatcher
32
+ }
worker/node_modules/undici/lib/handler/DecoratorHandler.js ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict'
2
+
3
+ module.exports = class DecoratorHandler {
4
+ constructor (handler) {
5
+ this.handler = handler
6
+ }
7
+
8
+ onConnect (...args) {
9
+ return this.handler.onConnect(...args)
10
+ }
11
+
12
+ onError (...args) {
13
+ return this.handler.onError(...args)
14
+ }
15
+
16
+ onUpgrade (...args) {
17
+ return this.handler.onUpgrade(...args)
18
+ }
19
+
20
+ onHeaders (...args) {
21
+ return this.handler.onHeaders(...args)
22
+ }
23
+
24
+ onData (...args) {
25
+ return this.handler.onData(...args)
26
+ }
27
+
28
+ onComplete (...args) {
29
+ return this.handler.onComplete(...args)
30
+ }
31
+
32
+ onBodySent (...args) {
33
+ return this.handler.onBodySent(...args)
34
+ }
35
+ }