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
|
import fs from 'node:fs';
import { j as join, d as dirname } from './chunk-pathe.M-eThtNZ.js';
const packageCache = new Map();
function findNearestPackageData(basedir) {
const originalBasedir = basedir;
while (basedir) {
var _tryStatSync;
const cached = getCachedData(packageCache, basedir, originalBasedir);
if (cached) {
return cached;
}
const pkgPath = join(basedir, "package.json");
if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) {
const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
if (packageCache) {
setCacheData(packageCache, pkgData, basedir, originalBasedir);
}
return pkgData;
}
const nextBasedir = dirname(basedir);
if (nextBasedir === basedir) {
break;
}
basedir = nextBasedir;
}
return {};
}
function stripBomTag(content) {
if (content.charCodeAt(0) === 65279) {
return content.slice(1);
}
return content;
}
function tryStatSync(file) {
try {
// The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
return fs.statSync(file, { throwIfNoEntry: false });
} catch {}
}
function getCachedData(cache, basedir, originalBasedir) {
const pkgData = cache.get(getFnpdCacheKey(basedir));
if (pkgData) {
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), pkgData);
});
return pkgData;
}
}
function setCacheData(cache, data, basedir, originalBasedir) {
cache.set(getFnpdCacheKey(basedir), data);
traverseBetweenDirs(originalBasedir, basedir, (dir) => {
cache.set(getFnpdCacheKey(dir), data);
});
}
function getFnpdCacheKey(basedir) {
return `fnpd_${basedir}`;
}
/**
* Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
* @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
* @param shorterDir Shorter dir path, e.g. `/User/foo`
*/
function traverseBetweenDirs(longerDir, shorterDir, cb) {
while (longerDir !== shorterDir) {
cb(longerDir);
longerDir = dirname(longerDir);
}
}
export { findNearestPackageData, getCachedData, setCacheData };
|