-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathremark-variables.js
79 lines (68 loc) · 2.25 KB
/
remark-variables.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
/* eslint-env node */
/* eslint import/no-nodejs-modules:0 */
/* eslint-disable no-console */
import {visit} from 'unist-util-visit';
function scopedEval(expr, context = {}) {
// eslint-disable-next-line no-new-func
const evaluator = Function.apply(null, [
...Object.keys(context),
'expr',
'return eval(expr)',
]);
return evaluator.apply(null, [...Object.values(context), expr]);
}
const matchEach = (text, pattern, callback) => {
let match, rv;
const promises = [];
// eslint-disable-next-line no-cond-assign
while ((match = pattern.exec(text)) !== null) {
rv = callback(match);
if (rv instanceof Promise) {
promises.push(rv);
}
}
return Promise.all(promises);
};
export default function remarkVariables(options) {
return async (markdownAST, markdownNode) => {
const page = markdownNode.data?.frontmatter;
const scope = await options.resolveScopeData();
visit(
markdownAST,
() => true,
node => {
// XXX(dcramer): by far the worst template language of all time
if (!node.value) {
return;
}
// TODO(dcramer): this could be improved by parsing the string piece by piece so you can
// safely quote template literals e.g. {{ '{{ foo }}' }}
matchEach(node.value, /\{\{\\?@inject (\s*[^}]+) \}\}/gi, match => {
const expr = match[1].trim();
// Inject sequence is escaped
if (match[0].includes('{{\\@inject')) {
node.value = node.value.replace('\\@inject', '@inject');
return;
}
// YOU CAN EXECUTE CODE HERE JUST FYI
let result;
try {
result = scopedEval(expr, {...scope, page});
} catch (err) {
console.error(`Failed to interpolate expression: "${expr}"`);
throw err;
}
// replace the match with the result (even if it's empty)
node.value = node.value.replace(match[0], result);
if (!result) {
console.error(new Error(`Failed to interpolate expression: "${expr}"`));
// fail the build process in production
if (process.env.NODE_ENV === 'production') {
process.exit(1);
}
}
});
}
);
};
}