Repository navigation
Expand file tree
/
Copy pathimport.node.ts
More file actions
61 lines (57 loc) · 2.26 KB
/
Copy pathimport.node.ts
File metadata and controls
61 lines (57 loc) · 2.26 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
import { Script, constants } from "node:vm"
import { registerHooks } from "node:module"
import { statSync } from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
export async function importModule(specifier: string) {
const imported = (await new Script(`import(${JSON.stringify(specifier)})`, {
importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
}).runInThisContext()) as unknown
if (typeof imported !== "object" || imported === null) return imported
const module = imported as Record<string, unknown>
const exports = module["module.exports"]
if (exports !== module.default || (typeof exports !== "object" && typeof exports !== "function") || exports === null)
return imported
return Object.assign({}, module, exports)
}
export function resolveModule(specifier: string, directory: string) {
// Node only accepts import.meta.resolve's parent URL behind an experimental
// flag. Scope this synchronous resolution to the caller's package directory
// through the supported resolver hook instead.
const hook = registerHooks({
resolve(specifier, context, nextResolve) {
return nextResolve(specifier, { ...context, parentURL: pathToFileURL(path.join(directory, "package.json")).href })
},
})
try {
const resolve = (target: string) => {
const resolved = import.meta.resolve(path.isAbsolute(target) ? pathToFileURL(target).href : target)
if (resolved.startsWith("file:")) statSync(new URL(resolved))
return resolved
}
try {
return resolve(specifier)
} catch (error) {
if (path.extname(specifier) || !missing(error)) throw error
// Node does not infer extensions for local files or legacy package
// subpaths. Resolve each candidate natively so package exports still apply.
for (const extension of [".ts", ".tsx", ".js", ".jsx", ".mts", ".mjs", ".cts", ".cjs"]) {
try {
return resolve(specifier + extension)
} catch (cause) {
if (!missing(cause)) throw cause
}
}
throw error
}
} finally {
hook.deregister()
}
}
function missing(error: unknown) {
return (
error instanceof Error &&
"code" in error &&
["ENOENT", "ENOTDIR", "ERR_MODULE_NOT_FOUND"].includes(String(error.code))
)
}