0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 11:51:01 +01:00
hono/deno_dist/router/reg-exp-router/trie.ts
Taku Amano 01b9fd4537
feat(reg-exp-router): Lookup static path by using Object (#845)
* feat(reg-exp-router): Search by key of Object if `path` has no variables.

* feat(reg-exp-router): Returns an empty RegExp if node is not added.

* feat(reg-exp-router): Check ambiguous path for static.

* chore: fix typo in test case

* chore: denoify
2023-01-29 13:55:27 +09:00

76 lines
2.0 KiB
TypeScript

import type { ParamMap, Context } from './node.ts'
import { Node } from './node.ts'
export type { ParamMap } from './node.ts'
export type ReplacementMap = number[]
export class Trie {
context: Context = { varIndex: 0 }
root: Node = new Node()
insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamMap {
const paramMap: ParamMap = []
const groups: [string, string][] = [] // [mark, original string]
for (let i = 0; ; ) {
let replaced = false
path = path.replace(/\{[^}]+\}/g, (m) => {
const mark = `@\\${i}`
groups[i] = [mark, m]
i++
replaced = true
return mark
})
if (!replaced) {
break
}
}
/**
* - pattern (:label, :label{0-9]+}, ...)
* - /* wildcard
* - character
*/
const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []
for (let i = groups.length - 1; i >= 0; i--) {
const [mark] = groups[i]
for (let j = tokens.length - 1; j >= 0; j--) {
if (tokens[j].indexOf(mark) !== -1) {
tokens[j] = tokens[j].replace(mark, groups[i][1])
break
}
}
}
this.root.insert(tokens, index, paramMap, this.context, pathErrorCheckOnly)
return paramMap
}
buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {
let regexp = this.root.buildRegExpStr()
if (regexp === '') {
return [/^$/, [], []] // never match
}
let captureIndex = 0
const indexReplacementMap: ReplacementMap = []
const paramReplacementMap: ReplacementMap = []
regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
if (typeof handlerIndex !== 'undefined') {
indexReplacementMap[++captureIndex] = Number(handlerIndex)
return '$()'
}
if (typeof paramIndex !== 'undefined') {
paramReplacementMap[Number(paramIndex)] = ++captureIndex
return ''
}
return ''
})
return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]
}
}