summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Util/Require.js
blob: 5f6412d287a9d3a7518fe2c84c8591bf6e37097a (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
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
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import module from "node:module";
import { MessageChannel } from "node:worker_threads";

import { TemplatePath } from "@11ty/eleventy-utils";

import EleventyBaseError from "../Errors/EleventyBaseError.js";
import eventBus from "../EventBus.js";

class EleventyImportError extends EleventyBaseError {}

const { port1, port2 } = new MessageChannel();

// ESM Cache Buster is an enhancement that works in Node 18.19+
// https://nodejs.org/docs/latest/api/module.html#moduleregisterspecifier-parenturl-options
// Fixes https://github.com/11ty/eleventy/issues/3270
// ENV variable for https://github.com/11ty/eleventy/issues/3371
if ("register" in module && !process?.env?.ELEVENTY_SKIP_ESM_RESOLVER) {
	module.register("./EsmResolver.js", import.meta.url, {
		parentURL: import.meta.url,
		data: {
			port: port2,
		},
		transferList: [port2],
	});
}

// important to clear the require.cache in CJS projects
const require = module.createRequire(import.meta.url);

const requestPromiseCache = new Map();

function getImportErrorMessage(filePath, type) {
	return `There was a problem importing '${path.relative(".", filePath)}' via ${type}`;
}

// Used for JSON imports, suffering from Node warning that import assertions experimental but also
// throwing an error if you try to import() a JSON file without an import assertion.
/**
 *
 * @returns {string|undefined}
 */
function loadContents(path, options = {}) {
	let rawInput;
	/** @type {string} */
	let encoding = "utf8"; // JSON is utf8
	if (options?.encoding || options?.encoding === null) {
		encoding = options.encoding;
	}

	try {
		// @ts-expect-error This is an error in the upstream types
		rawInput = fs.readFileSync(path, encoding);
	} catch (error) {
		// @ts-expect-error Temporary
		if (error?.code === "ENOENT") {
			// if file does not exist, return nothing
			return;
		}

		throw error;
	}

	// Can return a buffer, string, etc
	if (typeof rawInput === "string") {
		rawInput = rawInput.trim();
	}

	return rawInput;
}

let lastModifiedPaths = new Map();
eventBus.on("eleventy.importCacheReset", (fileQueue) => {
	for (let filePath of fileQueue) {
		let absolutePath = TemplatePath.absolutePath(filePath);
		let newDate = Date.now();
		lastModifiedPaths.set(absolutePath, newDate);

		// post to EsmResolver worker thread
		if (port1) {
			port1.postMessage({ path: absolutePath, newDate });
		}

		// ESM Eleventy when using `import()` on a CJS project file still adds to require.cache
		if (absolutePath in (require?.cache || {})) {
			delete require.cache[absolutePath];
		}
	}
});

// raw means we don’t normalize away the `default` export
async function dynamicImportAbsolutePath(absolutePath, options = {}) {
	let { type, returnRaw, cacheBust } = Object.assign(
		{
			type: undefined,
			returnRaw: false,
			cacheBust: false, // force cache bust
		},
		options,
	);

	// Short circuit for JSON files (that are optional and can be empty)
	if (absolutePath.endsWith(".json") || type === "json") {
		try {
			// https://v8.dev/features/import-assertions#dynamic-import() is still experimental in Node 20
			let rawInput = loadContents(absolutePath);
			if (!rawInput) {
				// should not error when file exists but is _empty_
				return;
			}
			return JSON.parse(rawInput);
		} catch (e) {
			return Promise.reject(
				new EleventyImportError(getImportErrorMessage(absolutePath, "fs.readFile(json)"), e),
			);
		}
	}

	// Removed a `require` short circuit from this piece originally added
	// in https://github.com/11ty/eleventy/pull/3493 Was a bit faster but
	// error messaging was worse for require(esm)

	let urlPath;
	try {
		let u = new URL(`file:${absolutePath}`);

		// Bust the import cache if this is the last modified file (or cache busting is forced)
		if (cacheBust) {
			lastModifiedPaths.set(absolutePath, Date.now());
		}

		if (cacheBust || lastModifiedPaths.has(absolutePath)) {
			u.searchParams.set("_cache_bust", lastModifiedPaths.get(absolutePath));
		}

		urlPath = u.toString();
	} catch (e) {
		urlPath = absolutePath;
	}

	let promise;
	if (requestPromiseCache.has(urlPath)) {
		promise = requestPromiseCache.get(urlPath);
	} else {
		promise = import(urlPath);
		requestPromiseCache.set(urlPath, promise);
	}

	return promise.then(
		(target) => {
			if (returnRaw) {
				return target;
			}

			// If the only export is `default`, elevate to top (for ESM and CJS)
			if (Object.keys(target).length === 1 && "default" in target) {
				return target.default;
			}

			// When using import() on a CommonJS file that exports an object sometimes it
			// returns duplicated values in `default` key, e.g. `{ default: {key: value}, key: value }`

			// A few examples:
			// module.exports = { key: false };
			//    returns `{ default: {key: false}, key: false }` as not expected.
			// module.exports = { key: true };
			// module.exports = { key: null };
			// module.exports = { key: undefined };
			// module.exports = { key: class {} };

			// A few examples where it does not duplicate:
			// module.exports = { key: 1 };
			//    returns `{ default: {key: 1} }` as expected.
			// module.exports = { key: "value" };
			// module.exports = { key: {} };
			// module.exports = { key: [] };

			if (type === "cjs" && "default" in target) {
				let match = true;
				for (let key in target) {
					if (key === "default") {
						continue;
					}
					if (key === "module.exports") {
						continue;
					}
					if (target[key] !== target.default[key]) {
						match = false;
					}
				}

				if (match) {
					return target.default;
				}
			}

			// Otherwise return { default: value, named: value }
			// Object.assign here so we can add things to it in JavaScript.js
			return Object.assign({}, target);
		},
		(error) => {
			return Promise.reject(
				new EleventyImportError(getImportErrorMessage(absolutePath, `import(${type})`), error),
			);
		},
	);
}

function normalizeFilePathInEleventyPackage(file) {
	// Back up relative paths from ./src/Util/Require.js
	return path.resolve(fileURLToPath(import.meta.url), "../../../", file);
}

async function dynamicImportFromEleventyPackage(file) {
	// points to files relative to the top level Eleventy directory
	let filePath = normalizeFilePathInEleventyPackage(file);

	// Returns promise
	return dynamicImportAbsolutePath(filePath, { type: "esm" });
}

async function dynamicImport(localPath, type, options = {}) {
	let absolutePath = TemplatePath.absolutePath(localPath);
	options.type = type;

	// Returns promise
	return dynamicImportAbsolutePath(absolutePath, options);
}

/* Used to import default Eleventy configuration file, raw means we don’t normalize away the `default` export */
async function dynamicImportRawFromEleventyPackage(file) {
	// points to files relative to the top level Eleventy directory
	let filePath = normalizeFilePathInEleventyPackage(file);

	// Returns promise
	return dynamicImportAbsolutePath(filePath, { type: "esm", returnRaw: true });
}

/* Used to import app configuration files, raw means we don’t normalize away the `default` export */
async function dynamicImportRaw(localPath, type) {
	let absolutePath = TemplatePath.absolutePath(localPath);

	// Returns promise
	return dynamicImportAbsolutePath(absolutePath, { type, returnRaw: true });
}

export {
	loadContents as EleventyLoadContent,
	dynamicImport as EleventyImport,
	dynamicImportRaw as EleventyImportRaw,
	normalizeFilePathInEleventyPackage,

	// no longer used in core
	dynamicImportFromEleventyPackage as EleventyImportFromEleventy,
	dynamicImportRawFromEleventyPackage as EleventyImportRawFromEleventy,
};