( incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string )
| 551 | Object.setPrototypeOf(requestPrototype, Request.prototype) |
| 552 | |
| 553 | export const newRequest = ( |
| 554 | incoming: IncomingMessage | Http2ServerRequest, |
| 555 | defaultHostname?: string |
| 556 | ) => { |
| 557 | const req = Object.create(requestPrototype) |
| 558 | req[incomingKey] = incoming |
| 559 | req[methodKey] = normalizeIncomingMethod(incoming.method) |
| 560 | |
| 561 | const incomingUrl = incoming.url || '' |
| 562 | |
| 563 | // handle absolute URL in request.url |
| 564 | if ( |
| 565 | incomingUrl[0] !== '/' && // short-circuit for performance. most requests are relative URL. |
| 566 | (incomingUrl.startsWith('http://') || incomingUrl.startsWith('https://')) |
| 567 | ) { |
| 568 | if (incoming instanceof Http2ServerRequest) { |
| 569 | throw new RequestError('Absolute URL for :path is not allowed in HTTP/2') // RFC 9113 8.3.1. |
| 570 | } |
| 571 | |
| 572 | try { |
| 573 | const url = new URL(incomingUrl) |
| 574 | req[urlKey] = url.href |
| 575 | } catch (e) { |
| 576 | throw new RequestError('Invalid absolute URL', { cause: e }) |
| 577 | } |
| 578 | |
| 579 | return req |
| 580 | } |
| 581 | |
| 582 | // Otherwise, relative URL |
| 583 | const host = |
| 584 | (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || |
| 585 | defaultHostname |
| 586 | if (!host) { |
| 587 | throw new RequestError('Missing host header') |
| 588 | } |
| 589 | |
| 590 | let scheme: string |
| 591 | if (incoming instanceof Http2ServerRequest) { |
| 592 | scheme = incoming.scheme |
| 593 | if (!(scheme === 'http' || scheme === 'https')) { |
| 594 | throw new RequestError('Unsupported scheme') |
| 595 | } |
| 596 | } else { |
| 597 | scheme = incoming.socket && (incoming.socket as TLSSocket).encrypted ? 'https' : 'http' |
| 598 | } |
| 599 | |
| 600 | try { |
| 601 | req[urlKey] = buildUrl(scheme, host, incomingUrl) |
| 602 | } catch (e) { |
| 603 | if (e instanceof RequestError) { |
| 604 | throw e |
| 605 | } else { |
| 606 | throw new RequestError('Invalid URL', { cause: e }) |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | return req |
searching dependent graphs…