summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Plugins/InputPathToUrl.js
blob: aca148bf4523f3cf100b7c761f739a2bf0097c4a (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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import path from "node:path";
import { TemplatePath } from "@11ty/eleventy-utils";
import isValidUrl from "../Util/ValidUrl.js";

function getValidPath(contentMap, testPath) {
	// if the path is coming from Markdown, it may be encoded
	let normalized = TemplatePath.addLeadingDotSlash(decodeURIComponent(testPath));

	// it must exist in the content map to be valid
	if (contentMap[normalized]) {
		return normalized;
	}
}

function normalizeInputPath(targetInputPath, inputDir, sourceInputPath, contentMap) {
	// inputDir is optional at the beginning of the developer supplied-path

	// Input directory already on the input path
	if (TemplatePath.join(targetInputPath).startsWith(TemplatePath.join(inputDir))) {
		let absolutePath = getValidPath(contentMap, targetInputPath);
		if (absolutePath) {
			return absolutePath;
		}
	}

	// Relative to project input directory
	let relativeToInputDir = getValidPath(contentMap, TemplatePath.join(inputDir, targetInputPath));
	if (relativeToInputDir) {
		return relativeToInputDir;
	}

	if (targetInputPath && !path.isAbsolute(targetInputPath)) {
		// Relative to source file’s input path
		let sourceInputDir = TemplatePath.getDirFromFilePath(sourceInputPath);
		let relativeToSourceFile = getValidPath(
			contentMap,
			TemplatePath.join(sourceInputDir, targetInputPath),
		);
		if (relativeToSourceFile) {
			return relativeToSourceFile;
		}
	}

	// the transform may have sent in a URL so we just return it as-is
	return targetInputPath;
}

function parseFilePath(filepath) {
	if (filepath.startsWith("#") || filepath.startsWith("?")) {
		return [filepath, ""];
	}

	try {
		/* u: URL {
			href: 'file:///tmpl.njk#anchor',
			origin: 'null',
			protocol: 'file:',
			username: '',
			password: '',
			host: '',
			hostname: '',
			port: '',
			pathname: '/tmpl.njk',
			search: '',
			searchParams: URLSearchParams {},
			hash: '#anchor'
		} */

		// Note that `node:url` -> pathToFileURL creates an absolute path, which we don’t want
		// URL(`file:#anchor`) gives back a pathname of `/`
		let u = new URL(`file:${filepath}`);
		filepath = filepath.replace(u.search, ""); // includes ?
		filepath = filepath.replace(u.hash, ""); // includes #

		return [
			// search includes ?, hash includes #
			u.search + u.hash,
			filepath,
		];
	} catch (e) {
		return ["", filepath];
	}
}

function FilterPlugin(eleventyConfig) {
	let contentMap;
	eleventyConfig.on("eleventy.contentMap", function ({ inputPathToUrl }) {
		contentMap = inputPathToUrl;
	});

	eleventyConfig.addFilter("inputPathToUrl", function (targetFilePath) {
		if (!contentMap) {
			throw new Error("Internal error: contentMap not available for `inputPathToUrl` filter.");
		}

		if (isValidUrl(targetFilePath)) {
			return targetFilePath;
		}

		let inputDir = eleventyConfig.directories.input;
		let suffix = "";
		[suffix, targetFilePath] = parseFilePath(targetFilePath);
		if (targetFilePath) {
			targetFilePath = normalizeInputPath(
				targetFilePath,
				inputDir,
				// @ts-ignore
				this.page.inputPath,
				contentMap,
			);
		}

		let urls = contentMap[targetFilePath];
		if (!urls || urls.length === 0) {
			throw new Error(
				"`inputPathToUrl` filter could not find a matching target for " + targetFilePath,
			);
		}

		return `${urls[0]}${suffix}`;
	});
}

function TransformPlugin(eleventyConfig, defaultOptions = {}) {
	let opts = Object.assign(
		{
			extensions: "html",
		},
		defaultOptions,
	);

	let contentMap = null;
	eleventyConfig.on("eleventy.contentMap", function ({ inputPathToUrl }) {
		contentMap = inputPathToUrl;
	});

	eleventyConfig.htmlTransformer.addUrlTransform(opts.extensions, function (targetFilepathOrUrl) {
		if (!contentMap) {
			throw new Error("Internal error: contentMap not available for the `pathToUrl` Transform.");
		}
		if (isValidUrl(targetFilepathOrUrl)) {
			return targetFilepathOrUrl;
		}

		let inputDir = eleventyConfig.directories.input;

		let suffix = "";
		[suffix, targetFilepathOrUrl] = parseFilePath(targetFilepathOrUrl);
		if (targetFilepathOrUrl) {
			targetFilepathOrUrl = normalizeInputPath(
				targetFilepathOrUrl,
				inputDir,
				// @ts-ignore
				this.page.inputPath,
				contentMap,
			);
		}

		let urls = contentMap[targetFilepathOrUrl];
		if (!targetFilepathOrUrl || !urls || urls.length === 0) {
			// fallback, transforms don’t error on missing paths (though the pathToUrl filter does)
			return `${targetFilepathOrUrl}${suffix}`;
		}

		return `${urls[0]}${suffix}`;
	});
}

Object.defineProperty(FilterPlugin, "eleventyPackage", {
	value: "@11ty/eleventy/inputpath-to-url-filter-plugin",
});

Object.defineProperty(FilterPlugin, "eleventyPluginOptions", {
	value: {
		unique: true,
	},
});

Object.defineProperty(TransformPlugin, "eleventyPackage", {
	value: "@11ty/eleventy/inputpath-to-url-transform-plugin",
});

Object.defineProperty(TransformPlugin, "eleventyPluginOptions", {
	value: {
		unique: true,
	},
});

export default TransformPlugin;

export { FilterPlugin, TransformPlugin };