Repository navigation
Expand file tree
/
Copy pathTemplateWriter.js
More file actions
executable file
·577 lines (483 loc) · 16.1 KB
/
Copy pathTemplateWriter.js
File metadata and controls
executable file
·577 lines (483 loc) · 16.1 KB
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
import { TemplatePath, isPlainObject } from "@11ty/eleventy-utils";
import Template from "./Template.js";
import TemplateMap from "./TemplateMap.js";
import BaseError from "./Errors/BaseError.js";
import ErrorUtil from "./Errors/ErrorUtil.js";
import { createDebug } from "./Util/DebugLogUtil.js";
const debug = createDebug("TemplateWriter");
class TemplateWriterMissingConfigArgError extends BaseError {}
class PassthroughCopyError extends BaseError {}
class TemplateError extends BaseError {}
class TemplateWriter {
#eleventyFiles;
#passthroughManager;
#errorHandler;
#logger;
#extensionMap;
#incrementalFiles = [];
constructor(
templateFormats, // TODO remove this in favor of this.#eleventyFiles
templateData,
templateConfig,
) {
if (!templateConfig) {
throw new TemplateWriterMissingConfigArgError("Missing config argument.");
}
this.templateConfig = templateConfig;
this.config = templateConfig.getConfig();
this.userConfig = templateConfig.userConfig;
this.templateFormats = templateFormats;
this.templateData = templateData;
this.isDryRun = false;
this.writeCount = 0;
this.renderCount = 0;
this.skippedCount = 0;
this.isRunInitialBuild = true;
this._templatePathCache = new Map();
}
get dirs() {
return this.templateConfig.directories;
}
get inputDir() {
return this.dirs.input;
}
get outputDir() {
return this.dirs.output;
}
get templateFormats() {
return this._templateFormats;
}
set templateFormats(value) {
this._templateFormats = value;
}
/* Getter for error handler */
get errorHandler() {
if (!this.#errorHandler) {
throw new Error("Internal error: missing ErrorHandler instance.");
}
return this.#errorHandler;
}
set errorHandler(errorHandler) {
this.#errorHandler = errorHandler;
}
get logger() {
if (!this.#logger) {
throw new Error("Internal error: missing ConsoleLogger instance.");
}
return this.#logger;
}
set logger(logger) {
this.#logger = logger;
}
/* For testing */
overrideConfig(config) {
this.config = config;
}
restart() {
this.writeCount = 0;
this.renderCount = 0;
this.skippedCount = 0;
}
set extensionMap(extensionMap) {
this.#extensionMap = extensionMap;
}
get extensionMap() {
if (!this.#extensionMap) {
throw new Error("Internal error: missing `extensionMap` in TemplateWriter.");
}
return this.#extensionMap;
}
setPassthroughManager(mgr) {
this.#passthroughManager = mgr;
}
setEleventyFiles(eleventyFiles) {
this.#eleventyFiles = eleventyFiles;
}
// Tests
getPassthroughGlobs() {
return this.#eleventyFiles?.passthroughGlobs;
}
getPathsWithVirtualTemplates(paths) {
// Support for virtual templates added in 3.0
if (this.config.virtualTemplates && isPlainObject(this.config.virtualTemplates)) {
let virtualTemplates = Object.keys(this.config.virtualTemplates)
.filter((path) => {
// Filter out includes/layouts
return this.dirs.isTemplateFile(this.dirs.getInputPath(path));
})
.map((path) => {
let fullVirtualPath = this.dirs.getInputPath(path);
if (!this.extensionMap.getKey(fullVirtualPath)) {
throw new Error(
`The virtual template at ${fullVirtualPath} is using a template format that’s not valid for your project. Your project is using: "${this.formats}". Read more about formats: https://v3.11ty.dev/docs/config/#template-formats`,
);
}
return fullVirtualPath;
});
paths = paths.concat(virtualTemplates);
// Virtual templates can not live at the same place as files on the file system!
if (paths.length !== new Set(paths).size) {
let conflicts = {};
for (let path of paths) {
if (conflicts[path]) {
throw new Error(
`A virtual template had the same path as a file on the file system: "${path}"`,
);
}
conflicts[path] = true;
}
}
}
return paths;
}
async _getAllPaths() {
if (!this.#eleventyFiles) {
return this.getPathsWithVirtualTemplates([]);
}
// this is now cached upstream by FileSystemSearch
let paths = await this.#eleventyFiles.getFiles();
paths = this.getPathsWithVirtualTemplates(paths);
return paths;
}
createTemplate(path, to = "fs") {
let tmpl = this._templatePathCache.get(path);
let wasCached = false;
if (tmpl) {
wasCached = true;
// Update config for https://github.com/11ty/eleventy/issues/3468
// TODO reset other constructor things here like inputDir/outputDir
tmpl.resetCachedTemplate({
templateData: this.templateData,
extensionMap: this.extensionMap,
eleventyConfig: this.templateConfig,
});
} else {
tmpl = new Template(path, this.templateData, this.extensionMap, this.templateConfig);
tmpl.setOutputFormat(to);
tmpl.logger = this.logger;
this._templatePathCache.set(path, tmpl);
}
tmpl.setTransforms(this.config.transforms);
tmpl.setPreprocessors(this.config.preprocessors);
tmpl.setLinters(this.config.linters);
tmpl.setDryRun(this.isDryRun);
tmpl.reset();
return {
template: tmpl,
wasCached,
};
}
// incrementalFileShape is `template` or `copy` (for passthrough file copy)
async #addToTemplateMapIncrementalBuild(incrementalFileShapes, paths, to = "fs") {
// Render overrides are only used when `--ignore-initial` is in play and an initial build is not run
let ignoreInitialBuild = !this.isRunInitialBuild;
let secondOrderRelevantLookup = {};
let templates = [];
let cacheResetTracker = new Set();
// Delete incremental file from the dependency graph so we get fresh entries!
// This _must_ happen before any additions: data files and global data reads (via TemplateMap->add),
// Custom.js, and GlobalDependencyMap.js (from the eleventy.layouts Event)
for (let p of this.#incrementalFiles) {
this.config.uses.resetNode(p);
}
let promises = [];
for (let path of paths) {
let { template: tmpl } = this.createTemplate(path, to);
// Note: removed a fix here to fetch missing templateRender instances
// that was tested as no longer needed (Issue #3170)
// Related: #3870, improved configuration reset
templates.push(tmpl);
// required for tmpl.isFileRelevantToThisTemplate below
await tmpl.asyncTemplateInitialization();
// This must happen before data is generated for the incremental file only
if (
(incrementalFileShapes[path] === "template" &&
this.#incrementalFiles.includes(tmpl.inputPath)) ||
// Issue #3824 #3870
this.#incrementalFiles.find((p) =>
tmpl.isFileRelevantToThisTemplate(p, {
isFullTemplate: incrementalFileShapes[p] === "template",
}),
)
) {
cacheResetTracker.add(tmpl.inputPath);
tmpl.resetCaches();
}
// IMPORTANT: This is where the data is first generated for the template
promises.push(this.templateMap.add(tmpl));
}
// Important to set up template dependency relationships first
await Promise.all(promises);
// write new template relationships to the global dependency graph for next time
this.templateMap.addAllToGlobalDependencyGraph();
// Always disable render for --ignore-initial
if (ignoreInitialBuild) {
for (let tmpl of templates) {
tmpl.setRenderableOverride(false); // disable render
}
return;
}
for (let tmpl of templates) {
if (
incrementalFileShapes[tmpl.inputPath] === "template" &&
this.#incrementalFiles.includes(tmpl.inputPath)
) {
tmpl.setRenderableOverride(undefined); // unset, probably render
} else if (
this.#incrementalFiles.find((p) =>
tmpl.isFileRelevantToThisTemplate(p, {
isFullTemplate: incrementalFileShapes[p] === "template",
}),
)
) {
// changed file is used by template
// template uses the changed file
tmpl.setRenderableOverride(undefined); // unset, probably render
secondOrderRelevantLookup[tmpl.inputPath] = true;
} else if (this.config.uses.areFilesUsedBy(this.#incrementalFiles, tmpl.inputPath)) {
// changed file uses this template
tmpl.setRenderableOverride("optional");
} else {
// For incremental, always disable render on irrelevant templates
tmpl.setRenderableOverride(false); // disable render
}
}
let secondOrderRelevantArray = this.config.uses
.getTemplatesRelevantToTemplateList(Object.keys(secondOrderRelevantLookup))
.map((entry) => TemplatePath.addLeadingDotSlash(entry));
let secondOrderTemplates = Object.fromEntries(
Object.entries(secondOrderRelevantArray).map(([index, value]) => [value, true]),
);
for (let tmpl of templates) {
// second order templates must also be rendered if not yet already rendered at least once and available in cache.
if (secondOrderTemplates[tmpl.inputPath]) {
if (tmpl.isRenderableDisabled()) {
tmpl.setRenderableOverride("optional");
}
}
}
// Order of templates does not matter here, they’re reordered later based on dependencies in TemplateMap.js
for (let tmpl of templates) {
if (
incrementalFileShapes[tmpl.inputPath] === "template" &&
this.#incrementalFiles.includes(tmpl.inputPath)
) {
// Cache is reset above (to invalidate data cache at the right time)
tmpl.setDryRunViaIncremental(false);
} else if (!tmpl.isRenderableDisabled() && !tmpl.isRenderableOptional()) {
if (!cacheResetTracker.has(tmpl.inputPath)) {
// Related to the template but not the template (reset the render cache, not the read cache)
tmpl.resetCaches({
render: true,
});
}
tmpl.setDryRunViaIncremental(false);
} else {
// During incremental we don’t reset cache here, keep cache for read/reader (data cache is always reset elsewhere), see https://github.com/11ty/eleventy/issues/2710
tmpl.setDryRunViaIncremental(true);
this.skippedCount++;
}
}
}
async #addToTemplateMapFullBuild(paths, to = "fs") {
if (this.#incrementalFiles?.length > 0) {
throw new Error("Internal error: improper mixing of full build and incremental builds.");
}
let ignoreInitialBuild = !this.isRunInitialBuild;
let promises = [];
for (let path of paths) {
let { template: tmpl, wasCached } = this.createTemplate(path, to);
// Render overrides are only used when `--ignore-initial` is in play and an initial build is not run
if (ignoreInitialBuild) {
tmpl.setRenderableOverride(false); // disable render
} else {
tmpl.setRenderableOverride(undefined); // unset, render
}
if (wasCached) {
tmpl.resetCaches();
}
// IMPORTANT: This is where the data is first generated for the template
promises.push(this.templateMap.add(tmpl));
}
await Promise.all(promises);
// write new template relationships to the global dependency graph for next time
this.templateMap.addAllToGlobalDependencyGraph();
}
getIncrementalFileShapes(paths) {
// browser-based fork
if (!this.#eleventyFiles) {
let shapes = {};
for (let incFile of this.#incrementalFiles) {
// this is an assumption for browser-based Eleventy only
shapes[incFile] = "template";
}
return shapes;
}
return this.#eleventyFiles?.getIncrementalFileShapes(paths, this.#incrementalFiles);
}
async #addToTemplateMap(paths, to = "fs") {
let incrementalFileShapes = this.getIncrementalFileShapes(paths);
// Filter out passthrough copy files
paths = paths.filter((path) => {
if (!this.extensionMap.hasEngine(path)) {
return false;
}
if (incrementalFileShapes[path] === "copy") {
this.skippedCount++;
// Filters out templates if the incremental file is a passthrough copy file
return false;
}
return true;
});
if (this.#incrementalFiles?.length > 0) {
await this.#addToTemplateMapIncrementalBuild(incrementalFileShapes, paths, to);
} else {
await this.#addToTemplateMapFullBuild(paths, to);
}
}
async createTemplateMap(paths, to) {
this.templateMap = new TemplateMap(this.templateConfig);
this.templateMap.logger = this.#logger;
await this.#addToTemplateMap(paths, to);
await this.templateMap.cache();
// Return is used by tests
return this.templateMap;
}
async #generateTemplate(mapEntry, to) {
let tmpl = mapEntry.template;
return tmpl.generateMapEntry(mapEntry, to).then((pages) => {
this.renderCount += tmpl.getRenderCount();
this.writeCount += tmpl.getWriteCount();
return pages;
});
}
async writePassthroughCopy(templateExtensionPaths) {
if (!this.#passthroughManager) {
throw new Error("Internal error: Missing `passthroughManager` instance.");
}
return this.#passthroughManager.copyAll(templateExtensionPaths).catch((e) => {
this.errorHandler.warn(e, "Error with passthrough copy");
return Promise.reject(new PassthroughCopyError("Having trouble copying", e));
});
}
async generateTemplates(paths, to = "fs") {
let promises = [];
// TODO optimize await here
await this.createTemplateMap(paths, to);
debug("Template map created.");
let usedTemplateContentTooEarlyMap = [];
for (let mapEntry of this.templateMap.getMap()) {
promises.push(
this.#generateTemplate(mapEntry, to).catch(function (e) {
// Premature templateContent in layout render, this also happens in
// TemplateMap.populateContentDataInMap for non-layout content
if (ErrorUtil.isPrematureTemplateContentError(e)) {
usedTemplateContentTooEarlyMap.push(mapEntry);
} else {
let outputPaths = `"${mapEntry._pages.map((page) => page.outputPath).join(`", "`)}"`;
return Promise.reject(
new TemplateError(
`Having trouble writing to ${outputPaths} from "${mapEntry.inputPath}"`,
e,
).setFilePath(mapEntry.inputPath),
);
}
}),
);
}
for (let mapEntry of usedTemplateContentTooEarlyMap) {
promises.push(
this.#generateTemplate(mapEntry, to).catch(function (e) {
return Promise.reject(
new TemplateError(
`Having trouble writing to (second pass) "${mapEntry.outputPath}" from "${mapEntry.inputPath}"`,
e,
).setFilePath(mapEntry.inputPath),
);
}),
);
}
return promises;
}
// Similiar to `write()` but skips passthrough copy
async writeTemplates() {
let paths = await this._getAllPaths();
return Promise.all(await this.generateTemplates(paths)).then(
(templateResults) => {
return {
// New in 3.0: flatten and filter out falsy templates
templates: templateResults.flat().filter(Boolean),
};
},
(e) => {
return Promise.reject(e);
},
);
}
async write() {
let paths = await this._getAllPaths();
// This must happen before writePassthroughCopy
this.templateConfig.userConfig.emit("buildawesome#beforerender");
let aggregatePassthroughCopyPromise = this.writePassthroughCopy(paths);
let templatesPromise = Promise.all(await this.generateTemplates(paths)).then((results) => {
this.templateConfig.userConfig.emit("buildawesome#render");
return results;
});
return Promise.all([aggregatePassthroughCopyPromise, templatesPromise]).then(
async ([passthroughCopyResults, templateResults]) => {
return {
passthroughCopy: passthroughCopyResults,
// New in 3.0: flatten and filter out falsy templates
templates: templateResults.flat().filter(Boolean),
};
},
(e) => {
return Promise.reject(e);
},
);
}
// Passthrough copy not supported in JSON output.
// --incremental not supported in JSON output.
async getJSON(to = "json") {
let paths = await this._getAllPaths();
let promises = await this.generateTemplates(paths, to);
return Promise.all(promises).then(
(templateResults) => {
return {
// New in 3.0: flatten and filter out falsy templates
templates: templateResults.flat().filter(Boolean),
};
},
(e) => {
return Promise.reject(e);
},
);
}
setDryRun(isDryRun) {
this.isDryRun = Boolean(isDryRun);
}
setRunInitialBuild(runInitialBuild) {
this.isRunInitialBuild = runInitialBuild;
}
setIncrementalFiles(files = []) {
this.#incrementalFiles = files;
this.#passthroughManager?.setIncrementalFiles(files);
}
resetIncremental() {
this.#incrementalFiles = [];
this.#passthroughManager?.resetIncremental();
}
getMetadata() {
return {
// copyCount, copySize
...(this.#passthroughManager?.getMetadata() || {}),
skipCount: this.skippedCount,
writeCount: this.writeCount,
renderCount: this.renderCount,
};
}
get caches() {
return ["_templatePathCache"];
}
}
export default TemplateWriter;