@@ -14,6 +14,7 @@ import { DEBUG_BUILD } from './debug-build';
1414import { isPlainObject , isString } from './is' ;
1515import { logger } from './logger' ;
1616import { normalize } from './normalize' ;
17+ import { dropUndefinedKeys } from './object' ;
1718import { truncate } from './string' ;
1819import { stripUrlQueryAndFragment } from './url' ;
1920import { getClientIPAddress , ipHeaderNames } from './vendor/getIpAddress' ;
@@ -451,6 +452,43 @@ export function winterCGRequestToRequestData(req: WebFetchRequest): RequestEvent
451452 } ;
452453}
453454
455+ /**
456+ * Convert a HTTP request object to RequestEventData to be passed as normalizedRequest.
457+ * Instead of allowing `PolymorphicRequest` to be passed,
458+ * we want to be more specific and generally require a http.IncomingMessage-like object.
459+ */
460+ export function httpRequestToRequestData ( request : {
461+ method ?: string ;
462+ url ?: string ;
463+ headers ?: {
464+ [ key : string ] : string | string [ ] | undefined ;
465+ } ;
466+ protocol ?: string ;
467+ socket ?: unknown ;
468+ } ) : RequestEventData {
469+ const headers = request . headers || { } ;
470+ const host = headers . host || '<no host>' ;
471+ const protocol = request . socket && ( request . socket as { encrypted ?: boolean } ) . encrypted ? 'https' : 'http' ;
472+ const originalUrl = request . url || '' ;
473+ const absoluteUrl = originalUrl . startsWith ( protocol ) ? originalUrl : `${ protocol } ://${ host } ${ originalUrl } ` ;
474+
475+ // This is non-standard, but may be sometimes set
476+ // It may be overwritten later by our own body handling
477+ const data = ( request as PolymorphicRequest ) . body || undefined ;
478+
479+ // This is non-standard, but may be set on e.g. Next.js or Express requests
480+ const cookies = ( request as PolymorphicRequest ) . cookies ;
481+
482+ return dropUndefinedKeys ( {
483+ url : absoluteUrl ,
484+ method : request . method ,
485+ query_string : extractQueryParamsFromUrl ( originalUrl ) ,
486+ headers : headersToDict ( headers ) ,
487+ cookies,
488+ data,
489+ } ) ;
490+ }
491+
454492/** Extract the query params from an URL. */
455493export function extractQueryParamsFromUrl ( url : string ) : string | undefined {
456494 // url is path and query string
0 commit comments