/
router.ts
211 lines (178 loc) 路 5.37 KB
/
router.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import type {
RadixRouterContext,
RadixNode,
MatchedRoute,
RadixRouter,
RadixNodeData,
RadixRouterOptions,
} from "./types";
import { NODE_TYPES } from "./types";
export function createRouter<T extends RadixNodeData = RadixNodeData>(
options: RadixRouterOptions = {},
): RadixRouter<T> {
const ctx: RadixRouterContext = {
options,
rootNode: createRadixNode(),
staticRoutesMap: {},
};
const normalizeTrailingSlash = (p) =>
options.strictTrailingSlash ? p : p.replace(/\/$/, "") || "/";
if (options.routes) {
for (const path in options.routes) {
insert(ctx, normalizeTrailingSlash(path), options.routes[path]);
}
}
return {
ctx,
// @ts-ignore
lookup: (path: string) => lookup(ctx, normalizeTrailingSlash(path)),
insert: (path: string, data: any) =>
insert(ctx, normalizeTrailingSlash(path), data),
remove: (path: string) => remove(ctx, normalizeTrailingSlash(path)),
};
}
function lookup(ctx: RadixRouterContext, path: string): MatchedRoute {
const staticPathNode = ctx.staticRoutesMap[path];
if (staticPathNode) {
return staticPathNode.data;
}
const sections = path.split("/");
const params: MatchedRoute["params"] = {};
let paramsFound = false;
let wildcardNode = null;
let node = ctx.rootNode;
let wildCardParam = null;
for (let i = 0; i < sections.length; i++) {
const section = sections[i];
if (node.wildcardChildNode !== null) {
wildcardNode = node.wildcardChildNode;
wildCardParam = sections.slice(i).join("/");
}
// Exact matches take precedence over placeholders
const nextNode = node.children.get(section);
if (nextNode === undefined) {
node = node.placeholderChildNode;
if (node === null) {
break;
} else {
if (node.type === NODE_TYPES.MIXED && node.paramMatcher) {
const matches = section.match(node.paramMatcher);
Object.assign(params, matches.groups);
} else {
params[node.paramName] = section;
}
paramsFound = true;
}
} else {
node = nextNode;
}
}
if ((node === null || node.data === null) && wildcardNode !== null) {
node = wildcardNode;
params[node.paramName || "_"] = wildCardParam;
paramsFound = true;
}
if (!node) {
return null;
}
if (paramsFound) {
return {
...node.data,
params: paramsFound ? params : undefined,
};
}
return node.data;
}
function insert(ctx: RadixRouterContext, path: string, data: any) {
let isStaticRoute = true;
const sections = path.split("/");
let node = ctx.rootNode;
let _unnamedPlaceholderCtr = 0;
for (const section of sections) {
let childNode: RadixNode<RadixNodeData>;
if ((childNode = node.children.get(section))) {
node = childNode;
} else {
const type = getNodeType(section);
// Create new node to represent the next part of the path
childNode = createRadixNode({ type, parent: node });
node.children.set(section, childNode);
if (type === NODE_TYPES.PLACEHOLDER) {
if (section === "*") {
childNode.paramName = `_${_unnamedPlaceholderCtr++}`;
} else {
const PARAMS_RE = /:\w+|[^:]+/g;
const params = [...section.matchAll(PARAMS_RE)].map((i) => i[0]);
if (params.length === 1) {
childNode.paramName = params[0].slice(1);
} else {
childNode.type = NODE_TYPES.MIXED;
const sectionRegexString = section.replace(
/:(\w+)/g,
(_, id) => `(?<${id}>\\w+)`,
);
childNode.paramMatcher = new RegExp(`^${sectionRegexString}$`);
}
}
node.placeholderChildNode = childNode;
isStaticRoute = false;
} else if (type === NODE_TYPES.WILDCARD) {
node.wildcardChildNode = childNode;
childNode.paramName = section.slice(3 /* "**:" */) || "_";
isStaticRoute = false;
}
node = childNode;
}
}
// Store whatever data was provided into the node
node.data = data;
// Optimization, if a route is static and does not have any
// variable sections, we can store it into a map for faster retrievals
if (isStaticRoute === true) {
ctx.staticRoutesMap[path] = node;
}
return node;
}
function remove(ctx: RadixRouterContext, path: string) {
let success = false;
const sections = path.split("/");
let node = ctx.rootNode;
for (const section of sections) {
node = node.children.get(section);
if (!node) {
return success;
}
}
if (node.data) {
const lastSection = sections.at(-1);
node.data = null;
if (node.children.size === 0) {
const parentNode = node.parent;
parentNode.children.delete(lastSection);
parentNode.wildcardChildNode = null;
parentNode.placeholderChildNode = null;
}
success = true;
}
return success;
}
function createRadixNode(options: Partial<RadixNode> = {}): RadixNode {
return {
type: options.type || NODE_TYPES.NORMAL,
parent: options.parent || null,
children: new Map(),
data: options.data || null,
paramName: options.paramName || null,
wildcardChildNode: null,
placeholderChildNode: null,
};
}
function getNodeType(str: string) {
if (str.startsWith("**")) {
return NODE_TYPES.WILDCARD;
}
if (str.includes(":") || str === "*") {
return NODE_TYPES.PLACEHOLDER;
}
return NODE_TYPES.NORMAL;
}