blob: fa7fd5cd1ef33314287df6c432e5747f8d360c15 (
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
|
'use strict';
const path = require('path');
const {promisify} = require('util');
const readFile = promisify(require('fs').readFile);
const isNodeModules = require('./is-node-modules.cjs');
const resultsCache = require('./cache.cjs');
const promiseCache = new Map();
async function getDirectoryTypeActual(directory) {
if (isNodeModules(directory)) {
return 'commonjs';
}
try {
return JSON.parse(await readFile(path.resolve(directory, 'package.json'))).type || 'commonjs';
} catch (_) {
}
const parent = path.dirname(directory);
if (parent === directory) {
return 'commonjs';
}
return getDirectoryType(parent);
}
async function getDirectoryType(directory) {
if (resultsCache.has(directory)) {
return resultsCache.get(directory);
}
if (promiseCache.has(directory)) {
return promiseCache.get(directory);
}
const promise = getDirectoryTypeActual(directory);
promiseCache.set(directory, promise);
const result = await promise;
resultsCache.set(directory, result);
promiseCache.delete(directory);
return result;
}
function getPackageType(filename) {
return getDirectoryType(path.resolve(path.dirname(filename)));
}
module.exports = getPackageType;
|