import { isDate , isNull , isPlainObject , isUndefined } from './is' ; function encode ( str ) { return encodeURIComponent ( str ) . replace ( /%40/gi , '@' ) . replace ( /%3A/gi , ':' ) . replace ( /%24/g , '$' ) . replace ( /%2C/gi , ',' ) . replace ( /%20/g , '+' ) . replace ( /%5B/gi , '[' ) . replace ( /%5D/gi , ']' ) ; } export function buildURL ( url = '' , params ? , paramsSerializer = paramsSerialization ) { if ( ! isPlainObject ( params ) ) { return url ; } return generateURL ( url , paramsSerializer ( params ) ) ; } const combineREG = /([^:])\/{2,}/g ; export function combineURL ( baseURL = '' , url ) { const separator = '/' ; const replaceStr = `$1${ separator }` ; return `${ baseURL }${ separator }${ url }` . replace ( combineREG , replaceStr ) ; } const dynamicREG = /\/?(:([a-zA-Z_$][\w-$]*))\/??/g ; export function dynamicInterpolation ( url , sourceData ? ) { if ( ! isPlainObject ( sourceData ) ) { return url ; } return url . replace ( dynamicREG , ( key1 , key2 , key3 ) => key1 . replace ( key2 , sourceData [ key3 ] ) ) ; } const absoluteREG = /^([a-z][a-z\d+\-.]*:)?\/\//i ; export function isAbsoluteURL ( url ) { return absoluteREG . test ( url ) ; } export function isDynamicURL ( url ) { dynamicREG . lastIndex = 0 ; return dynamicREG . test ( url ) ; } function generateURL ( url , serializedParams ) { const hashIndex = url . indexOf ( '#' ) ; if ( hashIndex !== - 1 ) { url = url . slice ( 0 , hashIndex ) ; } if ( serializedParams === '' ) { return url ; } const prefix = url . indexOf ( '?' ) === - 1 ? '?' : '&' ; serializedParams = `${ prefix }${ serializedParams }` ; return `${ url }${ serializedParams }` ; } function paramsSerialization ( params ? ) { if ( ! isPlainObject ( params ) ) { return '' ; } const parts = [ ] ; Object . keys ( params ) . forEach ( ( key ) : void => { const value = params [ key ] ; if ( isNull ( value ) || isUndefined ( value ) || value !== value ) { return ; } if ( Array . isArray ( value ) ) { key += '[]' ; } const values = [ ] . concat ( value ) ; values . forEach ( ( val ) : void => { if ( isPlainObject ( val ) ) { val = JSON . stringify ( val ) ; } else if ( isDate ( val ) ) { val = ( val as Date ) . toISOString ( ) ; } parts . push ( `${ encode ( key ) }=${ encode ( val ) }` ) ; } ) ; } ) ; return parts . join ( '&' ) ; }