UNPKG

1.07 kBJavaScriptView Raw
1'use strict'
2
3const vm = require('vm')
4const matchHelper = require('posthtml-match-helper')
5const { render } = require('posthtml-render')
6const { match } = require('posthtml/lib/api')
7
8const ctx = vm.createContext({ module })
9
10/**
11 * @description Get the script tag with locals attribute from a node list and return locals.
12 *
13 * @method scriptDataLocals
14 *
15 * @param {Array} tree Nodes
16 *
17 * @return {Object} {} Locals
18 */
19function scriptDataLocals (tree, options) {
20 const locals = {}
21 const localsAttr = options.localsAttr
22 const localsContext = options.locals || {}
23
24 match.call(tree, matchHelper(`script[${localsAttr}]`), node => {
25 if (node.content) {
26 const code = render(node.content)
27
28 try {
29 const parsedContext = vm.createContext({ ...ctx, locals: localsContext })
30 const local = vm.runInContext(code, parsedContext)
31
32 Object.assign(locals, local)
33 } catch {};
34 }
35
36 if (options.removeScriptLocals) {
37 return ''
38 }
39
40 return node
41 })
42
43 return {
44 locals
45 }
46}
47
48module.exports = scriptDataLocals