-
Notifications
You must be signed in to change notification settings - Fork 0
/
rcapture-regexp.ts
107 lines (90 loc) · 2.75 KB
/
rcapture-regexp.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
import type { RouteCaptor } from '../route-captor.js';
import type { RouteMatch } from '../route-match.js';
import { routeMatch } from '../route-match.js';
import type { RouteMatcher } from '../route-matcher.js';
const removeGlobalAndStickyFlagsPattern = /[gy]/;
/**
* Builds a route matcher that matches a part of the name against expected regular expression, and optionally captures
* the match.
*
* Reports the capture as {@link RouteCaptorSignatureMap.regexp `regexp`}.
*
* @param expected - The regular expression the name part expected to match.
* @param name - The name of the capture or nothing to capture under match index.
*
* @returns New route matcher.
*/
export function rcaptureRegExp(expected: RegExp, name?: string): RouteMatcher {
const key = name ?? 0;
const { global, sticky, flags } = expected;
const re = sticky ? new RegExp(expected) : new RegExp(expected.source, `${flags}y`);
let searchRe: RegExp | undefined;
return {
test(context): RouteMatcher.Match | undefined {
const { entry, nameOffset } = context;
re.lastIndex = nameOffset;
let execResult = re.exec(entry.name);
if (!execResult) {
return;
}
let nameChars = re.lastIndex;
let resultCallback!: RouteMatch | undefined;
// Fill group names.
for (;;) {
const prevCallback = resultCallback;
const match = execResult;
const nextCallback = (captor: RouteCaptor): void => captor('regexp', key, match, context);
resultCallback = prevCallback
? captor => {
prevCallback(captor);
nextCallback(captor);
}
: nextCallback;
if (!global) {
break;
}
// Repeat the search for global pattern.
execResult = re.exec(entry.name);
if (!execResult) {
break;
}
nameChars = re.lastIndex;
}
return {
nameChars,
callback: resultCallback,
};
},
find({
route,
entry,
entryIndex: fromEntry,
nameOffset,
pattern,
matcherIndex: fromMatcher,
}): [RouteMatch, number] | null | undefined {
if (!searchRe) {
if (global || sticky) {
searchRe = new RegExp(
expected.source,
flags.split(removeGlobalAndStickyFlagsPattern).join(''),
);
} else {
searchRe = expected;
}
}
const name = entry.name.substring(nameOffset);
const found = searchRe.exec(name);
if (!found) {
return;
}
const offset = nameOffset + found.index;
const match = routeMatch(route, pattern, {
fromEntry,
nameOffset: offset,
fromMatcher,
});
return match && [match, offset];
},
};
}