summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Util/ImportJsonSync.js
blob: fa59365921668061578fdcb9e86e57a173da4420 (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
import fs from "node:fs";
import { createRequire } from "node:module";
import debugUtil from "debug";

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

import { normalizeFilePathInEleventyPackage } from "./Require.js";

const debug = debugUtil("Eleventy:ImportJsonSync");
const require = createRequire(import.meta.url);

function findFilePathInParentDirs(dir, filename) {
	// `package.json` searches look in parent dirs:
	// https://docs.npmjs.com/cli/v7/configuring-npm/folders#more-information
	// Fixes issue #3178, limited to working dir paths only
	let workingDir = TemplatePath.getWorkingDir();
	// TODO use DirContains
	let allDirs = TemplatePath.getAllDirs(dir).filter((entry) => entry.startsWith(workingDir));

	for (let dir of allDirs) {
		let newPath = TemplatePath.join(dir, filename);
		if (fs.existsSync(newPath)) {
			debug("Found %o searching parent directories at: %o", filename, dir);
			return newPath;
		}
	}
}

function importJsonSync(filePath) {
	if (!filePath || !filePath.endsWith(".json")) {
		throw new Error(`importJsonSync expects a .json file extension (received: ${filePath})`);
	}

	return require(filePath);
}

function getEleventyPackageJson() {
	let filePath = normalizeFilePathInEleventyPackage("package.json");
	return importJsonSync(filePath);
}

function getModulePackageJson(dir) {
	let filePath = findFilePathInParentDirs(TemplatePath.absolutePath(dir), "package.json");

	// optional!
	if (!filePath) {
		return {};
	}

	return importJsonSync(filePath);
}

// This will *not* find a package.json in a parent directory above root
function getWorkingProjectPackageJsonPath() {
	let dir = TemplatePath.absolutePath(TemplatePath.getWorkingDir());
	return findFilePathInParentDirs(dir, "package.json");
}

function getWorkingProjectPackageJson() {
	let filePath = getWorkingProjectPackageJsonPath();

	// optional!
	if (!filePath) {
		return {};
	}

	return importJsonSync(filePath);
}

export {
	importJsonSync,
	findFilePathInParentDirs,
	getEleventyPackageJson,
	getModulePackageJson,
	getWorkingProjectPackageJson,
	getWorkingProjectPackageJsonPath,
};