2023-10-15 23:39:37 +00:00
|
|
|
import type { ParamAssocArray, Context } from './node.ts'
|
2022-07-02 06:09:45 +00:00
|
|
|
import { Node } from './node.ts'
|
|
|
|
|
|
|
|
export type ReplacementMap = number[]
|
|
|
|
|
|
|
|
export class Trie {
|
|
|
|
context: Context = { varIndex: 0 }
|
2022-09-13 23:01:14 +00:00
|
|
|
root: Node = new Node()
|
2022-07-02 06:09:45 +00:00
|
|
|
|
2023-10-15 23:39:37 +00:00
|
|
|
insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {
|
|
|
|
const paramAssoc: ParamAssocArray = []
|
2022-07-02 06:09:45 +00:00
|
|
|
|
2023-01-08 08:22:58 +00:00
|
|
|
const groups: [string, string][] = [] // [mark, original string]
|
2023-01-29 04:55:27 +00:00
|
|
|
for (let i = 0; ; ) {
|
2023-01-08 08:22:58 +00:00
|
|
|
let replaced = false
|
|
|
|
path = path.replace(/\{[^}]+\}/g, (m) => {
|
|
|
|
const mark = `@\\${i}`
|
|
|
|
groups[i] = [mark, m]
|
|
|
|
i++
|
|
|
|
replaced = true
|
|
|
|
return mark
|
|
|
|
})
|
|
|
|
if (!replaced) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-07-02 06:09:45 +00:00
|
|
|
/**
|
|
|
|
* - pattern (:label, :label{0-9]+}, ...)
|
|
|
|
* - /* wildcard
|
|
|
|
* - character
|
|
|
|
*/
|
2023-01-08 08:22:58 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-15 23:39:37 +00:00
|
|
|
this.root.insert(tokens, index, paramAssoc, this.context, pathErrorCheckOnly)
|
2022-07-02 06:09:45 +00:00
|
|
|
|
2023-10-15 23:39:37 +00:00
|
|
|
return paramAssoc
|
2022-07-02 06:09:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {
|
|
|
|
let regexp = this.root.buildRegExpStr()
|
2023-01-29 04:55:27 +00:00
|
|
|
if (regexp === '') {
|
|
|
|
return [/^$/, [], []] // never match
|
|
|
|
}
|
2022-07-02 06:09:45 +00:00
|
|
|
|
|
|
|
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]
|
|
|
|
}
|
|
|
|
}
|