import { format as formatUrl } from 'url' ; import { stringify , ParsedQuery } from 'query-string' ; import { parseUrl , parseUrlHash } from './parse' ; import { url as urlUtils } from '../../../common' ; export function replaceUrlQuery ( rawUrl , queryReplacer ) { const url = parseUrl ( rawUrl ) ; const newQuery = queryReplacer ( url . query || { } ) ; const searchQueryString = stringify ( urlUtils . encodeQuery ( newQuery ) , { sort : false , encode : false , } ) ; if ( ! url . search && ! searchQueryString ) return rawUrl ; return formatUrl ( { ... url , search : searchQueryString , } ) ; } export function replaceUrlHashQuery ( rawUrl , queryReplacer ) { const url = parseUrl ( rawUrl ) ; const hash = parseUrlHash ( rawUrl ) ; const newQuery = queryReplacer ( hash ?. query || { } ) ; const searchQueryString = stringify ( urlUtils . encodeQuery ( newQuery ) , { sort : false , encode : false , } ) ; if ( ( ! hash || ! hash . search ) && ! searchQueryString ) return rawUrl ; return formatUrl ( { ... url , hash : formatUrl ( { pathname : hash ?. pathname || '' , search : searchQueryString , } ) , } ) ; }