| 'use strict' |
|
|
| const Busboy = require('@fastify/busboy') |
| const util = require('../core/util') |
| const { |
| ReadableStreamFrom, |
| isBlobLike, |
| isReadableStreamLike, |
| readableStreamClose, |
| createDeferredPromise, |
| fullyReadBody |
| } = require('./util') |
| const { FormData } = require('./formdata') |
| const { kState } = require('./symbols') |
| const { webidl } = require('./webidl') |
| const { DOMException, structuredClone } = require('./constants') |
| const { Blob, File: NativeFile } = require('buffer') |
| const { kBodyUsed } = require('../core/symbols') |
| const assert = require('assert') |
| const { isErrored } = require('../core/util') |
| const { isUint8Array, isArrayBuffer } = require('util/types') |
| const { File: UndiciFile } = require('./file') |
| const { parseMIMEType, serializeAMimeType } = require('./dataURL') |
|
|
| let random |
| try { |
| const crypto = require('node:crypto') |
| random = (max) => crypto.randomInt(0, max) |
| } catch { |
| random = (max) => Math.floor(Math.random(max)) |
| } |
|
|
| let ReadableStream = globalThis.ReadableStream |
|
|
| |
| const File = NativeFile ?? UndiciFile |
| const textEncoder = new TextEncoder() |
| const textDecoder = new TextDecoder() |
|
|
| |
| function extractBody (object, keepalive = false) { |
| if (!ReadableStream) { |
| ReadableStream = require('stream/web').ReadableStream |
| } |
|
|
| |
| let stream = null |
|
|
| |
| if (object instanceof ReadableStream) { |
| stream = object |
| } else if (isBlobLike(object)) { |
| |
| |
| stream = object.stream() |
| } else { |
| |
| |
| stream = new ReadableStream({ |
| async pull (controller) { |
| controller.enqueue( |
| typeof source === 'string' ? textEncoder.encode(source) : source |
| ) |
| queueMicrotask(() => readableStreamClose(controller)) |
| }, |
| start () {}, |
| type: undefined |
| }) |
| } |
|
|
| |
| assert(isReadableStreamLike(stream)) |
|
|
| |
| let action = null |
|
|
| |
| let source = null |
|
|
| |
| let length = null |
|
|
| |
| let type = null |
|
|
| |
| if (typeof object === 'string') { |
| |
| |
| source = object |
|
|
| |
| type = 'text/plain;charset=UTF-8' |
| } else if (object instanceof URLSearchParams) { |
| |
|
|
| |
| |
| |
| |
|
|
| |
| source = object.toString() |
|
|
| |
| type = 'application/x-www-form-urlencoded;charset=UTF-8' |
| } else if (isArrayBuffer(object)) { |
| |
|
|
| |
| source = new Uint8Array(object.slice()) |
| } else if (ArrayBuffer.isView(object)) { |
| |
|
|
| |
| source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) |
| } else if (util.isFormDataLike(object)) { |
| const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` |
| const prefix = `--${boundary}\r\nContent-Disposition: form-data` |
|
|
| |
| const escape = (str) => |
| str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') |
| const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') |
|
|
| |
| |
| |
| |
| |
|
|
| const blobParts = [] |
| const rn = new Uint8Array([13, 10]) |
| length = 0 |
| let hasUnknownSizeValue = false |
|
|
| for (const [name, value] of object) { |
| if (typeof value === 'string') { |
| const chunk = textEncoder.encode(prefix + |
| `; name="${escape(normalizeLinefeeds(name))}"` + |
| `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) |
| blobParts.push(chunk) |
| length += chunk.byteLength |
| } else { |
| const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + |
| (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + |
| `Content-Type: ${ |
| value.type || 'application/octet-stream' |
| }\r\n\r\n`) |
| blobParts.push(chunk, value, rn) |
| if (typeof value.size === 'number') { |
| length += chunk.byteLength + value.size + rn.byteLength |
| } else { |
| hasUnknownSizeValue = true |
| } |
| } |
| } |
|
|
| const chunk = textEncoder.encode(`--${boundary}--`) |
| blobParts.push(chunk) |
| length += chunk.byteLength |
| if (hasUnknownSizeValue) { |
| length = null |
| } |
|
|
| |
| source = object |
|
|
| action = async function * () { |
| for (const part of blobParts) { |
| if (part.stream) { |
| yield * part.stream() |
| } else { |
| yield part |
| } |
| } |
| } |
|
|
| |
| |
| |
| type = 'multipart/form-data; boundary=' + boundary |
| } else if (isBlobLike(object)) { |
| |
|
|
| |
| source = object |
|
|
| |
| length = object.size |
|
|
| |
| |
| if (object.type) { |
| type = object.type |
| } |
| } else if (typeof object[Symbol.asyncIterator] === 'function') { |
| |
| if (keepalive) { |
| throw new TypeError('keepalive') |
| } |
|
|
| |
| if (util.isDisturbed(object) || object.locked) { |
| throw new TypeError( |
| 'Response body object should not be disturbed or locked' |
| ) |
| } |
|
|
| stream = |
| object instanceof ReadableStream ? object : ReadableStreamFrom(object) |
| } |
|
|
| |
| |
| if (typeof source === 'string' || util.isBuffer(source)) { |
| length = Buffer.byteLength(source) |
| } |
|
|
| |
| if (action != null) { |
| |
| let iterator |
| stream = new ReadableStream({ |
| async start () { |
| iterator = action(object)[Symbol.asyncIterator]() |
| }, |
| async pull (controller) { |
| const { value, done } = await iterator.next() |
| if (done) { |
| |
| queueMicrotask(() => { |
| controller.close() |
| }) |
| } else { |
| |
| |
| |
| if (!isErrored(stream)) { |
| controller.enqueue(new Uint8Array(value)) |
| } |
| } |
| return controller.desiredSize > 0 |
| }, |
| async cancel (reason) { |
| await iterator.return() |
| }, |
| type: undefined |
| }) |
| } |
|
|
| |
| |
| const body = { stream, source, length } |
|
|
| |
| return [body, type] |
| } |
|
|
| |
| function safelyExtractBody (object, keepalive = false) { |
| if (!ReadableStream) { |
| |
| ReadableStream = require('stream/web').ReadableStream |
| } |
|
|
| |
| |
|
|
| |
| if (object instanceof ReadableStream) { |
| |
| |
| assert(!util.isDisturbed(object), 'The body has already been consumed.') |
| |
| assert(!object.locked, 'The stream is locked.') |
| } |
|
|
| |
| return extractBody(object, keepalive) |
| } |
|
|
| function cloneBody (body) { |
| |
|
|
| |
|
|
| |
| const [out1, out2] = body.stream.tee() |
| const out2Clone = structuredClone(out2, { transfer: [out2] }) |
| |
| |
| const [, finalClone] = out2Clone.tee() |
|
|
| |
| body.stream = out1 |
|
|
| |
| return { |
| stream: finalClone, |
| length: body.length, |
| source: body.source |
| } |
| } |
|
|
| async function * consumeBody (body) { |
| if (body) { |
| if (isUint8Array(body)) { |
| yield body |
| } else { |
| const stream = body.stream |
|
|
| if (util.isDisturbed(stream)) { |
| throw new TypeError('The body has already been consumed.') |
| } |
|
|
| if (stream.locked) { |
| throw new TypeError('The stream is locked.') |
| } |
|
|
| |
| stream[kBodyUsed] = true |
|
|
| yield * stream |
| } |
| } |
| } |
|
|
| function throwIfAborted (state) { |
| if (state.aborted) { |
| throw new DOMException('The operation was aborted.', 'AbortError') |
| } |
| } |
|
|
| function bodyMixinMethods (instance) { |
| const methods = { |
| blob () { |
| |
| |
| |
| |
| |
| return specConsumeBody(this, (bytes) => { |
| let mimeType = bodyMimeType(this) |
|
|
| if (mimeType === 'failure') { |
| mimeType = '' |
| } else if (mimeType) { |
| mimeType = serializeAMimeType(mimeType) |
| } |
|
|
| |
| |
| return new Blob([bytes], { type: mimeType }) |
| }, instance) |
| }, |
|
|
| arrayBuffer () { |
| |
| |
| |
| |
| return specConsumeBody(this, (bytes) => { |
| return new Uint8Array(bytes).buffer |
| }, instance) |
| }, |
|
|
| text () { |
| |
| |
| return specConsumeBody(this, utf8DecodeBytes, instance) |
| }, |
|
|
| json () { |
| |
| |
| return specConsumeBody(this, parseJSONFromBytes, instance) |
| }, |
|
|
| async formData () { |
| webidl.brandCheck(this, instance) |
|
|
| throwIfAborted(this[kState]) |
|
|
| const contentType = this.headers.get('Content-Type') |
|
|
| |
| if (/multipart\/form-data/.test(contentType)) { |
| const headers = {} |
| for (const [key, value] of this.headers) headers[key.toLowerCase()] = value |
|
|
| const responseFormData = new FormData() |
|
|
| let busboy |
|
|
| try { |
| busboy = new Busboy({ |
| headers, |
| preservePath: true |
| }) |
| } catch (err) { |
| throw new DOMException(`${err}`, 'AbortError') |
| } |
|
|
| busboy.on('field', (name, value) => { |
| responseFormData.append(name, value) |
| }) |
| busboy.on('file', (name, value, filename, encoding, mimeType) => { |
| const chunks = [] |
|
|
| if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { |
| let base64chunk = '' |
|
|
| value.on('data', (chunk) => { |
| base64chunk += chunk.toString().replace(/[\r\n]/gm, '') |
|
|
| const end = base64chunk.length - base64chunk.length % 4 |
| chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) |
|
|
| base64chunk = base64chunk.slice(end) |
| }) |
| value.on('end', () => { |
| chunks.push(Buffer.from(base64chunk, 'base64')) |
| responseFormData.append(name, new File(chunks, filename, { type: mimeType })) |
| }) |
| } else { |
| value.on('data', (chunk) => { |
| chunks.push(chunk) |
| }) |
| value.on('end', () => { |
| responseFormData.append(name, new File(chunks, filename, { type: mimeType })) |
| }) |
| } |
| }) |
|
|
| const busboyResolve = new Promise((resolve, reject) => { |
| busboy.on('finish', resolve) |
| busboy.on('error', (err) => reject(new TypeError(err))) |
| }) |
|
|
| if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) |
| busboy.end() |
| await busboyResolve |
|
|
| return responseFormData |
| } else if (/application\/x-www-form-urlencoded/.test(contentType)) { |
| |
|
|
| |
| let entries |
| try { |
| let text = '' |
| |
| |
| |
| const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) |
|
|
| for await (const chunk of consumeBody(this[kState].body)) { |
| if (!isUint8Array(chunk)) { |
| throw new TypeError('Expected Uint8Array chunk') |
| } |
| text += streamingDecoder.decode(chunk, { stream: true }) |
| } |
| text += streamingDecoder.decode() |
| entries = new URLSearchParams(text) |
| } catch (err) { |
| |
| |
| throw Object.assign(new TypeError(), { cause: err }) |
| } |
|
|
| |
| const formData = new FormData() |
| for (const [name, value] of entries) { |
| formData.append(name, value) |
| } |
| return formData |
| } else { |
| |
| |
| await Promise.resolve() |
|
|
| throwIfAborted(this[kState]) |
|
|
| |
| throw webidl.errors.exception({ |
| header: `${instance.name}.formData`, |
| message: 'Could not parse content as FormData.' |
| }) |
| } |
| } |
| } |
|
|
| return methods |
| } |
|
|
| function mixinBody (prototype) { |
| Object.assign(prototype.prototype, bodyMixinMethods(prototype)) |
| } |
|
|
| |
| |
| |
| |
| |
| |
| async function specConsumeBody (object, convertBytesToJSValue, instance) { |
| webidl.brandCheck(object, instance) |
|
|
| throwIfAborted(object[kState]) |
|
|
| |
| |
| if (bodyUnusable(object[kState].body)) { |
| throw new TypeError('Body is unusable') |
| } |
|
|
| |
| const promise = createDeferredPromise() |
|
|
| |
| const errorSteps = (error) => promise.reject(error) |
|
|
| |
| |
| |
| |
| const successSteps = (data) => { |
| try { |
| promise.resolve(convertBytesToJSValue(data)) |
| } catch (e) { |
| errorSteps(e) |
| } |
| } |
|
|
| |
| |
| if (object[kState].body == null) { |
| successSteps(new Uint8Array()) |
| return promise.promise |
| } |
|
|
| |
| |
| await fullyReadBody(object[kState].body, successSteps, errorSteps) |
|
|
| |
| return promise.promise |
| } |
|
|
| |
| function bodyUnusable (body) { |
| |
| |
| |
| return body != null && (body.stream.locked || util.isDisturbed(body.stream)) |
| } |
|
|
| |
| |
| |
| |
| function utf8DecodeBytes (buffer) { |
| if (buffer.length === 0) { |
| return '' |
| } |
|
|
| |
| |
|
|
| |
| |
| if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { |
| buffer = buffer.subarray(3) |
| } |
|
|
| |
| |
| const output = textDecoder.decode(buffer) |
|
|
| |
| return output |
| } |
|
|
| |
| |
| |
| |
| function parseJSONFromBytes (bytes) { |
| return JSON.parse(utf8DecodeBytes(bytes)) |
| } |
|
|
| |
| |
| |
| |
| function bodyMimeType (object) { |
| const { headersList } = object[kState] |
| const contentType = headersList.get('content-type') |
|
|
| if (contentType === null) { |
| return 'failure' |
| } |
|
|
| return parseMIMEType(contentType) |
| } |
|
|
| module.exports = { |
| extractBody, |
| safelyExtractBody, |
| cloneBody, |
| mixinBody |
| } |
|
|