-
Notifications
You must be signed in to change notification settings - Fork 25
/
precompile.js
57 lines (49 loc) · 1.87 KB
/
precompile.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
import regexpuc from "regexpu-core";
import { parse } from "acorn";
import MagicString from "magic-string";
import { simple as simpleWalk } from "acorn-walk";
const PREAMBLE = `;{
// Precompiled regular expressions
const precompile = (r) => { r.exec('a'); r.exec('\\u1000'); };`;
const POSTAMBLE = "}";
/// Emit a block of javascript that will pre-compile the regular expressions given. As spidermonkey
/// will intern regular expressions, duplicating them at the top level and testing them with both
/// an ascii and utf8 string should ensure that they won't be re-compiled when run in the fetch
/// handler.
export function precompile(source, filename = "<input>") {
const magicString = new MagicString(source, {
filename,
});
const ast = parse(source, {
ecmaVersion: "latest",
sourceType: "script",
});
const precompileCalls = [];
simpleWalk(ast, {
Literal(node) {
if (!node.regex) return;
let transpiledPattern;
try {
transpiledPattern = regexpuc(node.regex.pattern, node.regex.flags, {
unicodePropertyEscapes: "transform",
});
} catch {
// swallow regex parse errors here to instead throw them at the engine level
// this then also avoids regex parser bugs being thrown unnecessarily
transpiledPattern = node.regex.pattern;
}
const transpiledRegex = `/${transpiledPattern}/${node.regex.flags}`;
precompileCalls.push(`precompile(${transpiledRegex});`);
magicString.overwrite(node.start, node.end, transpiledRegex);
},
});
if (!precompileCalls.length) return source;
magicString.prepend(`${PREAMBLE}${precompileCalls.join("\n")}${POSTAMBLE}`);
// When we're ready to pipe in source maps:
// const map = magicString.generateMap({
// source: 'source.js',
// file: 'converted.js.map',
// includeContent: true
// });
return magicString.toString();
}