-
-
Notifications
You must be signed in to change notification settings - Fork 124
/
loaders.ts
298 lines (263 loc) · 7.25 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import path from 'path';
import { pathToFileURL, fileURLToPath } from 'url';
import type {
ResolveFnOutput, ResolveHookContext, LoadHook, GlobalPreloadHook, InitializeHook,
} from 'module';
import type { TransformOptions } from 'esbuild';
import { transform } from '../utils/transform/index.js';
import { transformDynamicImport } from '../utils/transform/transform-dynamic-import.js';
import { resolveTsPath } from '../utils/resolve-ts-path.js';
import { installSourceMapSupport } from '../source-map.js';
import { isFeatureSupported, importAttributes } from '../utils/node-features.js';
import { connectingToServer, type SendToParent } from '../utils/ipc/client.js';
import {
tsconfigPathsMatcher,
fileMatcher,
tsExtensionsPattern,
isJsonPattern,
getFormatFromFileUrl,
fileProtocol,
allowJs,
type MaybePromise,
type NodeError,
} from './utils.js';
const applySourceMap = installSourceMapSupport();
const isDirectoryPattern = /\/(?:$|\?)/;
type NextResolve = (
specifier: string,
context?: ResolveHookContext,
) => MaybePromise<ResolveFnOutput>;
type resolve = (
specifier: string,
context: ResolveHookContext,
nextResolve: NextResolve,
recursiveCall?: boolean,
) => MaybePromise<ResolveFnOutput>;
export const initialize: InitializeHook = async (data) => {
if (!data) {
throw new Error('tsx must be loaded with --import instead of --loader\nThe --loader flag was deprecated in Node v20.6.0 and v18.19.0');
}
};
/**
* Technically globalPreload is deprecated so it should be in loaders-deprecated
* but it shares a closure with the new load hook
*/
export const globalPreload: GlobalPreloadHook = () => `
const require = getBuiltin('module').createRequire("${import.meta.url}");
require('../source-map.cjs').installSourceMapSupport();
`;
const resolveExplicitPath = async (
defaultResolve: NextResolve,
specifier: string,
context: ResolveHookContext,
) => {
const resolved = await defaultResolve(specifier, context);
if (
!resolved.format
&& resolved.url.startsWith(fileProtocol)
) {
resolved.format = await getFormatFromFileUrl(resolved.url);
}
return resolved;
};
const extensions = ['.js', '.json', '.ts', '.tsx', '.jsx'] as const;
const tryExtensions = async (
specifier: string,
context: ResolveHookContext,
defaultResolve: NextResolve,
) => {
const [specifierWithoutQuery, query] = specifier.split('?');
let throwError: Error | undefined;
for (const extension of extensions) {
try {
return await resolveExplicitPath(
defaultResolve,
specifierWithoutQuery + extension + (query ? `?${query}` : ''),
context,
);
} catch (_error) {
if (
throwError === undefined
&& _error instanceof Error
) {
const { message } = _error;
_error.message = _error.message.replace(`${extension}'`, "'");
_error.stack = _error.stack!.replace(message, _error.message);
throwError = _error;
}
}
}
throw throwError;
};
const tryDirectory = async (
specifier: string,
context: ResolveHookContext,
defaultResolve: NextResolve,
) => {
const isExplicitDirectory = isDirectoryPattern.test(specifier);
const appendIndex = isExplicitDirectory ? 'index' : '/index';
const [specifierWithoutQuery, query] = specifier.split('?');
try {
return await tryExtensions(
specifierWithoutQuery + appendIndex + (query ? `?${query}` : ''),
context,
defaultResolve,
);
} catch (_error) {
if (!isExplicitDirectory) {
try {
return await tryExtensions(specifier, context, defaultResolve);
} catch {}
}
const error = _error as Error;
const { message } = error;
error.message = error.message.replace(`${appendIndex.replace('/', path.sep)}'`, "'");
error.stack = error.stack!.replace(message, error.message);
throw error;
}
};
const isRelativePathPattern = /^\.{1,2}\//;
export const resolve: resolve = async (
specifier,
context,
defaultResolve,
recursiveCall,
) => {
// If directory, can be index.js, index.ts, etc.
if (isDirectoryPattern.test(specifier)) {
return await tryDirectory(specifier, context, defaultResolve);
}
const isPath = (
specifier.startsWith(fileProtocol)
|| isRelativePathPattern.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 `allowJs` is set in `tsconfig.json`, then we'll apply the same resolution logic
// to files without a TypeScript extension.
if (tsExtensionsPattern.test(context.parentURL!) || allowJs) {
const tsPaths = resolveTsPath(specifier);
if (tsPaths) {
for (const tsPath of tsPaths) {
try {
return await resolveExplicitPath(defaultResolve, tsPath, context);
// return await resolve(tsPath, context, defaultResolve, true);
} catch (error) {
const { code } = error as NodeError;
if (
code !== 'ERR_MODULE_NOT_FOUND'
&& code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED'
) {
throw error;
}
}
}
}
}
try {
return await resolveExplicitPath(defaultResolve, specifier, context);
} catch (error) {
if (
error instanceof Error
&& !recursiveCall
) {
const { code } = error as NodeError;
if (code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
try {
return await tryDirectory(specifier, context, defaultResolve);
} catch (error_) {
if ((error_ as NodeError).code !== 'ERR_PACKAGE_IMPORT_NOT_DEFINED') {
throw error_;
}
}
}
if (code === 'ERR_MODULE_NOT_FOUND') {
try {
return await tryExtensions(specifier, context, defaultResolve);
} catch {}
}
}
throw error;
}
};
let sendToParent: SendToParent | void;
connectingToServer.then(
(_sendToParent) => {
sendToParent = _sendToParent;
},
() => {},
);
const contextAttributesProperty = (
isFeatureSupported(importAttributes)
? 'importAttributes'
: 'importAssertions'
);
export const load: LoadHook = async (
url,
context,
defaultLoad,
) => {
/*
Filter out node:*
Maybe only handle files that start with file://
*/
if (sendToParent) {
sendToParent({
type: 'dependency',
path: url,
});
}
if (isJsonPattern.test(url)) {
if (!context[contextAttributesProperty]) {
context[contextAttributesProperty] = {};
}
context[contextAttributesProperty]!.type = 'json';
}
const loaded = await defaultLoad(url, context);
// CommonJS and Internal modules (e.g. node:*)
if (!loaded.source) {
return loaded;
}
const filePath = url.startsWith('file://') ? fileURLToPath(url) : url;
const code = loaded.source.toString();
if (
// Support named imports in JSON modules
loaded.format === 'json'
|| tsExtensionsPattern.test(url)
) {
const transformed = await transform(
code,
filePath,
{
tsconfigRaw: fileMatcher?.(filePath) as TransformOptions['tsconfigRaw'],
},
);
return {
format: 'module',
source: applySourceMap(transformed),
};
}
if (loaded.format === 'module') {
const dynamicImportTransformed = transformDynamicImport(filePath, code);
if (dynamicImportTransformed) {
loaded.source = applySourceMap(dynamicImportTransformed);
}
}
return loaded;
};