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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
|
import os from "node:os";
import fs from "node:fs";
import matter from "gray-matter";
import lodash from "@11ty/lodash-custom";
import { TemplatePath } from "@11ty/eleventy-utils";
import debugUtil from "debug";
import TemplateData from "./Data/TemplateData.js";
import TemplateRender from "./TemplateRender.js";
import EleventyBaseError from "./Errors/EleventyBaseError.js";
import EleventyErrorUtil from "./Errors/EleventyErrorUtil.js";
import eventBus from "./EventBus.js";
import { withResolvers } from "./Util/PromiseUtil.js";
const { set: lodashSet } = lodash;
const debug = debugUtil("Eleventy:TemplateContent");
const debugDev = debugUtil("Dev:Eleventy:TemplateContent");
class TemplateContentFrontMatterError extends EleventyBaseError {}
class TemplateContentCompileError extends EleventyBaseError {}
class TemplateContentRenderError extends EleventyBaseError {}
class TemplateContent {
#initialized = false;
#config;
#templateRender;
#preprocessorEngine;
#extensionMap;
#configOptions;
constructor(inputPath, templateConfig) {
if (!templateConfig || templateConfig.constructor.name !== "TemplateConfig") {
throw new Error("Missing or invalid `templateConfig` argument");
}
this.eleventyConfig = templateConfig;
this.inputPath = inputPath;
}
async asyncTemplateInitialization() {
if (!this.hasTemplateRender()) {
await this.getTemplateRender();
}
if (this.#initialized) {
return;
}
this.#initialized = true;
let preprocessorEngineName = this.templateRender.getPreprocessorEngineName();
if (preprocessorEngineName && this.templateRender.engine.getName() !== preprocessorEngineName) {
let engine = await this.templateRender.getEngineByName(preprocessorEngineName);
this.#preprocessorEngine = engine;
}
}
resetCachedTemplate({ eleventyConfig }) {
this.eleventyConfig = eleventyConfig;
}
get dirs() {
return this.eleventyConfig.directories;
}
get inputDir() {
return this.dirs.input;
}
get outputDir() {
return this.dirs.output;
}
getResetTypes(types) {
if (types) {
return Object.assign(
{
data: false,
read: false,
render: false,
},
types,
);
}
return {
data: true,
read: true,
render: true,
};
}
// Called during an incremental build when the template instance is cached but needs to be reset because it has changed
resetCaches(types) {
types = this.getResetTypes(types);
if (types.read) {
delete this.readingPromise;
delete this.inputContent;
delete this._frontMatterDataCache;
}
if (types.render) {
this.#templateRender = undefined;
}
}
get extensionMap() {
if (!this.#extensionMap) {
throw new Error("Internal error: Missing `extensionMap` in TemplateContent.");
}
return this.#extensionMap;
}
set extensionMap(map) {
this.#extensionMap = map;
}
set eleventyConfig(config) {
this.#config = config;
if (this.#config.constructor.name === "TemplateConfig") {
this.#configOptions = this.#config.getConfig();
} else {
throw new Error("Tried to get an TemplateConfig but none was found.");
}
}
get eleventyConfig() {
if (this.#config.constructor.name === "TemplateConfig") {
return this.#config;
}
throw new Error("Tried to get an TemplateConfig but none was found.");
}
get config() {
if (this.#config.constructor.name === "TemplateConfig" && !this.#configOptions) {
this.#configOptions = this.#config.getConfig();
}
return this.#configOptions;
}
get bench() {
return this.config.benchmarkManager.get("Aggregate");
}
get engine() {
return this.templateRender.engine;
}
get templateRender() {
if (!this.hasTemplateRender()) {
throw new Error(`\`templateRender\` has not yet initialized on ${this.inputPath}`);
}
return this.#templateRender;
}
hasTemplateRender() {
return !!this.#templateRender;
}
async getTemplateRender() {
if (!this.#templateRender) {
this.#templateRender = new TemplateRender(this.inputPath, this.eleventyConfig);
this.#templateRender.extensionMap = this.extensionMap;
return this.#templateRender.init().then(() => {
return this.#templateRender;
});
}
return this.#templateRender;
}
// For monkey patchers
get frontMatter() {
if (this.frontMatterOverride) {
return this.frontMatterOverride;
} else {
throw new Error(
"Unfortunately you’re using code that monkey patched some Eleventy internals and it isn’t async-friendly. Change your code to use the async `read()` method on the template instead!",
);
}
}
// For monkey patchers
set frontMatter(contentOverride) {
this.frontMatterOverride = contentOverride;
}
getInputPath() {
return this.inputPath;
}
getInputDir() {
return this.inputDir;
}
isVirtualTemplate() {
let def = this.getVirtualTemplateDefinition();
return !!def;
}
getVirtualTemplateDefinition() {
let inputDirRelativeInputPath =
this.eleventyConfig.directories.getInputPathRelativeToInputDirectory(this.inputPath);
return this.config.virtualTemplates[inputDirRelativeInputPath];
}
async #read() {
let content = await this.inputContent;
if (content || content === "") {
let tr = await this.getTemplateRender();
if (tr.engine.useJavaScriptImport()) {
return {
data: {},
content,
};
}
let options = this.config.frontMatterParsingOptions || {};
let fm;
try {
// Added in 3.0, passed along to front matter engines
options.filePath = this.inputPath;
fm = matter(content, options);
} catch (e) {
throw new TemplateContentFrontMatterError(
`Having trouble reading front matter from template ${this.inputPath}`,
e,
);
}
if (options.excerpt && fm.excerpt) {
let excerptString = fm.excerpt + (options.excerpt_separator || "---");
if (fm.content.startsWith(excerptString + os.EOL)) {
// with an os-specific newline after excerpt separator
fm.content = fm.excerpt.trim() + "\n" + fm.content.slice((excerptString + os.EOL).length);
} else if (fm.content.startsWith(excerptString + "\n")) {
// with a newline (\n) after excerpt separator
// This is necessary for some git configurations on windows
fm.content = fm.excerpt.trim() + "\n" + fm.content.slice((excerptString + 1).length);
} else if (fm.content.startsWith(excerptString)) {
// no newline after excerpt separator
fm.content = fm.excerpt + fm.content.slice(excerptString.length);
}
// alias, defaults to page.excerpt
let alias = options.excerpt_alias || "page.excerpt";
lodashSet(fm.data, alias, fm.excerpt);
}
// For monkey patchers that used `frontMatter` 🤧
// https://github.com/11ty/eleventy/issues/613#issuecomment-999637109
// https://github.com/11ty/eleventy/issues/2710#issuecomment-1373854834
// Removed this._frontMatter monkey patcher help in 3.0.0-alpha.7
return fm;
} else {
return {
data: {},
content: "",
excerpt: "",
};
}
}
async read() {
if (!this.readingPromise) {
if (!this.inputContent) {
// @cachedproperty
this.inputContent = this.getInputContent();
}
// @cachedproperty
this.readingPromise = this.#read();
}
return this.readingPromise;
}
/* Incremental builds cache the Template instances (in TemplateWriter) but
* these template specific caches are important for Pagination */
static cache(path, content) {
this._inputCache.set(TemplatePath.absolutePath(path), content);
}
static getCached(path) {
return this._inputCache.get(TemplatePath.absolutePath(path));
}
static deleteFromInputCache(path) {
this._inputCache.delete(TemplatePath.absolutePath(path));
}
// Used via clone
setInputContent(content) {
this.inputContent = content;
}
async getInputContent() {
let tr = await this.getTemplateRender();
let virtualTemplateDefinition = this.getVirtualTemplateDefinition();
if (virtualTemplateDefinition) {
let { content } = virtualTemplateDefinition;
return content;
}
if (
tr.engine.useJavaScriptImport() &&
typeof tr.engine.getInstanceFromInputPath === "function"
) {
return tr.engine.getInstanceFromInputPath(this.inputPath);
}
if (!tr.engine.needsToReadFileContents()) {
return "";
}
let templateBenchmark = this.bench.get("Template Read");
templateBenchmark.before();
let content;
if (this.config.useTemplateCache) {
content = TemplateContent.getCached(this.inputPath);
}
if (!content && content !== "") {
let contentBuffer = fs.readFileSync(this.inputPath);
content = contentBuffer.toString("utf8");
if (this.config.useTemplateCache) {
TemplateContent.cache(this.inputPath, content);
}
}
templateBenchmark.after();
return content;
}
async _testGetFrontMatter() {
let fm = this.frontMatterOverride ? this.frontMatterOverride : await this.read();
return fm;
}
async getPreRender() {
let fm = this.frontMatterOverride ? this.frontMatterOverride : await this.read();
return fm.content;
}
async #getFrontMatterData() {
let fm = await this.read();
// gray-matter isn’t async-friendly but can return a promise from custom front matter
if (fm.data instanceof Promise) {
fm.data = await fm.data;
}
let tr = await this.getTemplateRender();
let extraData = await tr.engine.getExtraDataFromFile(this.inputPath);
let virtualTemplateDefinition = this.getVirtualTemplateDefinition();
let virtualTemplateData;
if (virtualTemplateDefinition) {
virtualTemplateData = virtualTemplateDefinition.data;
}
let data = Object.assign(fm.data, extraData, virtualTemplateData);
TemplateData.cleanupData(data, {
file: this.inputPath,
isVirtualTemplate: Boolean(virtualTemplateData),
});
return {
data,
excerpt: fm.excerpt,
};
}
async getFrontMatterData() {
if (!this._frontMatterDataCache) {
// @cachedproperty
this._frontMatterDataCache = this.#getFrontMatterData();
}
return this._frontMatterDataCache;
}
async getEngineOverride() {
return this.getFrontMatterData().then((data) => {
return data[this.config.keys.engineOverride];
});
}
// checks engines
isTemplateCacheable() {
if (this.#preprocessorEngine) {
return this.#preprocessorEngine.cacheable;
}
return this.engine.cacheable;
}
_getCompileCache(str) {
// Caches used to be bifurcated based on engine name, now they’re based on inputPath
// TODO does `cacheable` need to help inform whether a cache is used here?
let inputPathMap = TemplateContent._compileCache.get(this.inputPath);
if (!inputPathMap) {
inputPathMap = new Map();
TemplateContent._compileCache.set(this.inputPath, inputPathMap);
}
let cacheable = this.isTemplateCacheable();
let { useCache, key } = this.engine.getCompileCacheKey(str, this.inputPath);
// We also tie the compile cache key to the UserConfig instance, to alleviate issues with global template cache
// Better to move the cache to the Eleventy instance instead, no?
// (This specifically failed I18nPluginTest cases with filters being cached across tests and not having access to each plugin’s options)
key = this.eleventyConfig.userConfig._getUniqueId() + key;
return [cacheable, key, inputPathMap, useCache];
}
async compile(str, options = {}) {
let { type, bypassMarkdown, engineOverride } = options;
// Must happen before cacheable fetch below
// Likely only necessary for Eleventy Layouts, see TemplateMap->initDependencyMap
await this.asyncTemplateInitialization();
// this.templateRender is guaranteed here
let tr = await this.getTemplateRender();
if (engineOverride !== undefined) {
debugDev("%o overriding template engine to use %o", this.inputPath, engineOverride);
await tr.setEngineOverride(engineOverride, bypassMarkdown);
} else {
tr.setUseMarkdown(!bypassMarkdown);
}
if (bypassMarkdown && !this.engine.needsCompilation(str)) {
return function () {
return str;
};
}
debugDev("%o compile() using engine: %o", this.inputPath, tr.engineName);
try {
let res;
if (this.config.useTemplateCache) {
let [cacheable, key, cache, useCache] = this._getCompileCache(str);
if (cacheable && key) {
if (useCache && cache.has(key)) {
this.bench.get("(count) Template Compile Cache Hit").incrementCount();
return cache.get(key);
}
this.bench.get("(count) Template Compile Cache Miss").incrementCount();
// Compile cache is cleared when the resource is modified (below)
// Compilation is async, so we eagerly cache a Promise that eventually
// resolves to the compiled function
let withRes = withResolvers();
res = withRes.resolve;
cache.set(key, withRes.promise);
}
}
let typeStr = type ? ` ${type}` : "";
let templateBenchmark = this.bench.get(`Template Compile${typeStr}`);
let inputPathBenchmark = this.bench.get(`> Compile${typeStr} > ${this.inputPath}`);
templateBenchmark.before();
inputPathBenchmark.before();
let fn = await tr.getCompiledTemplate(str);
inputPathBenchmark.after();
templateBenchmark.after();
debugDev("%o getCompiledTemplate function created", this.inputPath);
if (this.config.useTemplateCache && res) {
res(fn);
}
return fn;
} catch (e) {
let [cacheable, key, cache] = this._getCompileCache(str);
if (cacheable && key) {
cache.delete(key);
}
debug(`Having trouble compiling template ${this.inputPath}: %O`, str);
throw new TemplateContentCompileError(
`Having trouble compiling template ${this.inputPath}`,
e,
);
}
}
getParseForSymbolsFunction(str) {
let engine = this.engine;
// Don’t use markdown as the engine to parse for symbols
// TODO pass in engineOverride here
if (this.#preprocessorEngine) {
engine = this.#preprocessorEngine;
}
if ("parseForSymbols" in engine) {
return () => {
if (Array.isArray(str)) {
return str
.filter((entry) => typeof entry === "string")
.map((entry) => engine.parseForSymbols(entry))
.flat();
}
if (typeof str === "string") {
return engine.parseForSymbols(str);
}
return [];
};
}
}
// used by computed data or for permalink functions
async _renderFunction(fn, ...args) {
let mixins = Object.assign({}, this.config.javascriptFunctions);
let result = await fn.call(mixins, ...args);
// normalize Buffer away if returned from permalink
if (Buffer.isBuffer(result)) {
return result.toString();
}
return result;
}
async renderComputedData(str, data) {
if (typeof str === "function") {
return this._renderFunction(str, data);
}
return this._render(str, data, {
type: "Computed Data",
bypassMarkdown: true,
});
}
async renderPermalink(permalink, data) {
let tr = await this.getTemplateRender();
let permalinkCompilation = tr.engine.permalinkNeedsCompilation(permalink);
// No string compilation:
// ({ compileOptions: { permalink: "raw" }})
// These mean `permalink: false`, which is no file system writing:
// ({ compileOptions: { permalink: false }})
// ({ compileOptions: { permalink: () => false }})
// ({ compileOptions: { permalink: () => (() = > false) }})
if (permalinkCompilation === false && typeof permalink !== "function") {
return permalink;
}
/* Custom `compile` function for permalinks, usage:
permalink: function(permalinkString, inputPath) {
return async function(data) {
return "THIS IS MY RENDERED PERMALINK";
}
}
*/
if (permalinkCompilation && typeof permalinkCompilation === "function") {
permalink = await this._renderFunction(permalinkCompilation, permalink, this.inputPath);
}
// Raw permalink function (in the app code data cascade)
if (typeof permalink === "function") {
return this._renderFunction(permalink, data);
}
return this._render(permalink, data, {
type: "Permalink",
bypassMarkdown: true,
});
}
async render(str, data, bypassMarkdown) {
return this._render(str, data, {
type: "Content",
bypassMarkdown,
});
}
_getPaginationLogSuffix(data) {
let suffix = [];
if ("pagination" in data) {
suffix.push(" (");
if (data.pagination.pages) {
suffix.push(
`${data.pagination.pages.length} page${data.pagination.pages.length !== 1 ? "s" : ""}`,
);
} else {
suffix.push("Pagination");
}
suffix.push(")");
}
return suffix.join("");
}
async _render(str, data, options = {}) {
let { bypassMarkdown, type } = options;
try {
if (bypassMarkdown && !this.engine.needsCompilation(str)) {
return str;
}
let fn = await this.compile(str, {
bypassMarkdown,
engineOverride: data[this.config.keys.engineOverride],
type,
});
if (fn === undefined) {
return;
} else if (typeof fn !== "function") {
throw new Error(`The \`compile\` function did not return a function. Received ${fn}`);
}
// Benchmark
let templateBenchmark = this.bench.get("Render");
let inputPathBenchmark = this.bench.get(
`> Render${type ? ` ${type}` : ""} > ${this.inputPath}${this._getPaginationLogSuffix(data)}`,
);
templateBenchmark.before();
if (inputPathBenchmark) {
inputPathBenchmark.before();
}
let rendered = await fn(data);
if (inputPathBenchmark) {
inputPathBenchmark.after();
}
templateBenchmark.after();
debugDev("%o getCompiledTemplate called, rendered content created", this.inputPath);
return rendered;
} catch (e) {
if (EleventyErrorUtil.isPrematureTemplateContentError(e)) {
return Promise.reject(e);
} else {
let tr = await this.getTemplateRender();
let engine = tr.getReadableEnginesList();
debug(`Having trouble rendering ${engine} template ${this.inputPath}: %O`, str);
return Promise.reject(
new TemplateContentRenderError(
`Having trouble rendering ${engine} template ${this.inputPath}`,
e,
),
);
}
}
}
getExtensionEntries() {
return this.engine.extensionEntries;
}
isFileRelevantToThisTemplate(incrementalFile, metadata = {}) {
// always relevant if incremental file not set (build everything)
if (!incrementalFile) {
return true;
}
let hasDependencies = this.engine.hasDependencies(incrementalFile);
let isRelevant = this.engine.isFileRelevantTo(this.inputPath, incrementalFile);
debug(
"Test dependencies to see if %o is relevant to %o: %o",
this.inputPath,
incrementalFile,
isRelevant,
);
let extensionEntries = this.getExtensionEntries().filter((entry) => !!entry.isIncrementalMatch);
if (extensionEntries.length) {
for (let entry of extensionEntries) {
if (
entry.isIncrementalMatch.call(
{
inputPath: this.inputPath,
isFullTemplate: metadata.isFullTemplate,
isFileRelevantToInputPath: isRelevant,
doesFileHaveDependencies: hasDependencies,
},
incrementalFile,
)
) {
return true;
}
}
return false;
} else {
// Not great way of building all templates if this is a layout, include, JS dependency.
// TODO improve this for default template syntaxes
// This is the fallback way of determining if something is incremental (no isIncrementalMatch available)
// This will be true if the inputPath and incrementalFile are the same
if (isRelevant) {
return true;
}
// only return true here if dependencies are not known
if (!hasDependencies && !metadata.isFullTemplate) {
return true;
}
}
return false;
}
}
TemplateContent._inputCache = new Map();
TemplateContent._compileCache = new Map();
eventBus.on("eleventy.resourceModified", (path) => {
// delete from input cache
TemplateContent.deleteFromInputCache(path);
// delete from compile cache
let normalized = TemplatePath.addLeadingDotSlash(path);
let compileCache = TemplateContent._compileCache.get(normalized);
if (compileCache) {
compileCache.clear();
}
});
// Used when the configuration file reset https://github.com/11ty/eleventy/issues/2147
eventBus.on("eleventy.compileCacheReset", () => {
TemplateContent._compileCache = new Map();
});
export default TemplateContent;
|