-
-
Notifications
You must be signed in to change notification settings - Fork 481
/
JavaScript.js
234 lines (204 loc) · 5.94 KB
/
JavaScript.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import TemplateEngine from "./TemplateEngine.js";
import EleventyBaseError from "../Errors/EleventyBaseError.js";
import getJavaScriptData from "../Util/GetJavaScriptData.js";
import EventBusUtil from "../Util/EventBusUtil.js";
import { EleventyImport } from "../Util/Require.js";
class JavaScriptTemplateNotDefined extends EleventyBaseError {}
class JavaScript extends TemplateEngine {
// which data keys to bind to `this` in JavaScript template functions
static DATA_KEYS_TO_BIND = ["page", "eleventy"];
constructor(name, templateConfig) {
super(name, templateConfig);
this.instances = {};
this.cacheable = false;
EventBusUtil.soloOn("eleventy.templateModified", (inputPath, metadata = {}) => {
let { usedByDependants, relevantLayouts } = metadata;
// Remove from cached instances when modified
let instancesToDelete = [
inputPath,
...(usedByDependants || []),
...(relevantLayouts || []),
].map((entry) => TemplatePath.addLeadingDotSlash(entry));
for (let inputPath of instancesToDelete) {
if (inputPath in this.instances) {
delete this.instances[inputPath];
}
}
});
}
normalize(result) {
if (Buffer.isBuffer(result)) {
return result.toString();
}
return result;
}
// String, Buffer, Promise
// Function, Class
// Object
// Module
_getInstance(mod) {
let noop = function () {
return "";
};
if (typeof mod === "string" || mod instanceof Buffer || mod.then) {
return { render: () => mod };
} else if (typeof mod === "function") {
if (mod.prototype && ("data" in mod.prototype || "render" in mod.prototype)) {
if (!("render" in mod.prototype)) {
mod.prototype.render = noop;
}
return new mod();
} else {
return {
render: mod,
};
}
} else if (
"data" in mod ||
"render" in mod ||
("default" in mod && this.eleventyConfig.getIsProjectUsingEsm())
) {
if (!("render" in mod)) {
if ("default" in mod) {
mod.render = mod.default;
} else {
mod.render = noop;
}
}
return mod;
}
}
async #getInstanceFromInputPath(inputPath) {
let mod;
let relativeInputPath =
this.eleventyConfig.directories.getInputPathRelativeToInputDirectory(inputPath);
if (this.eleventyConfig.userConfig.isVirtualTemplate(relativeInputPath)) {
mod = this.eleventyConfig.userConfig.virtualTemplates[relativeInputPath].content;
} else {
let isEsm = this.eleventyConfig.getIsProjectUsingEsm();
mod = await EleventyImport(inputPath, isEsm ? "esm" : "cjs");
}
let inst = this._getInstance(mod);
if (inst) {
this.instances[inputPath] = inst;
} else {
throw new JavaScriptTemplateNotDefined(
`No JavaScript template returned from ${inputPath}. Did you assign module.exports (CommonJS) or export (ESM)?`,
);
}
return inst;
}
async getInstanceFromInputPath(inputPath) {
if (!this.instances[inputPath]) {
this.instances[inputPath] = this.#getInstanceFromInputPath(inputPath);
}
return this.instances[inputPath];
}
/**
* JavaScript files defer to the module loader rather than read the files to strings
*
* @override
*/
needsToReadFileContents() {
return false;
}
async getExtraDataFromFile(inputPath) {
let inst = await this.getInstanceFromInputPath(inputPath);
return getJavaScriptData(inst, inputPath);
}
getJavaScriptFunctions(inst) {
let fns = {};
let configFns = this.config.javascriptFunctions;
for (let key in configFns) {
// prefer pre-existing `page` javascriptFunction, if one exists
if (key === "page") {
// do nothing
} else {
// note: wrapping creates a new function
fns[key] = JavaScript.wrapJavaScriptFunction(inst, configFns[key]);
}
}
return fns;
}
static wrapJavaScriptFunction(inst, fn) {
return function (...args) {
for (let key of JavaScript.DATA_KEYS_TO_BIND) {
if (inst?.[key]) {
this[key] = inst[key];
}
}
return fn.call(this, ...args);
};
}
addExportsToBundles(inst, url) {
let cfg = this.eleventyConfig.userConfig;
if (!("getBundleManagers" in cfg)) {
return;
}
let managers = cfg.getBundleManagers();
for (let name in managers) {
let mgr = managers[name];
let key = mgr.getBundleExportKey();
if (!key) {
continue;
}
if (typeof inst[key] === "string") {
// export const css = ``;
mgr.addToPage(url, inst[key]);
} else if (isPlainObject(inst[key])) {
if (typeof inst[key][name] === "string") {
// Object with bundle names:
// export const bundle = {
// css: ``
// };
mgr.addToPage(url, inst[key][name]);
} else if (isPlainObject(inst[key][name])) {
// Object with bucket names:
// export const bundle = {
// css: {
// default: ``
// }
// };
for (let bucketName in inst[key][name]) {
mgr.addToPage(url, inst[key][name][bucketName], bucketName);
}
}
}
}
}
async compile(str, inputPath) {
let inst;
if (str) {
// When str has a value, it's being used for permalinks in data
inst = this._getInstance(str);
} else {
// For normal templates, str will be falsy.
inst = await this.getInstanceFromInputPath(inputPath);
}
if (inst && "render" in inst) {
return function (data = {}) {
// TODO does this do anything meaningful for non-classes?
// `inst` should have a normalized `render` function from _getInstance
// Map exports to bundles
if (data.page?.url) {
this.addExportsToBundles(inst, data.page.url);
}
for (let key of JavaScript.DATA_KEYS_TO_BIND) {
if (!inst[key] && data[key]) {
// only blow away existing inst.page if it has a page.url
if (key !== "page" || !inst.page || inst.page.url) {
inst[key] = data[key];
}
}
}
Object.assign(inst, this.getJavaScriptFunctions(inst));
return this.normalize(inst.render.call(inst, data));
}.bind(this);
}
}
static shouldSpiderJavaScriptDependencies() {
return true;
}
}
export default JavaScript;