-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathloadModule.ts
More file actions
290 lines (261 loc) · 7.7 KB
/
Copy pathloadModule.ts
File metadata and controls
290 lines (261 loc) · 7.7 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import { createRequire as createNativeRequire } from 'node:module';
import { isAbsolute } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import vm from 'node:vm';
import path from 'pathe';
import { logger } from '../../utils/logger';
import {
asModule,
clearSyntheticModuleCache,
createInteropProxy,
interopModule,
shouldInterop,
} from './interop';
const importMetaResolve = import.meta.resolve;
const isRelativePath = (p: string) => /^\.\.?\//.test(p);
const resolveModule = (specifier: string, resolveBase: string): string | URL =>
importMetaResolve(
specifier,
resolveBase.startsWith('file:')
? resolveBase
: pathToFileURL(resolveBase).href,
);
const createRequire = (
filename: string,
distPath: string,
rstestContext: Record<string, any>,
assetFiles: Record<string, string>,
interopDefault: boolean,
): NodeJS.Require => {
const _require = (() => {
try {
// compat with some testPath may not be an available path but the third-party package name
return createNativeRequire(filename);
} catch {
return createNativeRequire(distPath);
}
})();
const require = ((id: string) => {
const currentDirectory = path.dirname(distPath);
const joinedPath = isRelativePath(id)
? path.join(currentDirectory, id)
: id;
const content = assetFiles[joinedPath];
if (content) {
try {
return cacheableLoadModule({
codeContent: content,
testPath: joinedPath,
distPath: joinedPath,
rstestContext,
assetFiles,
interopDefault,
});
} catch (err) {
logger.error(
`load file ${joinedPath} failed:\n`,
err instanceof Error ? err.message : err,
);
}
}
const resolved = _require.resolve(id);
return _require(resolved);
}) as NodeJS.Require;
require.resolve = _require.resolve;
require.main = _require.main;
return require;
};
const defineRstestDynamicImport =
({
testPath,
interopDefault,
returnModule = false,
assetFiles,
}: {
returnModule?: boolean;
testPath: string;
interopDefault: boolean;
assetFiles: Record<string, string>;
}) =>
async (
specifier: string,
importAttributes: ImportCallOptions,
origin?: string,
) => {
// `origin` is the absolute path of the source module that produced the
// `import()` call, injected by rspack's `RstestPlugin` when
// `injectDynamicImportOrigin` is enabled. Falling back to `testPath`
// keeps the vm `importModuleDynamically` callback (which has no origin
// to pass) working as before.
const resolveBase = origin ?? testPath;
const resolvedPath = isAbsolute(specifier)
? pathToFileURL(specifier).href
: resolveModule(specifier, resolveBase);
// Use `.href` rather than `.pathname` so Windows absolute specifiers
// round-trip through Node's ESM loader as valid `file:///D:/...` URLs
// instead of `/D:/...`, which Node re-resolves as `D:\D:\...`.
const modulePath =
typeof resolvedPath === 'string' ? resolvedPath : resolvedPath.href;
if (modulePath.endsWith('.wasm')) {
const normalizedPath = path.normalize(
modulePath.startsWith('file://')
? fileURLToPath(modulePath)
: modulePath,
);
const content = assetFiles[normalizedPath];
if (content) {
const wasmBuffer = Buffer.from(content, 'base64');
const wasmModule = await WebAssembly.compile(wasmBuffer);
const wasmInstance = await WebAssembly.instantiate(wasmModule);
const exports = wasmInstance.exports as Record<string, any>;
return returnModule ? asModule(exports, modulePath, exports) : exports;
}
}
// Rstest importAttributes is used internally to distinguish `importActual` and normal imports,
// and should not be passed to Node.js side, otherwise it will cause ERR_IMPORT_ATTRIBUTE_UNSUPPORTED error.
if (importAttributes?.with?.rstest) {
delete importAttributes.with.rstest;
}
if (modulePath.endsWith('.json')) {
// const json = await import(jsonPath);
// should return { default: jsonExports, ...jsonExports }
const importedModule = await import(modulePath, {
with: { type: 'json' },
});
return returnModule
? asModule(importedModule.default, modulePath, importedModule.default)
: {
...importedModule.default,
default: importedModule.default,
};
}
const importedModule = await import(modulePath, importAttributes);
if (
shouldInterop({
interopDefault,
modulePath,
mod: importedModule,
})
) {
const { mod, defaultExport } = interopModule(importedModule);
if (returnModule) {
return asModule(mod, modulePath, defaultExport);
}
return createInteropProxy(mod, defaultExport);
}
return importedModule;
};
// setup and rstest module should not be cached
export const loadModule = ({
codeContent,
distPath,
testPath,
rstestContext,
assetFiles,
interopDefault,
}: {
interopDefault: boolean;
codeContent: string;
distPath: string;
testPath: string;
rstestContext: Record<string, any>;
assetFiles: Record<string, string>;
}): any => {
const fileDir = path.dirname(testPath);
const localModule = {
children: [],
exports: {},
filename: testPath,
id: testPath,
isPreloading: false,
loaded: false,
path: fileDir,
};
const context = {
module: localModule,
exports: localModule.exports,
require: createRequire(
testPath,
distPath,
rstestContext,
assetFiles,
interopDefault,
),
readWasmFile: (
wasmPath: string,
callback: (err: Error | null, data?: Buffer) => void,
) => {
const joinedPath = isRelativePath(wasmPath)
? path.join(path.dirname(distPath), wasmPath)
: wasmPath;
const content = assetFiles[path.normalize(joinedPath)];
if (content) {
callback(null, Buffer.from(content, 'base64'));
} else {
callback(
new Error(`WASM file ${joinedPath} not found in asset files.`),
);
}
},
__rstest_dynamic_import__: defineRstestDynamicImport({
testPath,
interopDefault,
assetFiles,
}),
__dirname: fileDir,
__filename: testPath,
...rstestContext,
};
const codeDefinition = `'use strict';(${Object.keys(context).join(',')})=>{`;
const code = `${codeDefinition}${codeContent}\n}`;
const fn = vm.runInThisContext(code, {
// Used in stack traces produced by this script.
filename: distPath,
lineOffset: 0,
columnOffset: -codeDefinition.length,
importModuleDynamically: (specifier, _referencer, importAttributes) => {
return defineRstestDynamicImport({
testPath,
interopDefault,
returnModule: true,
assetFiles,
})(specifier, importAttributes as ImportCallOptions);
},
});
fn(...Object.values(context));
return localModule.exports;
};
const moduleCache = new Map<string, any>();
export const cacheableLoadModule = ({
codeContent,
distPath,
testPath,
rstestContext,
assetFiles,
interopDefault,
}: {
interopDefault: boolean;
codeContent: string;
distPath: string;
testPath: string;
rstestContext: Record<string, any>;
assetFiles: Record<string, string>;
}): any => {
if (moduleCache.has(testPath)) {
return moduleCache.get(testPath);
}
const mod = loadModule({
codeContent,
distPath,
testPath,
rstestContext,
assetFiles,
interopDefault,
});
moduleCache.set(testPath, mod);
return mod;
};
export const clearModuleCache = (): void => {
moduleCache.clear();
clearSyntheticModuleCache();
};