index.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266
  1. // https://github.com/Ethan-Arrowood/undici-fetch
  2. 'use strict'
  3. const {
  4. makeNetworkError,
  5. makeAppropriateNetworkError,
  6. filterResponse,
  7. makeResponse,
  8. fromInnerResponse
  9. } = require('./response')
  10. const { HeadersList } = require('./headers')
  11. const { Request, cloneRequest } = require('./request')
  12. const zlib = require('node:zlib')
  13. const {
  14. bytesMatch,
  15. makePolicyContainer,
  16. clonePolicyContainer,
  17. requestBadPort,
  18. TAOCheck,
  19. appendRequestOriginHeader,
  20. responseLocationURL,
  21. requestCurrentURL,
  22. setRequestReferrerPolicyOnRedirect,
  23. tryUpgradeRequestToAPotentiallyTrustworthyURL,
  24. createOpaqueTimingInfo,
  25. appendFetchMetadata,
  26. corsCheck,
  27. crossOriginResourcePolicyCheck,
  28. determineRequestsReferrer,
  29. coarsenedSharedCurrentTime,
  30. createDeferredPromise,
  31. isBlobLike,
  32. sameOrigin,
  33. isCancelled,
  34. isAborted,
  35. isErrorLike,
  36. fullyReadBody,
  37. readableStreamClose,
  38. isomorphicEncode,
  39. urlIsLocal,
  40. urlIsHttpHttpsScheme,
  41. urlHasHttpsScheme,
  42. clampAndCoarsenConnectionTimingInfo,
  43. simpleRangeHeaderValue,
  44. buildContentRange,
  45. createInflate,
  46. extractMimeType
  47. } = require('./util')
  48. const { kState, kDispatcher } = require('./symbols')
  49. const assert = require('node:assert')
  50. const { safelyExtractBody, extractBody } = require('./body')
  51. const {
  52. redirectStatusSet,
  53. nullBodyStatus,
  54. safeMethodsSet,
  55. requestBodyHeader,
  56. subresourceSet
  57. } = require('./constants')
  58. const EE = require('node:events')
  59. const { Readable, pipeline, finished } = require('node:stream')
  60. const { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = require('../../core/util')
  61. const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url')
  62. const { getGlobalDispatcher } = require('../../global')
  63. const { webidl } = require('./webidl')
  64. const { STATUS_CODES } = require('node:http')
  65. const GET_OR_HEAD = ['GET', 'HEAD']
  66. const defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'
  67. ? 'node'
  68. : 'undici'
  69. /** @type {import('buffer').resolveObjectURL} */
  70. let resolveObjectURL
  71. class Fetch extends EE {
  72. constructor (dispatcher) {
  73. super()
  74. this.dispatcher = dispatcher
  75. this.connection = null
  76. this.dump = false
  77. this.state = 'ongoing'
  78. }
  79. terminate (reason) {
  80. if (this.state !== 'ongoing') {
  81. return
  82. }
  83. this.state = 'terminated'
  84. this.connection?.destroy(reason)
  85. this.emit('terminated', reason)
  86. }
  87. // https://fetch.spec.whatwg.org/#fetch-controller-abort
  88. abort (error) {
  89. if (this.state !== 'ongoing') {
  90. return
  91. }
  92. // 1. Set controller’s state to "aborted".
  93. this.state = 'aborted'
  94. // 2. Let fallbackError be an "AbortError" DOMException.
  95. // 3. Set error to fallbackError if it is not given.
  96. if (!error) {
  97. error = new DOMException('The operation was aborted.', 'AbortError')
  98. }
  99. // 4. Let serializedError be StructuredSerialize(error).
  100. // If that threw an exception, catch it, and let
  101. // serializedError be StructuredSerialize(fallbackError).
  102. // 5. Set controller’s serialized abort reason to serializedError.
  103. this.serializedAbortReason = error
  104. this.connection?.destroy(error)
  105. this.emit('terminated', error)
  106. }
  107. }
  108. function handleFetchDone (response) {
  109. finalizeAndReportTiming(response, 'fetch')
  110. }
  111. // https://fetch.spec.whatwg.org/#fetch-method
  112. function fetch (input, init = undefined) {
  113. webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')
  114. // 1. Let p be a new promise.
  115. let p = createDeferredPromise()
  116. // 2. Let requestObject be the result of invoking the initial value of
  117. // Request as constructor with input and init as arguments. If this throws
  118. // an exception, reject p with it and return p.
  119. let requestObject
  120. try {
  121. requestObject = new Request(input, init)
  122. } catch (e) {
  123. p.reject(e)
  124. return p.promise
  125. }
  126. // 3. Let request be requestObject’s request.
  127. const request = requestObject[kState]
  128. // 4. If requestObject’s signal’s aborted flag is set, then:
  129. if (requestObject.signal.aborted) {
  130. // 1. Abort the fetch() call with p, request, null, and
  131. // requestObject’s signal’s abort reason.
  132. abortFetch(p, request, null, requestObject.signal.reason)
  133. // 2. Return p.
  134. return p.promise
  135. }
  136. // 5. Let globalObject be request’s client’s global object.
  137. const globalObject = request.client.globalObject
  138. // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
  139. // request’s service-workers mode to "none".
  140. if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
  141. request.serviceWorkers = 'none'
  142. }
  143. // 7. Let responseObject be null.
  144. let responseObject = null
  145. // 8. Let relevantRealm be this’s relevant Realm.
  146. // 9. Let locallyAborted be false.
  147. let locallyAborted = false
  148. // 10. Let controller be null.
  149. let controller = null
  150. // 11. Add the following abort steps to requestObject’s signal:
  151. addAbortListener(
  152. requestObject.signal,
  153. () => {
  154. // 1. Set locallyAborted to true.
  155. locallyAborted = true
  156. // 2. Assert: controller is non-null.
  157. assert(controller != null)
  158. // 3. Abort controller with requestObject’s signal’s abort reason.
  159. controller.abort(requestObject.signal.reason)
  160. const realResponse = responseObject?.deref()
  161. // 4. Abort the fetch() call with p, request, responseObject,
  162. // and requestObject’s signal’s abort reason.
  163. abortFetch(p, request, realResponse, requestObject.signal.reason)
  164. }
  165. )
  166. // 12. Let handleFetchDone given response response be to finalize and
  167. // report timing with response, globalObject, and "fetch".
  168. // see function handleFetchDone
  169. // 13. Set controller to the result of calling fetch given request,
  170. // with processResponseEndOfBody set to handleFetchDone, and processResponse
  171. // given response being these substeps:
  172. const processResponse = (response) => {
  173. // 1. If locallyAborted is true, terminate these substeps.
  174. if (locallyAborted) {
  175. return
  176. }
  177. // 2. If response’s aborted flag is set, then:
  178. if (response.aborted) {
  179. // 1. Let deserializedError be the result of deserialize a serialized
  180. // abort reason given controller’s serialized abort reason and
  181. // relevantRealm.
  182. // 2. Abort the fetch() call with p, request, responseObject, and
  183. // deserializedError.
  184. abortFetch(p, request, responseObject, controller.serializedAbortReason)
  185. return
  186. }
  187. // 3. If response is a network error, then reject p with a TypeError
  188. // and terminate these substeps.
  189. if (response.type === 'error') {
  190. p.reject(new TypeError('fetch failed', { cause: response.error }))
  191. return
  192. }
  193. // 4. Set responseObject to the result of creating a Response object,
  194. // given response, "immutable", and relevantRealm.
  195. responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))
  196. // 5. Resolve p with responseObject.
  197. p.resolve(responseObject.deref())
  198. p = null
  199. }
  200. controller = fetching({
  201. request,
  202. processResponseEndOfBody: handleFetchDone,
  203. processResponse,
  204. dispatcher: requestObject[kDispatcher] // undici
  205. })
  206. // 14. Return p.
  207. return p.promise
  208. }
  209. // https://fetch.spec.whatwg.org/#finalize-and-report-timing
  210. function finalizeAndReportTiming (response, initiatorType = 'other') {
  211. // 1. If response is an aborted network error, then return.
  212. if (response.type === 'error' && response.aborted) {
  213. return
  214. }
  215. // 2. If response’s URL list is null or empty, then return.
  216. if (!response.urlList?.length) {
  217. return
  218. }
  219. // 3. Let originalURL be response’s URL list[0].
  220. const originalURL = response.urlList[0]
  221. // 4. Let timingInfo be response’s timing info.
  222. let timingInfo = response.timingInfo
  223. // 5. Let cacheState be response’s cache state.
  224. let cacheState = response.cacheState
  225. // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
  226. if (!urlIsHttpHttpsScheme(originalURL)) {
  227. return
  228. }
  229. // 7. If timingInfo is null, then return.
  230. if (timingInfo === null) {
  231. return
  232. }
  233. // 8. If response’s timing allow passed flag is not set, then:
  234. if (!response.timingAllowPassed) {
  235. // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
  236. timingInfo = createOpaqueTimingInfo({
  237. startTime: timingInfo.startTime
  238. })
  239. // 2. Set cacheState to the empty string.
  240. cacheState = ''
  241. }
  242. // 9. Set timingInfo’s end time to the coarsened shared current time
  243. // given global’s relevant settings object’s cross-origin isolated
  244. // capability.
  245. // TODO: given global’s relevant settings object’s cross-origin isolated
  246. // capability?
  247. timingInfo.endTime = coarsenedSharedCurrentTime()
  248. // 10. Set response’s timing info to timingInfo.
  249. response.timingInfo = timingInfo
  250. // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
  251. // global, and cacheState.
  252. markResourceTiming(
  253. timingInfo,
  254. originalURL.href,
  255. initiatorType,
  256. globalThis,
  257. cacheState
  258. )
  259. }
  260. // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
  261. const markResourceTiming = performance.markResourceTiming
  262. // https://fetch.spec.whatwg.org/#abort-fetch
  263. function abortFetch (p, request, responseObject, error) {
  264. // 1. Reject promise with error.
  265. if (p) {
  266. // We might have already resolved the promise at this stage
  267. p.reject(error)
  268. }
  269. // 2. If request’s body is not null and is readable, then cancel request’s
  270. // body with error.
  271. if (request.body != null && isReadable(request.body?.stream)) {
  272. request.body.stream.cancel(error).catch((err) => {
  273. if (err.code === 'ERR_INVALID_STATE') {
  274. // Node bug?
  275. return
  276. }
  277. throw err
  278. })
  279. }
  280. // 3. If responseObject is null, then return.
  281. if (responseObject == null) {
  282. return
  283. }
  284. // 4. Let response be responseObject’s response.
  285. const response = responseObject[kState]
  286. // 5. If response’s body is not null and is readable, then error response’s
  287. // body with error.
  288. if (response.body != null && isReadable(response.body?.stream)) {
  289. response.body.stream.cancel(error).catch((err) => {
  290. if (err.code === 'ERR_INVALID_STATE') {
  291. // Node bug?
  292. return
  293. }
  294. throw err
  295. })
  296. }
  297. }
  298. // https://fetch.spec.whatwg.org/#fetching
  299. function fetching ({
  300. request,
  301. processRequestBodyChunkLength,
  302. processRequestEndOfBody,
  303. processResponse,
  304. processResponseEndOfBody,
  305. processResponseConsumeBody,
  306. useParallelQueue = false,
  307. dispatcher = getGlobalDispatcher() // undici
  308. }) {
  309. // Ensure that the dispatcher is set accordingly
  310. assert(dispatcher)
  311. // 1. Let taskDestination be null.
  312. let taskDestination = null
  313. // 2. Let crossOriginIsolatedCapability be false.
  314. let crossOriginIsolatedCapability = false
  315. // 3. If request’s client is non-null, then:
  316. if (request.client != null) {
  317. // 1. Set taskDestination to request’s client’s global object.
  318. taskDestination = request.client.globalObject
  319. // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
  320. // isolated capability.
  321. crossOriginIsolatedCapability =
  322. request.client.crossOriginIsolatedCapability
  323. }
  324. // 4. If useParallelQueue is true, then set taskDestination to the result of
  325. // starting a new parallel queue.
  326. // TODO
  327. // 5. Let timingInfo be a new fetch timing info whose start time and
  328. // post-redirect start time are the coarsened shared current time given
  329. // crossOriginIsolatedCapability.
  330. const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
  331. const timingInfo = createOpaqueTimingInfo({
  332. startTime: currentTime
  333. })
  334. // 6. Let fetchParams be a new fetch params whose
  335. // request is request,
  336. // timing info is timingInfo,
  337. // process request body chunk length is processRequestBodyChunkLength,
  338. // process request end-of-body is processRequestEndOfBody,
  339. // process response is processResponse,
  340. // process response consume body is processResponseConsumeBody,
  341. // process response end-of-body is processResponseEndOfBody,
  342. // task destination is taskDestination,
  343. // and cross-origin isolated capability is crossOriginIsolatedCapability.
  344. const fetchParams = {
  345. controller: new Fetch(dispatcher),
  346. request,
  347. timingInfo,
  348. processRequestBodyChunkLength,
  349. processRequestEndOfBody,
  350. processResponse,
  351. processResponseConsumeBody,
  352. processResponseEndOfBody,
  353. taskDestination,
  354. crossOriginIsolatedCapability
  355. }
  356. // 7. If request’s body is a byte sequence, then set request’s body to
  357. // request’s body as a body.
  358. // NOTE: Since fetching is only called from fetch, body should already be
  359. // extracted.
  360. assert(!request.body || request.body.stream)
  361. // 8. If request’s window is "client", then set request’s window to request’s
  362. // client, if request’s client’s global object is a Window object; otherwise
  363. // "no-window".
  364. if (request.window === 'client') {
  365. // TODO: What if request.client is null?
  366. request.window =
  367. request.client?.globalObject?.constructor?.name === 'Window'
  368. ? request.client
  369. : 'no-window'
  370. }
  371. // 9. If request’s origin is "client", then set request’s origin to request’s
  372. // client’s origin.
  373. if (request.origin === 'client') {
  374. request.origin = request.client.origin
  375. }
  376. // 10. If all of the following conditions are true:
  377. // TODO
  378. // 11. If request’s policy container is "client", then:
  379. if (request.policyContainer === 'client') {
  380. // 1. If request’s client is non-null, then set request’s policy
  381. // container to a clone of request’s client’s policy container. [HTML]
  382. if (request.client != null) {
  383. request.policyContainer = clonePolicyContainer(
  384. request.client.policyContainer
  385. )
  386. } else {
  387. // 2. Otherwise, set request’s policy container to a new policy
  388. // container.
  389. request.policyContainer = makePolicyContainer()
  390. }
  391. }
  392. // 12. If request’s header list does not contain `Accept`, then:
  393. if (!request.headersList.contains('accept', true)) {
  394. // 1. Let value be `*/*`.
  395. const value = '*/*'
  396. // 2. A user agent should set value to the first matching statement, if
  397. // any, switching on request’s destination:
  398. // "document"
  399. // "frame"
  400. // "iframe"
  401. // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
  402. // "image"
  403. // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
  404. // "style"
  405. // `text/css,*/*;q=0.1`
  406. // TODO
  407. // 3. Append `Accept`/value to request’s header list.
  408. request.headersList.append('accept', value, true)
  409. }
  410. // 13. If request’s header list does not contain `Accept-Language`, then
  411. // user agents should append `Accept-Language`/an appropriate value to
  412. // request’s header list.
  413. if (!request.headersList.contains('accept-language', true)) {
  414. request.headersList.append('accept-language', '*', true)
  415. }
  416. // 14. If request’s priority is null, then use request’s initiator and
  417. // destination appropriately in setting request’s priority to a
  418. // user-agent-defined object.
  419. if (request.priority === null) {
  420. // TODO
  421. }
  422. // 15. If request is a subresource request, then:
  423. if (subresourceSet.has(request.destination)) {
  424. // TODO
  425. }
  426. // 16. Run main fetch given fetchParams.
  427. mainFetch(fetchParams)
  428. .catch(err => {
  429. fetchParams.controller.terminate(err)
  430. })
  431. // 17. Return fetchParam's controller
  432. return fetchParams.controller
  433. }
  434. // https://fetch.spec.whatwg.org/#concept-main-fetch
  435. async function mainFetch (fetchParams, recursive = false) {
  436. // 1. Let request be fetchParams’s request.
  437. const request = fetchParams.request
  438. // 2. Let response be null.
  439. let response = null
  440. // 3. If request’s local-URLs-only flag is set and request’s current URL is
  441. // not local, then set response to a network error.
  442. if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
  443. response = makeNetworkError('local URLs only')
  444. }
  445. // 4. Run report Content Security Policy violations for request.
  446. // TODO
  447. // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
  448. tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
  449. // 6. If should request be blocked due to a bad port, should fetching request
  450. // be blocked as mixed content, or should request be blocked by Content
  451. // Security Policy returns blocked, then set response to a network error.
  452. if (requestBadPort(request) === 'blocked') {
  453. response = makeNetworkError('bad port')
  454. }
  455. // TODO: should fetching request be blocked as mixed content?
  456. // TODO: should request be blocked by Content Security Policy?
  457. // 7. If request’s referrer policy is the empty string, then set request’s
  458. // referrer policy to request’s policy container’s referrer policy.
  459. if (request.referrerPolicy === '') {
  460. request.referrerPolicy = request.policyContainer.referrerPolicy
  461. }
  462. // 8. If request’s referrer is not "no-referrer", then set request’s
  463. // referrer to the result of invoking determine request’s referrer.
  464. if (request.referrer !== 'no-referrer') {
  465. request.referrer = determineRequestsReferrer(request)
  466. }
  467. // 9. Set request’s current URL’s scheme to "https" if all of the following
  468. // conditions are true:
  469. // - request’s current URL’s scheme is "http"
  470. // - request’s current URL’s host is a domain
  471. // - Matching request’s current URL’s host per Known HSTS Host Domain Name
  472. // Matching results in either a superdomain match with an asserted
  473. // includeSubDomains directive or a congruent match (with or without an
  474. // asserted includeSubDomains directive). [HSTS]
  475. // TODO
  476. // 10. If recursive is false, then run the remaining steps in parallel.
  477. // TODO
  478. // 11. If response is null, then set response to the result of running
  479. // the steps corresponding to the first matching statement:
  480. if (response === null) {
  481. response = await (async () => {
  482. const currentURL = requestCurrentURL(request)
  483. if (
  484. // - request’s current URL’s origin is same origin with request’s origin,
  485. // and request’s response tainting is "basic"
  486. (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
  487. // request’s current URL’s scheme is "data"
  488. (currentURL.protocol === 'data:') ||
  489. // - request’s mode is "navigate" or "websocket"
  490. (request.mode === 'navigate' || request.mode === 'websocket')
  491. ) {
  492. // 1. Set request’s response tainting to "basic".
  493. request.responseTainting = 'basic'
  494. // 2. Return the result of running scheme fetch given fetchParams.
  495. return await schemeFetch(fetchParams)
  496. }
  497. // request’s mode is "same-origin"
  498. if (request.mode === 'same-origin') {
  499. // 1. Return a network error.
  500. return makeNetworkError('request mode cannot be "same-origin"')
  501. }
  502. // request’s mode is "no-cors"
  503. if (request.mode === 'no-cors') {
  504. // 1. If request’s redirect mode is not "follow", then return a network
  505. // error.
  506. if (request.redirect !== 'follow') {
  507. return makeNetworkError(
  508. 'redirect mode cannot be "follow" for "no-cors" request'
  509. )
  510. }
  511. // 2. Set request’s response tainting to "opaque".
  512. request.responseTainting = 'opaque'
  513. // 3. Return the result of running scheme fetch given fetchParams.
  514. return await schemeFetch(fetchParams)
  515. }
  516. // request’s current URL’s scheme is not an HTTP(S) scheme
  517. if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
  518. // Return a network error.
  519. return makeNetworkError('URL scheme must be a HTTP(S) scheme')
  520. }
  521. // - request’s use-CORS-preflight flag is set
  522. // - request’s unsafe-request flag is set and either request’s method is
  523. // not a CORS-safelisted method or CORS-unsafe request-header names with
  524. // request’s header list is not empty
  525. // 1. Set request’s response tainting to "cors".
  526. // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
  527. // given fetchParams and true.
  528. // 3. If corsWithPreflightResponse is a network error, then clear cache
  529. // entries using request.
  530. // 4. Return corsWithPreflightResponse.
  531. // TODO
  532. // Otherwise
  533. // 1. Set request’s response tainting to "cors".
  534. request.responseTainting = 'cors'
  535. // 2. Return the result of running HTTP fetch given fetchParams.
  536. return await httpFetch(fetchParams)
  537. })()
  538. }
  539. // 12. If recursive is true, then return response.
  540. if (recursive) {
  541. return response
  542. }
  543. // 13. If response is not a network error and response is not a filtered
  544. // response, then:
  545. if (response.status !== 0 && !response.internalResponse) {
  546. // If request’s response tainting is "cors", then:
  547. if (request.responseTainting === 'cors') {
  548. // 1. Let headerNames be the result of extracting header list values
  549. // given `Access-Control-Expose-Headers` and response’s header list.
  550. // TODO
  551. // 2. If request’s credentials mode is not "include" and headerNames
  552. // contains `*`, then set response’s CORS-exposed header-name list to
  553. // all unique header names in response’s header list.
  554. // TODO
  555. // 3. Otherwise, if headerNames is not null or failure, then set
  556. // response’s CORS-exposed header-name list to headerNames.
  557. // TODO
  558. }
  559. // Set response to the following filtered response with response as its
  560. // internal response, depending on request’s response tainting:
  561. if (request.responseTainting === 'basic') {
  562. response = filterResponse(response, 'basic')
  563. } else if (request.responseTainting === 'cors') {
  564. response = filterResponse(response, 'cors')
  565. } else if (request.responseTainting === 'opaque') {
  566. response = filterResponse(response, 'opaque')
  567. } else {
  568. assert(false)
  569. }
  570. }
  571. // 14. Let internalResponse be response, if response is a network error,
  572. // and response’s internal response otherwise.
  573. let internalResponse =
  574. response.status === 0 ? response : response.internalResponse
  575. // 15. If internalResponse’s URL list is empty, then set it to a clone of
  576. // request’s URL list.
  577. if (internalResponse.urlList.length === 0) {
  578. internalResponse.urlList.push(...request.urlList)
  579. }
  580. // 16. If request’s timing allow failed flag is unset, then set
  581. // internalResponse’s timing allow passed flag.
  582. if (!request.timingAllowFailed) {
  583. response.timingAllowPassed = true
  584. }
  585. // 17. If response is not a network error and any of the following returns
  586. // blocked
  587. // - should internalResponse to request be blocked as mixed content
  588. // - should internalResponse to request be blocked by Content Security Policy
  589. // - should internalResponse to request be blocked due to its MIME type
  590. // - should internalResponse to request be blocked due to nosniff
  591. // TODO
  592. // 18. If response’s type is "opaque", internalResponse’s status is 206,
  593. // internalResponse’s range-requested flag is set, and request’s header
  594. // list does not contain `Range`, then set response and internalResponse
  595. // to a network error.
  596. if (
  597. response.type === 'opaque' &&
  598. internalResponse.status === 206 &&
  599. internalResponse.rangeRequested &&
  600. !request.headers.contains('range', true)
  601. ) {
  602. response = internalResponse = makeNetworkError()
  603. }
  604. // 19. If response is not a network error and either request’s method is
  605. // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
  606. // set internalResponse’s body to null and disregard any enqueuing toward
  607. // it (if any).
  608. if (
  609. response.status !== 0 &&
  610. (request.method === 'HEAD' ||
  611. request.method === 'CONNECT' ||
  612. nullBodyStatus.includes(internalResponse.status))
  613. ) {
  614. internalResponse.body = null
  615. fetchParams.controller.dump = true
  616. }
  617. // 20. If request’s integrity metadata is not the empty string, then:
  618. if (request.integrity) {
  619. // 1. Let processBodyError be this step: run fetch finale given fetchParams
  620. // and a network error.
  621. const processBodyError = (reason) =>
  622. fetchFinale(fetchParams, makeNetworkError(reason))
  623. // 2. If request’s response tainting is "opaque", or response’s body is null,
  624. // then run processBodyError and abort these steps.
  625. if (request.responseTainting === 'opaque' || response.body == null) {
  626. processBodyError(response.error)
  627. return
  628. }
  629. // 3. Let processBody given bytes be these steps:
  630. const processBody = (bytes) => {
  631. // 1. If bytes do not match request’s integrity metadata,
  632. // then run processBodyError and abort these steps. [SRI]
  633. if (!bytesMatch(bytes, request.integrity)) {
  634. processBodyError('integrity mismatch')
  635. return
  636. }
  637. // 2. Set response’s body to bytes as a body.
  638. response.body = safelyExtractBody(bytes)[0]
  639. // 3. Run fetch finale given fetchParams and response.
  640. fetchFinale(fetchParams, response)
  641. }
  642. // 4. Fully read response’s body given processBody and processBodyError.
  643. await fullyReadBody(response.body, processBody, processBodyError)
  644. } else {
  645. // 21. Otherwise, run fetch finale given fetchParams and response.
  646. fetchFinale(fetchParams, response)
  647. }
  648. }
  649. // https://fetch.spec.whatwg.org/#concept-scheme-fetch
  650. // given a fetch params fetchParams
  651. function schemeFetch (fetchParams) {
  652. // Note: since the connection is destroyed on redirect, which sets fetchParams to a
  653. // cancelled state, we do not want this condition to trigger *unless* there have been
  654. // no redirects. See https://github.com/nodejs/undici/issues/1776
  655. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  656. if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
  657. return Promise.resolve(makeAppropriateNetworkError(fetchParams))
  658. }
  659. // 2. Let request be fetchParams’s request.
  660. const { request } = fetchParams
  661. const { protocol: scheme } = requestCurrentURL(request)
  662. // 3. Switch on request’s current URL’s scheme and run the associated steps:
  663. switch (scheme) {
  664. case 'about:': {
  665. // If request’s current URL’s path is the string "blank", then return a new response
  666. // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
  667. // and body is the empty byte sequence as a body.
  668. // Otherwise, return a network error.
  669. return Promise.resolve(makeNetworkError('about scheme is not supported'))
  670. }
  671. case 'blob:': {
  672. if (!resolveObjectURL) {
  673. resolveObjectURL = require('node:buffer').resolveObjectURL
  674. }
  675. // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
  676. const blobURLEntry = requestCurrentURL(request)
  677. // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
  678. // Buffer.resolveObjectURL does not ignore URL queries.
  679. if (blobURLEntry.search.length !== 0) {
  680. return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
  681. }
  682. const blob = resolveObjectURL(blobURLEntry.toString())
  683. // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
  684. // object is not a Blob object, then return a network error.
  685. if (request.method !== 'GET' || !isBlobLike(blob)) {
  686. return Promise.resolve(makeNetworkError('invalid method'))
  687. }
  688. // 3. Let blob be blobURLEntry’s object.
  689. // Note: done above
  690. // 4. Let response be a new response.
  691. const response = makeResponse()
  692. // 5. Let fullLength be blob’s size.
  693. const fullLength = blob.size
  694. // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.
  695. const serializedFullLength = isomorphicEncode(`${fullLength}`)
  696. // 7. Let type be blob’s type.
  697. const type = blob.type
  698. // 8. If request’s header list does not contain `Range`:
  699. // 9. Otherwise:
  700. if (!request.headersList.contains('range', true)) {
  701. // 1. Let bodyWithType be the result of safely extracting blob.
  702. // Note: in the FileAPI a blob "object" is a Blob *or* a MediaSource.
  703. // In node, this can only ever be a Blob. Therefore we can safely
  704. // use extractBody directly.
  705. const bodyWithType = extractBody(blob)
  706. // 2. Set response’s status message to `OK`.
  707. response.statusText = 'OK'
  708. // 3. Set response’s body to bodyWithType’s body.
  709. response.body = bodyWithType[0]
  710. // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».
  711. response.headersList.set('content-length', serializedFullLength, true)
  712. response.headersList.set('content-type', type, true)
  713. } else {
  714. // 1. Set response’s range-requested flag.
  715. response.rangeRequested = true
  716. // 2. Let rangeHeader be the result of getting `Range` from request’s header list.
  717. const rangeHeader = request.headersList.get('range', true)
  718. // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.
  719. const rangeValue = simpleRangeHeaderValue(rangeHeader, true)
  720. // 4. If rangeValue is failure, then return a network error.
  721. if (rangeValue === 'failure') {
  722. return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
  723. }
  724. // 5. Let (rangeStart, rangeEnd) be rangeValue.
  725. let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue
  726. // 6. If rangeStart is null:
  727. // 7. Otherwise:
  728. if (rangeStart === null) {
  729. // 1. Set rangeStart to fullLength − rangeEnd.
  730. rangeStart = fullLength - rangeEnd
  731. // 2. Set rangeEnd to rangeStart + rangeEnd − 1.
  732. rangeEnd = rangeStart + rangeEnd - 1
  733. } else {
  734. // 1. If rangeStart is greater than or equal to fullLength, then return a network error.
  735. if (rangeStart >= fullLength) {
  736. return Promise.resolve(makeNetworkError('Range start is greater than the blob\'s size.'))
  737. }
  738. // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set
  739. // rangeEnd to fullLength − 1.
  740. if (rangeEnd === null || rangeEnd >= fullLength) {
  741. rangeEnd = fullLength - 1
  742. }
  743. }
  744. // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart,
  745. // rangeEnd + 1, and type.
  746. const slicedBlob = blob.slice(rangeStart, rangeEnd, type)
  747. // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.
  748. // Note: same reason as mentioned above as to why we use extractBody
  749. const slicedBodyWithType = extractBody(slicedBlob)
  750. // 10. Set response’s body to slicedBodyWithType’s body.
  751. response.body = slicedBodyWithType[0]
  752. // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.
  753. const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`)
  754. // 12. Let contentRange be the result of invoking build a content range given rangeStart,
  755. // rangeEnd, and fullLength.
  756. const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength)
  757. // 13. Set response’s status to 206.
  758. response.status = 206
  759. // 14. Set response’s status message to `Partial Content`.
  760. response.statusText = 'Partial Content'
  761. // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength),
  762. // (`Content-Type`, type), (`Content-Range`, contentRange) ».
  763. response.headersList.set('content-length', serializedSlicedLength, true)
  764. response.headersList.set('content-type', type, true)
  765. response.headersList.set('content-range', contentRange, true)
  766. }
  767. // 10. Return response.
  768. return Promise.resolve(response)
  769. }
  770. case 'data:': {
  771. // 1. Let dataURLStruct be the result of running the
  772. // data: URL processor on request’s current URL.
  773. const currentURL = requestCurrentURL(request)
  774. const dataURLStruct = dataURLProcessor(currentURL)
  775. // 2. If dataURLStruct is failure, then return a
  776. // network error.
  777. if (dataURLStruct === 'failure') {
  778. return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
  779. }
  780. // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
  781. const mimeType = serializeAMimeType(dataURLStruct.mimeType)
  782. // 4. Return a response whose status message is `OK`,
  783. // header list is « (`Content-Type`, mimeType) »,
  784. // and body is dataURLStruct’s body as a body.
  785. return Promise.resolve(makeResponse({
  786. statusText: 'OK',
  787. headersList: [
  788. ['content-type', { name: 'Content-Type', value: mimeType }]
  789. ],
  790. body: safelyExtractBody(dataURLStruct.body)[0]
  791. }))
  792. }
  793. case 'file:': {
  794. // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
  795. // When in doubt, return a network error.
  796. return Promise.resolve(makeNetworkError('not implemented... yet...'))
  797. }
  798. case 'http:':
  799. case 'https:': {
  800. // Return the result of running HTTP fetch given fetchParams.
  801. return httpFetch(fetchParams)
  802. .catch((err) => makeNetworkError(err))
  803. }
  804. default: {
  805. return Promise.resolve(makeNetworkError('unknown scheme'))
  806. }
  807. }
  808. }
  809. // https://fetch.spec.whatwg.org/#finalize-response
  810. function finalizeResponse (fetchParams, response) {
  811. // 1. Set fetchParams’s request’s done flag.
  812. fetchParams.request.done = true
  813. // 2, If fetchParams’s process response done is not null, then queue a fetch
  814. // task to run fetchParams’s process response done given response, with
  815. // fetchParams’s task destination.
  816. if (fetchParams.processResponseDone != null) {
  817. queueMicrotask(() => fetchParams.processResponseDone(response))
  818. }
  819. }
  820. // https://fetch.spec.whatwg.org/#fetch-finale
  821. function fetchFinale (fetchParams, response) {
  822. // 1. Let timingInfo be fetchParams’s timing info.
  823. let timingInfo = fetchParams.timingInfo
  824. // 2. If response is not a network error and fetchParams’s request’s client is a secure context,
  825. // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting
  826. // `Server-Timing` from response’s internal response’s header list.
  827. // TODO
  828. // 3. Let processResponseEndOfBody be the following steps:
  829. const processResponseEndOfBody = () => {
  830. // 1. Let unsafeEndTime be the unsafe shared current time.
  831. const unsafeEndTime = Date.now() // ?
  832. // 2. If fetchParams’s request’s destination is "document", then set fetchParams’s controller’s
  833. // full timing info to fetchParams’s timing info.
  834. if (fetchParams.request.destination === 'document') {
  835. fetchParams.controller.fullTimingInfo = timingInfo
  836. }
  837. // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:
  838. fetchParams.controller.reportTimingSteps = () => {
  839. // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.
  840. if (fetchParams.request.url.protocol !== 'https:') {
  841. return
  842. }
  843. // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.
  844. timingInfo.endTime = unsafeEndTime
  845. // 3. Let cacheState be response’s cache state.
  846. let cacheState = response.cacheState
  847. // 4. Let bodyInfo be response’s body info.
  848. const bodyInfo = response.bodyInfo
  849. // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an
  850. // opaque timing info for timingInfo and set cacheState to the empty string.
  851. if (!response.timingAllowPassed) {
  852. timingInfo = createOpaqueTimingInfo(timingInfo)
  853. cacheState = ''
  854. }
  855. // 6. Let responseStatus be 0.
  856. let responseStatus = 0
  857. // 7. If fetchParams’s request’s mode is not "navigate" or response’s has-cross-origin-redirects is false:
  858. if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {
  859. // 1. Set responseStatus to response’s status.
  860. responseStatus = response.status
  861. // 2. Let mimeType be the result of extracting a MIME type from response’s header list.
  862. const mimeType = extractMimeType(response.headersList)
  863. // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.
  864. if (mimeType !== 'failure') {
  865. bodyInfo.contentType = minimizeSupportedMimeType(mimeType)
  866. }
  867. }
  868. // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo,
  869. // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo,
  870. // and responseStatus.
  871. if (fetchParams.request.initiatorType != null) {
  872. // TODO: update markresourcetiming
  873. markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus)
  874. }
  875. }
  876. // 4. Let processResponseEndOfBodyTask be the following steps:
  877. const processResponseEndOfBodyTask = () => {
  878. // 1. Set fetchParams’s request’s done flag.
  879. fetchParams.request.done = true
  880. // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process
  881. // response end-of-body given response.
  882. if (fetchParams.processResponseEndOfBody != null) {
  883. queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
  884. }
  885. // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s
  886. // global object is fetchParams’s task destination, then run fetchParams’s controller’s report
  887. // timing steps given fetchParams’s request’s client’s global object.
  888. if (fetchParams.request.initiatorType != null) {
  889. fetchParams.controller.reportTimingSteps()
  890. }
  891. }
  892. // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination
  893. queueMicrotask(() => processResponseEndOfBodyTask())
  894. }
  895. // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s
  896. // process response given response, with fetchParams’s task destination.
  897. if (fetchParams.processResponse != null) {
  898. queueMicrotask(() => {
  899. fetchParams.processResponse(response)
  900. fetchParams.processResponse = null
  901. })
  902. }
  903. // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.
  904. const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response)
  905. // 6. If internalResponse’s body is null, then run processResponseEndOfBody.
  906. // 7. Otherwise:
  907. if (internalResponse.body == null) {
  908. processResponseEndOfBody()
  909. } else {
  910. // mcollina: all the following steps of the specs are skipped.
  911. // The internal transform stream is not needed.
  912. // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541
  913. // 1. Let transformStream be a new TransformStream.
  914. // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.
  915. // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm
  916. // set to processResponseEndOfBody.
  917. // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.
  918. finished(internalResponse.body.stream, () => {
  919. processResponseEndOfBody()
  920. })
  921. }
  922. }
  923. // https://fetch.spec.whatwg.org/#http-fetch
  924. async function httpFetch (fetchParams) {
  925. // 1. Let request be fetchParams’s request.
  926. const request = fetchParams.request
  927. // 2. Let response be null.
  928. let response = null
  929. // 3. Let actualResponse be null.
  930. let actualResponse = null
  931. // 4. Let timingInfo be fetchParams’s timing info.
  932. const timingInfo = fetchParams.timingInfo
  933. // 5. If request’s service-workers mode is "all", then:
  934. if (request.serviceWorkers === 'all') {
  935. // TODO
  936. }
  937. // 6. If response is null, then:
  938. if (response === null) {
  939. // 1. If makeCORSPreflight is true and one of these conditions is true:
  940. // TODO
  941. // 2. If request’s redirect mode is "follow", then set request’s
  942. // service-workers mode to "none".
  943. if (request.redirect === 'follow') {
  944. request.serviceWorkers = 'none'
  945. }
  946. // 3. Set response and actualResponse to the result of running
  947. // HTTP-network-or-cache fetch given fetchParams.
  948. actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
  949. // 4. If request’s response tainting is "cors" and a CORS check
  950. // for request and response returns failure, then return a network error.
  951. if (
  952. request.responseTainting === 'cors' &&
  953. corsCheck(request, response) === 'failure'
  954. ) {
  955. return makeNetworkError('cors failure')
  956. }
  957. // 5. If the TAO check for request and response returns failure, then set
  958. // request’s timing allow failed flag.
  959. if (TAOCheck(request, response) === 'failure') {
  960. request.timingAllowFailed = true
  961. }
  962. }
  963. // 7. If either request’s response tainting or response’s type
  964. // is "opaque", and the cross-origin resource policy check with
  965. // request’s origin, request’s client, request’s destination,
  966. // and actualResponse returns blocked, then return a network error.
  967. if (
  968. (request.responseTainting === 'opaque' || response.type === 'opaque') &&
  969. crossOriginResourcePolicyCheck(
  970. request.origin,
  971. request.client,
  972. request.destination,
  973. actualResponse
  974. ) === 'blocked'
  975. ) {
  976. return makeNetworkError('blocked')
  977. }
  978. // 8. If actualResponse’s status is a redirect status, then:
  979. if (redirectStatusSet.has(actualResponse.status)) {
  980. // 1. If actualResponse’s status is not 303, request’s body is not null,
  981. // and the connection uses HTTP/2, then user agents may, and are even
  982. // encouraged to, transmit an RST_STREAM frame.
  983. // See, https://github.com/whatwg/fetch/issues/1288
  984. if (request.redirect !== 'manual') {
  985. fetchParams.controller.connection.destroy(undefined, false)
  986. }
  987. // 2. Switch on request’s redirect mode:
  988. if (request.redirect === 'error') {
  989. // Set response to a network error.
  990. response = makeNetworkError('unexpected redirect')
  991. } else if (request.redirect === 'manual') {
  992. // Set response to an opaque-redirect filtered response whose internal
  993. // response is actualResponse.
  994. // NOTE(spec): On the web this would return an `opaqueredirect` response,
  995. // but that doesn't make sense server side.
  996. // See https://github.com/nodejs/undici/issues/1193.
  997. response = actualResponse
  998. } else if (request.redirect === 'follow') {
  999. // Set response to the result of running HTTP-redirect fetch given
  1000. // fetchParams and response.
  1001. response = await httpRedirectFetch(fetchParams, response)
  1002. } else {
  1003. assert(false)
  1004. }
  1005. }
  1006. // 9. Set response’s timing info to timingInfo.
  1007. response.timingInfo = timingInfo
  1008. // 10. Return response.
  1009. return response
  1010. }
  1011. // https://fetch.spec.whatwg.org/#http-redirect-fetch
  1012. function httpRedirectFetch (fetchParams, response) {
  1013. // 1. Let request be fetchParams’s request.
  1014. const request = fetchParams.request
  1015. // 2. Let actualResponse be response, if response is not a filtered response,
  1016. // and response’s internal response otherwise.
  1017. const actualResponse = response.internalResponse
  1018. ? response.internalResponse
  1019. : response
  1020. // 3. Let locationURL be actualResponse’s location URL given request’s current
  1021. // URL’s fragment.
  1022. let locationURL
  1023. try {
  1024. locationURL = responseLocationURL(
  1025. actualResponse,
  1026. requestCurrentURL(request).hash
  1027. )
  1028. // 4. If locationURL is null, then return response.
  1029. if (locationURL == null) {
  1030. return response
  1031. }
  1032. } catch (err) {
  1033. // 5. If locationURL is failure, then return a network error.
  1034. return Promise.resolve(makeNetworkError(err))
  1035. }
  1036. // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
  1037. // error.
  1038. if (!urlIsHttpHttpsScheme(locationURL)) {
  1039. return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
  1040. }
  1041. // 7. If request’s redirect count is 20, then return a network error.
  1042. if (request.redirectCount === 20) {
  1043. return Promise.resolve(makeNetworkError('redirect count exceeded'))
  1044. }
  1045. // 8. Increase request’s redirect count by 1.
  1046. request.redirectCount += 1
  1047. // 9. If request’s mode is "cors", locationURL includes credentials, and
  1048. // request’s origin is not same origin with locationURL’s origin, then return
  1049. // a network error.
  1050. if (
  1051. request.mode === 'cors' &&
  1052. (locationURL.username || locationURL.password) &&
  1053. !sameOrigin(request, locationURL)
  1054. ) {
  1055. return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
  1056. }
  1057. // 10. If request’s response tainting is "cors" and locationURL includes
  1058. // credentials, then return a network error.
  1059. if (
  1060. request.responseTainting === 'cors' &&
  1061. (locationURL.username || locationURL.password)
  1062. ) {
  1063. return Promise.resolve(makeNetworkError(
  1064. 'URL cannot contain credentials for request mode "cors"'
  1065. ))
  1066. }
  1067. // 11. If actualResponse’s status is not 303, request’s body is non-null,
  1068. // and request’s body’s source is null, then return a network error.
  1069. if (
  1070. actualResponse.status !== 303 &&
  1071. request.body != null &&
  1072. request.body.source == null
  1073. ) {
  1074. return Promise.resolve(makeNetworkError())
  1075. }
  1076. // 12. If one of the following is true
  1077. // - actualResponse’s status is 301 or 302 and request’s method is `POST`
  1078. // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
  1079. if (
  1080. ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
  1081. (actualResponse.status === 303 &&
  1082. !GET_OR_HEAD.includes(request.method))
  1083. ) {
  1084. // then:
  1085. // 1. Set request’s method to `GET` and request’s body to null.
  1086. request.method = 'GET'
  1087. request.body = null
  1088. // 2. For each headerName of request-body-header name, delete headerName from
  1089. // request’s header list.
  1090. for (const headerName of requestBodyHeader) {
  1091. request.headersList.delete(headerName)
  1092. }
  1093. }
  1094. // 13. If request’s current URL’s origin is not same origin with locationURL’s
  1095. // origin, then for each headerName of CORS non-wildcard request-header name,
  1096. // delete headerName from request’s header list.
  1097. if (!sameOrigin(requestCurrentURL(request), locationURL)) {
  1098. // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
  1099. request.headersList.delete('authorization', true)
  1100. // https://fetch.spec.whatwg.org/#authentication-entries
  1101. request.headersList.delete('proxy-authorization', true)
  1102. // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
  1103. request.headersList.delete('cookie', true)
  1104. request.headersList.delete('host', true)
  1105. }
  1106. // 14. If request’s body is non-null, then set request’s body to the first return
  1107. // value of safely extracting request’s body’s source.
  1108. if (request.body != null) {
  1109. assert(request.body.source != null)
  1110. request.body = safelyExtractBody(request.body.source)[0]
  1111. }
  1112. // 15. Let timingInfo be fetchParams’s timing info.
  1113. const timingInfo = fetchParams.timingInfo
  1114. // 16. Set timingInfo’s redirect end time and post-redirect start time to the
  1115. // coarsened shared current time given fetchParams’s cross-origin isolated
  1116. // capability.
  1117. timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
  1118. coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1119. // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
  1120. // redirect start time to timingInfo’s start time.
  1121. if (timingInfo.redirectStartTime === 0) {
  1122. timingInfo.redirectStartTime = timingInfo.startTime
  1123. }
  1124. // 18. Append locationURL to request’s URL list.
  1125. request.urlList.push(locationURL)
  1126. // 19. Invoke set request’s referrer policy on redirect on request and
  1127. // actualResponse.
  1128. setRequestReferrerPolicyOnRedirect(request, actualResponse)
  1129. // 20. Return the result of running main fetch given fetchParams and true.
  1130. return mainFetch(fetchParams, true)
  1131. }
  1132. // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
  1133. async function httpNetworkOrCacheFetch (
  1134. fetchParams,
  1135. isAuthenticationFetch = false,
  1136. isNewConnectionFetch = false
  1137. ) {
  1138. // 1. Let request be fetchParams’s request.
  1139. const request = fetchParams.request
  1140. // 2. Let httpFetchParams be null.
  1141. let httpFetchParams = null
  1142. // 3. Let httpRequest be null.
  1143. let httpRequest = null
  1144. // 4. Let response be null.
  1145. let response = null
  1146. // 5. Let storedResponse be null.
  1147. // TODO: cache
  1148. // 6. Let httpCache be null.
  1149. const httpCache = null
  1150. // 7. Let the revalidatingFlag be unset.
  1151. const revalidatingFlag = false
  1152. // 8. Run these steps, but abort when the ongoing fetch is terminated:
  1153. // 1. If request’s window is "no-window" and request’s redirect mode is
  1154. // "error", then set httpFetchParams to fetchParams and httpRequest to
  1155. // request.
  1156. if (request.window === 'no-window' && request.redirect === 'error') {
  1157. httpFetchParams = fetchParams
  1158. httpRequest = request
  1159. } else {
  1160. // Otherwise:
  1161. // 1. Set httpRequest to a clone of request.
  1162. httpRequest = cloneRequest(request)
  1163. // 2. Set httpFetchParams to a copy of fetchParams.
  1164. httpFetchParams = { ...fetchParams }
  1165. // 3. Set httpFetchParams’s request to httpRequest.
  1166. httpFetchParams.request = httpRequest
  1167. }
  1168. // 3. Let includeCredentials be true if one of
  1169. const includeCredentials =
  1170. request.credentials === 'include' ||
  1171. (request.credentials === 'same-origin' &&
  1172. request.responseTainting === 'basic')
  1173. // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
  1174. // body is non-null; otherwise null.
  1175. const contentLength = httpRequest.body ? httpRequest.body.length : null
  1176. // 5. Let contentLengthHeaderValue be null.
  1177. let contentLengthHeaderValue = null
  1178. // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
  1179. // `PUT`, then set contentLengthHeaderValue to `0`.
  1180. if (
  1181. httpRequest.body == null &&
  1182. ['POST', 'PUT'].includes(httpRequest.method)
  1183. ) {
  1184. contentLengthHeaderValue = '0'
  1185. }
  1186. // 7. If contentLength is non-null, then set contentLengthHeaderValue to
  1187. // contentLength, serialized and isomorphic encoded.
  1188. if (contentLength != null) {
  1189. contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
  1190. }
  1191. // 8. If contentLengthHeaderValue is non-null, then append
  1192. // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
  1193. // list.
  1194. if (contentLengthHeaderValue != null) {
  1195. httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)
  1196. }
  1197. // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
  1198. // contentLengthHeaderValue) to httpRequest’s header list.
  1199. // 10. If contentLength is non-null and httpRequest’s keepalive is true,
  1200. // then:
  1201. if (contentLength != null && httpRequest.keepalive) {
  1202. // NOTE: keepalive is a noop outside of browser context.
  1203. }
  1204. // 11. If httpRequest’s referrer is a URL, then append
  1205. // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
  1206. // to httpRequest’s header list.
  1207. if (httpRequest.referrer instanceof URL) {
  1208. httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true)
  1209. }
  1210. // 12. Append a request `Origin` header for httpRequest.
  1211. appendRequestOriginHeader(httpRequest)
  1212. // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
  1213. appendFetchMetadata(httpRequest)
  1214. // 14. If httpRequest’s header list does not contain `User-Agent`, then
  1215. // user agents should append `User-Agent`/default `User-Agent` value to
  1216. // httpRequest’s header list.
  1217. if (!httpRequest.headersList.contains('user-agent', true)) {
  1218. httpRequest.headersList.append('user-agent', defaultUserAgent)
  1219. }
  1220. // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
  1221. // list contains `If-Modified-Since`, `If-None-Match`,
  1222. // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
  1223. // httpRequest’s cache mode to "no-store".
  1224. if (
  1225. httpRequest.cache === 'default' &&
  1226. (httpRequest.headersList.contains('if-modified-since', true) ||
  1227. httpRequest.headersList.contains('if-none-match', true) ||
  1228. httpRequest.headersList.contains('if-unmodified-since', true) ||
  1229. httpRequest.headersList.contains('if-match', true) ||
  1230. httpRequest.headersList.contains('if-range', true))
  1231. ) {
  1232. httpRequest.cache = 'no-store'
  1233. }
  1234. // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
  1235. // no-cache cache-control header modification flag is unset, and
  1236. // httpRequest’s header list does not contain `Cache-Control`, then append
  1237. // `Cache-Control`/`max-age=0` to httpRequest’s header list.
  1238. if (
  1239. httpRequest.cache === 'no-cache' &&
  1240. !httpRequest.preventNoCacheCacheControlHeaderModification &&
  1241. !httpRequest.headersList.contains('cache-control', true)
  1242. ) {
  1243. httpRequest.headersList.append('cache-control', 'max-age=0', true)
  1244. }
  1245. // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
  1246. if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
  1247. // 1. If httpRequest’s header list does not contain `Pragma`, then append
  1248. // `Pragma`/`no-cache` to httpRequest’s header list.
  1249. if (!httpRequest.headersList.contains('pragma', true)) {
  1250. httpRequest.headersList.append('pragma', 'no-cache', true)
  1251. }
  1252. // 2. If httpRequest’s header list does not contain `Cache-Control`,
  1253. // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
  1254. if (!httpRequest.headersList.contains('cache-control', true)) {
  1255. httpRequest.headersList.append('cache-control', 'no-cache', true)
  1256. }
  1257. }
  1258. // 18. If httpRequest’s header list contains `Range`, then append
  1259. // `Accept-Encoding`/`identity` to httpRequest’s header list.
  1260. if (httpRequest.headersList.contains('range', true)) {
  1261. httpRequest.headersList.append('accept-encoding', 'identity', true)
  1262. }
  1263. // 19. Modify httpRequest’s header list per HTTP. Do not append a given
  1264. // header if httpRequest’s header list contains that header’s name.
  1265. // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
  1266. if (!httpRequest.headersList.contains('accept-encoding', true)) {
  1267. if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
  1268. httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true)
  1269. } else {
  1270. httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true)
  1271. }
  1272. }
  1273. httpRequest.headersList.delete('host', true)
  1274. // 20. If includeCredentials is true, then:
  1275. if (includeCredentials) {
  1276. // 1. If the user agent is not configured to block cookies for httpRequest
  1277. // (see section 7 of [COOKIES]), then:
  1278. // TODO: credentials
  1279. // 2. If httpRequest’s header list does not contain `Authorization`, then:
  1280. // TODO: credentials
  1281. }
  1282. // 21. If there’s a proxy-authentication entry, use it as appropriate.
  1283. // TODO: proxy-authentication
  1284. // 22. Set httpCache to the result of determining the HTTP cache
  1285. // partition, given httpRequest.
  1286. // TODO: cache
  1287. // 23. If httpCache is null, then set httpRequest’s cache mode to
  1288. // "no-store".
  1289. if (httpCache == null) {
  1290. httpRequest.cache = 'no-store'
  1291. }
  1292. // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
  1293. // then:
  1294. if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {
  1295. // TODO: cache
  1296. }
  1297. // 9. If aborted, then return the appropriate network error for fetchParams.
  1298. // TODO
  1299. // 10. If response is null, then:
  1300. if (response == null) {
  1301. // 1. If httpRequest’s cache mode is "only-if-cached", then return a
  1302. // network error.
  1303. if (httpRequest.cache === 'only-if-cached') {
  1304. return makeNetworkError('only if cached')
  1305. }
  1306. // 2. Let forwardResponse be the result of running HTTP-network fetch
  1307. // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
  1308. const forwardResponse = await httpNetworkFetch(
  1309. httpFetchParams,
  1310. includeCredentials,
  1311. isNewConnectionFetch
  1312. )
  1313. // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
  1314. // in the range 200 to 399, inclusive, invalidate appropriate stored
  1315. // responses in httpCache, as per the "Invalidation" chapter of HTTP
  1316. // Caching, and set storedResponse to null. [HTTP-CACHING]
  1317. if (
  1318. !safeMethodsSet.has(httpRequest.method) &&
  1319. forwardResponse.status >= 200 &&
  1320. forwardResponse.status <= 399
  1321. ) {
  1322. // TODO: cache
  1323. }
  1324. // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
  1325. // then:
  1326. if (revalidatingFlag && forwardResponse.status === 304) {
  1327. // TODO: cache
  1328. }
  1329. // 5. If response is null, then:
  1330. if (response == null) {
  1331. // 1. Set response to forwardResponse.
  1332. response = forwardResponse
  1333. // 2. Store httpRequest and forwardResponse in httpCache, as per the
  1334. // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
  1335. // TODO: cache
  1336. }
  1337. }
  1338. // 11. Set response’s URL list to a clone of httpRequest’s URL list.
  1339. response.urlList = [...httpRequest.urlList]
  1340. // 12. If httpRequest’s header list contains `Range`, then set response’s
  1341. // range-requested flag.
  1342. if (httpRequest.headersList.contains('range', true)) {
  1343. response.rangeRequested = true
  1344. }
  1345. // 13. Set response’s request-includes-credentials to includeCredentials.
  1346. response.requestIncludesCredentials = includeCredentials
  1347. // 14. If response’s status is 401, httpRequest’s response tainting is not
  1348. // "cors", includeCredentials is true, and request’s window is an environment
  1349. // settings object, then:
  1350. // TODO
  1351. // 15. If response’s status is 407, then:
  1352. if (response.status === 407) {
  1353. // 1. If request’s window is "no-window", then return a network error.
  1354. if (request.window === 'no-window') {
  1355. return makeNetworkError()
  1356. }
  1357. // 2. ???
  1358. // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1359. if (isCancelled(fetchParams)) {
  1360. return makeAppropriateNetworkError(fetchParams)
  1361. }
  1362. // 4. Prompt the end user as appropriate in request’s window and store
  1363. // the result as a proxy-authentication entry. [HTTP-AUTH]
  1364. // TODO: Invoke some kind of callback?
  1365. // 5. Set response to the result of running HTTP-network-or-cache fetch given
  1366. // fetchParams.
  1367. // TODO
  1368. return makeNetworkError('proxy authentication required')
  1369. }
  1370. // 16. If all of the following are true
  1371. if (
  1372. // response’s status is 421
  1373. response.status === 421 &&
  1374. // isNewConnectionFetch is false
  1375. !isNewConnectionFetch &&
  1376. // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
  1377. (request.body == null || request.body.source != null)
  1378. ) {
  1379. // then:
  1380. // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
  1381. if (isCancelled(fetchParams)) {
  1382. return makeAppropriateNetworkError(fetchParams)
  1383. }
  1384. // 2. Set response to the result of running HTTP-network-or-cache
  1385. // fetch given fetchParams, isAuthenticationFetch, and true.
  1386. // TODO (spec): The spec doesn't specify this but we need to cancel
  1387. // the active response before we can start a new one.
  1388. // https://github.com/whatwg/fetch/issues/1293
  1389. fetchParams.controller.connection.destroy()
  1390. response = await httpNetworkOrCacheFetch(
  1391. fetchParams,
  1392. isAuthenticationFetch,
  1393. true
  1394. )
  1395. }
  1396. // 17. If isAuthenticationFetch is true, then create an authentication entry
  1397. if (isAuthenticationFetch) {
  1398. // TODO
  1399. }
  1400. // 18. Return response.
  1401. return response
  1402. }
  1403. // https://fetch.spec.whatwg.org/#http-network-fetch
  1404. async function httpNetworkFetch (
  1405. fetchParams,
  1406. includeCredentials = false,
  1407. forceNewConnection = false
  1408. ) {
  1409. assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
  1410. fetchParams.controller.connection = {
  1411. abort: null,
  1412. destroyed: false,
  1413. destroy (err, abort = true) {
  1414. if (!this.destroyed) {
  1415. this.destroyed = true
  1416. if (abort) {
  1417. this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
  1418. }
  1419. }
  1420. }
  1421. }
  1422. // 1. Let request be fetchParams’s request.
  1423. const request = fetchParams.request
  1424. // 2. Let response be null.
  1425. let response = null
  1426. // 3. Let timingInfo be fetchParams’s timing info.
  1427. const timingInfo = fetchParams.timingInfo
  1428. // 4. Let httpCache be the result of determining the HTTP cache partition,
  1429. // given request.
  1430. // TODO: cache
  1431. const httpCache = null
  1432. // 5. If httpCache is null, then set request’s cache mode to "no-store".
  1433. if (httpCache == null) {
  1434. request.cache = 'no-store'
  1435. }
  1436. // 6. Let networkPartitionKey be the result of determining the network
  1437. // partition key given request.
  1438. // TODO
  1439. // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
  1440. // "no".
  1441. const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
  1442. // 8. Switch on request’s mode:
  1443. if (request.mode === 'websocket') {
  1444. // Let connection be the result of obtaining a WebSocket connection,
  1445. // given request’s current URL.
  1446. // TODO
  1447. } else {
  1448. // Let connection be the result of obtaining a connection, given
  1449. // networkPartitionKey, request’s current URL’s origin,
  1450. // includeCredentials, and forceNewConnection.
  1451. // TODO
  1452. }
  1453. // 9. Run these steps, but abort when the ongoing fetch is terminated:
  1454. // 1. If connection is failure, then return a network error.
  1455. // 2. Set timingInfo’s final connection timing info to the result of
  1456. // calling clamp and coarsen connection timing info with connection’s
  1457. // timing info, timingInfo’s post-redirect start time, and fetchParams’s
  1458. // cross-origin isolated capability.
  1459. // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
  1460. // and request’s body’s source is null, then append (`Transfer-Encoding`,
  1461. // `chunked`) to request’s header list.
  1462. // 4. Set timingInfo’s final network-request start time to the coarsened
  1463. // shared current time given fetchParams’s cross-origin isolated
  1464. // capability.
  1465. // 5. Set response to the result of making an HTTP request over connection
  1466. // using request with the following caveats:
  1467. // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
  1468. // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
  1469. // - If request’s body is non-null, and request’s body’s source is null,
  1470. // then the user agent may have a buffer of up to 64 kibibytes and store
  1471. // a part of request’s body in that buffer. If the user agent reads from
  1472. // request’s body beyond that buffer’s size and the user agent needs to
  1473. // resend request, then instead return a network error.
  1474. // - Set timingInfo’s final network-response start time to the coarsened
  1475. // shared current time given fetchParams’s cross-origin isolated capability,
  1476. // immediately after the user agent’s HTTP parser receives the first byte
  1477. // of the response (e.g., frame header bytes for HTTP/2 or response status
  1478. // line for HTTP/1.x).
  1479. // - Wait until all the headers are transmitted.
  1480. // - Any responses whose status is in the range 100 to 199, inclusive,
  1481. // and is not 101, are to be ignored, except for the purposes of setting
  1482. // timingInfo’s final network-response start time above.
  1483. // - If request’s header list contains `Transfer-Encoding`/`chunked` and
  1484. // response is transferred via HTTP/1.0 or older, then return a network
  1485. // error.
  1486. // - If the HTTP request results in a TLS client certificate dialog, then:
  1487. // 1. If request’s window is an environment settings object, make the
  1488. // dialog available in request’s window.
  1489. // 2. Otherwise, return a network error.
  1490. // To transmit request’s body body, run these steps:
  1491. let requestBody = null
  1492. // 1. If body is null and fetchParams’s process request end-of-body is
  1493. // non-null, then queue a fetch task given fetchParams’s process request
  1494. // end-of-body and fetchParams’s task destination.
  1495. if (request.body == null && fetchParams.processRequestEndOfBody) {
  1496. queueMicrotask(() => fetchParams.processRequestEndOfBody())
  1497. } else if (request.body != null) {
  1498. // 2. Otherwise, if body is non-null:
  1499. // 1. Let processBodyChunk given bytes be these steps:
  1500. const processBodyChunk = async function * (bytes) {
  1501. // 1. If the ongoing fetch is terminated, then abort these steps.
  1502. if (isCancelled(fetchParams)) {
  1503. return
  1504. }
  1505. // 2. Run this step in parallel: transmit bytes.
  1506. yield bytes
  1507. // 3. If fetchParams’s process request body is non-null, then run
  1508. // fetchParams’s process request body given bytes’s length.
  1509. fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
  1510. }
  1511. // 2. Let processEndOfBody be these steps:
  1512. const processEndOfBody = () => {
  1513. // 1. If fetchParams is canceled, then abort these steps.
  1514. if (isCancelled(fetchParams)) {
  1515. return
  1516. }
  1517. // 2. If fetchParams’s process request end-of-body is non-null,
  1518. // then run fetchParams’s process request end-of-body.
  1519. if (fetchParams.processRequestEndOfBody) {
  1520. fetchParams.processRequestEndOfBody()
  1521. }
  1522. }
  1523. // 3. Let processBodyError given e be these steps:
  1524. const processBodyError = (e) => {
  1525. // 1. If fetchParams is canceled, then abort these steps.
  1526. if (isCancelled(fetchParams)) {
  1527. return
  1528. }
  1529. // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
  1530. if (e.name === 'AbortError') {
  1531. fetchParams.controller.abort()
  1532. } else {
  1533. fetchParams.controller.terminate(e)
  1534. }
  1535. }
  1536. // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
  1537. // processBodyError, and fetchParams’s task destination.
  1538. requestBody = (async function * () {
  1539. try {
  1540. for await (const bytes of request.body.stream) {
  1541. yield * processBodyChunk(bytes)
  1542. }
  1543. processEndOfBody()
  1544. } catch (err) {
  1545. processBodyError(err)
  1546. }
  1547. })()
  1548. }
  1549. try {
  1550. // socket is only provided for websockets
  1551. const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
  1552. if (socket) {
  1553. response = makeResponse({ status, statusText, headersList, socket })
  1554. } else {
  1555. const iterator = body[Symbol.asyncIterator]()
  1556. fetchParams.controller.next = () => iterator.next()
  1557. response = makeResponse({ status, statusText, headersList })
  1558. }
  1559. } catch (err) {
  1560. // 10. If aborted, then:
  1561. if (err.name === 'AbortError') {
  1562. // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1563. fetchParams.controller.connection.destroy()
  1564. // 2. Return the appropriate network error for fetchParams.
  1565. return makeAppropriateNetworkError(fetchParams, err)
  1566. }
  1567. return makeNetworkError(err)
  1568. }
  1569. // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
  1570. // if it is suspended.
  1571. const pullAlgorithm = async () => {
  1572. await fetchParams.controller.resume()
  1573. }
  1574. // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
  1575. // controller with reason, given reason.
  1576. const cancelAlgorithm = (reason) => {
  1577. // If the aborted fetch was already terminated, then we do not
  1578. // need to do anything.
  1579. if (!isCancelled(fetchParams)) {
  1580. fetchParams.controller.abort(reason)
  1581. }
  1582. }
  1583. // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
  1584. // the user agent.
  1585. // TODO
  1586. // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
  1587. // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
  1588. // TODO
  1589. // 15. Let stream be a new ReadableStream.
  1590. // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,
  1591. // cancelAlgorithm set to cancelAlgorithm.
  1592. const stream = new ReadableStream(
  1593. {
  1594. async start (controller) {
  1595. fetchParams.controller.controller = controller
  1596. },
  1597. async pull (controller) {
  1598. await pullAlgorithm(controller)
  1599. },
  1600. async cancel (reason) {
  1601. await cancelAlgorithm(reason)
  1602. },
  1603. type: 'bytes'
  1604. }
  1605. )
  1606. // 17. Run these steps, but abort when the ongoing fetch is terminated:
  1607. // 1. Set response’s body to a new body whose stream is stream.
  1608. response.body = { stream, source: null, length: null }
  1609. // 2. If response is not a network error and request’s cache mode is
  1610. // not "no-store", then update response in httpCache for request.
  1611. // TODO
  1612. // 3. If includeCredentials is true and the user agent is not configured
  1613. // to block cookies for request (see section 7 of [COOKIES]), then run the
  1614. // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
  1615. // the value of each header whose name is a byte-case-insensitive match for
  1616. // `Set-Cookie` in response’s header list, if any, and request’s current URL.
  1617. // TODO
  1618. // 18. If aborted, then:
  1619. // TODO
  1620. // 19. Run these steps in parallel:
  1621. // 1. Run these steps, but abort when fetchParams is canceled:
  1622. fetchParams.controller.onAborted = onAborted
  1623. fetchParams.controller.on('terminated', onAborted)
  1624. fetchParams.controller.resume = async () => {
  1625. // 1. While true
  1626. while (true) {
  1627. // 1-3. See onData...
  1628. // 4. Set bytes to the result of handling content codings given
  1629. // codings and bytes.
  1630. let bytes
  1631. let isFailure
  1632. try {
  1633. const { done, value } = await fetchParams.controller.next()
  1634. if (isAborted(fetchParams)) {
  1635. break
  1636. }
  1637. bytes = done ? undefined : value
  1638. } catch (err) {
  1639. if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
  1640. // zlib doesn't like empty streams.
  1641. bytes = undefined
  1642. } else {
  1643. bytes = err
  1644. // err may be propagated from the result of calling readablestream.cancel,
  1645. // which might not be an error. https://github.com/nodejs/undici/issues/2009
  1646. isFailure = true
  1647. }
  1648. }
  1649. if (bytes === undefined) {
  1650. // 2. Otherwise, if the bytes transmission for response’s message
  1651. // body is done normally and stream is readable, then close
  1652. // stream, finalize response for fetchParams and response, and
  1653. // abort these in-parallel steps.
  1654. readableStreamClose(fetchParams.controller.controller)
  1655. finalizeResponse(fetchParams, response)
  1656. return
  1657. }
  1658. // 5. Increase timingInfo’s decoded body size by bytes’s length.
  1659. timingInfo.decodedBodySize += bytes?.byteLength ?? 0
  1660. // 6. If bytes is failure, then terminate fetchParams’s controller.
  1661. if (isFailure) {
  1662. fetchParams.controller.terminate(bytes)
  1663. return
  1664. }
  1665. // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
  1666. // into stream.
  1667. const buffer = new Uint8Array(bytes)
  1668. if (buffer.byteLength) {
  1669. fetchParams.controller.controller.enqueue(buffer)
  1670. }
  1671. // 8. If stream is errored, then terminate the ongoing fetch.
  1672. if (isErrored(stream)) {
  1673. fetchParams.controller.terminate()
  1674. return
  1675. }
  1676. // 9. If stream doesn’t need more data ask the user agent to suspend
  1677. // the ongoing fetch.
  1678. if (fetchParams.controller.controller.desiredSize <= 0) {
  1679. return
  1680. }
  1681. }
  1682. }
  1683. // 2. If aborted, then:
  1684. function onAborted (reason) {
  1685. // 2. If fetchParams is aborted, then:
  1686. if (isAborted(fetchParams)) {
  1687. // 1. Set response’s aborted flag.
  1688. response.aborted = true
  1689. // 2. If stream is readable, then error stream with the result of
  1690. // deserialize a serialized abort reason given fetchParams’s
  1691. // controller’s serialized abort reason and an
  1692. // implementation-defined realm.
  1693. if (isReadable(stream)) {
  1694. fetchParams.controller.controller.error(
  1695. fetchParams.controller.serializedAbortReason
  1696. )
  1697. }
  1698. } else {
  1699. // 3. Otherwise, if stream is readable, error stream with a TypeError.
  1700. if (isReadable(stream)) {
  1701. fetchParams.controller.controller.error(new TypeError('terminated', {
  1702. cause: isErrorLike(reason) ? reason : undefined
  1703. }))
  1704. }
  1705. }
  1706. // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
  1707. // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
  1708. fetchParams.controller.connection.destroy()
  1709. }
  1710. // 20. Return response.
  1711. return response
  1712. function dispatch ({ body }) {
  1713. const url = requestCurrentURL(request)
  1714. /** @type {import('../..').Agent} */
  1715. const agent = fetchParams.controller.dispatcher
  1716. return new Promise((resolve, reject) => agent.dispatch(
  1717. {
  1718. path: url.pathname + url.search,
  1719. origin: url.origin,
  1720. method: request.method,
  1721. body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
  1722. headers: request.headersList.entries,
  1723. maxRedirections: 0,
  1724. upgrade: request.mode === 'websocket' ? 'websocket' : undefined
  1725. },
  1726. {
  1727. body: null,
  1728. abort: null,
  1729. onConnect (abort) {
  1730. // TODO (fix): Do we need connection here?
  1731. const { connection } = fetchParams.controller
  1732. // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen
  1733. // connection timing info with connection’s timing info, timingInfo’s post-redirect start
  1734. // time, and fetchParams’s cross-origin isolated capability.
  1735. // TODO: implement connection timing
  1736. timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)
  1737. if (connection.destroyed) {
  1738. abort(new DOMException('The operation was aborted.', 'AbortError'))
  1739. } else {
  1740. fetchParams.controller.on('terminated', abort)
  1741. this.abort = connection.abort = abort
  1742. }
  1743. // Set timingInfo’s final network-request start time to the coarsened shared current time given
  1744. // fetchParams’s cross-origin isolated capability.
  1745. timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1746. },
  1747. onResponseStarted () {
  1748. // Set timingInfo’s final network-response start time to the coarsened shared current
  1749. // time given fetchParams’s cross-origin isolated capability, immediately after the
  1750. // user agent’s HTTP parser receives the first byte of the response (e.g., frame header
  1751. // bytes for HTTP/2 or response status line for HTTP/1.x).
  1752. timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
  1753. },
  1754. onHeaders (status, rawHeaders, resume, statusText) {
  1755. if (status < 200) {
  1756. return
  1757. }
  1758. /** @type {string[]} */
  1759. let codings = []
  1760. let location = ''
  1761. const headersList = new HeadersList()
  1762. for (let i = 0; i < rawHeaders.length; i += 2) {
  1763. headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
  1764. }
  1765. const contentEncoding = headersList.get('content-encoding', true)
  1766. if (contentEncoding) {
  1767. // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
  1768. // "All content-coding values are case-insensitive..."
  1769. codings = contentEncoding.toLowerCase().split(',').map((x) => x.trim())
  1770. }
  1771. location = headersList.get('location', true)
  1772. this.body = new Readable({ read: resume })
  1773. const decoders = []
  1774. const willFollow = location && request.redirect === 'follow' &&
  1775. redirectStatusSet.has(status)
  1776. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
  1777. if (codings.length !== 0 && request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
  1778. for (let i = codings.length - 1; i >= 0; --i) {
  1779. const coding = codings[i]
  1780. // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
  1781. if (coding === 'x-gzip' || coding === 'gzip') {
  1782. decoders.push(zlib.createGunzip({
  1783. // Be less strict when decoding compressed responses, since sometimes
  1784. // servers send slightly invalid responses that are still accepted
  1785. // by common browsers.
  1786. // Always using Z_SYNC_FLUSH is what cURL does.
  1787. flush: zlib.constants.Z_SYNC_FLUSH,
  1788. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1789. }))
  1790. } else if (coding === 'deflate') {
  1791. decoders.push(createInflate({
  1792. flush: zlib.constants.Z_SYNC_FLUSH,
  1793. finishFlush: zlib.constants.Z_SYNC_FLUSH
  1794. }))
  1795. } else if (coding === 'br') {
  1796. decoders.push(zlib.createBrotliDecompress({
  1797. flush: zlib.constants.BROTLI_OPERATION_FLUSH,
  1798. finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
  1799. }))
  1800. } else {
  1801. decoders.length = 0
  1802. break
  1803. }
  1804. }
  1805. }
  1806. const onError = this.onError.bind(this)
  1807. resolve({
  1808. status,
  1809. statusText,
  1810. headersList,
  1811. body: decoders.length
  1812. ? pipeline(this.body, ...decoders, (err) => {
  1813. if (err) {
  1814. this.onError(err)
  1815. }
  1816. }).on('error', onError)
  1817. : this.body.on('error', onError)
  1818. })
  1819. return true
  1820. },
  1821. onData (chunk) {
  1822. if (fetchParams.controller.dump) {
  1823. return
  1824. }
  1825. // 1. If one or more bytes have been transmitted from response’s
  1826. // message body, then:
  1827. // 1. Let bytes be the transmitted bytes.
  1828. const bytes = chunk
  1829. // 2. Let codings be the result of extracting header list values
  1830. // given `Content-Encoding` and response’s header list.
  1831. // See pullAlgorithm.
  1832. // 3. Increase timingInfo’s encoded body size by bytes’s length.
  1833. timingInfo.encodedBodySize += bytes.byteLength
  1834. // 4. See pullAlgorithm...
  1835. return this.body.push(bytes)
  1836. },
  1837. onComplete () {
  1838. if (this.abort) {
  1839. fetchParams.controller.off('terminated', this.abort)
  1840. }
  1841. if (fetchParams.controller.onAborted) {
  1842. fetchParams.controller.off('terminated', fetchParams.controller.onAborted)
  1843. }
  1844. fetchParams.controller.ended = true
  1845. this.body.push(null)
  1846. },
  1847. onError (error) {
  1848. if (this.abort) {
  1849. fetchParams.controller.off('terminated', this.abort)
  1850. }
  1851. this.body?.destroy(error)
  1852. fetchParams.controller.terminate(error)
  1853. reject(error)
  1854. },
  1855. onUpgrade (status, rawHeaders, socket) {
  1856. if (status !== 101) {
  1857. return
  1858. }
  1859. const headersList = new HeadersList()
  1860. for (let i = 0; i < rawHeaders.length; i += 2) {
  1861. headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)
  1862. }
  1863. resolve({
  1864. status,
  1865. statusText: STATUS_CODES[status],
  1866. headersList,
  1867. socket
  1868. })
  1869. return true
  1870. }
  1871. }
  1872. ))
  1873. }
  1874. }
  1875. module.exports = {
  1876. fetch,
  1877. Fetch,
  1878. fetching,
  1879. finalizeAndReportTiming
  1880. }