import is from '@sindresorhus/is' ; import _parseLinkHeader from 'parse-link-header' ; import urlJoin from 'url-join' ; import { logger } from '../logger' ; import { regEx } from './regex' ; export function joinUrlParts ( ... parts ) { return urlJoin ( ... parts ) ; } export function ensurePathPrefix ( url , prefix ) { const parsed = new URL ( url ) ; const fullPath = parsed . pathname + parsed . search ; if ( fullPath . startsWith ( prefix ) ) { return url ; } return parsed . origin + prefix + fullPath ; } export function ensureTrailingSlash ( url ) { return url . replace ( /\/?$/ , '/' ) ; } export function trimTrailingSlash ( url ) { return url . replace ( regEx ( /\/+$/ ) , '' ) ; } export function resolveBaseUrl ( baseUrl , input ) { const inputString = input . toString ( ) ; let host ; let pathname ; try { ( { host , pathname } = new URL ( inputString ) ) ; } catch ( e ) { pathname = inputString ; } return host ? inputString : urlJoin ( baseUrl , pathname || '' ) ; } export function getQueryString ( params ) { const usp = new URLSearchParams ( ) ; for ( const [ k , v ] of Object . entries ( params ) ) { if ( Array . isArray ( v ) ) { for ( const item of v ) { usp . append ( k , item . toString ( ) ) ; } } else { usp . append ( k , v . toString ( ) ) ; } } const res = usp . toString ( ) ; return res ; } export function validateUrl ( url ? , httpOnly = true ) { if ( ! url ) { return false ; } try { const { protocol } = new URL ( url ) ; return httpOnly ? ! ! protocol . startsWith ( 'http' ) : ! ! protocol ; } catch ( err ) { return false ; } } export function parseUrl ( url ) { try { return new URL ( url ) ; } catch ( err ) { return null ; } } param url returns export function createURLFromHostOrURL ( url ) { return parseUrl ( url ) ?? parseUrl ( `https://${ url }` ) ; } export type LinkHeaderLinks = _parseLinkHeader . Links ; export function parseLinkHeader ( linkHeader ) { if ( ! is . nonEmptyString ( linkHeader ) ) { return null ; } if ( linkHeader . length > 2000 ) { logger . warn ( { linkHeader } , 'Link header too long.' ) ; return null ; } return _parseLinkHeader ( linkHeader ) ; }