vite-node 3.0.9 → 3.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.mjs CHANGED
@@ -14,545 +14,383 @@ import 'node:module';
14
14
  import 'node:path';
15
15
 
16
16
  function hashCode(s) {
17
- return s.split("").reduce((a, b) => {
18
- a = (a << 5) - a + b.charCodeAt(0);
19
- return a & a;
20
- }, 0);
17
+ return s.split("").reduce((a, b) => {
18
+ a = (a << 5) - a + b.charCodeAt(0);
19
+ return a & a;
20
+ }, 0);
21
21
  }
22
22
  class Debugger {
23
- constructor(root, options) {
24
- this.options = options;
25
- if (options.dumpModules) {
26
- this.dumpDir = resolve(
27
- root,
28
- options.dumpModules === true ? ".vite-node/dump" : options.dumpModules
29
- );
30
- }
31
- if (this.dumpDir) {
32
- if (options.loadDumppedModules) {
33
- console.info(
34
- s.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`)
35
- );
36
- } else {
37
- console.info(
38
- s.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`)
39
- );
40
- }
41
- }
42
- this.initPromise = this.clearDump();
43
- }
44
- dumpDir;
45
- initPromise;
46
- externalizeMap = /* @__PURE__ */ new Map();
47
- async clearDump() {
48
- if (!this.dumpDir) {
49
- return;
50
- }
51
- if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) {
52
- await promises.rm(this.dumpDir, { recursive: true, force: true });
53
- }
54
- await promises.mkdir(this.dumpDir, { recursive: true });
55
- }
56
- encodeId(id) {
57
- return `${id.replace(/[^\w@\-]/g, "_").replace(/_+/g, "_")}-${hashCode(
58
- id
59
- )}.js`;
60
- }
61
- async recordExternalize(id, path) {
62
- if (!this.dumpDir) {
63
- return;
64
- }
65
- this.externalizeMap.set(id, path);
66
- await this.writeInfo();
67
- }
68
- async dumpFile(id, result) {
69
- if (!result || !this.dumpDir) {
70
- return;
71
- }
72
- await this.initPromise;
73
- const name = this.encodeId(id);
74
- return await promises.writeFile(
75
- join(this.dumpDir, name),
76
- `// ${id.replace(/\0/g, "\\0")}
77
- ${result.code}`,
78
- "utf-8"
79
- );
80
- }
81
- async loadDump(id) {
82
- if (!this.dumpDir) {
83
- return null;
84
- }
85
- await this.initPromise;
86
- const name = this.encodeId(id);
87
- const path = join(this.dumpDir, name);
88
- if (!existsSync(path)) {
89
- return null;
90
- }
91
- const code = await promises.readFile(path, "utf-8");
92
- return {
93
- code: code.replace(/^\/\/.*\n/, ""),
94
- map: void 0
95
- };
96
- }
97
- async writeInfo() {
98
- if (!this.dumpDir) {
99
- return;
100
- }
101
- const info = JSON.stringify(
102
- {
103
- time: (/* @__PURE__ */ new Date()).toLocaleString(),
104
- externalize: Object.fromEntries(this.externalizeMap.entries())
105
- },
106
- null,
107
- 2
108
- );
109
- return promises.writeFile(join(this.dumpDir, "info.json"), info, "utf-8");
110
- }
23
+ dumpDir;
24
+ initPromise;
25
+ externalizeMap = new Map();
26
+ constructor(root, options) {
27
+ this.options = options;
28
+ if (options.dumpModules) this.dumpDir = resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
29
+ if (this.dumpDir) if (options.loadDumppedModules) console.info(s.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
30
+ else console.info(s.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
31
+ this.initPromise = this.clearDump();
32
+ }
33
+ async clearDump() {
34
+ if (!this.dumpDir) return;
35
+ if (!this.options.loadDumppedModules && existsSync(this.dumpDir)) await promises.rm(this.dumpDir, {
36
+ recursive: true,
37
+ force: true
38
+ });
39
+ await promises.mkdir(this.dumpDir, { recursive: true });
40
+ }
41
+ encodeId(id) {
42
+ return `${id.replace(/[^\w@\-]/g, "_").replace(/_+/g, "_")}-${hashCode(id)}.js`;
43
+ }
44
+ async recordExternalize(id, path) {
45
+ if (!this.dumpDir) return;
46
+ this.externalizeMap.set(id, path);
47
+ await this.writeInfo();
48
+ }
49
+ async dumpFile(id, result) {
50
+ if (!result || !this.dumpDir) return;
51
+ await this.initPromise;
52
+ const name = this.encodeId(id);
53
+ return await promises.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, "\\0")}\n${result.code}`, "utf-8");
54
+ }
55
+ async loadDump(id) {
56
+ if (!this.dumpDir) return null;
57
+ await this.initPromise;
58
+ const name = this.encodeId(id);
59
+ const path = join(this.dumpDir, name);
60
+ if (!existsSync(path)) return null;
61
+ const code = await promises.readFile(path, "utf-8");
62
+ return {
63
+ code: code.replace(/^\/\/.*\n/, ""),
64
+ map: void 0
65
+ };
66
+ }
67
+ async writeInfo() {
68
+ if (!this.dumpDir) return;
69
+ const info = JSON.stringify({
70
+ time: new Date().toLocaleString(),
71
+ externalize: Object.fromEntries(this.externalizeMap.entries())
72
+ }, null, 2);
73
+ return promises.writeFile(join(this.dumpDir, "info.json"), info, "utf-8");
74
+ }
111
75
  }
112
76
 
113
- const BUILTIN_EXTENSIONS = /* @__PURE__ */ new Set([".mjs", ".cjs", ".node", ".wasm"]);
77
+ const BUILTIN_EXTENSIONS = new Set([
78
+ ".mjs",
79
+ ".cjs",
80
+ ".node",
81
+ ".wasm"
82
+ ]);
114
83
  const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
115
84
  const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
116
85
  const defaultInline = [
117
- /virtual:/,
118
- /\.[mc]?ts$/,
119
- // special Vite query strings
120
- /[?&](init|raw|url|inline)\b/,
121
- // Vite returns a string for assets imports, even if it's inside "node_modules"
122
- KNOWN_ASSET_RE
123
- ];
124
- const depsExternal = [
125
- /\/node_modules\/.*\.cjs\.js$/,
126
- /\/node_modules\/.*\.mjs$/
86
+ /virtual:/,
87
+ /\.[mc]?ts$/,
88
+ /[?&](init|raw|url|inline)\b/,
89
+ KNOWN_ASSET_RE
127
90
  ];
91
+ const depsExternal = [/\/node_modules\/.*\.cjs\.js$/, /\/node_modules\/.*\.mjs$/];
128
92
  function guessCJSversion(id) {
129
- if (id.match(ESM_EXT_RE)) {
130
- for (const i of [
131
- id.replace(ESM_EXT_RE, ".mjs"),
132
- id.replace(ESM_EXT_RE, ".umd.js"),
133
- id.replace(ESM_EXT_RE, ".cjs.js"),
134
- id.replace(ESM_EXT_RE, ".js")
135
- ]) {
136
- if (existsSync(i)) {
137
- return i;
138
- }
139
- }
140
- }
141
- if (id.match(ESM_FOLDER_RE)) {
142
- for (const i of [
143
- id.replace(ESM_FOLDER_RE, "/umd/$1"),
144
- id.replace(ESM_FOLDER_RE, "/cjs/$1"),
145
- id.replace(ESM_FOLDER_RE, "/lib/$1"),
146
- id.replace(ESM_FOLDER_RE, "/$1")
147
- ]) {
148
- if (existsSync(i)) {
149
- return i;
150
- }
151
- }
152
- }
93
+ if (id.match(ESM_EXT_RE)) {
94
+ for (const i of [
95
+ id.replace(ESM_EXT_RE, ".mjs"),
96
+ id.replace(ESM_EXT_RE, ".umd.js"),
97
+ id.replace(ESM_EXT_RE, ".cjs.js"),
98
+ id.replace(ESM_EXT_RE, ".js")
99
+ ]) if (existsSync(i)) return i;
100
+ }
101
+ if (id.match(ESM_FOLDER_RE)) {
102
+ for (const i of [
103
+ id.replace(ESM_FOLDER_RE, "/umd/$1"),
104
+ id.replace(ESM_FOLDER_RE, "/cjs/$1"),
105
+ id.replace(ESM_FOLDER_RE, "/lib/$1"),
106
+ id.replace(ESM_FOLDER_RE, "/$1")
107
+ ]) if (existsSync(i)) return i;
108
+ }
153
109
  }
154
110
  async function isValidNodeImport(id) {
155
- const extension = extname(id);
156
- if (BUILTIN_EXTENSIONS.has(extension)) {
157
- return true;
158
- }
159
- if (extension !== ".js") {
160
- return false;
161
- }
162
- id = id.replace("file:///", "");
163
- const package_ = await findNearestPackageData(dirname(id));
164
- if (package_.type === "module") {
165
- return true;
166
- }
167
- if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) {
168
- return false;
169
- }
170
- try {
171
- await esModuleLexer.init;
172
- const code = await promises.readFile(id, "utf8");
173
- const [, , , hasModuleSyntax] = esModuleLexer.parse(code);
174
- return !hasModuleSyntax;
175
- } catch {
176
- return false;
177
- }
111
+ const extension = extname(id);
112
+ if (BUILTIN_EXTENSIONS.has(extension)) return true;
113
+ if (extension !== ".js") return false;
114
+ id = id.replace("file:///", "");
115
+ const package_ = await findNearestPackageData(dirname(id));
116
+ if (package_.type === "module") return true;
117
+ if (/\.(?:\w+-)?esm?(?:-\w+)?\.js$|\/esm?\//.test(id)) return false;
118
+ try {
119
+ await esModuleLexer.init;
120
+ const code = await promises.readFile(id, "utf8");
121
+ const [, , , hasModuleSyntax] = esModuleLexer.parse(code);
122
+ return !hasModuleSyntax;
123
+ } catch {
124
+ return false;
125
+ }
178
126
  }
179
- const _defaultExternalizeCache = /* @__PURE__ */ new Map();
127
+ const _defaultExternalizeCache = new Map();
180
128
  async function shouldExternalize(id, options, cache = _defaultExternalizeCache) {
181
- if (!cache.has(id)) {
182
- cache.set(id, _shouldExternalize(id, options));
183
- }
184
- return cache.get(id);
129
+ if (!cache.has(id)) cache.set(id, _shouldExternalize(id, options));
130
+ return cache.get(id);
185
131
  }
186
132
  async function _shouldExternalize(id, options) {
187
- if (isNodeBuiltin(id)) {
188
- return id;
189
- }
190
- if (id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) {
191
- return id;
192
- }
193
- id = patchWindowsImportPath(id);
194
- const moduleDirectories = (options == null ? void 0 : options.moduleDirectories) || ["/node_modules/"];
195
- if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.inline)) {
196
- return false;
197
- }
198
- if ((options == null ? void 0 : options.inlineFiles) && (options == null ? void 0 : options.inlineFiles.includes(id))) {
199
- return false;
200
- }
201
- if (matchExternalizePattern(id, moduleDirectories, options == null ? void 0 : options.external)) {
202
- return id;
203
- }
204
- if ((options == null ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) {
205
- return id;
206
- }
207
- const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
208
- const guessCJS = isLibraryModule && (options == null ? void 0 : options.fallbackCJS);
209
- id = guessCJS ? guessCJSversion(id) || id : id;
210
- if (matchExternalizePattern(id, moduleDirectories, defaultInline)) {
211
- return false;
212
- }
213
- if (matchExternalizePattern(id, moduleDirectories, depsExternal)) {
214
- return id;
215
- }
216
- if (isLibraryModule && await isValidNodeImport(id)) {
217
- return id;
218
- }
219
- return false;
133
+ if (isNodeBuiltin(id)) return id;
134
+ if (id.startsWith("data:") || /^(?:https?:)?\/\//.test(id)) return id;
135
+ id = patchWindowsImportPath(id);
136
+ const moduleDirectories = (options === null || options === void 0 ? void 0 : options.moduleDirectories) || ["/node_modules/"];
137
+ if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.inline)) return false;
138
+ if ((options === null || options === void 0 ? void 0 : options.inlineFiles) && (options === null || options === void 0 ? void 0 : options.inlineFiles.includes(id))) return false;
139
+ if (matchExternalizePattern(id, moduleDirectories, options === null || options === void 0 ? void 0 : options.external)) return id;
140
+ if ((options === null || options === void 0 ? void 0 : options.cacheDir) && id.includes(options.cacheDir)) return id;
141
+ const isLibraryModule = moduleDirectories.some((dir) => id.includes(dir));
142
+ const guessCJS = isLibraryModule && (options === null || options === void 0 ? void 0 : options.fallbackCJS);
143
+ id = guessCJS ? guessCJSversion(id) || id : id;
144
+ if (matchExternalizePattern(id, moduleDirectories, defaultInline)) return false;
145
+ if (matchExternalizePattern(id, moduleDirectories, depsExternal)) return id;
146
+ if (isLibraryModule && await isValidNodeImport(id)) return id;
147
+ return false;
220
148
  }
221
149
  function matchExternalizePattern(id, moduleDirectories, patterns) {
222
- if (patterns == null) {
223
- return false;
224
- }
225
- if (patterns === true) {
226
- return true;
227
- }
228
- for (const ex of patterns) {
229
- if (typeof ex === "string") {
230
- if (moduleDirectories.some((dir) => id.includes(join(dir, ex)))) {
231
- return true;
232
- }
233
- } else {
234
- if (ex.test(id)) {
235
- return true;
236
- }
237
- }
238
- }
239
- return false;
150
+ if (patterns == null) return false;
151
+ if (patterns === true) return true;
152
+ for (const ex of patterns) if (typeof ex === "string") {
153
+ if (moduleDirectories.some((dir) => id.includes(join(dir, ex)))) return true;
154
+ } else if (ex.test(id)) return true;
155
+ return false;
240
156
  }
241
157
  function patchWindowsImportPath(path) {
242
- if (path.match(/^\w:\\/)) {
243
- return `file:///${slash(path)}`;
244
- } else if (path.match(/^\w:\//)) {
245
- return `file:///${path}`;
246
- } else {
247
- return path;
248
- }
158
+ if (path.match(/^\w:\\/)) return `file:///${slash(path)}`;
159
+ else if (path.match(/^\w:\//)) return `file:///${path}`;
160
+ else return path;
249
161
  }
250
162
 
251
163
  const debugRequest = createDebug("vite-node:server:request");
252
164
  class ViteNodeServer {
253
- constructor(server, options = {}) {
254
- this.server = server;
255
- this.options = options;
256
- var _a, _b, _c;
257
- const ssrOptions = server.config.ssr;
258
- options.deps ?? (options.deps = {});
259
- options.deps.cacheDir = relative(
260
- server.config.root,
261
- options.deps.cacheDir || server.config.cacheDir
262
- );
263
- if (ssrOptions) {
264
- if (ssrOptions.noExternal === true) {
265
- (_a = options.deps).inline ?? (_a.inline = true);
266
- } else if (options.deps.inline !== true) {
267
- (_b = options.deps).inline ?? (_b.inline = []);
268
- const inline = options.deps.inline;
269
- options.deps.inline.push(
270
- ...toArray(ssrOptions.noExternal).filter(
271
- (dep) => !inline.includes(dep)
272
- )
273
- );
274
- }
275
- }
276
- if (process.env.VITE_NODE_DEBUG_DUMP) {
277
- options.debug = Object.assign(
278
- {
279
- dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
280
- loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
281
- },
282
- options.debug ?? {}
283
- );
284
- }
285
- if (options.debug) {
286
- this.debugger = new Debugger(server.config.root, options.debug);
287
- }
288
- if (options.deps.inlineFiles) {
289
- options.deps.inlineFiles = options.deps.inlineFiles.flatMap((file) => {
290
- if (file.startsWith("file://")) {
291
- return file;
292
- }
293
- const resolvedId = resolve(file);
294
- return [resolvedId, pathToFileURL(resolvedId).href];
295
- });
296
- }
297
- (_c = options.deps).moduleDirectories ?? (_c.moduleDirectories = []);
298
- const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES;
299
- const customModuleDirectories = envValue == null ? void 0 : envValue.split(",");
300
- if (customModuleDirectories) {
301
- options.deps.moduleDirectories.push(...customModuleDirectories);
302
- }
303
- options.deps.moduleDirectories = options.deps.moduleDirectories.map(
304
- (dir) => {
305
- if (!dir.startsWith("/")) {
306
- dir = `/${dir}`;
307
- }
308
- if (!dir.endsWith("/")) {
309
- dir += "/";
310
- }
311
- return normalize(dir);
312
- }
313
- );
314
- if (!options.deps.moduleDirectories.includes("/node_modules/")) {
315
- options.deps.moduleDirectories.push("/node_modules/");
316
- }
317
- }
318
- fetchPromiseMap = {
319
- ssr: /* @__PURE__ */ new Map(),
320
- web: /* @__PURE__ */ new Map()
321
- };
322
- transformPromiseMap = {
323
- ssr: /* @__PURE__ */ new Map(),
324
- web: /* @__PURE__ */ new Map()
325
- };
326
- durations = {
327
- ssr: /* @__PURE__ */ new Map(),
328
- web: /* @__PURE__ */ new Map()
329
- };
330
- existingOptimizedDeps = /* @__PURE__ */ new Set();
331
- fetchCaches = {
332
- ssr: /* @__PURE__ */ new Map(),
333
- web: /* @__PURE__ */ new Map()
334
- };
335
- fetchCache = /* @__PURE__ */ new Map();
336
- externalizeCache = /* @__PURE__ */ new Map();
337
- debugger;
338
- shouldExternalize(id) {
339
- return shouldExternalize(id, this.options.deps, this.externalizeCache);
340
- }
341
- getTotalDuration() {
342
- const ssrDurations = [...this.durations.ssr.values()].flat();
343
- const webDurations = [...this.durations.web.values()].flat();
344
- return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0);
345
- }
346
- async ensureExists(id) {
347
- if (this.existingOptimizedDeps.has(id)) {
348
- return true;
349
- }
350
- if (existsSync(id)) {
351
- this.existingOptimizedDeps.add(id);
352
- return true;
353
- }
354
- return new Promise((resolve2) => {
355
- setTimeout(() => {
356
- this.ensureExists(id).then(() => {
357
- resolve2(true);
358
- });
359
- });
360
- });
361
- }
362
- async resolveId(id, importer, transformMode) {
363
- if (importer && !importer.startsWith(withTrailingSlash(this.server.config.root))) {
364
- importer = resolve(this.server.config.root, importer);
365
- }
366
- const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr");
367
- return this.server.pluginContainer.resolveId(id, importer, {
368
- ssr: mode === "ssr"
369
- });
370
- }
371
- getSourceMap(source) {
372
- var _a, _b;
373
- source = normalizeModuleId(source);
374
- const fetchResult = (_a = this.fetchCache.get(source)) == null ? void 0 : _a.result;
375
- if (fetchResult == null ? void 0 : fetchResult.map) {
376
- return fetchResult.map;
377
- }
378
- const ssrTransformResult = (_b = this.server.moduleGraph.getModuleById(source)) == null ? void 0 : _b.ssrTransformResult;
379
- return (ssrTransformResult == null ? void 0 : ssrTransformResult.map) || null;
380
- }
381
- assertMode(mode) {
382
- assert(
383
- mode === "web" || mode === "ssr",
384
- `"transformMode" can only be "web" or "ssr", received "${mode}".`
385
- );
386
- }
387
- async fetchModule(id, transformMode) {
388
- const mode = transformMode || this.getTransformMode(id);
389
- return this.fetchResult(id, mode).then((r) => {
390
- return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
391
- });
392
- }
393
- async fetchResult(id, mode) {
394
- const moduleId = normalizeModuleId(id);
395
- this.assertMode(mode);
396
- const promiseMap = this.fetchPromiseMap[mode];
397
- if (!promiseMap.has(moduleId)) {
398
- promiseMap.set(
399
- moduleId,
400
- this._fetchModule(moduleId, mode).finally(() => {
401
- promiseMap.delete(moduleId);
402
- })
403
- );
404
- }
405
- return promiseMap.get(moduleId);
406
- }
407
- async transformRequest(id, filepath = id, transformMode) {
408
- const mode = transformMode || this.getTransformMode(id);
409
- this.assertMode(mode);
410
- const promiseMap = this.transformPromiseMap[mode];
411
- if (!promiseMap.has(id)) {
412
- promiseMap.set(
413
- id,
414
- this._transformRequest(id, filepath, mode).finally(() => {
415
- promiseMap.delete(id);
416
- })
417
- );
418
- }
419
- return promiseMap.get(id);
420
- }
421
- async transformModule(id, transformMode) {
422
- if (transformMode !== "web") {
423
- throw new Error(
424
- '`transformModule` only supports `transformMode: "web"`.'
425
- );
426
- }
427
- const normalizedId = normalizeModuleId(id);
428
- const mod = this.server.moduleGraph.getModuleById(normalizedId);
429
- const result = (mod == null ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
430
- return {
431
- code: result == null ? void 0 : result.code
432
- };
433
- }
434
- getTransformMode(id) {
435
- var _a, _b, _c, _d;
436
- const withoutQuery = id.split("?")[0];
437
- if ((_b = (_a = this.options.transformMode) == null ? void 0 : _a.web) == null ? void 0 : _b.some((r) => withoutQuery.match(r))) {
438
- return "web";
439
- }
440
- if ((_d = (_c = this.options.transformMode) == null ? void 0 : _c.ssr) == null ? void 0 : _d.some((r) => withoutQuery.match(r))) {
441
- return "ssr";
442
- }
443
- if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) {
444
- return "ssr";
445
- }
446
- return "web";
447
- }
448
- getChangedModule(id, file) {
449
- const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file);
450
- if (module) {
451
- return module;
452
- }
453
- const _modules = this.server.moduleGraph.getModulesByFile(file);
454
- if (!_modules || !_modules.size) {
455
- return null;
456
- }
457
- const modules = [..._modules];
458
- let mod = modules[0];
459
- let latestMax = -1;
460
- for (const m of _modules) {
461
- const timestamp = Math.max(
462
- m.lastHMRTimestamp,
463
- m.lastInvalidationTimestamp
464
- );
465
- if (timestamp > latestMax) {
466
- latestMax = timestamp;
467
- mod = m;
468
- }
469
- }
470
- return mod;
471
- }
472
- async _fetchModule(id, transformMode) {
473
- var _a, _b;
474
- let result;
475
- const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir;
476
- if (cacheDir && id.includes(cacheDir)) {
477
- if (!id.startsWith(withTrailingSlash(this.server.config.root))) {
478
- id = join(this.server.config.root, id);
479
- }
480
- const timeout = setTimeout(() => {
481
- throw new Error(
482
- `ViteNodeServer: ${id} not found. This is a bug, please report it.`
483
- );
484
- }, 5e3);
485
- await this.ensureExists(id);
486
- clearTimeout(timeout);
487
- }
488
- const { path: filePath } = toFilePath(id, this.server.config.root);
489
- const moduleNode = this.getChangedModule(id, filePath);
490
- const cache = this.fetchCaches[transformMode].get(filePath);
491
- const timestamp = moduleNode ? Math.max(
492
- moduleNode.lastHMRTimestamp,
493
- moduleNode.lastInvalidationTimestamp
494
- ) : 0;
495
- if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) {
496
- return cache.result;
497
- }
498
- const time = Date.now();
499
- const externalize = await this.shouldExternalize(filePath);
500
- let duration;
501
- if (externalize) {
502
- result = { externalize };
503
- (_b = this.debugger) == null ? void 0 : _b.recordExternalize(id, externalize);
504
- } else {
505
- const start = performance.now();
506
- const r = await this._transformRequest(id, filePath, transformMode);
507
- duration = performance.now() - start;
508
- result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
509
- }
510
- const cacheEntry = {
511
- duration,
512
- timestamp: time,
513
- result
514
- };
515
- const durations = this.durations[transformMode].get(filePath) || [];
516
- this.durations[transformMode].set(filePath, [...durations, duration ?? 0]);
517
- this.fetchCaches[transformMode].set(filePath, cacheEntry);
518
- this.fetchCache.set(filePath, cacheEntry);
519
- return result;
520
- }
521
- async processTransformResult(filepath, result) {
522
- const mod = this.server.moduleGraph.getModuleById(filepath);
523
- return withInlineSourcemap(result, {
524
- filepath: (mod == null ? void 0 : mod.file) || filepath,
525
- root: this.server.config.root,
526
- noFirstLineMapping: Number(version.split(".")[0]) >= 6
527
- });
528
- }
529
- async _transformRequest(id, filepath, transformMode) {
530
- var _a, _b, _c, _d;
531
- debugRequest(id);
532
- let result = null;
533
- if ((_a = this.options.debug) == null ? void 0 : _a.loadDumppedModules) {
534
- result = await ((_b = this.debugger) == null ? void 0 : _b.loadDump(id)) ?? null;
535
- if (result) {
536
- return result;
537
- }
538
- }
539
- if (transformMode === "web") {
540
- result = await this.server.transformRequest(id);
541
- if (result) {
542
- result = await this.server.ssrTransform(result.code, result.map, id);
543
- }
544
- } else {
545
- result = await this.server.transformRequest(id, { ssr: true });
546
- }
547
- const sourcemap = this.options.sourcemap ?? "inline";
548
- if (sourcemap === "inline" && result) {
549
- result = await this.processTransformResult(filepath, result);
550
- }
551
- if ((_c = this.options.debug) == null ? void 0 : _c.dumpModules) {
552
- await ((_d = this.debugger) == null ? void 0 : _d.dumpFile(id, result));
553
- }
554
- return result;
555
- }
165
+ fetchPromiseMap = {
166
+ ssr: new Map(),
167
+ web: new Map()
168
+ };
169
+ transformPromiseMap = {
170
+ ssr: new Map(),
171
+ web: new Map()
172
+ };
173
+ durations = {
174
+ ssr: new Map(),
175
+ web: new Map()
176
+ };
177
+ existingOptimizedDeps = new Set();
178
+ fetchCaches = {
179
+ ssr: new Map(),
180
+ web: new Map()
181
+ };
182
+ fetchCache = new Map();
183
+ externalizeCache = new Map();
184
+ debugger;
185
+ constructor(server, options = {}) {
186
+ this.server = server;
187
+ this.options = options;
188
+ var _options$deps3;
189
+ const ssrOptions = server.config.ssr;
190
+ options.deps ?? (options.deps = {});
191
+ options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir);
192
+ if (ssrOptions) {
193
+ if (ssrOptions.noExternal === true) {
194
+ var _options$deps;
195
+ (_options$deps = options.deps).inline ?? (_options$deps.inline = true);
196
+ } else if (options.deps.inline !== true) {
197
+ var _options$deps2;
198
+ (_options$deps2 = options.deps).inline ?? (_options$deps2.inline = []);
199
+ const inline = options.deps.inline;
200
+ options.deps.inline.push(...toArray(ssrOptions.noExternal).filter((dep) => !inline.includes(dep)));
201
+ }
202
+ }
203
+ if (process.env.VITE_NODE_DEBUG_DUMP) options.debug = Object.assign({
204
+ dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
205
+ loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === "load"
206
+ }, options.debug ?? {});
207
+ if (options.debug) this.debugger = new Debugger(server.config.root, options.debug);
208
+ if (options.deps.inlineFiles) options.deps.inlineFiles = options.deps.inlineFiles.flatMap((file) => {
209
+ if (file.startsWith("file://")) return file;
210
+ const resolvedId = resolve(file);
211
+ return [resolvedId, pathToFileURL(resolvedId).href];
212
+ });
213
+ (_options$deps3 = options.deps).moduleDirectories ?? (_options$deps3.moduleDirectories = []);
214
+ const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES;
215
+ const customModuleDirectories = envValue === null || envValue === void 0 ? void 0 : envValue.split(",");
216
+ if (customModuleDirectories) options.deps.moduleDirectories.push(...customModuleDirectories);
217
+ options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
218
+ if (!dir.startsWith("/")) dir = `/${dir}`;
219
+ if (!dir.endsWith("/")) dir += "/";
220
+ return normalize(dir);
221
+ });
222
+ if (!options.deps.moduleDirectories.includes("/node_modules/")) options.deps.moduleDirectories.push("/node_modules/");
223
+ }
224
+ shouldExternalize(id) {
225
+ return shouldExternalize(id, this.options.deps, this.externalizeCache);
226
+ }
227
+ getTotalDuration() {
228
+ const ssrDurations = [...this.durations.ssr.values()].flat();
229
+ const webDurations = [...this.durations.web.values()].flat();
230
+ return [...ssrDurations, ...webDurations].reduce((a, b) => a + b, 0);
231
+ }
232
+ async ensureExists(id) {
233
+ if (this.existingOptimizedDeps.has(id)) return true;
234
+ if (existsSync(id)) {
235
+ this.existingOptimizedDeps.add(id);
236
+ return true;
237
+ }
238
+ return new Promise((resolve) => {
239
+ setTimeout(() => {
240
+ this.ensureExists(id).then(() => {
241
+ resolve(true);
242
+ });
243
+ });
244
+ });
245
+ }
246
+ async resolveId(id, importer, transformMode) {
247
+ if (importer && !importer.startsWith(withTrailingSlash(this.server.config.root))) importer = resolve(this.server.config.root, importer);
248
+ const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr");
249
+ return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
250
+ }
251
+ getSourceMap(source) {
252
+ var _this$fetchCache$get, _this$server$moduleGr;
253
+ source = normalizeModuleId(source);
254
+ const fetchResult = (_this$fetchCache$get = this.fetchCache.get(source)) === null || _this$fetchCache$get === void 0 ? void 0 : _this$fetchCache$get.result;
255
+ if (fetchResult === null || fetchResult === void 0 ? void 0 : fetchResult.map) return fetchResult.map;
256
+ const ssrTransformResult = (_this$server$moduleGr = this.server.moduleGraph.getModuleById(source)) === null || _this$server$moduleGr === void 0 ? void 0 : _this$server$moduleGr.ssrTransformResult;
257
+ return (ssrTransformResult === null || ssrTransformResult === void 0 ? void 0 : ssrTransformResult.map) || null;
258
+ }
259
+ assertMode(mode) {
260
+ assert(mode === "web" || mode === "ssr", `"transformMode" can only be "web" or "ssr", received "${mode}".`);
261
+ }
262
+ async fetchModule(id, transformMode) {
263
+ const mode = transformMode || this.getTransformMode(id);
264
+ return this.fetchResult(id, mode).then((r) => {
265
+ return this.options.sourcemap !== true ? {
266
+ ...r,
267
+ map: void 0
268
+ } : r;
269
+ });
270
+ }
271
+ async fetchResult(id, mode) {
272
+ const moduleId = normalizeModuleId(id);
273
+ this.assertMode(mode);
274
+ const promiseMap = this.fetchPromiseMap[mode];
275
+ if (!promiseMap.has(moduleId)) promiseMap.set(moduleId, this._fetchModule(moduleId, mode).finally(() => {
276
+ promiseMap.delete(moduleId);
277
+ }));
278
+ return promiseMap.get(moduleId);
279
+ }
280
+ async transformRequest(id, filepath = id, transformMode) {
281
+ const mode = transformMode || this.getTransformMode(id);
282
+ this.assertMode(mode);
283
+ const promiseMap = this.transformPromiseMap[mode];
284
+ if (!promiseMap.has(id)) promiseMap.set(id, this._transformRequest(id, filepath, mode).finally(() => {
285
+ promiseMap.delete(id);
286
+ }));
287
+ return promiseMap.get(id);
288
+ }
289
+ async transformModule(id, transformMode) {
290
+ if (transformMode !== "web") throw new Error("`transformModule` only supports `transformMode: \"web\"`.");
291
+ const normalizedId = normalizeModuleId(id);
292
+ const mod = this.server.moduleGraph.getModuleById(normalizedId);
293
+ const result = (mod === null || mod === void 0 ? void 0 : mod.transformResult) || await this.server.transformRequest(normalizedId);
294
+ return { code: result === null || result === void 0 ? void 0 : result.code };
295
+ }
296
+ getTransformMode(id) {
297
+ var _this$options$transfo, _this$options$transfo2;
298
+ const withoutQuery = id.split("?")[0];
299
+ if ((_this$options$transfo = this.options.transformMode) === null || _this$options$transfo === void 0 || (_this$options$transfo = _this$options$transfo.web) === null || _this$options$transfo === void 0 ? void 0 : _this$options$transfo.some((r) => withoutQuery.match(r))) return "web";
300
+ if ((_this$options$transfo2 = this.options.transformMode) === null || _this$options$transfo2 === void 0 || (_this$options$transfo2 = _this$options$transfo2.ssr) === null || _this$options$transfo2 === void 0 ? void 0 : _this$options$transfo2.some((r) => withoutQuery.match(r))) return "ssr";
301
+ if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/)) return "ssr";
302
+ return "web";
303
+ }
304
+ getChangedModule(id, file) {
305
+ const module = this.server.moduleGraph.getModuleById(id) || this.server.moduleGraph.getModuleById(file);
306
+ if (module) return module;
307
+ const _modules = this.server.moduleGraph.getModulesByFile(file);
308
+ if (!_modules || !_modules.size) return null;
309
+ const modules = [..._modules];
310
+ let mod = modules[0];
311
+ let latestMax = -1;
312
+ for (const m of _modules) {
313
+ const timestamp = Math.max(m.lastHMRTimestamp, m.lastInvalidationTimestamp);
314
+ if (timestamp > latestMax) {
315
+ latestMax = timestamp;
316
+ mod = m;
317
+ }
318
+ }
319
+ return mod;
320
+ }
321
+ async _fetchModule(id, transformMode) {
322
+ var _this$options$deps;
323
+ let result;
324
+ const cacheDir = (_this$options$deps = this.options.deps) === null || _this$options$deps === void 0 ? void 0 : _this$options$deps.cacheDir;
325
+ if (cacheDir && id.includes(cacheDir)) {
326
+ if (!id.startsWith(withTrailingSlash(this.server.config.root))) id = join(this.server.config.root, id);
327
+ const timeout = setTimeout(() => {
328
+ throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
329
+ }, 5e3);
330
+ await this.ensureExists(id);
331
+ clearTimeout(timeout);
332
+ }
333
+ const { path: filePath } = toFilePath(id, this.server.config.root);
334
+ const moduleNode = this.getChangedModule(id, filePath);
335
+ const cache = this.fetchCaches[transformMode].get(filePath);
336
+ const timestamp = moduleNode ? Math.max(moduleNode.lastHMRTimestamp, moduleNode.lastInvalidationTimestamp) : 0;
337
+ if (cache && (timestamp === 0 || cache.timestamp >= timestamp)) return cache.result;
338
+ const time = Date.now();
339
+ const externalize = await this.shouldExternalize(filePath);
340
+ let duration;
341
+ if (externalize) {
342
+ var _this$debugger;
343
+ result = { externalize };
344
+ (_this$debugger = this.debugger) === null || _this$debugger === void 0 || _this$debugger.recordExternalize(id, externalize);
345
+ } else {
346
+ const start = performance.now();
347
+ const r = await this._transformRequest(id, filePath, transformMode);
348
+ duration = performance.now() - start;
349
+ result = {
350
+ code: r === null || r === void 0 ? void 0 : r.code,
351
+ map: r === null || r === void 0 ? void 0 : r.map
352
+ };
353
+ }
354
+ const cacheEntry = {
355
+ duration,
356
+ timestamp: time,
357
+ result
358
+ };
359
+ const durations = this.durations[transformMode].get(filePath) || [];
360
+ this.durations[transformMode].set(filePath, [...durations, duration ?? 0]);
361
+ this.fetchCaches[transformMode].set(filePath, cacheEntry);
362
+ this.fetchCache.set(filePath, cacheEntry);
363
+ return result;
364
+ }
365
+ async processTransformResult(filepath, result) {
366
+ const mod = this.server.moduleGraph.getModuleById(filepath);
367
+ return withInlineSourcemap(result, {
368
+ filepath: (mod === null || mod === void 0 ? void 0 : mod.file) || filepath,
369
+ root: this.server.config.root,
370
+ noFirstLineMapping: Number(version.split(".")[0]) >= 6
371
+ });
372
+ }
373
+ async _transformRequest(id, filepath, transformMode) {
374
+ var _this$options$debug, _this$options$debug2;
375
+ debugRequest(id);
376
+ let result = null;
377
+ if ((_this$options$debug = this.options.debug) === null || _this$options$debug === void 0 ? void 0 : _this$options$debug.loadDumppedModules) {
378
+ var _this$debugger2;
379
+ result = await ((_this$debugger2 = this.debugger) === null || _this$debugger2 === void 0 ? void 0 : _this$debugger2.loadDump(id)) ?? null;
380
+ if (result) return result;
381
+ }
382
+ if (transformMode === "web") {
383
+ result = await this.server.transformRequest(id);
384
+ if (result) result = await this.server.ssrTransform(result.code, result.map, id);
385
+ } else result = await this.server.transformRequest(id, { ssr: true });
386
+ const sourcemap = this.options.sourcemap ?? "inline";
387
+ if (sourcemap === "inline" && result) result = await this.processTransformResult(filepath, result);
388
+ if ((_this$options$debug2 = this.options.debug) === null || _this$options$debug2 === void 0 ? void 0 : _this$options$debug2.dumpModules) {
389
+ var _this$debugger3;
390
+ await ((_this$debugger3 = this.debugger) === null || _this$debugger3 === void 0 ? void 0 : _this$debugger3.dumpFile(id, result));
391
+ }
392
+ return result;
393
+ }
556
394
  }
557
395
 
558
396
  export { ViteNodeServer, guessCJSversion, shouldExternalize };