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