1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
|
/* globals AbortController */
'use strict'
const { test, teardown } = require('tap')
const { createServer } = require('http')
const { ReadableStream } = require('stream/web')
const { Blob } = require('buffer')
const { fetch, Response, Request, FormData, File } = require('../..')
const { Client, setGlobalDispatcher, Agent } = require('../..')
const { nodeMajor, nodeMinor } = require('../../lib/core/util')
const nodeFetch = require('../../index-fetch')
const { once } = require('events')
const { gzipSync } = require('zlib')
const { promisify } = require('util')
const { randomFillSync, createHash } = require('crypto')
setGlobalDispatcher(new Agent({
keepAliveTimeout: 1,
keepAliveMaxTimeout: 1
}))
test('function signature', (t) => {
t.plan(2)
t.equal(fetch.name, 'fetch')
t.equal(fetch.length, 1)
})
test('args validation', async (t) => {
t.plan(2)
await t.rejects(fetch(), TypeError)
await t.rejects(fetch('ftp://unsupported'), TypeError)
})
test('request json', (t) => {
t.plan(1)
const obj = { asd: true }
const server = createServer((req, res) => {
res.end(JSON.stringify(obj))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const body = await fetch(`http://localhost:${server.address().port}`)
t.strictSame(obj, await body.json())
})
})
test('request text', (t) => {
t.plan(1)
const obj = { asd: true }
const server = createServer((req, res) => {
res.end(JSON.stringify(obj))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const body = await fetch(`http://localhost:${server.address().port}`)
t.strictSame(JSON.stringify(obj), await body.text())
})
})
test('request arrayBuffer', (t) => {
t.plan(1)
const obj = { asd: true }
const server = createServer((req, res) => {
res.end(JSON.stringify(obj))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const body = await fetch(`http://localhost:${server.address().port}`)
t.strictSame(Buffer.from(JSON.stringify(obj)), Buffer.from(await body.arrayBuffer()))
})
})
test('should set type of blob object to the value of the `Content-Type` header from response', (t) => {
t.plan(1)
const obj = { asd: true }
const server = createServer((req, res) => {
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify(obj))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const response = await fetch(`http://localhost:${server.address().port}`)
t.equal('application/json', (await response.blob()).type)
})
})
test('pre aborted with readable request body', (t) => {
t.plan(2)
const server = createServer((req, res) => {
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const ac = new AbortController()
ac.abort()
await fetch(`http://localhost:${server.address().port}`, {
signal: ac.signal,
method: 'POST',
body: new ReadableStream({
async cancel (reason) {
t.equal(reason.name, 'AbortError')
}
}),
duplex: 'half'
}).catch(err => {
t.equal(err.name, 'AbortError')
})
})
})
test('pre aborted with closed readable request body', (t) => {
t.plan(2)
const server = createServer((req, res) => {
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const ac = new AbortController()
ac.abort()
const body = new ReadableStream({
async start (c) {
t.pass()
c.close()
},
async cancel (reason) {
t.fail()
}
})
queueMicrotask(() => {
fetch(`http://localhost:${server.address().port}`, {
signal: ac.signal,
method: 'POST',
body,
duplex: 'half'
}).catch(err => {
t.equal(err.name, 'AbortError')
})
})
})
})
test('unsupported formData 1', (t) => {
t.plan(1)
const server = createServer((req, res) => {
res.setHeader('content-type', 'asdasdsad')
res.end()
})
t.teardown(server.close.bind(server))
server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.formData())
.catch(err => {
t.equal(err.name, 'TypeError')
})
})
})
test('multipart formdata not base64', async (t) => {
t.plan(2)
// Construct example form data, with text and blob fields
const formData = new FormData()
formData.append('field1', 'value1')
const blob = new Blob(['example\ntext file'], { type: 'text/plain' })
formData.append('field2', blob, 'file.txt')
const tempRes = new Response(formData)
const boundary = tempRes.headers.get('content-type').split('boundary=')[1]
const formRaw = await tempRes.text()
const server = createServer((req, res) => {
res.setHeader('content-type', 'multipart/form-data; boundary=' + boundary)
res.write(formRaw)
res.end()
})
t.teardown(server.close.bind(server))
const listen = promisify(server.listen.bind(server))
await listen(0)
const res = await fetch(`http://localhost:${server.address().port}`)
const form = await res.formData()
t.equal(form.get('field1'), 'value1')
const text = await form.get('field2').text()
t.equal(text, 'example\ntext file')
})
// TODO(@KhafraDev): re-enable this test once the issue is fixed
// See https://github.com/nodejs/node/issues/47301
test('multipart formdata base64', { skip: nodeMajor >= 19 && nodeMinor >= 8 }, (t) => {
t.plan(1)
// Example form data with base64 encoding
const data = randomFillSync(Buffer.alloc(256))
const formRaw = `------formdata-undici-0.5786922755719377\r\nContent-Disposition: form-data; name="file"; filename="test.txt"\r\nContent-Type: application/octet-stream\r\nContent-Transfer-Encoding: base64\r\n\r\n${data.toString('base64')}\r\n------formdata-undici-0.5786922755719377--`
const server = createServer(async (req, res) => {
res.setHeader('content-type', 'multipart/form-data; boundary=----formdata-undici-0.5786922755719377')
for (let offset = 0; offset < formRaw.length;) {
res.write(formRaw.slice(offset, offset += 2))
await new Promise(resolve => setTimeout(resolve))
}
res.end()
})
t.teardown(server.close.bind(server))
server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.formData())
.then(form => form.get('file').arrayBuffer())
.then(buffer => createHash('sha256').update(Buffer.from(buffer)).digest('base64'))
.then(digest => {
t.equal(createHash('sha256').update(data).digest('base64'), digest)
})
})
})
test('multipart fromdata non-ascii filed names', async (t) => {
t.plan(1)
const request = new Request('http://localhost', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data; boundary=----formdata-undici-0.6204674738279623'
},
body:
'------formdata-undici-0.6204674738279623\r\n' +
'Content-Disposition: form-data; name="fiŝo"\r\n' +
'\r\n' +
'value1\r\n' +
'------formdata-undici-0.6204674738279623--'
})
const form = await request.formData()
t.equal(form.get('fiŝo'), 'value1')
})
test('busboy emit error', async (t) => {
t.plan(1)
const formData = new FormData()
formData.append('field1', 'value1')
const tempRes = new Response(formData)
const formRaw = await tempRes.text()
const server = createServer((req, res) => {
res.setHeader('content-type', 'multipart/form-data; boundary=wrongboundary')
res.write(formRaw)
res.end()
})
t.teardown(server.close.bind(server))
const listen = promisify(server.listen.bind(server))
await listen(0)
const res = await fetch(`http://localhost:${server.address().port}`)
await t.rejects(res.formData(), 'Unexpected end of multipart data')
})
// https://github.com/nodejs/undici/issues/2244
test('parsing formData preserve full path on files', async (t) => {
t.plan(1)
const formData = new FormData()
formData.append('field1', new File(['foo'], 'a/b/c/foo.txt'))
const tempRes = new Response(formData)
const form = await tempRes.formData()
t.equal(form.get('field1').name, 'a/b/c/foo.txt')
})
test('urlencoded formData', (t) => {
t.plan(2)
const server = createServer((req, res) => {
res.setHeader('content-type', 'application/x-www-form-urlencoded')
res.end('field1=value1&field2=value2')
})
t.teardown(server.close.bind(server))
server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.formData())
.then(formData => {
t.equal(formData.get('field1'), 'value1')
t.equal(formData.get('field2'), 'value2')
})
})
})
test('text with BOM', (t) => {
t.plan(1)
const server = createServer((req, res) => {
res.setHeader('content-type', 'application/x-www-form-urlencoded')
res.end('\uFEFFtest=\uFEFF')
})
t.teardown(server.close.bind(server))
server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.text())
.then(text => {
t.equal(text, 'test=\uFEFF')
})
})
})
test('formData with BOM', (t) => {
t.plan(1)
const server = createServer((req, res) => {
res.setHeader('content-type', 'application/x-www-form-urlencoded')
res.end('\uFEFFtest=\uFEFF')
})
t.teardown(server.close.bind(server))
server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`)
.then(res => res.formData())
.then(formData => {
t.equal(formData.get('\uFEFFtest'), '\uFEFF')
})
})
})
test('locked blob body', (t) => {
t.plan(1)
const server = createServer((req, res) => {
res.end()
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}`)
const reader = res.body.getReader()
res.blob().catch(err => {
t.equal(err.message, 'Body is unusable')
reader.cancel()
})
})
})
test('disturbed blob body', (t) => {
t.plan(2)
const server = createServer((req, res) => {
res.end()
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}`)
res.blob().then(() => {
t.pass(2)
})
res.blob().catch(err => {
t.equal(err.message, 'Body is unusable')
})
})
})
test('redirect with body', (t) => {
t.plan(3)
let count = 0
const server = createServer(async (req, res) => {
let body = ''
for await (const chunk of req) {
body += chunk
}
t.equal(body, 'asd')
if (count++ === 0) {
res.setHeader('location', 'asd')
res.statusCode = 302
res.end()
} else {
res.end(String(count))
}
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}`, {
method: 'PUT',
body: 'asd'
})
t.equal(await res.text(), '2')
})
})
test('redirect with stream', (t) => {
t.plan(3)
const location = '/asd'
const body = 'hello!'
const server = createServer(async (req, res) => {
res.writeHead(302, { location })
let count = 0
const l = setInterval(() => {
res.write(body[count++])
if (count === body.length) {
res.end()
clearInterval(l)
}
}, 50)
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}`, {
redirect: 'manual'
})
t.equal(res.status, 302)
t.equal(res.headers.get('location'), location)
t.equal(await res.text(), body)
})
})
test('fail to extract locked body', (t) => {
t.plan(1)
const stream = new ReadableStream({})
const reader = stream.getReader()
try {
// eslint-disable-next-line
new Response(stream)
} catch (err) {
t.equal(err.name, 'TypeError')
}
reader.cancel()
})
test('fail to extract locked body', (t) => {
t.plan(1)
const stream = new ReadableStream({})
const reader = stream.getReader()
try {
// eslint-disable-next-line
new Request('http://asd', {
method: 'PUT',
body: stream,
keepalive: true
})
} catch (err) {
t.equal(err.message, 'keepalive')
}
reader.cancel()
})
test('post FormData with Blob', (t) => {
t.plan(1)
const body = new FormData()
body.append('field1', new Blob(['asd1']))
const server = createServer((req, res) => {
req.pipe(res)
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}`, {
method: 'PUT',
body
})
t.ok(/asd1/.test(await res.text()))
})
})
test('post FormData with File', (t) => {
t.plan(2)
const body = new FormData()
body.append('field1', new File(['asd1'], 'filename123'))
const server = createServer((req, res) => {
req.pipe(res)
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const res = await fetch(`http://localhost:${server.address().port}`, {
method: 'PUT',
body
})
const result = await res.text()
t.ok(/asd1/.test(result))
t.ok(/filename123/.test(result))
})
})
test('invalid url', async (t) => {
t.plan(1)
try {
await fetch('http://invalid')
} catch (e) {
t.match(e.cause.message, 'invalid')
}
})
test('custom agent', (t) => {
t.plan(2)
const obj = { asd: true }
const server = createServer((req, res) => {
res.end(JSON.stringify(obj))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const dispatcher = new Client('http://localhost:' + server.address().port, {
keepAliveTimeout: 1,
keepAliveMaxTimeout: 1
})
const oldDispatch = dispatcher.dispatch
dispatcher.dispatch = function (options, handler) {
t.pass('custom dispatcher')
return oldDispatch.call(this, options, handler)
}
t.teardown(server.close.bind(server))
const body = await fetch(`http://localhost:${server.address().port}`, {
dispatcher
})
t.strictSame(obj, await body.json())
})
})
test('custom agent node fetch', (t) => {
t.plan(2)
const obj = { asd: true }
const server = createServer((req, res) => {
res.end(JSON.stringify(obj))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const dispatcher = new Client('http://localhost:' + server.address().port, {
keepAliveTimeout: 1,
keepAliveMaxTimeout: 1
})
const oldDispatch = dispatcher.dispatch
dispatcher.dispatch = function (options, handler) {
t.pass('custom dispatcher')
return oldDispatch.call(this, options, handler)
}
t.teardown(server.close.bind(server))
const body = await nodeFetch.fetch(`http://localhost:${server.address().port}`, {
dispatcher
})
t.strictSame(obj, await body.json())
})
})
test('error on redirect', async (t) => {
const server = createServer((req, res) => {
res.statusCode = 302
res.end()
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const errorCause = await fetch(`http://localhost:${server.address().port}`, {
redirect: 'error'
}).catch((e) => e.cause)
t.equal(errorCause.message, 'unexpected redirect')
})
})
// https://github.com/nodejs/undici/issues/1527
test('fetching with Request object - issue #1527', async (t) => {
const server = createServer((req, res) => {
t.pass()
res.end()
}).listen(0)
t.teardown(server.close.bind(server))
await once(server, 'listening')
const body = JSON.stringify({ foo: 'bar' })
const request = new Request(`http://localhost:${server.address().port}`, {
method: 'POST',
body
})
await t.resolves(fetch(request))
t.end()
})
test('do not decode redirect body', (t) => {
t.plan(3)
const obj = { asd: true }
const server = createServer((req, res) => {
if (req.url === '/resource') {
t.pass('we redirect')
res.statusCode = 301
res.setHeader('location', '/resource/')
// Some dumb http servers set the content-encoding gzip
// even if there is no response
res.setHeader('content-encoding', 'gzip')
res.end()
return
}
t.pass('actual response')
res.setHeader('content-encoding', 'gzip')
res.end(gzipSync(JSON.stringify(obj)))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const body = await fetch(`http://localhost:${server.address().port}/resource`)
t.strictSame(JSON.stringify(obj), await body.text())
})
})
test('decode non-redirect body with location header', (t) => {
t.plan(2)
const obj = { asd: true }
const server = createServer((req, res) => {
t.pass('response')
res.statusCode = 201
res.setHeader('location', '/resource/')
res.setHeader('content-encoding', 'gzip')
res.end(gzipSync(JSON.stringify(obj)))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const body = await fetch(`http://localhost:${server.address().port}/resource`)
t.strictSame(JSON.stringify(obj), await body.text())
})
})
test('Receiving non-Latin1 headers', async (t) => {
const ContentDisposition = [
'inline; filename=rock&roll.png',
'inline; filename="rock\'n\'roll.png"',
'inline; filename="image â\x80\x94 copy (1).png"; filename*=UTF-8\'\'image%20%E2%80%94%20copy%20(1).png',
'inline; filename="_å\x9C\x96ç\x89\x87_ð\x9F\x96¼_image_.png"; filename*=UTF-8\'\'_%E5%9C%96%E7%89%87_%F0%9F%96%BC_image_.png',
'inline; filename="100 % loading&perf.png"; filename*=UTF-8\'\'100%20%25%20loading%26perf.png'
]
const server = createServer((req, res) => {
for (let i = 0; i < ContentDisposition.length; i++) {
res.setHeader(`Content-Disposition-${i + 1}`, ContentDisposition[i])
}
res.end()
}).listen(0)
t.teardown(server.close.bind(server))
await once(server, 'listening')
const url = `http://localhost:${server.address().port}`
const response = await fetch(url, { method: 'HEAD' })
const cdHeaders = [...response.headers]
.filter(([k]) => k.startsWith('content-disposition'))
.map(([, v]) => v)
const lengths = cdHeaders.map(h => h.length)
t.same(cdHeaders, ContentDisposition)
t.same(lengths, [30, 34, 94, 104, 90])
t.end()
})
teardown(() => process.exit())
|