Skip to content
Myr

url.ts

This file

Path

src/utils/url.ts

337 lines · 9.2 KiB · TypeScript

Last changed by

Merge commit from forkTaku Amanobefore adoption9c28d72

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–135why, one step back
1/**
2 * @module3 * URL utility.4 */56export type Pattern = readonly [string, string, RegExp | true] | '*'78export const splitPath = (path: string): string[] => {9 const paths = path.split('/')10 if (paths[0] === '') {11 paths.shift()12 }13 return paths14}1516export const splitRoutingPath = (routePath: string): string[] => {17 const { groups, path } = extractGroupsFromPath(routePath)1819 const paths = splitPath(path)20 return replaceGroupMarks(paths, groups)21}2223const extractGroupsFromPath = (path: string): { groups: [string, string][]; path: string } => {24 const groups: [string, string][] = []2526 path = path.replace(/\{[^}]+\}/g, (match, index) => {27 const mark = `@${index}`28 groups.push([mark, match])29 return mark30 })3132 return { groups, path }33}3435const replaceGroupMarks = (paths: string[], groups: [string, string][]): string[] => {36 for (let i = groups.length - 1; i >= 0; i--) {37 const [mark] = groups[i]3839 for (let j = paths.length - 1; j >= 0; j--) {40 if (paths[j].includes(mark)) {41 paths[j] = paths[j].replace(mark, groups[i][1])42 break43 }44 }45 }4647 return paths48}4950const patternCache: { [key: string]: Pattern } = {}51export const getPattern = (label: string, next?: string): Pattern | null => {52 // * => wildcard53 // :id{[0-9]+} => ([0-9]+)54 // :id => (.+)5556 if (label === '*') {57 return '*'58 }5960 const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)61 if (match) {62 const cacheKey = `${label}#${next}`63 if (!patternCache[cacheKey]) {64 if (match[2]) {65 patternCache[cacheKey] =66 next && next[0] !== ':' && next[0] !== '*'67 ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)]68 : [label, match[1], new RegExp(`^${match[2]}$`)]69 } else {70 patternCache[cacheKey] = [label, match[1], true]71 }72 }7374 return patternCache[cacheKey]75 }7677 return null78}7980type Decoder = (str: string) => string81export const tryDecode = (str: string, decoder: Decoder): string => {82 try {83 return decoder(str)84 } catch {85 return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {86 try {87 return decoder(match)88 } catch {89 return match90 }91 })92 }93}9495/**96 * Try to apply decodeURI() to given string.97 * If it fails, skip invalid percent encoding or invalid UTF-8 sequences, and apply decodeURI() to the rest as much as possible.98 * @param str The string to decode.99 * @returns The decoded string that sometimes contains undecodable percent encoding.100 * @example101 * tryDecodeURI('Hello%20World') // 'Hello World'102 * tryDecodeURI('Hello%20World/%A4%A2') // 'Hello World/%A4%A2'103 */104export const tryDecodeURI = (str: string): string => tryDecode(str, decodeURI)105106export const getPath = (request: Request): string => {107 const url = request.url108 const start = url.indexOf('/', url.indexOf(':') + 4)109 let i = start110 for (; i < url.length; i++) {111 const charCode = url.charCodeAt(i)112 if (charCode === 37) {113 // '%'114 // If the path contains percent encoding, use `indexOf()` to find '?' or '#' and return the result immediately.115 // Although this is a performance disadvantage, it is acceptable since we prefer cases that do not include percent encoding.116 const queryIndex = url.indexOf('?', i)117 const hashIndex = url.indexOf('#', i)118 const end =119 queryIndex === -1120 ? hashIndex === -1121 ? undefined122 : hashIndex123 : hashIndex === -1124 ? queryIndex125 : Math.min(queryIndex, hashIndex)126 const path = url.slice(start, end)127 return tryDecodeURI(path.includes('%25') ? path.replace(/%25/g, '%2525') : path)128 } else if (charCode === 63 || charCode === 35) {129 // '?' or '#'130 break131 }132 }133 return url.slice(start, i)134}135

Merge commit from forkTaku Amanobefore adoption9c28d72

lines 136–139why, one step back
136/**
137 * @deprecated138 * Use the `URL` API instead.139 */

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 140–141why, one step back
140export const getQueryStrings = (url: string): string => {
141 const queryIndex = url.indexOf('?', 8)

Merge commit from forkTaku Amanobefore adoption9c28d72

lines 142–151why, one step back
142 if (queryIndex === -1) {
143 return ''144 }145146 const hashIndex = url.indexOf('#', 8)147 return hashIndex === -1148 ? url.slice(queryIndex)149 : queryIndex < hashIndex150 ? url.slice(queryIndex, hashIndex)151 : ''

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 152–202why, one step back
152}
153154export const getPathNoStrict = (request: Request): string => {155 const result = getPath(request)156157 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same158 return result.length > 1 && result.at(-1) === '/' ? result.slice(0, -1) : result159}160161/**162 * Merge paths.163 * @param {string[]} ...paths - The paths to merge.164 * @returns {string} The merged path.165 * @example166 * mergePath('/api', '/users') // '/api/users'167 * mergePath('/api/', '/users') // '/api/users'168 * mergePath('/api', '/') // '/api'169 * mergePath('/api/', '/') // '/api/'170 */171export const mergePath: (...paths: string[]) => string = (172 base: string | undefined,173 sub: string | undefined,174 ...rest: string[]175): string => {176 if (rest.length) {177 sub = mergePath(sub as string, ...rest)178 }179 return `${base?.[0] === '/' ? '' : '/'}${base}${180 sub === '/' ? '' : `${base?.at(-1) === '/' ? '' : '/'}${sub?.[0] === '/' ? sub.slice(1) : sub}`181 }`182}183184export const checkOptionalParameter = (path: string): string[] | null => {185 /*186 If path is `/api/animals/:type?` it will return:187 [`/api/animals`, `/api/animals/:type`]188 in other cases it will return null189 */190191 if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(':')) {192 return null193 }194195 const segments = path.split('/')196 const results: string[] = []197 let basePath = ''198199 segments.forEach((segment) => {200 if (segment !== '' && !/\:/.test(segment)) {201 basePath += '/' + segment202 } else if (/\:/.test(segment)) {

fix(url): strip trailing question mark correctly for optional params with regex quantifiers (#5209)Nanasibefore adoptiond982f63

line 203why, one step back
203 if (segment.charCodeAt(segment.length - 1) === 63) {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 204–208why, one step back
204 if (results.length === 0 && basePath === '') {
205 results.push('/')206 } else {207 results.push(basePath)208 }

fix(url): strip trailing question mark correctly for optional params with regex quantifiers (#5209)Nanasibefore adoptiond982f63

line 209why, one step back
209 const optionalSegment = segment.slice(0, -1)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 210–220why, one step back
210 basePath += '/' + optionalSegment
211 results.push(basePath)212 } else {213 basePath += '/' + segment214 }215 }216 })217218 return results.filter((v, i, a) => a.indexOf(v) === i)219}220

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 221–223why, one step back
221export const tryDecodeURIComponent = (str: string): string =>
222 str.indexOf('%') !== -1 ? tryDecode(str, decodeURIComponent_) : str223

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 224why, one step back
224// Optimized

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 225why, one step back
225const _decodeURI = (value: string): string => {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 226–228why, one step back
226 if (value.indexOf('+') !== -1) {
227 value = value.replace(/\+/g, ' ')228 }

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 229why, one step back
229 return tryDecodeURIComponent(value)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 230–236why, one step back
230}
231232const _getQueryParam = (233 url: string,234 key?: string,235 multiple?: boolean236): string | undefined | Record<string, string> | string[] | Record<string, string[]> => {

Merge commit from forkTaku Amanobefore adoption9c28d72

lines 237–241why, one step back
237 const hashIndex = url.indexOf('#', 8)
238 if (hashIndex !== -1) {239 url = url.slice(0, hashIndex)240 }241

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 242–243why, one step back
242 let encoded
243

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 244why, one step back
244 if (!multiple && key && key.indexOf('%') === -1 && key.indexOf('+') === -1) {

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 245–272why, one step back
245 // optimized for unencoded key
246247 let keyIndex = url.indexOf('?', 8)248 if (keyIndex === -1) {249 return undefined250 }251 if (!url.startsWith(key, keyIndex + 1)) {252 keyIndex = url.indexOf(`&${key}`, keyIndex + 1)253 }254 while (keyIndex !== -1) {255 const trailingKeyCode = url.charCodeAt(keyIndex + key.length + 1)256 if (trailingKeyCode === 61) {257 const valueIndex = keyIndex + key.length + 2258 const endIndex = url.indexOf('&', valueIndex)259 return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex))260 } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {261 return ''262 }263 keyIndex = url.indexOf(`&${key}`, keyIndex + 1)264 }265266 encoded = /[%+]/.test(url)267 if (!encoded) {268 return undefined269 }270 // fallback to default routine271 }272

fix: use `Object.create(null)` when parsing query, headers, and params (#5161)Yusuke Wadabefore adoptionc85aead

line 273why, one step back
273 const results: Record<string, string> | Record<string, string[]> = Object.create(null)

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 274–337why, one step back
274 encoded ??= /[%+]/.test(url)
275276 let keyIndex = url.indexOf('?', 8)277 while (keyIndex !== -1) {278 const nextKeyIndex = url.indexOf('&', keyIndex + 1)279 let valueIndex = url.indexOf('=', keyIndex)280 if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {281 valueIndex = -1282 }283 let name = url.slice(284 keyIndex + 1,285 valueIndex === -1 ? (nextKeyIndex === -1 ? undefined : nextKeyIndex) : valueIndex286 )287 if (encoded) {288 name = _decodeURI(name)289 }290291 keyIndex = nextKeyIndex292293 if (name === '') {294 continue295 }296297 let value298 if (valueIndex === -1) {299 value = ''300 } else {301 value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex)302 if (encoded) {303 value = _decodeURI(value)304 }305 }306307 if (multiple) {308 if (!(results[name] && Array.isArray(results[name]))) {309 results[name] = []310 }311 ;(results[name] as string[]).push(value)312 } else {313 results[name] ??= value314 }315 }316317 return key ? results[key] : results318}319320export const getQueryParam: (321 url: string,322 key?: string323) => string | undefined | Record<string, string> = _getQueryParam as (324 url: string,325 key?: string326) => string | undefined | Record<string, string>327328export const getQueryParams = (329 url: string,330 key?: string331): string[] | undefined | Record<string, string[]> => {332 return _getQueryParam(url, key, true) as string[] | undefined | Record<string, string[]>333}334335// `decodeURIComponent` is a long name.336// By making it a function, we can use it commonly when minified, reducing the amount of code.337export const decodeURIComponent_ = decodeURIComponent