body.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. 'use strict'
  2. const util = require('../../core/util')
  3. const {
  4. ReadableStreamFrom,
  5. isBlobLike,
  6. isReadableStreamLike,
  7. readableStreamClose,
  8. createDeferredPromise,
  9. fullyReadBody,
  10. extractMimeType,
  11. utf8DecodeBytes
  12. } = require('./util')
  13. const { FormData } = require('./formdata')
  14. const { kState } = require('./symbols')
  15. const { webidl } = require('./webidl')
  16. const { Blob } = require('node:buffer')
  17. const assert = require('node:assert')
  18. const { isErrored, isDisturbed } = require('node:stream')
  19. const { isArrayBuffer } = require('node:util/types')
  20. const { serializeAMimeType } = require('./data-url')
  21. const { multipartFormDataParser } = require('./formdata-parser')
  22. const textEncoder = new TextEncoder()
  23. function noop () {}
  24. const hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0
  25. let streamRegistry
  26. if (hasFinalizationRegistry) {
  27. streamRegistry = new FinalizationRegistry((weakRef) => {
  28. const stream = weakRef.deref()
  29. if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {
  30. stream.cancel('Response object has been garbage collected').catch(noop)
  31. }
  32. })
  33. }
  34. // https://fetch.spec.whatwg.org/#concept-bodyinit-extract
  35. function extractBody (object, keepalive = false) {
  36. // 1. Let stream be null.
  37. let stream = null
  38. // 2. If object is a ReadableStream object, then set stream to object.
  39. if (object instanceof ReadableStream) {
  40. stream = object
  41. } else if (isBlobLike(object)) {
  42. // 3. Otherwise, if object is a Blob object, set stream to the
  43. // result of running object’s get stream.
  44. stream = object.stream()
  45. } else {
  46. // 4. Otherwise, set stream to a new ReadableStream object, and set
  47. // up stream with byte reading support.
  48. stream = new ReadableStream({
  49. async pull (controller) {
  50. const buffer = typeof source === 'string' ? textEncoder.encode(source) : source
  51. if (buffer.byteLength) {
  52. controller.enqueue(buffer)
  53. }
  54. queueMicrotask(() => readableStreamClose(controller))
  55. },
  56. start () {},
  57. type: 'bytes'
  58. })
  59. }
  60. // 5. Assert: stream is a ReadableStream object.
  61. assert(isReadableStreamLike(stream))
  62. // 6. Let action be null.
  63. let action = null
  64. // 7. Let source be null.
  65. let source = null
  66. // 8. Let length be null.
  67. let length = null
  68. // 9. Let type be null.
  69. let type = null
  70. // 10. Switch on object:
  71. if (typeof object === 'string') {
  72. // Set source to the UTF-8 encoding of object.
  73. // Note: setting source to a Uint8Array here breaks some mocking assumptions.
  74. source = object
  75. // Set type to `text/plain;charset=UTF-8`.
  76. type = 'text/plain;charset=UTF-8'
  77. } else if (object instanceof URLSearchParams) {
  78. // URLSearchParams
  79. // spec says to run application/x-www-form-urlencoded on body.list
  80. // this is implemented in Node.js as apart of an URLSearchParams instance toString method
  81. // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
  82. // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
  83. // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
  84. source = object.toString()
  85. // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
  86. type = 'application/x-www-form-urlencoded;charset=UTF-8'
  87. } else if (isArrayBuffer(object)) {
  88. // BufferSource/ArrayBuffer
  89. // Set source to a copy of the bytes held by object.
  90. source = new Uint8Array(object.slice())
  91. } else if (ArrayBuffer.isView(object)) {
  92. // BufferSource/ArrayBufferView
  93. // Set source to a copy of the bytes held by object.
  94. source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
  95. } else if (util.isFormDataLike(object)) {
  96. const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
  97. const prefix = `--${boundary}\r\nContent-Disposition: form-data`
  98. /*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
  99. const escape = (str) =>
  100. str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
  101. const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
  102. // Set action to this step: run the multipart/form-data
  103. // encoding algorithm, with object’s entry list and UTF-8.
  104. // - This ensures that the body is immutable and can't be changed afterwords
  105. // - That the content-length is calculated in advance.
  106. // - And that all parts are pre-encoded and ready to be sent.
  107. const blobParts = []
  108. const rn = new Uint8Array([13, 10]) // '\r\n'
  109. length = 0
  110. let hasUnknownSizeValue = false
  111. for (const [name, value] of object) {
  112. if (typeof value === 'string') {
  113. const chunk = textEncoder.encode(prefix +
  114. `; name="${escape(normalizeLinefeeds(name))}"` +
  115. `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
  116. blobParts.push(chunk)
  117. length += chunk.byteLength
  118. } else {
  119. const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
  120. (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
  121. `Content-Type: ${
  122. value.type || 'application/octet-stream'
  123. }\r\n\r\n`)
  124. blobParts.push(chunk, value, rn)
  125. if (typeof value.size === 'number') {
  126. length += chunk.byteLength + value.size + rn.byteLength
  127. } else {
  128. hasUnknownSizeValue = true
  129. }
  130. }
  131. }
  132. const chunk = textEncoder.encode(`--${boundary}--`)
  133. blobParts.push(chunk)
  134. length += chunk.byteLength
  135. if (hasUnknownSizeValue) {
  136. length = null
  137. }
  138. // Set source to object.
  139. source = object
  140. action = async function * () {
  141. for (const part of blobParts) {
  142. if (part.stream) {
  143. yield * part.stream()
  144. } else {
  145. yield part
  146. }
  147. }
  148. }
  149. // Set type to `multipart/form-data; boundary=`,
  150. // followed by the multipart/form-data boundary string generated
  151. // by the multipart/form-data encoding algorithm.
  152. type = `multipart/form-data; boundary=${boundary}`
  153. } else if (isBlobLike(object)) {
  154. // Blob
  155. // Set source to object.
  156. source = object
  157. // Set length to object’s size.
  158. length = object.size
  159. // If object’s type attribute is not the empty byte sequence, set
  160. // type to its value.
  161. if (object.type) {
  162. type = object.type
  163. }
  164. } else if (typeof object[Symbol.asyncIterator] === 'function') {
  165. // If keepalive is true, then throw a TypeError.
  166. if (keepalive) {
  167. throw new TypeError('keepalive')
  168. }
  169. // If object is disturbed or locked, then throw a TypeError.
  170. if (util.isDisturbed(object) || object.locked) {
  171. throw new TypeError(
  172. 'Response body object should not be disturbed or locked'
  173. )
  174. }
  175. stream =
  176. object instanceof ReadableStream ? object : ReadableStreamFrom(object)
  177. }
  178. // 11. If source is a byte sequence, then set action to a
  179. // step that returns source and length to source’s length.
  180. if (typeof source === 'string' || util.isBuffer(source)) {
  181. length = Buffer.byteLength(source)
  182. }
  183. // 12. If action is non-null, then run these steps in in parallel:
  184. if (action != null) {
  185. // Run action.
  186. let iterator
  187. stream = new ReadableStream({
  188. async start () {
  189. iterator = action(object)[Symbol.asyncIterator]()
  190. },
  191. async pull (controller) {
  192. const { value, done } = await iterator.next()
  193. if (done) {
  194. // When running action is done, close stream.
  195. queueMicrotask(() => {
  196. controller.close()
  197. controller.byobRequest?.respond(0)
  198. })
  199. } else {
  200. // Whenever one or more bytes are available and stream is not errored,
  201. // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
  202. // bytes into stream.
  203. if (!isErrored(stream)) {
  204. const buffer = new Uint8Array(value)
  205. if (buffer.byteLength) {
  206. controller.enqueue(buffer)
  207. }
  208. }
  209. }
  210. return controller.desiredSize > 0
  211. },
  212. async cancel (reason) {
  213. await iterator.return()
  214. },
  215. type: 'bytes'
  216. })
  217. }
  218. // 13. Let body be a body whose stream is stream, source is source,
  219. // and length is length.
  220. const body = { stream, source, length }
  221. // 14. Return (body, type).
  222. return [body, type]
  223. }
  224. // https://fetch.spec.whatwg.org/#bodyinit-safely-extract
  225. function safelyExtractBody (object, keepalive = false) {
  226. // To safely extract a body and a `Content-Type` value from
  227. // a byte sequence or BodyInit object object, run these steps:
  228. // 1. If object is a ReadableStream object, then:
  229. if (object instanceof ReadableStream) {
  230. // Assert: object is neither disturbed nor locked.
  231. // istanbul ignore next
  232. assert(!util.isDisturbed(object), 'The body has already been consumed.')
  233. // istanbul ignore next
  234. assert(!object.locked, 'The stream is locked.')
  235. }
  236. // 2. Return the results of extracting object.
  237. return extractBody(object, keepalive)
  238. }
  239. function cloneBody (instance, body) {
  240. // To clone a body body, run these steps:
  241. // https://fetch.spec.whatwg.org/#concept-body-clone
  242. // 1. Let « out1, out2 » be the result of teeing body’s stream.
  243. const [out1, out2] = body.stream.tee()
  244. if (hasFinalizationRegistry) {
  245. streamRegistry.register(instance, new WeakRef(out1))
  246. }
  247. // 2. Set body’s stream to out1.
  248. body.stream = out1
  249. // 3. Return a body whose stream is out2 and other members are copied from body.
  250. return {
  251. stream: out2,
  252. length: body.length,
  253. source: body.source
  254. }
  255. }
  256. function throwIfAborted (state) {
  257. if (state.aborted) {
  258. throw new DOMException('The operation was aborted.', 'AbortError')
  259. }
  260. }
  261. function bodyMixinMethods (instance) {
  262. const methods = {
  263. blob () {
  264. // The blob() method steps are to return the result of
  265. // running consume body with this and the following step
  266. // given a byte sequence bytes: return a Blob whose
  267. // contents are bytes and whose type attribute is this’s
  268. // MIME type.
  269. return consumeBody(this, (bytes) => {
  270. let mimeType = bodyMimeType(this)
  271. if (mimeType === null) {
  272. mimeType = ''
  273. } else if (mimeType) {
  274. mimeType = serializeAMimeType(mimeType)
  275. }
  276. // Return a Blob whose contents are bytes and type attribute
  277. // is mimeType.
  278. return new Blob([bytes], { type: mimeType })
  279. }, instance)
  280. },
  281. arrayBuffer () {
  282. // The arrayBuffer() method steps are to return the result
  283. // of running consume body with this and the following step
  284. // given a byte sequence bytes: return a new ArrayBuffer
  285. // whose contents are bytes.
  286. return consumeBody(this, (bytes) => {
  287. return new Uint8Array(bytes).buffer
  288. }, instance)
  289. },
  290. text () {
  291. // The text() method steps are to return the result of running
  292. // consume body with this and UTF-8 decode.
  293. return consumeBody(this, utf8DecodeBytes, instance)
  294. },
  295. json () {
  296. // The json() method steps are to return the result of running
  297. // consume body with this and parse JSON from bytes.
  298. return consumeBody(this, parseJSONFromBytes, instance)
  299. },
  300. formData () {
  301. // The formData() method steps are to return the result of running
  302. // consume body with this and the following step given a byte sequence bytes:
  303. return consumeBody(this, (value) => {
  304. // 1. Let mimeType be the result of get the MIME type with this.
  305. const mimeType = bodyMimeType(this)
  306. // 2. If mimeType is non-null, then switch on mimeType’s essence and run
  307. // the corresponding steps:
  308. if (mimeType !== null) {
  309. switch (mimeType.essence) {
  310. case 'multipart/form-data': {
  311. // 1. ... [long step]
  312. const parsed = multipartFormDataParser(value, mimeType)
  313. // 2. If that fails for some reason, then throw a TypeError.
  314. if (parsed === 'failure') {
  315. throw new TypeError('Failed to parse body as FormData.')
  316. }
  317. // 3. Return a new FormData object, appending each entry,
  318. // resulting from the parsing operation, to its entry list.
  319. const fd = new FormData()
  320. fd[kState] = parsed
  321. return fd
  322. }
  323. case 'application/x-www-form-urlencoded': {
  324. // 1. Let entries be the result of parsing bytes.
  325. const entries = new URLSearchParams(value.toString())
  326. // 2. If entries is failure, then throw a TypeError.
  327. // 3. Return a new FormData object whose entry list is entries.
  328. const fd = new FormData()
  329. for (const [name, value] of entries) {
  330. fd.append(name, value)
  331. }
  332. return fd
  333. }
  334. }
  335. }
  336. // 3. Throw a TypeError.
  337. throw new TypeError(
  338. 'Content-Type was not one of "multipart/form-data" or "application/x-www-form-urlencoded".'
  339. )
  340. }, instance)
  341. },
  342. bytes () {
  343. // The bytes() method steps are to return the result of running consume body
  344. // with this and the following step given a byte sequence bytes: return the
  345. // result of creating a Uint8Array from bytes in this’s relevant realm.
  346. return consumeBody(this, (bytes) => {
  347. return new Uint8Array(bytes)
  348. }, instance)
  349. }
  350. }
  351. return methods
  352. }
  353. function mixinBody (prototype) {
  354. Object.assign(prototype.prototype, bodyMixinMethods(prototype))
  355. }
  356. /**
  357. * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
  358. * @param {Response|Request} object
  359. * @param {(value: unknown) => unknown} convertBytesToJSValue
  360. * @param {Response|Request} instance
  361. */
  362. async function consumeBody (object, convertBytesToJSValue, instance) {
  363. webidl.brandCheck(object, instance)
  364. // 1. If object is unusable, then return a promise rejected
  365. // with a TypeError.
  366. if (bodyUnusable(object)) {
  367. throw new TypeError('Body is unusable: Body has already been read')
  368. }
  369. throwIfAborted(object[kState])
  370. // 2. Let promise be a new promise.
  371. const promise = createDeferredPromise()
  372. // 3. Let errorSteps given error be to reject promise with error.
  373. const errorSteps = (error) => promise.reject(error)
  374. // 4. Let successSteps given a byte sequence data be to resolve
  375. // promise with the result of running convertBytesToJSValue
  376. // with data. If that threw an exception, then run errorSteps
  377. // with that exception.
  378. const successSteps = (data) => {
  379. try {
  380. promise.resolve(convertBytesToJSValue(data))
  381. } catch (e) {
  382. errorSteps(e)
  383. }
  384. }
  385. // 5. If object’s body is null, then run successSteps with an
  386. // empty byte sequence.
  387. if (object[kState].body == null) {
  388. successSteps(Buffer.allocUnsafe(0))
  389. return promise.promise
  390. }
  391. // 6. Otherwise, fully read object’s body given successSteps,
  392. // errorSteps, and object’s relevant global object.
  393. await fullyReadBody(object[kState].body, successSteps, errorSteps)
  394. // 7. Return promise.
  395. return promise.promise
  396. }
  397. // https://fetch.spec.whatwg.org/#body-unusable
  398. function bodyUnusable (object) {
  399. const body = object[kState].body
  400. // An object including the Body interface mixin is
  401. // said to be unusable if its body is non-null and
  402. // its body’s stream is disturbed or locked.
  403. return body != null && (body.stream.locked || util.isDisturbed(body.stream))
  404. }
  405. /**
  406. * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
  407. * @param {Uint8Array} bytes
  408. */
  409. function parseJSONFromBytes (bytes) {
  410. return JSON.parse(utf8DecodeBytes(bytes))
  411. }
  412. /**
  413. * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
  414. * @param {import('./response').Response|import('./request').Request} requestOrResponse
  415. */
  416. function bodyMimeType (requestOrResponse) {
  417. // 1. Let headers be null.
  418. // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list.
  419. // 3. Otherwise, set headers to requestOrResponse’s response’s header list.
  420. /** @type {import('./headers').HeadersList} */
  421. const headers = requestOrResponse[kState].headersList
  422. // 4. Let mimeType be the result of extracting a MIME type from headers.
  423. const mimeType = extractMimeType(headers)
  424. // 5. If mimeType is failure, then return null.
  425. if (mimeType === 'failure') {
  426. return null
  427. }
  428. // 6. Return mimeType.
  429. return mimeType
  430. }
  431. module.exports = {
  432. extractBody,
  433. safelyExtractBody,
  434. cloneBody,
  435. mixinBody,
  436. streamRegistry,
  437. hasFinalizationRegistry,
  438. bodyUnusable
  439. }