forked from 4Catalyzer/found
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Matcher.ts
346 lines (288 loc) · 9.44 KB
/
Matcher.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
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
import { dequal } from 'dequal';
import warning from 'tiny-warning';
import pathToRegexp, { compile } from './pathToRegexp';
import type {
IsActiveOptions,
LocationDescriptorObject,
Match,
MatchBase,
MatcherResult,
Params,
ParamsDescriptor,
Query,
QueryDescriptor,
RouteConfig,
RouteIndices,
RouteObject,
} from './typeUtils';
export type RouteConfigGroups = Record<string, RouteConfig>;
export type IntermediateRouteMatch =
| {
index: number;
params: Params;
}
| { groups: Record<string, IntermediateRouteMatch[]> };
export interface MatcherOptions {
warnOnPotentialMissingIndexRoutes?: boolean;
warnOnPartiallyMatchedNamedRoutes?: boolean;
}
export default class Matcher {
private routeConfig: RouteConfig;
private options: MatcherOptions;
constructor(routeConfig: RouteConfig, options: MatcherOptions = {}) {
this.routeConfig = routeConfig;
this.options = {
warnOnPotentialMissingIndexRoutes: true,
warnOnPartiallyMatchedNamedRoutes: true,
...options,
};
}
match({ pathname }: { pathname: string }) {
const matches = this.matchRoutes(this.routeConfig, pathname);
if (!matches) {
return null;
}
return this.makePayload(matches);
}
getRoutes({ routeIndices }: MatchBase) {
if (!routeIndices) {
return null;
}
return this.getRoutesFromIndices(routeIndices, this.routeConfig);
}
protected joinPaths(basePath: string, path?: string | null) {
if (!path) {
return basePath;
}
if (basePath.charAt(basePath.length - 1) === '/') {
// eslint-disable-next-line no-param-reassign
basePath = basePath.slice(0, -1);
}
return `${basePath}${this.getCanonicalPattern(path)}`;
}
isActive(
{ location: matchLocation }: Match,
location: LocationDescriptorObject,
{ exact = false }: IsActiveOptions = {},
) {
return (
this.isPathnameActive(
matchLocation.pathname,
location.pathname,
exact,
) && this.isQueryActive(matchLocation.query, location.query)
);
}
format(pattern: string, params: ParamsDescriptor): string {
return compile(pattern)(params);
}
protected matchRoutes(
routeConfig: RouteConfig,
pathname: string,
): null | IntermediateRouteMatch[] {
for (let index = 0; index < routeConfig.length; ++index) {
const route = routeConfig[index];
const match = this.matchRoute(route, pathname);
if (!match) {
continue; // eslint-disable-line no-continue
}
const { params, remaining } = match;
const { children } = route;
if (children) {
if (Array.isArray(children)) {
const childMatches = this.matchRoutes(children, remaining);
if (childMatches) {
return [{ index, params }, ...childMatches];
}
if (!remaining && route.allowAsIndex) {
return [{ index, params }];
}
if (this.options.warnOnPotentialMissingIndexRoutes)
warning(
remaining,
`Route matching pathname "${pathname}" has child routes, but no index route causing it to 404.\n` +
`If this is intended ignore this warning otherwise in order to resolve this route add \`index\` to the route object or add route with no \`path\` and a \`Component\` to it's \`children\`.\n` +
'This warning can be disabled by setting `warnOnPotentialMissingIndexRoutes` to `false` in the Matcher.',
);
} else {
const groups = this.matchGroups(children, remaining, pathname);
if (groups) {
return [{ index, params }, { groups }];
}
}
}
if (!remaining && !children) {
return [{ index, params }];
}
}
return null;
}
protected matchRoute(route: RouteObject, pathname: string) {
const routePath = route.path;
if (!routePath) {
return {
params: {},
remaining: pathname,
};
}
const pattern = this.getCanonicalPattern(routePath);
const keys: { name: string }[] = [];
const regexp = pathToRegexp(pattern, keys, { end: false });
const match = regexp.exec(pathname);
if (match === null) {
return null;
}
const params: Params = {};
keys.forEach(({ name }, index) => {
const value = match[index + 1];
params[name] = value && decodeURIComponent(value);
});
return {
params,
remaining: pathname.slice(match[0].length),
};
}
protected matchGroups(
routeGroups: Record<string, RouteConfig>,
pathname: string,
parentPathname: string,
) {
const groups: Record<string, IntermediateRouteMatch[]> = {};
const failedGroups = [] as string[];
const abortEarly =
process.env.NODE_ENV === 'production' ||
!this.options.warnOnPartiallyMatchedNamedRoutes;
for (const [groupName, routes] of Object.entries(routeGroups)) {
const groupMatch = this.matchRoutes(routes, pathname);
if (!groupMatch) {
if (abortEarly) {
return null;
}
failedGroups.push(groupName);
} else {
groups[groupName] = groupMatch;
}
}
if (failedGroups.length) {
warning(
!this.options.warnOnPartiallyMatchedNamedRoutes,
`Route matching pathname "${parentPathname}" only partially matched against its named child routes causing it to 404. ` +
`The following named routes failed to match "${pathname}":\n\n` +
`${failedGroups.join(', ')}\n\n` +
`If this is intended ignore this warning, otherwise the unmatched groups may need at catch all route "path=(.*)?".\n` +
'This warning can be disabled by setting `warnOnPartiallyMatchedNamedRoutes` to `false` in the Matcher.',
);
return null;
}
return groups;
}
protected getCanonicalPattern(pattern: string) {
return pattern.charAt(0) === '/' ? pattern : `/${pattern}`;
}
protected makePayload(matches: IntermediateRouteMatch[]): MatcherResult {
const routeMatch = matches[0];
if ('groups' in routeMatch) {
warning(
matches.length === 1,
`Route match with groups ${Object.keys(routeMatch.groups).join(
', ',
)} has children, which are ignored.`,
);
const groupRouteIndices: Record<string, RouteIndices> = {};
const routeParams: MatcherResult['routeParams'] = [];
const params = {};
Object.entries(routeMatch.groups).forEach(
([groupName, groupMatches]) => {
const groupPayload = this.makePayload(groupMatches);
// Retain the nested group structure for route indices so we can
// reconstruct the element tree from flattened route elements.
groupRouteIndices[groupName] = groupPayload.routeIndices;
// Flatten route groups for route params matching getRoutesFromIndices
// below.
routeParams.push(...groupPayload.routeParams);
// Just merge all the params depth-first; it's the easiest option.
Object.assign(params, groupPayload.params);
},
);
return {
routeIndices: [groupRouteIndices],
routeParams,
params,
};
}
const { index, params } = routeMatch;
if (matches.length === 1) {
return {
routeIndices: [index],
routeParams: [params],
params,
};
}
const childPayload = this.makePayload(matches.slice(1));
return {
routeIndices: [index, ...childPayload.routeIndices],
routeParams: [params, ...childPayload.routeParams],
params: { ...params, ...childPayload.params },
};
}
protected getRoutesFromIndices(
routeIndices: RouteIndices,
routeConfigOrGroups: RouteConfig | Record<string, RouteConfig> | undefined,
): RouteObject[] {
const routeIndex = routeIndices[0];
if (typeof routeIndex === 'object') {
// Flatten route groups to save resolvers from having to explicitly
// handle them.
const groupRoutes = [];
for (const [groupName, groupRouteIndices] of Object.entries(
routeIndex,
)) {
groupRoutes.push(
...this.getRoutesFromIndices(
groupRouteIndices,
(routeConfigOrGroups as RouteConfigGroups)[groupName],
),
);
}
return groupRoutes;
}
const route = (routeConfigOrGroups as RouteConfig)[routeIndex];
if (routeIndices.length === 1) {
return [route];
}
return [
route,
...this.getRoutesFromIndices(routeIndices.slice(1), route.children),
];
}
isPathnameActive(matchPathname: string, pathname: string, exact?: boolean) {
if (pathname === matchPathname) {
return true;
}
if (exact) {
// The above condition is necessary for an exact match.
return false;
}
// Require that a partial match be followed by a path separator.
const pathnameWithSeparator =
pathname.slice(-1) !== '/' ? `${pathname}/` : pathname;
// Can't use startsWith, as that requires a polyfill.
return matchPathname.indexOf(pathnameWithSeparator) === 0;
}
isQueryActive(
matchQuery: Query,
query?: QueryDescriptor | undefined | null,
) {
if (!query) {
return true;
}
return Object.entries(query).every(([key, value]) =>
Object.prototype.hasOwnProperty.call(matchQuery, key)
? dequal(matchQuery[key], value)
: value === undefined,
);
}
replaceRouteConfig(routeConfig: RouteConfig) {
this.routeConfig = routeConfig;
}
}