summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Util/HtmlTransformer.js
blob: f28910fc67e401b64a8ae722bb54c1b8ed1cdb91 (plain)
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
import posthtml from "posthtml";
import urls from "@11ty/posthtml-urls";
import { FilePathUtil } from "./FilePathUtil.js";

import { arrayDelete } from "./ArrayUtil.js";

class HtmlTransformer {
	// feature test for Eleventy Bundle Plugin
	static SUPPORTS_PLUGINS_ENABLED_CALLBACK = true;

	static TYPES = ["callbacks", "plugins"];

	constructor() {
		// execution order is important (not order of addition/object key order)
		this.callbacks = {};
		this.posthtmlProcessOptions = {};
		this.plugins = {};
	}

	get aggregateBench() {
		if (!this.userConfig) {
			throw new Error("Internal error: Missing `userConfig` in HtmlTransformer.");
		}
		return this.userConfig.benchmarkManager.get("Aggregate");
	}

	setUserConfig(config) {
		this.userConfig = config;
	}

	static prioritySort(a, b) {
		if (b.priority > a.priority) {
			return 1;
		}
		if (a.priority > b.priority) {
			return -1;
		}
		return 0;
	}

	// context is important as it is used in html base plugin for page specific URL
	static _getPosthtmlInstance(callbacks = [], plugins = [], context = {}) {
		let inst = posthtml();

		// already sorted by priority when added
		for (let { fn: plugin, options } of plugins) {
			inst.use(plugin(Object.assign({}, context, options)));
		}

		// Run the built-ins last
		if (callbacks.length > 0) {
			inst.use(
				urls({
					eachURL: (url, attrName, tagName) => {
						for (let { fn: callback } of callbacks) {
							// already sorted by priority when added
							url = callback.call(context, url, { attribute: attrName, tag: tagName });
						}

						return url;
					},
				}),
			);
		}

		return inst;
	}

	_add(extensions, addType, value, options = {}) {
		options = Object.assign(
			{
				priority: 0,
			},
			options,
		);

		let extensionsArray = (extensions || "").split(",");
		for (let ext of extensionsArray) {
			let target = this[addType];
			if (!target[ext]) {
				target[ext] = [];
			}

			target[ext].push({
				// *could* fallback to function name, `value.name`
				name: options.name, // for `remove` and debugging
				fn: value, // callback or plugin
				priority: options.priority, // sorted in descending order
				enabled: options.enabled || (() => true),
				options: options.pluginOptions,
			});

			target[ext].sort(HtmlTransformer.prioritySort);
		}
	}

	addPosthtmlPlugin(extensions, plugin, options = {}) {
		this._add(extensions, "plugins", plugin, options);
	}

	// match can be a plugin function or a filter callback(plugin => true);
	remove(extensions, match) {
		for (let removeType of HtmlTransformer.TYPES) {
			for (let ext of (extensions || "").split(",")) {
				this[removeType][ext] = arrayDelete(this[removeType][ext], match);
			}
		}
	}

	addUrlTransform(extensions, callback, options = {}) {
		this._add(extensions, "callbacks", callback, options);
	}

	setPosthtmlProcessOptions(options) {
		Object.assign(this.posthtmlProcessOptions, options);
	}

	isTransformable(extension, context) {
		return (
			this.getCallbacks(extension, context).length > 0 || this.getPlugins(extension).length > 0
		);
	}

	getCallbacks(extension, context) {
		let callbacks = this.callbacks[extension] || [];
		return callbacks.filter(({ enabled }) => {
			if (!enabled || typeof enabled !== "function") {
				return true;
			}
			return enabled(context);
		});
	}

	getPlugins(extension) {
		let plugins = this.plugins[extension] || [];
		return plugins.filter(({ enabled }) => {
			if (!enabled || typeof enabled !== "function") {
				return true;
			}
			return enabled();
		});
	}

	static async transformStandalone(content, callback, posthtmlProcessOptions = {}) {
		let posthtmlInstance = this._getPosthtmlInstance([
			{
				fn: callback,
				enabled: () => true,
			},
		]);
		let result = await posthtmlInstance.process(content, posthtmlProcessOptions);
		return result.html;
	}

	async transformContent(outputPath, content, context) {
		let extension = FilePathUtil.getFileExtension(outputPath);
		if (!this.isTransformable(extension, context)) {
			return content;
		}

		let bench = this.aggregateBench.get(`Transforming \`${extension}\` with posthtml`);
		bench.before();
		let callbacks = this.getCallbacks(extension, context);
		let plugins = this.getPlugins(extension);
		let posthtmlInstance = HtmlTransformer._getPosthtmlInstance(callbacks, plugins, context);
		let result = await posthtmlInstance.process(content, this.posthtmlProcessOptions);
		bench.after();
		return result.html;
	}
}

export { HtmlTransformer };