-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
parse.ts
351 lines (289 loc) · 9.97 KB
/
parse.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
347
348
349
350
351
"use strict";
export default parse;
export interface Options {
lowerCaseAttributeNames?: boolean;
lowerCaseTags?: boolean;
xmlMode?: boolean;
}
export type Selector =
| PseudoSelector
| PseudoElement
| AttributeSelector
| TagSelector
| UniversalSelector
| Traversal;
export interface AttributeSelector {
type: "attribute";
name: string;
action: AttributeAction;
value: string;
ignoreCase: boolean;
}
type DataType = Selector[][] | null | string;
export interface PseudoSelector {
type: "pseudo";
name: string;
data: DataType;
}
export interface PseudoElement {
type: "pseudo-element";
name: string;
}
export interface TagSelector {
type: "tag";
name: string;
}
export interface UniversalSelector {
type: "universal";
}
export interface Traversal {
type: TraversalType;
}
export type AttributeAction =
| "any"
| "element"
| "end"
| "equals"
| "exists"
| "hyphen"
| "not"
| "start";
export type TraversalType =
| "adjacent"
| "child"
| "descendant"
| "parent"
| "sibling";
const reName = /^[^\\]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/;
const reEscape = /\\([\da-f]{1,6}\s?|.)/gi;
//modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
const reAttr = /^\s*((?:\\.|[\w\u00b0-\uFFFF-])+)\s*(?:(\S?)=\s*(?:(['"])([^]*?)\3|(#?(?:\\.|[\w\u00b0-\uFFFF-])*)|)|)\s*(i)?\]/;
const actionTypes: { [key: string]: AttributeAction } = {
undefined: "exists",
"": "equals",
"~": "element",
"^": "start",
$: "end",
"*": "any",
"!": "not",
"|": "hyphen",
};
const Traversals: { [key: string]: TraversalType } = {
">": "child",
"<": "parent",
"~": "sibling",
"+": "adjacent",
};
const attribSelectors: { [key: string]: [string, AttributeAction] } = {
"#": ["id", "equals"],
".": ["class", "element"],
};
//pseudos, whose data-property is parsed as well
const unpackPseudos = new Set(["has", "not", "matches"]);
const stripQuotesFromPseudos = new Set(["contains", "icontains"]);
const quotes = new Set(['"', "'"]);
//unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L152
function funescape(_: string, escaped: string, escapedWhitespace?: string) {
const high = parseInt(escaped, 16) - 0x10000;
// NaN means non-codepoint
return high !== high || escapedWhitespace
? escaped
: high < 0
? // BMP codepoint
String.fromCharCode(high + 0x10000)
: // Supplemental Plane codepoint (surrogate pair)
String.fromCharCode((high >> 10) | 0xd800, (high & 0x3ff) | 0xdc00);
}
function unescapeCSS(str: string) {
return str.replace(reEscape, funescape);
}
function isWhitespace(c: string) {
return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}
function parse(selector: string, options?: Options): Selector[][] {
const subselects: Selector[][] = [];
selector = parseSelector(subselects, `${selector}`, options);
if (selector !== "") {
throw new Error(`Unmatched selector: ${selector}`);
}
return subselects;
}
function parseSelector(
subselects: Selector[][],
selector: string,
options?: Options
): string {
let tokens: Selector[] = [];
let sawWS = false;
function getName(): string {
const match = selector.match(reName);
if (!match) {
throw new Error(`Expected name, found ${selector}`);
}
const [sub] = match;
selector = selector.substr(sub.length);
return unescapeCSS(sub);
}
function stripWhitespace(start: number) {
while (isWhitespace(selector.charAt(start))) start++;
selector = selector.substr(start);
}
function isEscaped(pos: number): boolean {
let slashCount = 0;
while (selector.charAt(--pos) === "\\") slashCount++;
return (slashCount & 1) === 1;
}
stripWhitespace(0);
while (selector !== "") {
const firstChar = selector.charAt(0);
if (isWhitespace(firstChar)) {
sawWS = true;
stripWhitespace(1);
} else if (firstChar in Traversals) {
tokens.push({ type: Traversals[firstChar] });
sawWS = false;
stripWhitespace(1);
} else if (firstChar === ",") {
if (tokens.length === 0) {
throw new Error("Empty sub-selector");
}
subselects.push(tokens);
tokens = [];
sawWS = false;
stripWhitespace(1);
} else {
if (sawWS) {
if (tokens.length > 0) {
tokens.push({ type: "descendant" });
}
sawWS = false;
}
if (firstChar === "*") {
selector = selector.substr(1);
tokens.push({ type: "universal" });
} else if (firstChar in attribSelectors) {
const [name, action] = attribSelectors[firstChar];
selector = selector.substr(1);
tokens.push({
type: "attribute",
name,
action,
value: getName(),
ignoreCase: false,
});
} else if (firstChar === "[") {
selector = selector.substr(1);
const data = selector.match(reAttr);
if (!data) {
throw new Error(
`Malformed attribute selector: ${selector}`
);
}
selector = selector.substr(data[0].length);
let name = unescapeCSS(data[1]);
if (
!options ||
("lowerCaseAttributeNames" in options
? options.lowerCaseAttributeNames
: !options.xmlMode)
) {
name = name.toLowerCase();
}
tokens.push({
type: "attribute",
name,
action: actionTypes[data[2]],
value: unescapeCSS(data[4] || data[5] || ""),
ignoreCase: !!data[6],
});
} else if (firstChar === ":") {
if (selector.charAt(1) === ":") {
selector = selector.substr(2);
tokens.push({
type: "pseudo-element",
name: getName().toLowerCase(),
});
continue;
}
selector = selector.substr(1);
const name = getName().toLowerCase();
let data: DataType = null;
if (selector.charAt(0) === "(") {
if (unpackPseudos.has(name)) {
const quot = selector.charAt(1);
const quoted = quotes.has(quot);
selector = selector.substr(quoted ? 2 : 1);
data = [];
selector = parseSelector(data, selector, options);
if (quoted) {
if (selector.charAt(0) !== quot) {
throw new Error(`Unmatched quotes in :${name}`);
} else {
selector = selector.substr(1);
}
}
if (selector.charAt(0) !== ")") {
throw new Error(
`Missing closing parenthesis in :${name} (${selector})`
);
}
selector = selector.substr(1);
} else {
let pos = 1;
let counter = 1;
for (; counter > 0 && pos < selector.length; pos++) {
if (selector.charAt(pos) === "(" && !isEscaped(pos))
counter++;
else if (
selector.charAt(pos) === ")" &&
!isEscaped(pos)
)
counter--;
}
if (counter) {
throw new Error("Parenthesis not matched");
}
data = selector.substr(1, pos - 2);
selector = selector.substr(pos);
if (stripQuotesFromPseudos.has(name)) {
const quot = data.charAt(0);
if (quot === data.slice(-1) && quotes.has(quot)) {
data = data.slice(1, -1);
}
data = unescapeCSS(data);
}
}
}
tokens.push({ type: "pseudo", name, data });
} else if (reName.test(selector)) {
let name = getName();
if (
!options ||
("lowerCaseTags" in options
? options.lowerCaseTags
: !options.xmlMode)
) {
name = name.toLowerCase();
}
tokens.push({ type: "tag", name });
} else {
if (
tokens.length &&
tokens[tokens.length - 1].type === "descendant"
) {
tokens.pop();
}
addToken(subselects, tokens);
return selector;
}
}
}
addToken(subselects, tokens);
return selector;
}
function addToken(subselects: Selector[][], tokens: Selector[]) {
if (subselects.length > 0 && tokens.length === 0) {
throw new Error("Empty sub-selector");
}
subselects.push(tokens);
}