-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmodule-loader.ts
80 lines (70 loc) · 2.13 KB
/
module-loader.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
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
import path from 'path';
import fs from 'fs-extra';
import { fileURLToPath } from 'url';
import { installPackage } from '@antfu/install-pkg';
import { ModuleLoader } from '@hypermod/fetcher';
const filename = fileURLToPath(import.meta.url);
const dirname = path.dirname(filename);
/**
* Register the TSX plugin to allow require TS(X) files.
*/
import { register } from 'tsx/esm/api';
register();
const ModuleLoader = (config: {
npmRegistryUrl?: string;
authToken?: string;
}): ModuleLoader => {
const getInfo = async (packageName: string) => {
// @ts-expect-error - TS doesn't know about import.meta
const entryPath = await import.meta.resolve(packageName);
const location = (entryPath.split(packageName)[0] + packageName).replace(
'file://',
'',
);
const pkgJsonRaw = fs.readFileSync(
path.join(location, 'package.json'),
'utf8',
);
const pkgJson = JSON.parse(pkgJsonRaw);
return {
location,
entryPath,
pkgJson,
};
};
const install = async (packageName: string) => {
await installPackage(packageName, {
cwd: dirname,
packageManager: 'npm',
additionalArgs: [
'--force',
// --registry=https://your-custom-registry-url/ --//your-custom-registry-url/:_authToken=YOUR_AUTH_TOKEN
config.npmRegistryUrl ? `--registry=${config.npmRegistryUrl}` : '',
config.authToken
? `--${config.npmRegistryUrl}/:_authToken=${config.authToken}`
: '',
],
});
const { pkgJson } = await getInfo(packageName);
// Install whitelisted devDependencies
if (pkgJson?.hypermod?.dependencies) {
await Promise.all(
pkgJson.hypermod.dependencies.map((dep: string) => {
const version = pkgJson.devDependencies[dep];
if (!version) return;
return installPackage(`${dep}@${version}`, {
cwd: dirname,
packageManager: 'npm',
additionalArgs: ['--force'],
});
}),
);
}
};
return {
install,
getInfo,
require: async (packageName: string) => await import(packageName),
};
};
export default ModuleLoader;