-
Notifications
You must be signed in to change notification settings - Fork 0
/
use.mjs
214 lines (203 loc) · 7.53 KB
/
use.mjs
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
export const parseModuleSpecifier = (moduleSpecifier) => {
if (!moduleSpecifier || typeof moduleSpecifier !== 'string' || moduleSpecifier.length <= 0) {
throw new Error(
`Name for a package to be imported is not provided.
Please specify package name and an optional version (e.g., 'lodash', '[email protected]' or '@chakra-ui/[email protected]').`
);
}
const regex = /^(?<packageName>@?([^@/]+\/)?[^@/]+)?(?:@(?<version>[^/]*))?(?<modulePath>(?:\/[^@]+)*)?$/;
const match = moduleSpecifier.match(regex);
if (!match || typeof match.groups.packageName !== 'string' || match.groups.packageName.trim() === '') {
throw new Error(
`Failed to parse package identifier '${moduleSpecifier}'.
Please specify a package name, and an optional version (e.g.: 'lodash', '[email protected]' or '@chakra-ui/[email protected]').`
);
}
let { packageName, version, modulePath } = match.groups;
if (typeof version !== 'string' || version.trim() === '') {
version = 'latest';
}
if (typeof modulePath !== 'string' || modulePath.trim() === '') {
modulePath = '';
}
return { packageName, version, modulePath };
}
export const resolvers = {
npm: async (moduleSpecifier, pathResolver) => {
const path = await import('path');
const { exec } = await import('child_process');
const { promisify } = await import('util');
const { stat, readFile } = await import('fs/promises');
const execAsync = promisify(exec);
if (!pathResolver) {
throw new Error('Failed to get the current resolver.');
}
const directoryExists = async (directoryPath) => {
try {
const stats = await stat(directoryPath);
return stats.isDirectory();
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
return false;
}
};
const tryResolveModule = async (packagePath) => {
try {
return await pathResolver(packagePath);
} catch (error) {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
return null;
}
};
const getLatestVersion = async (packageName) => {
const { stdout: version } = await execAsync(`npm show ${packageName} version`);
return version.trim();
};
const getInstalledPackageVersion = async (packagePath) => {
try {
const packageJsonPath = path.join(packagePath, 'package.json');
const data = await readFile(packageJsonPath, 'utf8');
const { version } = JSON.parse(data);
return version;
} catch {
return null;
}
};
const ensurePackageInstalled = async ({ packageName, version }) => {
const alias = `${packageName.replace('@', '').replace('/', '-')}-v-${version}`;
const { stdout: globalModulesPath } = await execAsync('npm root -g');
const packagePath = path.join(globalModulesPath.trim(), alias);
if (version !== 'latest' && await directoryExists(packagePath)) {
return packagePath;
}
if (version === 'latest') {
const latestVersion = await getLatestVersion(packageName);
const installedVersion = await getInstalledPackageVersion(packagePath);
if (installedVersion === latestVersion) {
return packagePath;
}
}
try {
await execAsync(`npm install -g ${alias}@npm:${packageName}@${version}`, { stdio: 'ignore' });
} catch (error) {
throw new Error(`Failed to install ${packageName}@${version} globally.`, { cause: error });
}
return packagePath;
};
const { packageName, version, modulePath } = parseModuleSpecifier(moduleSpecifier);
const packagePath = await ensurePackageInstalled({ packageName, version });
const packageModulePath = modulePath ? path.join(packagePath, modulePath) : packagePath;
const resolvedPath = await tryResolveModule(packageModulePath);
if (!resolvedPath) {
throw new Error(`Failed to resolve the path to '${moduleSpecifier}' from '${packageModulePath}'.`);
}
return resolvedPath;
},
skypack: async (moduleSpecifier, pathResolver) => {
const resolvedPath = `https://cdn.skypack.dev/${moduleSpecifier}`;
return resolvedPath;
},
jsdelivr: async (moduleSpecifier, pathResolver) => {
const { packageName, version, modulePath } = parseModuleSpecifier(moduleSpecifier);
// If no modulePath is provided, append /{packageName}.js
let path = modulePath ? modulePath : `/${packageName}`;
if (/\.(mc)?js$/.test(path) === false) {
path += '.js';
}
const resolvedPath = `https://cdn.jsdelivr.net/npm/${packageName}-es@${version}${path}`;
return resolvedPath;
},
unpkg: async (moduleSpecifier, pathResolver) => {
const { packageName, version, modulePath } = parseModuleSpecifier(moduleSpecifier);
// If no modulePath is provided, append /{packageName}.js
let path = modulePath ? modulePath : `/${packageName}`;
if (/\.(mc)?js$/.test(path) === false) {
path += '.js';
}
const resolvedPath = `https://unpkg.com/${packageName}-es@${version}${path}`;
return resolvedPath;
},
esm: async (moduleSpecifier, pathResolver) => {
const resolvedPath = `https://esm.sh/${moduleSpecifier}`;
return resolvedPath;
},
jspm: async (moduleSpecifier, pathResolver) => {
let { packageName, version, modulePath } = parseModuleSpecifier(moduleSpecifier);
if (version === 'latest') {
version = '';
}
const resolvedPath = `https://jspm.dev/${packageName}${version ? `@${version}` : ''}${modulePath}`;
return resolvedPath;
},
}
export const baseUse = async (modulePath) => {
// Dynamically import the module
try {
const module = await import(modulePath);
// Check if the only key in the module is 'default'
const keys = Object.keys(module);
if (keys.length === 1 && keys[0] === 'default') {
return module.default || module;
}
return module;
} catch (error) {
throw new Error(`Failed to import module from '${modulePath}'.`, { cause: error });
}
}
export const makeUse = async (options) => {
let scriptPath = options?.scriptPath;
if (!scriptPath && typeof __filename !== 'undefined') {
scriptPath = __filename;
}
const metaUrl = options?.meta?.url;
if (!scriptPath && metaUrl) {
scriptPath = metaUrl;
}
let protocol;
if (!scriptPath) {
scriptPath = import.meta.url;
protocol = new URL(scriptPath).protocol;
}
let specifierResolver = options?.specifierResolver;
if (typeof specifierResolver !== 'function') {
if (typeof window !== 'undefined' || (protocol && (protocol === 'http:' || protocol === 'https:'))) {
specifierResolver = resolvers[specifierResolver || 'esm'];
} else {
specifierResolver = resolvers[specifierResolver || 'npm'];
}
}
let pathResolver = options?.pathResolver;
if (!pathResolver) {
if (typeof require !== 'undefined') {
pathResolver = require.resolve;
} else if (scriptPath && (!protocol || protocol === 'file:')) {
pathResolver = await import('module')
.then(module => module.createRequire(scriptPath))
.then(require => require.resolve);
} else {
pathResolver = (path) => path;
}
}
return async (moduleSpecifier) => {
const modulePath = await specifierResolver(moduleSpecifier, pathResolver);
return baseUse(modulePath);
};
}
let __use = null;
const _use = async (moduleSpecifier) => {
if (!__use) {
__use = await makeUse();
}
return __use(moduleSpecifier);
}
_use.all = async (...moduleSpecifiers) => {
if (!__use) {
__use = await makeUse();
}
return Promise.all(moduleSpecifiers.map(__use));
}
export const use = _use;