-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprocess-script.js
49 lines (40 loc) · 1.26 KB
/
process-script.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
'use strict';
const vm = require('vm');
const {existsSync, readFileSync} = require('fs');
const {render} = require('posthtml-render');
const {match} = require('posthtml/lib/api');
const ctx = vm.createContext({module, require});
/**
* Get the script tag with props from a node list and return process props.
* Custom posthtml-expressions/lib/locals.
*
* @param {Array} tree Nodes
* @param {Object} options Options
* @param {string} scriptPath - Component path
* @return {Object} {} Locals
*/
module.exports = (tree, options, scriptPath) => {
const props = {};
const propsContext = options.props;
const utilities = {...options.utilities};
const context = {...utilities, ...ctx, [options.propsContext]: propsContext, $slots: options.$slots};
const runInContext = code => {
try {
const parsedContext = vm.createContext(context);
const parsedProps = vm.runInContext(code, parsedContext);
Object.assign(props, parsedProps);
} catch {}
};
if (existsSync(scriptPath)) {
runInContext(readFileSync(scriptPath, 'utf8'));
}
match.call(tree, {tag: 'script', attrs: {[options.propsScriptAttribute]: ''}}, node => {
if (node.content) {
runInContext(render(node.content));
}
return '';
});
return {
props
};
};