Skip to content

Commit

Permalink
feat!: custom url parser
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Dec 16, 2020
1 parent b22eb2e commit be8578f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 21 deletions.
39 changes: 20 additions & 19 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,31 @@ export interface ParsedURL {
params?: ParamsObject
}

export function parseURLNative (input: string = ''): ParsedURL {
const url: URL & { params: ParamsObject } = new URL(input) as any
url.params = parsedParamsToObject(Array.from(url.searchParams.entries()))
return url
}

export function parsePath (input: string = ''): ParsedURL {
const searchIndex = input.indexOf('?')
const hashIndex = input.indexOf('#')
let search, hash
export function parseURL (input: string = ''): ParsedURL {
const [protocol, auth, hostAndPath] = (input.match(/([^/]+:)\/\/([^/@]+@)?(.*)/) || []).splice(1)
const [host = '', path = ''] = (hostAndPath.match(/([^/]*)(.*)?/) || []).splice(1)
const [hostname = '', port = ''] = host.split(':')
const { pathname, params, hash } = parsePath(path)
const [username, password] = auth ? auth.substr(0, auth.length - 1).split(':') : []

if (hashIndex >= 0) {
hash = input.substr(hashIndex)
input = input.substr(0, hashIndex)
return {
protocol,
username,
password,
hostname,
port,
pathname,
params,
hash
}
}

if (searchIndex >= 0) {
search = input.substr(searchIndex + 1)
input = input.substr(0, searchIndex)
}
export function parsePath (input: string = ''): ParsedURL {
const [pathname = '', search = '', hash = ''] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1)

return {
pathname: input,
params: search ? parsedParamsToObject(parseParams(search)) : {},
pathname,
params: search ? parsedParamsToObject(parseParams(search.substr(1))) : {},
hash
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/ufo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { hasProtocol, parsePath, parseURLNative, ParamsObject } from './parse'
import { hasProtocol, parsePath, ParamsObject, parseURL } from './parse'
import { withoutLeadingSlash, withLeadingSlash, withTrailingSlash } from './utils'
import { encodeSearchParam, encodeHash, encode, encodePath, decode } from './encoding'

Expand All @@ -20,7 +20,7 @@ export class UFO implements URL {
const _isAbsolute = _hasProtocol || input[0] === '/'

// Use native URL for parsing (replacable)
const parsed = _hasProtocol ? parseURLNative(input) : parsePath(input)
const parsed = _hasProtocol ? parseURL(input) : parsePath(input)
this.hash = decode(parsed.hash || '')
this.hostname = decode(parsed.hostname || '')
this.pathname = decode(_isAbsolute ? withLeadingSlash(parsed.pathname) : withoutLeadingSlash(parsed.pathname))
Expand Down

0 comments on commit be8578f

Please sign in to comment.