This repository has been archived by the owner on Oct 18, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
loaders.ts
266 lines (234 loc) · 5.49 KB
/
loaders.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
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
import path from 'path';
import { pathToFileURL, fileURLToPath } from 'url';
import {
transform,
transformDynamicImport,
resolveTsPath,
compareNodeVersion,
} from '@esbuild-kit/core-utils';
import type { TransformOptions } from 'esbuild';
import {
applySourceMap,
tsconfigPathsMatcher,
fileMatcher,
tsExtensionsPattern,
getFormatFromFileUrl,
fileProtocol,
type ModuleFormat,
type MaybePromise,
} from './utils.js';
type Resolved = {
url: string;
format: ModuleFormat | undefined;
};
type Context = {
conditions: string[];
parentURL: string | undefined;
};
type resolve = (
specifier: string,
context: Context,
defaultResolve: resolve,
recursiveCall?: boolean,
) => MaybePromise<Resolved>;
const extensions = ['.js', '.json', '.ts', '.tsx', '.jsx'] as const;
async function tryExtensions(
specifier: string,
context: Context,
defaultResolve: resolve,
) {
let error;
for (const extension of extensions) {
try {
return await resolve(
specifier + extension,
context,
defaultResolve,
true,
);
} catch (_error: any) {
if (error === undefined) {
const { message } = _error;
_error.message = _error.message.replace(`${extension}'`, "'");
_error.stack = _error.stack.replace(message, _error.message);
error = _error;
}
}
}
throw error;
}
async function tryDirectory(
specifier: string,
context: Context,
defaultResolve: resolve,
) {
const isExplicitDirectory = specifier.endsWith('/');
const appendIndex = isExplicitDirectory ? 'index' : '/index';
try {
return await tryExtensions(specifier + appendIndex, context, defaultResolve);
} catch (error: any) {
if (!isExplicitDirectory) {
try {
return await tryExtensions(specifier, context, defaultResolve);
} catch {}
}
const { message } = error;
error.message = error.message.replace(`${appendIndex.replace('/', path.sep)}'`, "'");
error.stack = error.stack.replace(message, error.message);
throw error;
}
}
const isPathPattern = /^\.{0,2}\//;
const supportsNodePrefix = (
compareNodeVersion([14, 13, 1]) >= 0
|| compareNodeVersion([12, 20, 0]) >= 0
);
export const resolve: resolve = async function (
specifier,
context,
defaultResolve,
recursiveCall,
) {
// Added in v12.20.0
// https://nodejs.org/api/esm.html#esm_node_imports
if (!supportsNodePrefix && specifier.startsWith('node:')) {
specifier = specifier.slice(5);
}
// If directory, can be index.js, index.ts, etc.
if (specifier.endsWith('/')) {
return await tryDirectory(specifier, context, defaultResolve);
}
const isPath = (
specifier.startsWith(fileProtocol)
|| isPathPattern.test(specifier)
);
if (
tsconfigPathsMatcher
&& !isPath // bare specifier
&& !context.parentURL?.includes('/node_modules/')
) {
const possiblePaths = tsconfigPathsMatcher(specifier);
for (const possiblePath of possiblePaths) {
try {
return await resolve(
pathToFileURL(possiblePath).toString(),
context,
defaultResolve,
);
} catch {}
}
}
/**
* Typescript gives .ts, .cts, or .mts priority over actual .js, .cjs, or .mjs extensions
*/
if (tsExtensionsPattern.test(context.parentURL!)) {
const tsPath = resolveTsPath(specifier);
if (tsPath) {
try {
return await resolve(tsPath, context, defaultResolve, true);
} catch (error) {
const { code } = error as any;
if (
code !== 'ERR_MODULE_NOT_FOUND'
&& code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED'
) {
throw error;
}
}
}
}
let resolved: Resolved;
try {
resolved = await defaultResolve(specifier, context, defaultResolve);
} catch (error) {
if (
error instanceof Error
&& !recursiveCall
) {
const { code } = error as any;
if (code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
try {
return await tryDirectory(specifier, context, defaultResolve);
} catch (error_) {
if ((error_ as any).code !== 'ERR_PACKAGE_IMPORT_NOT_DEFINED') {
throw error_;
}
}
}
if (code === 'ERR_MODULE_NOT_FOUND') {
try {
return await tryExtensions(specifier, context, defaultResolve);
} catch {}
}
}
throw error;
}
if (
!resolved.format
&& resolved.url.startsWith(fileProtocol)
) {
resolved.format = await getFormatFromFileUrl(resolved.url);
}
return resolved;
};
type load = (
url: string,
context: {
format: string;
importAssertions: Record<string, string>;
},
defaultLoad: load,
) => MaybePromise<{
format: string;
source: string | ArrayBuffer | SharedArrayBuffer | Uint8Array;
}>;
export const load: load = async function (
url,
context,
defaultLoad,
) {
if (process.send) {
process.send({
type: 'dependency',
path: url,
});
}
if (url.endsWith('.json')) {
if (!context.importAssertions) {
context.importAssertions = {};
}
context.importAssertions.type = 'json';
}
const loaded = await defaultLoad(url, context, defaultLoad);
if (!loaded.source) {
return loaded;
}
const filePath = url.startsWith('file://') ? fileURLToPath(url) : url;
const code = loaded.source.toString();
if (
loaded.format === 'json'
|| tsExtensionsPattern.test(url)
) {
const transformed = await transform(
code,
filePath,
{
tsconfigRaw: fileMatcher?.(filePath) as TransformOptions['tsconfigRaw'],
},
);
return {
format: 'module',
source: applySourceMap(transformed, url),
};
}
if (loaded.format === 'module') {
const dynamicImportTransformed = transformDynamicImport(filePath, code);
if (dynamicImportTransformed) {
loaded.source = applySourceMap(
dynamicImportTransformed,
url,
);
}
}
return loaded;
};