-
Notifications
You must be signed in to change notification settings - Fork 31
/
resolve.ts
226 lines (197 loc) · 5.59 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
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
import { existsSync, realpathSync } from "node:fs";
import { pathToFileURL } from "node:url";
import { joinURL } from "ufo";
import { isAbsolute, normalize } from "pathe";
import { moduleResolve } from "import-meta-resolve";
import { PackageJson, readPackageJSON } from "pkg-types";
import { fileURLToPath, normalizeid } from "./utils";
import { pcall, BUILTIN_MODULES } from "./_utils";
const DEFAULT_CONDITIONS_SET = new Set(["node", "import"]);
const DEFAULT_URL = pathToFileURL(process.cwd());
const DEFAULT_EXTENSIONS = [".mjs", ".cjs", ".js", ".json"];
const NOT_FOUND_ERRORS = new Set([
"ERR_MODULE_NOT_FOUND",
"ERR_UNSUPPORTED_DIR_IMPORT",
"MODULE_NOT_FOUND",
"ERR_PACKAGE_PATH_NOT_EXPORTED",
]);
export interface ResolveOptions {
url?: string | URL | (string | URL)[];
extensions?: string[];
conditions?: string[];
}
function _tryModuleResolve(
id: string,
url: URL,
conditions: any
): any | undefined {
try {
return moduleResolve(id, url, conditions);
} catch (error) {
if (!NOT_FOUND_ERRORS.has(error.code)) {
throw error;
}
}
}
function _resolve(id: string, options: ResolveOptions = {}): string {
// Skip if already has a protocol
if (/(node|data|http|https):/.test(id)) {
return id;
}
// Skip builtins
if (BUILTIN_MODULES.has(id)) {
return "node:" + id;
}
// Skip resolve for absolute paths
if (isAbsolute(id) && existsSync(id)) {
// Resolve realPath and normalize slash
const realPath = realpathSync(fileURLToPath(id));
return pathToFileURL(realPath).toString();
}
// Condition set
const conditionsSet = options.conditions
? new Set(options.conditions)
: DEFAULT_CONDITIONS_SET;
// Search paths
const _urls: URL[] = (
Array.isArray(options.url) ? options.url : [options.url]
)
.filter(Boolean)
.map((u) => new URL(normalizeid(u.toString())));
if (_urls.length === 0) {
_urls.push(DEFAULT_URL);
}
const urls = [..._urls];
for (const url of _urls) {
if (url.protocol === "file:") {
urls.push(
new URL("./", url),
// If url is directory
new URL(joinURL(url.pathname, "_index.js"), url),
// TODO: Remove in next major version?
new URL("node_modules", url)
);
}
}
let resolved;
for (const url of urls) {
// Try simple resolve
resolved = _tryModuleResolve(id, url, conditionsSet);
if (resolved) {
break;
}
// Try other extensions if not found
for (const prefix of ["", "/index"]) {
for (const extension of options.extensions || DEFAULT_EXTENSIONS) {
resolved = _tryModuleResolve(
id + prefix + extension,
url,
conditionsSet
);
if (resolved) {
break;
}
}
if (resolved) {
break;
}
}
if (resolved) {
break;
}
}
// Throw error if not found
if (!resolved) {
const error = new Error(
`Cannot find module ${id} imported from ${urls.join(", ")}`
);
// @ts-ignore
error.code = "ERR_MODULE_NOT_FOUND";
throw error;
}
// Resolve realPath and normalize slash
const realPath = realpathSync(fileURLToPath(resolved));
return pathToFileURL(realPath).toString();
}
export function resolveSync(id: string, options?: ResolveOptions): string {
return _resolve(id, options);
}
export function resolve(id: string, options?: ResolveOptions): Promise<string> {
return pcall(resolveSync, id, options);
}
export function resolvePathSync(id: string, options?: ResolveOptions): string {
return fileURLToPath(resolveSync(id, options));
}
export function resolvePath(
id: string,
options?: ResolveOptions
): Promise<string> {
return pcall(resolvePathSync, id, options);
}
export function createResolve(defaults?: ResolveOptions) {
return (id: string, url?: ResolveOptions["url"]) => {
return resolve(id, { url, ...defaults });
};
}
const NODE_MODULES_RE = /^(.+\/node_modules\/)([^/@]+|@[^/]+\/[^/]+)(\/?.*?)?$/;
export function parseNodeModulePath(path: string) {
if (!path) {
return {};
}
path = normalize(fileURLToPath(path));
const match = NODE_MODULES_RE.exec(path);
if (!match) {
return {};
}
const [, dir, name, subpath] = match;
return {
dir,
name,
subpath: subpath ? `.${subpath}` : undefined,
};
}
/** Reverse engineer a subpath export if possible */
export async function lookupNodeModuleSubpath(
path: string
): Promise<string | undefined> {
path = normalize(fileURLToPath(path));
const { name, subpath } = parseNodeModulePath(path);
if (!name || !subpath) {
return subpath;
}
const { exports } = (await readPackageJSON(path).catch(() => {})) || {};
if (exports) {
const resolvedSubpath = _findSubpath(subpath, exports);
if (resolvedSubpath) {
return resolvedSubpath;
}
}
return subpath;
}
// --- Internal ---
function _findSubpath(subpath: string, exports: PackageJson["exports"]) {
if (typeof exports === "string") {
exports = { ".": exports };
}
if (!subpath.startsWith(".")) {
subpath = subpath.startsWith("/") ? `.${subpath}` : `./${subpath}`;
}
if (subpath in exports) {
return subpath;
}
const flattenedExports = _flattenExports(exports);
const [foundPath] =
// eslint-disable-next-line @typescript-eslint/no-unused-vars
flattenedExports.find(([_, resolved]) => resolved === subpath) || [];
return foundPath;
}
function _flattenExports(
exports: Exclude<PackageJson["exports"], string>,
path?: string
) {
return Object.entries(exports).flatMap(([key, value]) =>
typeof value === "string"
? [[path ?? key, value]]
: _flattenExports(value, path ?? key)
);
}