vite-node 5.3.0 → 6.0.0

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.
@@ -1,505 +0,0 @@
1
- import { c as isNodeBuiltin, d as normalizeModuleId, f as normalizeRequestId, g as toFilePath, l as isPrimitive, m as slash, n as cleanUrl, o as isBareImport, r as createImportMetaEnvProxy, s as isInternalRequest } from "./utils-ExLpYVUV.mjs";
2
- import { a as originalPositionFor, i as TraceMap, t as extractSourceMap } from "./source-map-CysB5F9m.mjs";
3
- import { createRequire } from "node:module";
4
- import process from "node:process";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
6
- import { createDebug } from "obug";
7
- import { dirname, resolve } from "node:path";
8
- import vm from "node:vm";
9
-
10
- //#region src/client.ts
11
- const { setTimeout, clearTimeout } = globalThis;
12
- const debugExecute = createDebug("vite-node:client:execute");
13
- const debugNative = createDebug("vite-node:client:native");
14
- const clientStub = {
15
- injectQuery: (id) => id,
16
- createHotContext: () => {
17
- return {
18
- accept: () => {},
19
- prune: () => {},
20
- dispose: () => {},
21
- decline: () => {},
22
- invalidate: () => {},
23
- on: () => {},
24
- send: () => {}
25
- };
26
- },
27
- updateStyle: () => {},
28
- removeStyle: () => {}
29
- };
30
- const env = createImportMetaEnvProxy();
31
- const DEFAULT_REQUEST_STUBS = {
32
- "/@vite/client": clientStub,
33
- "@vite/client": clientStub
34
- };
35
- var ModuleCacheMap = class extends Map {
36
- normalizePath(fsPath) {
37
- return normalizeModuleId(fsPath);
38
- }
39
- /**
40
- * Assign partial data to the map
41
- */
42
- update(fsPath, mod) {
43
- fsPath = this.normalizePath(fsPath);
44
- if (!super.has(fsPath)) this.setByModuleId(fsPath, mod);
45
- else Object.assign(super.get(fsPath), mod);
46
- return this;
47
- }
48
- setByModuleId(modulePath, mod) {
49
- return super.set(modulePath, mod);
50
- }
51
- set(fsPath, mod) {
52
- return this.setByModuleId(this.normalizePath(fsPath), mod);
53
- }
54
- getByModuleId(modulePath) {
55
- if (!super.has(modulePath)) this.setByModuleId(modulePath, {});
56
- const mod = super.get(modulePath);
57
- if (!mod.imports) Object.assign(mod, {
58
- imports: /* @__PURE__ */ new Set(),
59
- importers: /* @__PURE__ */ new Set()
60
- });
61
- return mod;
62
- }
63
- get(fsPath) {
64
- return this.getByModuleId(this.normalizePath(fsPath));
65
- }
66
- deleteByModuleId(modulePath) {
67
- return super.delete(modulePath);
68
- }
69
- delete(fsPath) {
70
- return this.deleteByModuleId(this.normalizePath(fsPath));
71
- }
72
- invalidateModule(mod) {
73
- delete mod.evaluated;
74
- delete mod.resolving;
75
- delete mod.promise;
76
- delete mod.exports;
77
- mod.importers?.clear();
78
- mod.imports?.clear();
79
- return true;
80
- }
81
- /**
82
- * Invalidate modules that dependent on the given modules, up to the main entry
83
- */
84
- invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
85
- for (const _id of ids) {
86
- const id = this.normalizePath(_id);
87
- if (invalidated.has(id)) continue;
88
- invalidated.add(id);
89
- const mod = super.get(id);
90
- if (mod?.importers) this.invalidateDepTree(mod.importers, invalidated);
91
- super.delete(id);
92
- }
93
- return invalidated;
94
- }
95
- /**
96
- * Invalidate dependency modules of the given modules, down to the bottom-level dependencies
97
- */
98
- invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
99
- for (const _id of ids) {
100
- const id = this.normalizePath(_id);
101
- if (invalidated.has(id)) continue;
102
- invalidated.add(id);
103
- const subIds = Array.from(super.entries()).filter(([, mod]) => mod.importers?.has(id)).map(([key]) => key);
104
- if (subIds.length) this.invalidateSubDepTree(subIds, invalidated);
105
- super.delete(id);
106
- }
107
- return invalidated;
108
- }
109
- /**
110
- * Return parsed source map based on inlined source map of the module
111
- */
112
- getSourceMap(id) {
113
- const cache = this.get(id);
114
- if (cache.map) return cache.map;
115
- const map = cache.code && extractSourceMap(cache.code);
116
- if (map) {
117
- cache.map = map;
118
- return map;
119
- }
120
- return null;
121
- }
122
- };
123
- var ViteNodeRunner = class {
124
- root;
125
- debug;
126
- /**
127
- * Holds the cache of modules
128
- * Keys of the map are filepaths, or plain package names
129
- */
130
- moduleCache;
131
- /**
132
- * Tracks the stack of modules being executed for the purpose of calculating import self-time.
133
- *
134
- * Note that while in most cases, imports are a linear stack of modules,
135
- * this is occasionally not the case, for example when you have parallel top-level dynamic imports like so:
136
- *
137
- * ```ts
138
- * await Promise.all([
139
- * import('./module1'),
140
- * import('./module2'),
141
- * ]);
142
- * ```
143
- *
144
- * In this case, the self time will be reported incorrectly for one of the modules (could go negative).
145
- * As top-level awaits with dynamic imports like this are uncommon, we don't handle this case specifically.
146
- */
147
- executionStack = [];
148
- performanceNow = performance.now.bind(performance);
149
- constructor(options) {
150
- this.options = options;
151
- this.root = options.root ?? process.cwd();
152
- this.moduleCache = options.moduleCache ?? new ModuleCacheMap();
153
- this.debug = options.debug ?? (typeof process !== "undefined" ? !!process.env.VITE_NODE_DEBUG_RUNNER : false);
154
- }
155
- async executeFile(file) {
156
- const url = `/@fs/${slash(resolve(file))}`;
157
- return await this.cachedRequest(url, url, []);
158
- }
159
- async executeId(rawId) {
160
- const [id, url] = await this.resolveUrl(rawId);
161
- return await this.cachedRequest(id, url, []);
162
- }
163
- /** @internal */
164
- async cachedRequest(id, fsPath, callstack) {
165
- const importee = callstack[callstack.length - 1];
166
- const mod = this.moduleCache.get(fsPath);
167
- const { imports, importers } = mod;
168
- if (importee) importers.add(importee);
169
- const getStack = () => `stack:\n${[...callstack, fsPath].reverse().map((p) => ` - ${p}`).join("\n")}`;
170
- if (callstack.includes(fsPath) || Array.from(imports.values()).some((i) => importers.has(i))) {
171
- if (mod.exports) return mod.exports;
172
- }
173
- let debugTimer;
174
- if (this.debug) debugTimer = setTimeout(() => console.warn(`[vite-node] module ${fsPath} takes over 2s to load.\n${getStack()}`), 2e3);
175
- try {
176
- if (mod.promise) return await mod.promise;
177
- const promise = this.directRequest(id, fsPath, callstack);
178
- Object.assign(mod, {
179
- promise,
180
- evaluated: false
181
- });
182
- return await promise;
183
- } finally {
184
- mod.evaluated = true;
185
- if (debugTimer) clearTimeout(debugTimer);
186
- }
187
- }
188
- shouldResolveId(id, _importee) {
189
- return !isInternalRequest(id) && !isNodeBuiltin(id) && !id.startsWith("data:");
190
- }
191
- async _resolveUrl(id, importer) {
192
- const dep = normalizeRequestId(id, this.options.base);
193
- if (!this.shouldResolveId(dep)) return [dep, dep];
194
- const { path: path$1, exists } = toFilePath(dep, this.root);
195
- if (!this.options.resolveId || exists) return [dep, path$1];
196
- const resolved = await this.options.resolveId(dep, importer);
197
- if (resolved?.meta?.["vite:alias"]?.noResolved) {
198
- const error = /* @__PURE__ */ new Error(`Cannot find module '${id}'${importer ? ` imported from '${importer}'` : ""}.
199
-
200
- - If you rely on tsconfig.json's "paths" to resolve modules, please install "vite-tsconfig-paths" plugin to handle module resolution.
201
- - Make sure you don't have relative aliases in your Vitest config. Use absolute paths instead. Read more: https://vitest.dev/guide/common-errors`);
202
- Object.defineProperty(error, "code", {
203
- value: "ERR_MODULE_NOT_FOUND",
204
- enumerable: true
205
- });
206
- Object.defineProperty(error, Symbol.for("vitest.error.not_found.data"), {
207
- value: {
208
- id: dep,
209
- importer
210
- },
211
- enumerable: false
212
- });
213
- throw error;
214
- }
215
- const resolvedId = resolved ? normalizeRequestId(resolved.id, this.options.base) : dep;
216
- return [resolvedId, resolvedId];
217
- }
218
- async resolveUrl(id, importee) {
219
- const resolveKey = `resolve:${id}`;
220
- this.moduleCache.setByModuleId(resolveKey, { resolving: true });
221
- try {
222
- return await this._resolveUrl(id, importee);
223
- } finally {
224
- this.moduleCache.deleteByModuleId(resolveKey);
225
- }
226
- }
227
- /** @internal */
228
- async dependencyRequest(id, fsPath, callstack) {
229
- return await this.cachedRequest(id, fsPath, callstack);
230
- }
231
- async _fetchModule(id, importer) {
232
- try {
233
- return await this.options.fetchModule(id);
234
- } catch (cause) {
235
- if (typeof cause === "object" && cause.code === "ERR_LOAD_URL" || typeof cause?.message === "string" && cause.message.includes("Failed to load url")) {
236
- const error = new Error(`Cannot find ${isBareImport(id) ? "package" : "module"} '${id}'${importer ? ` imported from '${importer}'` : ""}`, { cause });
237
- error.code = "ERR_MODULE_NOT_FOUND";
238
- throw error;
239
- }
240
- throw cause;
241
- }
242
- }
243
- /** @internal */
244
- async directRequest(id, fsPath, _callstack) {
245
- const moduleId = normalizeModuleId(fsPath);
246
- const callstack = [..._callstack, moduleId];
247
- const mod = this.moduleCache.getByModuleId(moduleId);
248
- const request = async (dep) => {
249
- const [id$1, depFsPath] = await this.resolveUrl(String(dep), fsPath);
250
- this.moduleCache.getByModuleId(depFsPath).importers.add(moduleId);
251
- mod.imports.add(depFsPath);
252
- return this.dependencyRequest(id$1, depFsPath, callstack);
253
- };
254
- const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS;
255
- if (id in requestStubs) return requestStubs[id];
256
- let { code: transformed, externalize } = await this._fetchModule(id, callstack[callstack.length - 2]);
257
- if (externalize) {
258
- debugNative(externalize);
259
- const exports$1 = await this.interopedImport(externalize);
260
- mod.exports = exports$1;
261
- return exports$1;
262
- }
263
- if (transformed == null) throw new Error(`[vite-node] Failed to load "${id}" imported from ${callstack[callstack.length - 2]}`);
264
- const { Object: Object$1, Reflect: Reflect$1, Symbol: Symbol$1 } = this.getContextPrimitives();
265
- const modulePath = cleanUrl(moduleId);
266
- const href = pathToFileURL(modulePath).href;
267
- const __filename = fileURLToPath(href);
268
- const __dirname = dirname(__filename);
269
- const meta = {
270
- url: href,
271
- env,
272
- filename: __filename,
273
- dirname: __dirname
274
- };
275
- const exports = Object$1.create(null);
276
- Object$1.defineProperty(exports, Symbol$1.toStringTag, {
277
- value: "Module",
278
- enumerable: false,
279
- configurable: false
280
- });
281
- const SYMBOL_NOT_DEFINED = Symbol$1("not defined");
282
- let moduleExports = SYMBOL_NOT_DEFINED;
283
- const cjsExports = new Proxy(exports, {
284
- get: (target, p, receiver) => {
285
- if (Reflect$1.has(target, p)) return Reflect$1.get(target, p, receiver);
286
- return Reflect$1.get(Object$1.prototype, p, receiver);
287
- },
288
- getPrototypeOf: () => Object$1.prototype,
289
- set: (_, p, value) => {
290
- if (p === "default" && this.shouldInterop(modulePath, { default: value }) && cjsExports !== value) {
291
- exportAll(cjsExports, value);
292
- exports.default = value;
293
- return true;
294
- }
295
- if (!Reflect$1.has(exports, "default")) exports.default = {};
296
- if (moduleExports !== SYMBOL_NOT_DEFINED && isPrimitive(moduleExports)) {
297
- defineExport(exports, p, () => void 0);
298
- return true;
299
- }
300
- if (!isPrimitive(exports.default)) exports.default[p] = value;
301
- if (p !== "default") defineExport(exports, p, () => value);
302
- return true;
303
- }
304
- });
305
- Object$1.assign(mod, {
306
- code: transformed,
307
- exports
308
- });
309
- const moduleProxy = {
310
- set exports(value) {
311
- exportAll(cjsExports, value);
312
- exports.default = value;
313
- moduleExports = value;
314
- },
315
- get exports() {
316
- return cjsExports;
317
- }
318
- };
319
- let hotContext;
320
- if (this.options.createHotContext) Object$1.defineProperty(meta, "hot", {
321
- enumerable: true,
322
- get: () => {
323
- hotContext ||= this.options.createHotContext?.(this, moduleId);
324
- return hotContext;
325
- },
326
- set: (value) => {
327
- hotContext = value;
328
- }
329
- });
330
- const context = this.prepareContext({
331
- __vite_ssr_import__: request,
332
- __vite_ssr_dynamic_import__: request,
333
- __vite_ssr_exports__: exports,
334
- __vite_ssr_exportAll__: (obj) => exportAll(exports, obj),
335
- __vite_ssr_exportName__: (name, getter) => Object$1.defineProperty(exports, name, {
336
- enumerable: true,
337
- configurable: true,
338
- get: getter
339
- }),
340
- __vite_ssr_import_meta__: meta,
341
- require: createRequire(href),
342
- exports: cjsExports,
343
- module: moduleProxy,
344
- __filename,
345
- __dirname
346
- });
347
- debugExecute(__filename);
348
- if (transformed[0] === "#") transformed = transformed.replace(/^#!.*/, (s) => " ".repeat(s.length));
349
- await this.runModule(context, transformed);
350
- return exports;
351
- }
352
- getContextPrimitives() {
353
- return {
354
- Object,
355
- Reflect,
356
- Symbol
357
- };
358
- }
359
- async runModule(context, transformed) {
360
- const codeDefinition = `'use strict';async (${Object.keys(context).join(",")})=>{{`;
361
- const code = `${codeDefinition}${transformed}\n}}`;
362
- const options = {
363
- filename: context.__filename,
364
- lineOffset: 0,
365
- columnOffset: -codeDefinition.length
366
- };
367
- const finishModuleExecutionInfo = this.startCalculateModuleExecutionInfo(options.filename, codeDefinition.length);
368
- try {
369
- await vm.runInThisContext(code, options)(...Object.values(context));
370
- } finally {
371
- this.options.moduleExecutionInfo?.set(options.filename, finishModuleExecutionInfo());
372
- }
373
- }
374
- /**
375
- * mutate the given error to have fixed stacktraces based on source maps
376
- * Does the same thing as Vite's ssrFixStacktrace
377
- */
378
- async ssrFixStacktrace(error) {
379
- const stack = (error.stack || "").split("\n");
380
- const rewrittenStack = [];
381
- for (const line of stack) {
382
- const match = line.match(/\((.*):(\d+):(\d+)\)$/);
383
- if (match) {
384
- const [, file, lineStr, columnStr] = match;
385
- const lineNum = Number(lineStr);
386
- const columnNum = Number(columnStr);
387
- const sourceMap = this.moduleCache.getSourceMap(file);
388
- if (sourceMap) {
389
- const originalPos = originalPositionFor(new TraceMap(sourceMap), {
390
- line: lineNum,
391
- column: columnNum
392
- });
393
- if (originalPos.source) {
394
- const rewrittenLine = line.replace(/\(.*:\d+:\d+\)$/, `(${file}:${originalPos.line || lineNum}:${originalPos.column || columnNum})`);
395
- rewrittenStack.push(rewrittenLine);
396
- continue;
397
- }
398
- }
399
- }
400
- rewrittenStack.push(line);
401
- }
402
- error.stack = rewrittenStack.join("\n") || error.stack;
403
- return error;
404
- }
405
- /**
406
- * Starts calculating the module execution info such as the total duration and self time spent on executing the module.
407
- * Returns a function to call once the module has finished executing.
408
- */
409
- startCalculateModuleExecutionInfo(filename, startOffset) {
410
- const startTime = this.performanceNow();
411
- this.executionStack.push({
412
- filename,
413
- startTime,
414
- subImportTime: 0
415
- });
416
- return () => {
417
- const duration = this.performanceNow() - startTime;
418
- const currentExecution = this.executionStack.pop();
419
- if (currentExecution == null) throw new Error("Execution stack is empty, this should never happen");
420
- const selfTime = duration - currentExecution.subImportTime;
421
- if (this.executionStack.length > 0) this.executionStack.at(-1).subImportTime += duration;
422
- return {
423
- startOffset,
424
- duration,
425
- selfTime
426
- };
427
- };
428
- }
429
- prepareContext(context) {
430
- return context;
431
- }
432
- /**
433
- * Define if a module should be interop-ed
434
- * This function mostly for the ability to override by subclass
435
- */
436
- shouldInterop(path$1, mod) {
437
- if (this.options.interopDefault === false) return false;
438
- return !path$1.endsWith(".mjs") && "default" in mod;
439
- }
440
- importExternalModule(path$1) {
441
- return import(
442
- /* @vite-ignore */
443
- path$1
444
- );
445
- }
446
- /**
447
- * Import a module and interop it
448
- */
449
- async interopedImport(path$1) {
450
- const importedModule = await this.importExternalModule(path$1);
451
- if (!this.shouldInterop(path$1, importedModule)) return importedModule;
452
- const { mod, defaultExport } = interopModule(importedModule);
453
- return new Proxy(mod, {
454
- get(mod$1, prop) {
455
- if (prop === "default") return defaultExport;
456
- return mod$1[prop] ?? defaultExport?.[prop];
457
- },
458
- has(mod$1, prop) {
459
- if (prop === "default") return defaultExport !== void 0;
460
- return prop in mod$1 || defaultExport && prop in defaultExport;
461
- },
462
- getOwnPropertyDescriptor(mod$1, prop) {
463
- const descriptor = Reflect.getOwnPropertyDescriptor(mod$1, prop);
464
- if (descriptor) return descriptor;
465
- if (prop === "default" && defaultExport !== void 0) return {
466
- value: defaultExport,
467
- enumerable: true,
468
- configurable: true
469
- };
470
- }
471
- });
472
- }
473
- };
474
- function interopModule(mod) {
475
- if (isPrimitive(mod)) return {
476
- mod: { default: mod },
477
- defaultExport: mod
478
- };
479
- let defaultExport = "default" in mod ? mod.default : mod;
480
- if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) {
481
- mod = defaultExport;
482
- if ("default" in defaultExport) defaultExport = defaultExport.default;
483
- }
484
- return {
485
- mod,
486
- defaultExport
487
- };
488
- }
489
- function defineExport(exports, key, value) {
490
- Object.defineProperty(exports, key, {
491
- enumerable: true,
492
- configurable: true,
493
- get: value
494
- });
495
- }
496
- function exportAll(exports, sourceModule) {
497
- if (exports === sourceModule) return;
498
- if (isPrimitive(sourceModule) || Array.isArray(sourceModule) || sourceModule instanceof Promise) return;
499
- for (const key in sourceModule) if (key !== "default" && !(key in exports)) try {
500
- defineExport(exports, key, () => sourceModule[key]);
501
- } catch {}
502
- }
503
-
504
- //#endregion
505
- export { ModuleCacheMap as n, ViteNodeRunner as r, DEFAULT_REQUEST_STUBS as t };
@@ -1,34 +0,0 @@
1
- //#region src/constants.ts
2
- const KNOWN_ASSET_TYPES = [
3
- "apng",
4
- "bmp",
5
- "png",
6
- "jpe?g",
7
- "jfif",
8
- "pjpeg",
9
- "pjp",
10
- "gif",
11
- "svg",
12
- "ico",
13
- "webp",
14
- "avif",
15
- "mp4",
16
- "webm",
17
- "ogg",
18
- "mp3",
19
- "wav",
20
- "flac",
21
- "aac",
22
- "woff2?",
23
- "eot",
24
- "ttf",
25
- "otf",
26
- "webmanifest",
27
- "pdf",
28
- "txt"
29
- ];
30
- const KNOWN_ASSET_RE = /* @__PURE__ */ new RegExp(`\\.(${KNOWN_ASSET_TYPES.join("|")})$`);
31
- const CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/;
32
-
33
- //#endregion
34
- export { KNOWN_ASSET_RE as n, KNOWN_ASSET_TYPES as r, CSS_LANGS_RE as t };