-
Notifications
You must be signed in to change notification settings - Fork 34
/
resolve.ts
50 lines (41 loc) · 1.5 KB
/
resolve.ts
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
import path from 'path';
import fs from 'fs';
import {fileURLToPath} from 'url';
import {bundleRequire} from 'bundle-require';
import resolveCore from 'resolve';
// @ts-expect-error
import caller from 'caller';
export const resolveFrom = (base: string) => (id: string) => {
const execute = (resolve: (resolved: string) => void, reject: (error: Error) => void) => resolveCore(
id,
{basedir: base},
(err, resolved) => {
if (err) {
return reject(err);
}
if (!resolved) {
return reject(new Error(`ENOENT, unable to resolve ${id}`));
}
resolve(resolved);
}
);
return new Promise(execute);
};
export const resolveSync = (id: string) => {
const callerUrl = caller();
const callerPath = callerUrl.startsWith('file://') ? fileURLToPath(callerUrl) : callerUrl;
return resolveCore.sync(id, {basedir: callerPath});
};
const USER_MODULES_EXTENSIONS = ['.ts', '.mjs'];
export const importUserModule = async <T>(moduleName: string, defaultValue?: T): Promise<T> => {
const target = USER_MODULES_EXTENSIONS.map(v => moduleName + v).find(fs.existsSync);
if (target) {
const {mod} = await bundleRequire({filepath: target});
return mod;
}
if (defaultValue) {
return defaultValue;
}
throw new Error(`Unable to find module ${moduleName}`);
};
export const dirFromImportMeta = (importMetaUrl: string) => path.dirname(fileURLToPath(importMetaUrl));