-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
89 lines (76 loc) · 2.44 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
const fs = require("fs");
const path = require("path");
const { Compiler } = require("@adobe/htlengine");
// Basic loader query parser allowing for `?data=JSON_OBJECT`
function parseQuery(resourceQuery) {
const result = {};
const params = new URLSearchParams(resourceQuery.slice(1));
for (const [key, value] of params.entries()) {
if (key === "data") {
result[key] = JSON.parse(value);
} else {
result[key] = value;
}
}
return result;
}
module.exports = async function (source) {
const options = this.getOptions();
const query = this.resourceQuery ? parseQuery(this.resourceQuery) : null;
const settings = Object.assign(
{
globalName: "htl",
model: "default",
transformSource: null,
transformCompiled: null,
includeRuntime: true,
runtimeVars: [],
moduleImportGenerator: null,
templateLoader: null,
scriptResolver: null,
data: {}
},
options,
query
);
let input = source;
// Optionally transform source, e.g. remove directives `@adobe/htlengine` does not understand
if (settings.transformSource) {
input = settings.transformSource(source, settings);
}
// Set up compiler
const compiler = new Compiler()
.withDirectory(this.rootContext)
.includeRuntime(settings.includeRuntime)
.withRuntimeGlobalName(settings.globalName);
settings.runtimeVars.forEach(name => {
compiler.withRuntimeVar(name);
});
if (settings.moduleImportGenerator) {
compiler.withModuleImportGenerator(settings.moduleImportGenerator);
}
if (settings.templateLoader) {
compiler.withTemplateLoader(settings.templateLoader);
}
if (settings.scriptResolver) {
compiler.withScriptResolver(settings.scriptResolver);
}
// Set proper context for path resolution. When including the runtime, we run `eval` and require paths to be relative to this file
const compilationContext = settings.includeRuntime
? path.relative(__dirname, this.context)
: this.context;
// Compile
let compiledCode = await compiler.compileToString(input, compilationContext);
// Optionally transform compiled, e.g. to customize runtime
if (settings.transformCompiled) {
compiledCode = settings.transformCompiled(compiledCode, settings);
}
if (settings.includeRuntime) {
// Run
const template = eval(compiledCode);
const html = await template(settings.data);
return `module.exports = \`${html}\``;
} else {
return compiledCode;
}
};