-
Notifications
You must be signed in to change notification settings - Fork 3
/
Router.js
349 lines (284 loc) · 9.47 KB
/
Router.js
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
'use strict';
function createNode(pathPart, staticChildren) {
return {
pathPart,
store: null,
staticChildren: staticChildren === undefined
? null
: new Map(staticChildren.map(child => [child.pathPart.charCodeAt(0), child])),
parametricChild: null,
wildcardStore: null,
};
}
function cloneNode(node, newPathPart) {
return {
pathPart: newPathPart,
store: node.store,
staticChildren: node.staticChildren,
parametricChild: node.parametricChild,
wildcardStore: node.wildcardStore,
};
}
function createParametricNode(paramName) {
return {
paramName,
store: null,
staticChild: null,
};
}
function defaultStoreFactory() {
return Object.create(null);
}
class Router {
constructor({storeFactory} = {}) {
if (storeFactory === undefined) {
storeFactory = defaultStoreFactory;
} else if (typeof storeFactory === 'function') {
const customStoreFactory = storeFactory;
storeFactory = () => {
const store = customStoreFactory();
if (store === null) {
throw new Error('Custom storeFactory returned `null`, which is not allowed');
}
return store;
};
} else {
throw new TypeError('`storeFactory` must be a function');
}
this._root = createNode('/');
this._storeFactory = storeFactory;
}
register(path) {
if (typeof path !== 'string') {
throw new TypeError('Route path must be a string');
}
if (path === '' || path[0] !== '/') {
throw new Error(`Invalid route: ${path}\nRoute path must begin with a "/"`);
}
const endsWithWildcard = path.endsWith('*');
if (endsWithWildcard) {
path = path.slice(0, -1); // Slice off trailing '*'
}
const staticParts = path.split(/:.+?(?=\/|$)/);
const paramParts = path.match(/:.+?(?=\/|$)/g) || [];
if (staticParts[staticParts.length - 1] === '') {
staticParts.pop();
}
let node = this._root;
let paramPartsIndex = 0;
for (let i = 0; i < staticParts.length; ++i) {
let pathPart = staticParts[i];
if (i > 0) { // Set parametric properties on the node
const paramName = paramParts[paramPartsIndex++].slice(1);
if (node.parametricChild === null) {
node.parametricChild = createParametricNode(paramName);
} else if (node.parametricChild.paramName !== paramName) {
throw new Error(
`Cannot create route "${path}" with parameter "${paramName}" ` +
'because a route already exists with a different parameter name ' +
`("${node.parametricChild.paramName}") in the same location`
);
}
const {parametricChild} = node;
if (parametricChild.staticChild === null) {
node = parametricChild.staticChild = createNode(pathPart);
continue;
}
node = parametricChild.staticChild;
}
for (let j = 0; ;) {
if (j === pathPart.length) {
if (j < node.pathPart.length) { // Move the current node down
const childNode = cloneNode(node, node.pathPart.slice(j));
Object.assign(node, createNode(pathPart, [childNode]));
}
break;
}
if (j === node.pathPart.length) { // Add static child
if (node.staticChildren === null) {
node.staticChildren = new Map();
} else if (node.staticChildren.has(pathPart.charCodeAt(j))) {
// Re-run loop with existing static node
node = node.staticChildren.get(pathPart.charCodeAt(j));
pathPart = pathPart.slice(j);
j = 0;
continue;
}
// Create new node
const childNode = createNode(pathPart.slice(j));
node.staticChildren.set(pathPart.charCodeAt(j), childNode);
node = childNode;
break;
}
if (pathPart[j] !== node.pathPart[j]) { // Split the node
const existingChild = cloneNode(node, node.pathPart.slice(j));
const newChild = createNode(pathPart.slice(j));
Object.assign(node, createNode(node.pathPart.slice(0, j), [existingChild, newChild]));
node = newChild;
break;
}
++j;
}
}
if (paramPartsIndex < paramParts.length) { // The final part is a parameter
const param = paramParts[paramPartsIndex];
const paramName = param.slice(1);
if (node.parametricChild === null) {
node.parametricChild = createParametricNode(paramName);
} else if (node.parametricChild.paramName !== paramName) {
throw new Error(
`Cannot create route "${path}" with parameter "${paramName}" ` +
'because a route already exists with a different parameter name ' +
`("${node.parametricChild.paramName}") in the same location`
);
}
if (node.parametricChild.store === null) {
node.parametricChild.store = this._storeFactory();
}
return node.parametricChild.store;
}
if (endsWithWildcard) { // The final part is a wildcard
if (node.wildcardStore === null) {
node.wildcardStore = this._storeFactory();
}
return node.wildcardStore;
}
// The final part is static
if (node.store === null) {
node.store = this._storeFactory();
}
return node.store;
}
find(url) {
if (url === '' || url[0] !== '/') {
return null;
}
const queryIndex = url.indexOf('?');
const urlLength = queryIndex >= 0 ? queryIndex : url.length;
return matchRoute(url, urlLength, this._root, 0);
}
debugTree() {
return require('object-treeify')(debugNode(this._root))
.replace(/^.{3}/gm, ''); // Remove the first 3 characters of every line
}
}
function matchRoute(url, urlLength, node, startIndex) {
const {pathPart} = node;
const pathPartLen = pathPart.length;
const pathPartEndIndex = startIndex + pathPartLen;
// Only check the pathPart if its length is > 1 since the parent has
// already checked that the url matches the first character
if (pathPartLen > 1) {
if (pathPartEndIndex > urlLength) {
return null;
}
if (pathPartLen < 15) { // Using a loop is faster for short strings
for (let i = 1, j = startIndex + 1; i < pathPartLen; ++i, ++j) {
if (pathPart[i] !== url[j]) {
return null;
}
}
} else if (url.slice(startIndex, pathPartEndIndex) !== pathPart) {
return null;
}
}
startIndex = pathPartEndIndex;
if (startIndex === urlLength) { // Reached the end of the URL
if (node.store !== null) {
return {
store: node.store,
params: {},
};
}
if (node.wildcardStore !== null) {
return {
store: node.wildcardStore,
params: {'*': ''},
};
}
return null;
}
if (node.staticChildren !== null) {
const staticChild = node.staticChildren.get(url.charCodeAt(startIndex));
if (staticChild !== undefined) {
const route = matchRoute(url, urlLength, staticChild, startIndex);
if (route !== null) {
return route;
}
}
}
if (node.parametricChild !== null) {
const parametricNode = node.parametricChild;
const slashIndex = url.indexOf('/', startIndex);
if (slashIndex !== startIndex) { // Params cannot be empty
if (slashIndex === -1 || slashIndex >= urlLength) {
if (parametricNode.store !== null) {
const params = {}; // This is much faster than using a computed property
params[parametricNode.paramName] = url.slice(startIndex, urlLength);
return {
store: parametricNode.store,
params,
};
}
} else if (parametricNode.staticChild !== null) {
const route = matchRoute(url, urlLength, parametricNode.staticChild, slashIndex);
if (route !== null) {
route.params[parametricNode.paramName] = url.slice(startIndex, slashIndex);
return route;
}
}
}
}
if (node.wildcardStore !== null) {
return {
store: node.wildcardStore,
params: {
'*': url.slice(startIndex, urlLength),
},
};
}
return null;
}
function debugNode(node) {
if (node.store === null && node.staticChildren === null) { // Can compress output better
if (node.parametricChild === null) { // There is only a wildcard store
return {[node.pathPart + '* (s)']: null};
}
if (node.wildcardStore === null) { // There is only a parametric child
if (node.parametricChild.store === null) {
return {
[node.pathPart + ':' + node.parametricChild.paramName]:
debugNode(node.parametricChild.staticChild),
};
}
if (node.parametricChild.staticChild === null) {
return {
[node.pathPart + ':' + node.parametricChild.paramName + ' (s)']: null,
};
}
}
}
const childRoutes = {};
if (node.staticChildren !== null) {
for (const childNode of node.staticChildren.values()) {
Object.assign(childRoutes, debugNode(childNode));
}
}
if (node.parametricChild !== null) {
const {parametricChild} = node;
const label = ':' + parametricChild.paramName + debugStore(parametricChild.store);
childRoutes[label] = parametricChild.staticChild === null
? null
: debugNode(parametricChild.staticChild);
}
if (node.wildcardStore !== null) {
childRoutes['* (s)'] = null;
}
return {
[node.pathPart + debugStore(node.store)]: childRoutes,
};
}
function debugStore(store) {
return store === null ? '' : ' (s)';
}
module.exports = Router;