summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy-plugin-bundle/src/bundlePlucker.js
blob: 5dcad467a8eaba0b2df5a6c8de273e0dcd0096f8 (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
import debugUtil from "debug";
import matchHelper from "posthtml-match-helper";

const debug = debugUtil("Eleventy:Bundle");

const ATTRS = {
	ignore: "eleventy:ignore",
	bucket: "eleventy:bucket",
};

const POSTHTML_PLUGIN_NAME = "11ty/eleventy/html-bundle-plucker";

function hasAttribute(node, name) {
	return node?.attrs?.[name] !== undefined;
}

function addHtmlPlucker(eleventyConfig, bundleManager) {
	let matchSelector = bundleManager.getPluckedSelector();

	if(!matchSelector) {
		throw new Error("Internal error: missing plucked selector on bundle manager.");
	}

	eleventyConfig.htmlTransformer.addPosthtmlPlugin(
		"html",
		function (context = {}) {
			let pageUrl = context?.url;
			if(!pageUrl) {
				throw new Error("Internal error: missing `url` property from context.");
			}

			return function (tree, ...args) {
				tree.match(matchHelper(matchSelector), function (node) {
					try {
						// ignore
						if(hasAttribute(node, ATTRS.ignore)) {
							delete node.attrs[ATTRS.ignore];
							return node;
						}

						if(Array.isArray(node?.content) && node.content.length > 0) {
							// TODO make this better decoupled
							if(node?.content.find(entry => entry.includes(`/*__EleventyBundle:`))) {
								// preserve {% getBundle %} calls as-is
								return node;
							}

							let bucketName = node?.attrs?.[ATTRS.bucket];
							bundleManager.addToPage(pageUrl, [ ...node.content ], bucketName);

							return { attrs: [], content: [], tag: false };
						}
					} catch(e) {
						debug(`Bundle plucker: error adding content to bundle in HTML Assets: %o`, e);
						return node;
					}

					return node;
				});
			};
		},
		{
			// pluginOptions
			name: POSTHTML_PLUGIN_NAME,
		},
	);
}

export { addHtmlPlucker };