vite-node 0.22.0 → 0.23.1

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/cli.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ interface CliOptions {
2
+ files?: string[];
3
+ _?: string[];
4
+ root?: string;
5
+ config?: string;
6
+ }
7
+
8
+ export { CliOptions };
package/client.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { ViteNodeRunnerOptions, ModuleCache } from './types.js';
2
+
3
+ declare const DEFAULT_REQUEST_STUBS: {
4
+ '/@vite/client': {
5
+ injectQuery: (id: string) => string;
6
+ createHotContext(): {
7
+ accept: () => void;
8
+ prune: () => void;
9
+ };
10
+ updateStyle(): void;
11
+ };
12
+ };
13
+ declare class ViteNodeRunner {
14
+ options: ViteNodeRunnerOptions;
15
+ root: string;
16
+ moduleCache: Map<string, ModuleCache>;
17
+ constructor(options: ViteNodeRunnerOptions);
18
+ executeFile(file: string): Promise<any>;
19
+ executeId(id: string): Promise<any>;
20
+ cachedRequest(rawId: string, callstack: string[]): Promise<any>;
21
+ directRequest(id: string, fsPath: string, callstack: string[]): Promise<any>;
22
+ prepareContext(context: Record<string, any>): Record<string, any>;
23
+ setCache(id: string, mod: Partial<ModuleCache>): void;
24
+ shouldResolveId(dep: string): boolean;
25
+ /**
26
+ * Define if a module should be interop-ed
27
+ * This function mostly for the ability to override by subclass
28
+ */
29
+ shouldInterop(path: string, mod: any): boolean;
30
+ /**
31
+ * Import a module and interop it
32
+ */
33
+ interopedImport(path: string): Promise<any>;
34
+ hasNestedDefault(target: any): any;
35
+ }
36
+
37
+ export { DEFAULT_REQUEST_STUBS, ViteNodeRunner };
@@ -98,17 +98,19 @@ async function fetchUpdate(runner, { path, acceptedPath }) {
98
98
  const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
99
99
  return deps.some((dep) => modulesToUpdate.has(dep));
100
100
  });
101
- await Promise.all(Array.from(modulesToUpdate).map(async (dep) => {
102
- const disposer = maps.disposeMap.get(dep);
103
- if (disposer)
104
- await disposer(maps.dataMap.get(dep));
105
- try {
106
- const newMod = await reload(runner, [dep]);
107
- moduleMap.set(dep, newMod);
108
- } catch (e) {
109
- warnFailedFetch(e, dep);
110
- }
111
- }));
101
+ await Promise.all(
102
+ Array.from(modulesToUpdate).map(async (dep) => {
103
+ const disposer = maps.disposeMap.get(dep);
104
+ if (disposer)
105
+ await disposer(maps.dataMap.get(dep));
106
+ try {
107
+ const newMod = await reload(runner, [dep]);
108
+ moduleMap.set(dep, newMod);
109
+ } catch (e) {
110
+ warnFailedFetch(e, dep);
111
+ }
112
+ })
113
+ );
112
114
  return () => {
113
115
  for (const { deps, fn } of qualifiedCallbacks)
114
116
  fn(deps.map((dep) => moduleMap.get(dep)));
@@ -119,7 +121,9 @@ async function fetchUpdate(runner, { path, acceptedPath }) {
119
121
  function warnFailedFetch(err, path) {
120
122
  if (!err.message.match("fetch"))
121
123
  console.error(err);
122
- console.error(`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
124
+ console.error(
125
+ `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
126
+ );
123
127
  }
124
128
  async function handleMessage(runner, emitter, files, payload) {
125
129
  const maps = getCache(runner);
@@ -92,17 +92,19 @@ async function fetchUpdate(runner, { path, acceptedPath }) {
92
92
  const qualifiedCallbacks = mod.callbacks.filter(({ deps }) => {
93
93
  return deps.some((dep) => modulesToUpdate.has(dep));
94
94
  });
95
- await Promise.all(Array.from(modulesToUpdate).map(async (dep) => {
96
- const disposer = maps.disposeMap.get(dep);
97
- if (disposer)
98
- await disposer(maps.dataMap.get(dep));
99
- try {
100
- const newMod = await reload(runner, [dep]);
101
- moduleMap.set(dep, newMod);
102
- } catch (e) {
103
- warnFailedFetch(e, dep);
104
- }
105
- }));
95
+ await Promise.all(
96
+ Array.from(modulesToUpdate).map(async (dep) => {
97
+ const disposer = maps.disposeMap.get(dep);
98
+ if (disposer)
99
+ await disposer(maps.dataMap.get(dep));
100
+ try {
101
+ const newMod = await reload(runner, [dep]);
102
+ moduleMap.set(dep, newMod);
103
+ } catch (e) {
104
+ warnFailedFetch(e, dep);
105
+ }
106
+ })
107
+ );
106
108
  return () => {
107
109
  for (const { deps, fn } of qualifiedCallbacks)
108
110
  fn(deps.map((dep) => moduleMap.get(dep)));
@@ -113,7 +115,9 @@ async function fetchUpdate(runner, { path, acceptedPath }) {
113
115
  function warnFailedFetch(err, path) {
114
116
  if (!err.message.match("fetch"))
115
117
  console.error(err);
116
- console.error(`[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`);
118
+ console.error(
119
+ `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
120
+ );
117
121
  }
118
122
  async function handleMessage(runner, emitter, files, payload) {
119
123
  const maps = getCache(runner);
package/dist/cli.cjs CHANGED
@@ -8,6 +8,7 @@ var client = require('./client.cjs');
8
8
  var utils = require('./utils.cjs');
9
9
  var hmr = require('./chunk-hmr.cjs');
10
10
  require('tty');
11
+ require('perf_hooks');
11
12
  require('pathe');
12
13
  require('debug');
13
14
  require('fs');
@@ -629,7 +630,7 @@ class CAC extends events.EventEmitter {
629
630
 
630
631
  const cac = (name = "") => new CAC(name);
631
632
 
632
- var version = "0.22.0";
633
+ var version = "0.23.1";
633
634
 
634
635
  const cli = cac("vite-node");
635
636
  cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options <options>", "Use specified Vite server options").help();
package/dist/cli.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { e as ViteNodeServerOptions } from './types-24fd0349.js';
1
+ import { e as ViteNodeServerOptions } from './types-dca976ee.js';
2
2
 
3
3
  interface CliOptions {
4
4
  root?: string;
package/dist/cli.mjs CHANGED
@@ -6,6 +6,7 @@ import { ViteNodeRunner } from './client.mjs';
6
6
  import { toArray } from './utils.mjs';
7
7
  import { v as viteNodeHmrPlugin, c as createHotContext, h as handleMessage } from './chunk-hmr.mjs';
8
8
  import 'tty';
9
+ import 'perf_hooks';
9
10
  import 'pathe';
10
11
  import 'debug';
11
12
  import 'fs';
@@ -627,7 +628,7 @@ class CAC extends EventEmitter {
627
628
 
628
629
  const cac = (name = "") => new CAC(name);
629
630
 
630
- var version = "0.22.0";
631
+ var version = "0.23.1";
631
632
 
632
633
  const cli = cac("vite-node");
633
634
  cli.version(version).option("-r, --root <path>", "Use specified root directory").option("-c, --config <path>", "Use specified config file").option("-w, --watch", 'Restart on file changes, similar to "nodemon"').option("--options <options>", "Use specified Vite server options").help();
package/dist/client.cjs CHANGED
@@ -73,7 +73,7 @@ class ModuleCacheMap extends Map {
73
73
  normalizePath(fsPath) {
74
74
  return utils.normalizeModuleId(fsPath);
75
75
  }
76
- set(fsPath, mod) {
76
+ update(fsPath, mod) {
77
77
  fsPath = this.normalizePath(fsPath);
78
78
  if (!super.has(fsPath))
79
79
  super.set(fsPath, mod);
@@ -81,14 +81,48 @@ class ModuleCacheMap extends Map {
81
81
  Object.assign(super.get(fsPath), mod);
82
82
  return this;
83
83
  }
84
+ set(fsPath, mod) {
85
+ fsPath = this.normalizePath(fsPath);
86
+ return super.set(fsPath, mod);
87
+ }
84
88
  get(fsPath) {
85
89
  fsPath = this.normalizePath(fsPath);
90
+ if (!super.has(fsPath))
91
+ super.set(fsPath, {});
86
92
  return super.get(fsPath);
87
93
  }
88
94
  delete(fsPath) {
89
95
  fsPath = this.normalizePath(fsPath);
90
96
  return super.delete(fsPath);
91
97
  }
98
+ invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
99
+ for (const _id of ids) {
100
+ const id = this.normalizePath(_id);
101
+ if (invalidated.has(id))
102
+ continue;
103
+ invalidated.add(id);
104
+ const mod = super.get(id);
105
+ if (mod == null ? void 0 : mod.importers)
106
+ this.invalidateDepTree(mod.importers, invalidated);
107
+ super.delete(id);
108
+ }
109
+ return invalidated;
110
+ }
111
+ invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
112
+ for (const _id of ids) {
113
+ const id = this.normalizePath(_id);
114
+ if (invalidated.has(id))
115
+ continue;
116
+ invalidated.add(id);
117
+ const subIds = Array.from(super.entries()).filter(([, mod]) => {
118
+ var _a;
119
+ return (_a = mod.importers) == null ? void 0 : _a.has(id);
120
+ }).map(([key]) => key);
121
+ subIds.length && this.invalidateSubDepTree(subIds, invalidated);
122
+ super.delete(id);
123
+ }
124
+ return invalidated;
125
+ }
92
126
  }
93
127
  class ViteNodeRunner {
94
128
  constructor(options) {
@@ -104,39 +138,44 @@ class ViteNodeRunner {
104
138
  return await this.cachedRequest(id, []);
105
139
  }
106
140
  async cachedRequest(rawId, callstack) {
107
- var _a, _b, _c, _d;
108
141
  const id = utils.normalizeRequestId(rawId, this.options.base);
109
142
  const fsPath = utils.toFilePath(id, this.root);
110
- if (callstack.includes(fsPath) && ((_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports))
111
- return (_b = this.moduleCache.get(fsPath)) == null ? void 0 : _b.exports;
112
- if ((_c = this.moduleCache.get(fsPath)) == null ? void 0 : _c.promise)
113
- return (_d = this.moduleCache.get(fsPath)) == null ? void 0 : _d.promise;
143
+ const mod = this.moduleCache.get(fsPath);
144
+ const importee = callstack[callstack.length - 1];
145
+ if (!mod.importers)
146
+ mod.importers = /* @__PURE__ */ new Set();
147
+ if (importee)
148
+ mod.importers.add(importee);
149
+ if (callstack.includes(fsPath) && mod.exports)
150
+ return mod.exports;
151
+ if (mod.promise)
152
+ return mod.promise;
114
153
  const promise = this.directRequest(id, fsPath, callstack);
115
- this.moduleCache.set(fsPath, { promise });
154
+ Object.assign(mod, { promise });
116
155
  return await promise;
117
156
  }
118
157
  async directRequest(id, fsPath, _callstack) {
119
158
  const callstack = [..._callstack, fsPath];
159
+ const mod = this.moduleCache.get(fsPath);
120
160
  const request = async (dep) => {
121
161
  var _a;
122
- const fsPath2 = utils.toFilePath(utils.normalizeRequestId(dep, this.options.base), this.root);
162
+ const depFsPath = utils.toFilePath(utils.normalizeRequestId(dep, this.options.base), this.root);
123
163
  const getStack = () => {
124
164
  return `stack:
125
- ${[...callstack, fsPath2].reverse().map((p) => `- ${p}`).join("\n")}`;
165
+ ${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
126
166
  };
127
167
  let debugTimer;
128
168
  if (this.debug)
129
- debugTimer = setTimeout(() => console.warn(() => `module ${fsPath2} takes over 2s to load.
169
+ debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
130
170
  ${getStack()}`), 2e3);
131
171
  try {
132
- if (callstack.includes(fsPath2)) {
133
- const depExports = (_a = this.moduleCache.get(fsPath2)) == null ? void 0 : _a.exports;
172
+ if (callstack.includes(depFsPath)) {
173
+ const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
134
174
  if (depExports)
135
175
  return depExports;
136
176
  throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
137
177
  }
138
- const mod = await this.cachedRequest(dep, callstack);
139
- return mod;
178
+ return await this.cachedRequest(dep, callstack);
140
179
  } finally {
141
180
  if (debugTimer)
142
181
  clearTimeout(debugTimer);
@@ -160,9 +199,9 @@ ${getStack()}`), 2e3);
160
199
  let { code: transformed, externalize } = await this.options.fetchModule(id);
161
200
  if (externalize) {
162
201
  debugNative(externalize);
163
- const mod = await this.interopedImport(externalize);
164
- this.moduleCache.set(fsPath, { exports: mod });
165
- return mod;
202
+ const exports2 = await this.interopedImport(externalize);
203
+ mod.exports = exports2;
204
+ return exports2;
166
205
  }
167
206
  if (transformed == null)
168
207
  throw new Error(`[vite-node] Failed to load ${id}`);
@@ -174,15 +213,34 @@ ${getStack()}`), 2e3);
174
213
  enumerable: false,
175
214
  configurable: false
176
215
  });
177
- this.moduleCache.set(fsPath, { code: transformed, exports });
216
+ const cjsExports = new Proxy(exports, {
217
+ get(_, p, receiver) {
218
+ return Reflect.get(exports, p, receiver);
219
+ },
220
+ set(_, p, value) {
221
+ if (p !== "default") {
222
+ if (!Reflect.has(exports, "default"))
223
+ exports.default = {};
224
+ if (exports.default === null || typeof exports.default !== "object") {
225
+ defineExport(exports, p, () => void 0);
226
+ return true;
227
+ }
228
+ exports.default[p] = value;
229
+ defineExport(exports, p, () => value);
230
+ return true;
231
+ }
232
+ return Reflect.set(exports, p, value);
233
+ }
234
+ });
235
+ Object.assign(mod, { code: transformed, exports });
178
236
  const __filename = url.fileURLToPath(url$1);
179
237
  const moduleProxy = {
180
238
  set exports(value) {
181
- exportAll(exports, value);
182
- exports.default = value;
239
+ exportAll(cjsExports, value);
240
+ cjsExports.default = value;
183
241
  },
184
242
  get exports() {
185
- return exports;
243
+ return cjsExports;
186
244
  }
187
245
  };
188
246
  let hotContext;
@@ -204,7 +262,7 @@ ${getStack()}`), 2e3);
204
262
  __vite_ssr_import_meta__: meta,
205
263
  __vitest_resolve_id__: resolveId,
206
264
  require: module$1.createRequire(url$1),
207
- exports,
265
+ exports: cjsExports,
208
266
  module: moduleProxy,
209
267
  __filename,
210
268
  __dirname: pathe.dirname(__filename)
@@ -260,19 +318,22 @@ function proxyMethod(name, tryDefault) {
260
318
  return result;
261
319
  };
262
320
  }
321
+ function defineExport(exports, key, value) {
322
+ Object.defineProperty(exports, key, {
323
+ enumerable: true,
324
+ configurable: true,
325
+ get: value
326
+ });
327
+ }
263
328
  function exportAll(exports, sourceModule) {
264
329
  if (exports === sourceModule)
265
330
  return;
331
+ if (typeof sourceModule !== "object" || Array.isArray(sourceModule) || !sourceModule)
332
+ return;
266
333
  for (const key in sourceModule) {
267
334
  if (key !== "default") {
268
335
  try {
269
- Object.defineProperty(exports, key, {
270
- enumerable: true,
271
- configurable: true,
272
- get() {
273
- return sourceModule[key];
274
- }
275
- });
336
+ defineExport(exports, key, () => sourceModule[key]);
276
337
  } catch (_err) {
277
338
  }
278
339
  }
package/dist/client.d.ts CHANGED
@@ -1 +1 @@
1
- export { j as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-24fd0349.js';
1
+ export { j as DEFAULT_REQUEST_STUBS, M as ModuleCacheMap, h as ViteNodeRunner } from './types-dca976ee.js';
package/dist/client.mjs CHANGED
@@ -46,7 +46,7 @@ class ModuleCacheMap extends Map {
46
46
  normalizePath(fsPath) {
47
47
  return normalizeModuleId(fsPath);
48
48
  }
49
- set(fsPath, mod) {
49
+ update(fsPath, mod) {
50
50
  fsPath = this.normalizePath(fsPath);
51
51
  if (!super.has(fsPath))
52
52
  super.set(fsPath, mod);
@@ -54,14 +54,48 @@ class ModuleCacheMap extends Map {
54
54
  Object.assign(super.get(fsPath), mod);
55
55
  return this;
56
56
  }
57
+ set(fsPath, mod) {
58
+ fsPath = this.normalizePath(fsPath);
59
+ return super.set(fsPath, mod);
60
+ }
57
61
  get(fsPath) {
58
62
  fsPath = this.normalizePath(fsPath);
63
+ if (!super.has(fsPath))
64
+ super.set(fsPath, {});
59
65
  return super.get(fsPath);
60
66
  }
61
67
  delete(fsPath) {
62
68
  fsPath = this.normalizePath(fsPath);
63
69
  return super.delete(fsPath);
64
70
  }
71
+ invalidateDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
72
+ for (const _id of ids) {
73
+ const id = this.normalizePath(_id);
74
+ if (invalidated.has(id))
75
+ continue;
76
+ invalidated.add(id);
77
+ const mod = super.get(id);
78
+ if (mod == null ? void 0 : mod.importers)
79
+ this.invalidateDepTree(mod.importers, invalidated);
80
+ super.delete(id);
81
+ }
82
+ return invalidated;
83
+ }
84
+ invalidateSubDepTree(ids, invalidated = /* @__PURE__ */ new Set()) {
85
+ for (const _id of ids) {
86
+ const id = this.normalizePath(_id);
87
+ if (invalidated.has(id))
88
+ continue;
89
+ invalidated.add(id);
90
+ const subIds = Array.from(super.entries()).filter(([, mod]) => {
91
+ var _a;
92
+ return (_a = mod.importers) == null ? void 0 : _a.has(id);
93
+ }).map(([key]) => key);
94
+ subIds.length && this.invalidateSubDepTree(subIds, invalidated);
95
+ super.delete(id);
96
+ }
97
+ return invalidated;
98
+ }
65
99
  }
66
100
  class ViteNodeRunner {
67
101
  constructor(options) {
@@ -77,39 +111,44 @@ class ViteNodeRunner {
77
111
  return await this.cachedRequest(id, []);
78
112
  }
79
113
  async cachedRequest(rawId, callstack) {
80
- var _a, _b, _c, _d;
81
114
  const id = normalizeRequestId(rawId, this.options.base);
82
115
  const fsPath = toFilePath(id, this.root);
83
- if (callstack.includes(fsPath) && ((_a = this.moduleCache.get(fsPath)) == null ? void 0 : _a.exports))
84
- return (_b = this.moduleCache.get(fsPath)) == null ? void 0 : _b.exports;
85
- if ((_c = this.moduleCache.get(fsPath)) == null ? void 0 : _c.promise)
86
- return (_d = this.moduleCache.get(fsPath)) == null ? void 0 : _d.promise;
116
+ const mod = this.moduleCache.get(fsPath);
117
+ const importee = callstack[callstack.length - 1];
118
+ if (!mod.importers)
119
+ mod.importers = /* @__PURE__ */ new Set();
120
+ if (importee)
121
+ mod.importers.add(importee);
122
+ if (callstack.includes(fsPath) && mod.exports)
123
+ return mod.exports;
124
+ if (mod.promise)
125
+ return mod.promise;
87
126
  const promise = this.directRequest(id, fsPath, callstack);
88
- this.moduleCache.set(fsPath, { promise });
127
+ Object.assign(mod, { promise });
89
128
  return await promise;
90
129
  }
91
130
  async directRequest(id, fsPath, _callstack) {
92
131
  const callstack = [..._callstack, fsPath];
132
+ const mod = this.moduleCache.get(fsPath);
93
133
  const request = async (dep) => {
94
134
  var _a;
95
- const fsPath2 = toFilePath(normalizeRequestId(dep, this.options.base), this.root);
135
+ const depFsPath = toFilePath(normalizeRequestId(dep, this.options.base), this.root);
96
136
  const getStack = () => {
97
137
  return `stack:
98
- ${[...callstack, fsPath2].reverse().map((p) => `- ${p}`).join("\n")}`;
138
+ ${[...callstack, depFsPath].reverse().map((p) => `- ${p}`).join("\n")}`;
99
139
  };
100
140
  let debugTimer;
101
141
  if (this.debug)
102
- debugTimer = setTimeout(() => console.warn(() => `module ${fsPath2} takes over 2s to load.
142
+ debugTimer = setTimeout(() => console.warn(() => `module ${depFsPath} takes over 2s to load.
103
143
  ${getStack()}`), 2e3);
104
144
  try {
105
- if (callstack.includes(fsPath2)) {
106
- const depExports = (_a = this.moduleCache.get(fsPath2)) == null ? void 0 : _a.exports;
145
+ if (callstack.includes(depFsPath)) {
146
+ const depExports = (_a = this.moduleCache.get(depFsPath)) == null ? void 0 : _a.exports;
107
147
  if (depExports)
108
148
  return depExports;
109
149
  throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`);
110
150
  }
111
- const mod = await this.cachedRequest(dep, callstack);
112
- return mod;
151
+ return await this.cachedRequest(dep, callstack);
113
152
  } finally {
114
153
  if (debugTimer)
115
154
  clearTimeout(debugTimer);
@@ -133,9 +172,9 @@ ${getStack()}`), 2e3);
133
172
  let { code: transformed, externalize } = await this.options.fetchModule(id);
134
173
  if (externalize) {
135
174
  debugNative(externalize);
136
- const mod = await this.interopedImport(externalize);
137
- this.moduleCache.set(fsPath, { exports: mod });
138
- return mod;
175
+ const exports2 = await this.interopedImport(externalize);
176
+ mod.exports = exports2;
177
+ return exports2;
139
178
  }
140
179
  if (transformed == null)
141
180
  throw new Error(`[vite-node] Failed to load ${id}`);
@@ -147,15 +186,34 @@ ${getStack()}`), 2e3);
147
186
  enumerable: false,
148
187
  configurable: false
149
188
  });
150
- this.moduleCache.set(fsPath, { code: transformed, exports });
189
+ const cjsExports = new Proxy(exports, {
190
+ get(_, p, receiver) {
191
+ return Reflect.get(exports, p, receiver);
192
+ },
193
+ set(_, p, value) {
194
+ if (p !== "default") {
195
+ if (!Reflect.has(exports, "default"))
196
+ exports.default = {};
197
+ if (exports.default === null || typeof exports.default !== "object") {
198
+ defineExport(exports, p, () => void 0);
199
+ return true;
200
+ }
201
+ exports.default[p] = value;
202
+ defineExport(exports, p, () => value);
203
+ return true;
204
+ }
205
+ return Reflect.set(exports, p, value);
206
+ }
207
+ });
208
+ Object.assign(mod, { code: transformed, exports });
151
209
  const __filename = fileURLToPath(url);
152
210
  const moduleProxy = {
153
211
  set exports(value) {
154
- exportAll(exports, value);
155
- exports.default = value;
212
+ exportAll(cjsExports, value);
213
+ cjsExports.default = value;
156
214
  },
157
215
  get exports() {
158
- return exports;
216
+ return cjsExports;
159
217
  }
160
218
  };
161
219
  let hotContext;
@@ -177,7 +235,7 @@ ${getStack()}`), 2e3);
177
235
  __vite_ssr_import_meta__: meta,
178
236
  __vitest_resolve_id__: resolveId,
179
237
  require: createRequire(url),
180
- exports,
238
+ exports: cjsExports,
181
239
  module: moduleProxy,
182
240
  __filename,
183
241
  __dirname: dirname(__filename)
@@ -233,19 +291,22 @@ function proxyMethod(name, tryDefault) {
233
291
  return result;
234
292
  };
235
293
  }
294
+ function defineExport(exports, key, value) {
295
+ Object.defineProperty(exports, key, {
296
+ enumerable: true,
297
+ configurable: true,
298
+ get: value
299
+ });
300
+ }
236
301
  function exportAll(exports, sourceModule) {
237
302
  if (exports === sourceModule)
238
303
  return;
304
+ if (typeof sourceModule !== "object" || Array.isArray(sourceModule) || !sourceModule)
305
+ return;
239
306
  for (const key in sourceModule) {
240
307
  if (key !== "default") {
241
308
  try {
242
- Object.defineProperty(exports, key, {
243
- enumerable: true,
244
- configurable: true,
245
- get() {
246
- return sourceModule[key];
247
- }
248
- });
309
+ defineExport(exports, key, () => sourceModule[key]);
249
310
  } catch (_err) {
250
311
  }
251
312
  }
package/dist/hmr.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { EventEmitter } from 'events';
2
2
  import { HMRPayload, Plugin } from 'vite';
3
- import { U as UpdatePayload, P as PrunePayload, g as FullReloadPayload, E as ErrorPayload, h as ViteNodeRunner, i as HMRPayload$1, H as HotContext } from './types-24fd0349.js';
3
+ import { U as UpdatePayload, P as PrunePayload, g as FullReloadPayload, E as ErrorPayload, h as ViteNodeRunner, i as HMRPayload$1, H as HotContext } from './types-dca976ee.js';
4
4
 
5
5
  declare type EventType = string | symbol;
6
6
  declare type Handler<T = unknown> = (event: T) => void;
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-24fd0349.js';
1
+ export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-dca976ee.js';
package/dist/server.cjs CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var perf_hooks = require('perf_hooks');
5
6
  var pathe = require('pathe');
6
7
  var createDebug = require('debug');
7
8
  var fs = require('fs');
@@ -141,19 +142,25 @@ class ViteNodeServer {
141
142
  }
142
143
  async fetchModule(id) {
143
144
  if (!this.fetchPromiseMap.has(id)) {
144
- this.fetchPromiseMap.set(id, this._fetchModule(id).then((r) => {
145
- return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
146
- }).finally(() => {
147
- this.fetchPromiseMap.delete(id);
148
- }));
145
+ this.fetchPromiseMap.set(
146
+ id,
147
+ this._fetchModule(id).then((r) => {
148
+ return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
149
+ }).finally(() => {
150
+ this.fetchPromiseMap.delete(id);
151
+ })
152
+ );
149
153
  }
150
154
  return this.fetchPromiseMap.get(id);
151
155
  }
152
156
  async transformRequest(id) {
153
157
  if (!this.transformPromiseMap.has(id)) {
154
- this.transformPromiseMap.set(id, this._transformRequest(id).finally(() => {
155
- this.transformPromiseMap.delete(id);
156
- }));
158
+ this.transformPromiseMap.set(
159
+ id,
160
+ this._transformRequest(id).finally(() => {
161
+ this.transformPromiseMap.delete(id);
162
+ })
163
+ );
157
164
  }
158
165
  return this.transformPromiseMap.get(id);
159
166
  }
@@ -178,14 +185,18 @@ class ViteNodeServer {
178
185
  if (timestamp && cache && cache.timestamp >= timestamp)
179
186
  return cache.result;
180
187
  const externalize = await this.shouldExternalize(filePath);
188
+ let duration;
181
189
  if (externalize) {
182
190
  result = { externalize };
183
191
  (_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
184
192
  } else {
193
+ const start = perf_hooks.performance.now();
185
194
  const r = await this._transformRequest(id);
195
+ duration = perf_hooks.performance.now() - start;
186
196
  result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
187
197
  }
188
198
  this.fetchCache.set(filePath, {
199
+ duration,
189
200
  timestamp,
190
201
  result
191
202
  });
package/dist/server.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TransformResult, ViteDevServer } from 'vite';
2
- import { f as DebuggerOptions, D as DepsHandlingOptions, e as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId } from './types-24fd0349.js';
2
+ import { f as DebuggerOptions, D as DepsHandlingOptions, e as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId } from './types-dca976ee.js';
3
3
 
4
4
  declare class Debugger {
5
5
  options: DebuggerOptions;
@@ -24,6 +24,7 @@ declare class ViteNodeServer {
24
24
  private fetchPromiseMap;
25
25
  private transformPromiseMap;
26
26
  fetchCache: Map<string, {
27
+ duration?: number | undefined;
27
28
  timestamp: number;
28
29
  result: FetchResult;
29
30
  }>;
package/dist/server.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { performance } from 'perf_hooks';
1
2
  import { resolve } from 'pathe';
2
3
  import createDebug from 'debug';
3
4
  import { existsSync } from 'fs';
@@ -133,19 +134,25 @@ class ViteNodeServer {
133
134
  }
134
135
  async fetchModule(id) {
135
136
  if (!this.fetchPromiseMap.has(id)) {
136
- this.fetchPromiseMap.set(id, this._fetchModule(id).then((r) => {
137
- return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
138
- }).finally(() => {
139
- this.fetchPromiseMap.delete(id);
140
- }));
137
+ this.fetchPromiseMap.set(
138
+ id,
139
+ this._fetchModule(id).then((r) => {
140
+ return this.options.sourcemap !== true ? { ...r, map: void 0 } : r;
141
+ }).finally(() => {
142
+ this.fetchPromiseMap.delete(id);
143
+ })
144
+ );
141
145
  }
142
146
  return this.fetchPromiseMap.get(id);
143
147
  }
144
148
  async transformRequest(id) {
145
149
  if (!this.transformPromiseMap.has(id)) {
146
- this.transformPromiseMap.set(id, this._transformRequest(id).finally(() => {
147
- this.transformPromiseMap.delete(id);
148
- }));
150
+ this.transformPromiseMap.set(
151
+ id,
152
+ this._transformRequest(id).finally(() => {
153
+ this.transformPromiseMap.delete(id);
154
+ })
155
+ );
149
156
  }
150
157
  return this.transformPromiseMap.get(id);
151
158
  }
@@ -170,14 +177,18 @@ class ViteNodeServer {
170
177
  if (timestamp && cache && cache.timestamp >= timestamp)
171
178
  return cache.result;
172
179
  const externalize = await this.shouldExternalize(filePath);
180
+ let duration;
173
181
  if (externalize) {
174
182
  result = { externalize };
175
183
  (_a = this.debugger) == null ? void 0 : _a.recordExternalize(id, externalize);
176
184
  } else {
185
+ const start = performance.now();
177
186
  const r = await this._transformRequest(id);
187
+ duration = performance.now() - start;
178
188
  result = { code: r == null ? void 0 : r.code, map: r == null ? void 0 : r.map };
179
189
  }
180
190
  this.fetchCache.set(filePath, {
191
+ duration,
181
192
  timestamp,
182
193
  result
183
194
  });
@@ -114,9 +114,21 @@ declare const DEFAULT_REQUEST_STUBS: {
114
114
  };
115
115
  declare class ModuleCacheMap extends Map<string, ModuleCache> {
116
116
  normalizePath(fsPath: string): string;
117
- set(fsPath: string, mod: Partial<ModuleCache>): this;
118
- get(fsPath: string): ModuleCache | undefined;
117
+ /**
118
+ * Assign partial data to the map
119
+ */
120
+ update(fsPath: string, mod: Partial<ModuleCache>): this;
121
+ set(fsPath: string, mod: ModuleCache): this;
122
+ get(fsPath: string): ModuleCache;
119
123
  delete(fsPath: string): boolean;
124
+ /**
125
+ * Invalidate modules that dependent on the given modules, up to the main entry
126
+ */
127
+ invalidateDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
128
+ /**
129
+ * Invalidate dependency modules of the given modules, down to the bottom-level dependencies
130
+ */
131
+ invalidateSubDepTree(ids: string[] | Set<string>, invalidated?: Set<string>): Set<string>;
120
132
  }
121
133
  declare class ViteNodeRunner {
122
134
  options: ViteNodeRunnerOptions;
@@ -183,6 +195,10 @@ interface ModuleCache {
183
195
  promise?: Promise<any>;
184
196
  exports?: any;
185
197
  code?: string;
198
+ /**
199
+ * Module ids that imports this module
200
+ */
201
+ importers?: Set<string>;
186
202
  }
187
203
  interface ViteNodeRunnerOptions {
188
204
  root: string;
package/dist/types.d.ts CHANGED
@@ -1 +1 @@
1
- export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-24fd0349.js';
1
+ export { A as Arrayable, C as CreateHotContextFunction, f as DebuggerOptions, D as DepsHandlingOptions, a as FetchFunction, F as FetchResult, H as HotContext, c as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, b as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, V as ViteNodeRunnerOptions, e as ViteNodeServerOptions } from './types-dca976ee.js';
package/dist/utils.cjs CHANGED
@@ -4,6 +4,7 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var url = require('url');
6
6
  var pathe = require('pathe');
7
+ var mlly = require('mlly');
7
8
 
8
9
  const isWindows = process.platform === "win32";
9
10
  function slash(str) {
@@ -23,6 +24,23 @@ function normalizeModuleId(id) {
23
24
  function isPrimitive(v) {
24
25
  return v !== Object(v);
25
26
  }
27
+ function pathFromRoot(root, filename) {
28
+ if (mlly.isNodeBuiltin(filename))
29
+ return filename;
30
+ filename = filename.replace(/^\/@fs\//, isWindows ? "" : "/");
31
+ if (!filename.startsWith(root))
32
+ return filename;
33
+ const relativePath = pathe.relative(root, filename);
34
+ if (!relativePath.startsWith("/") && !relativePath.startsWith("."))
35
+ return `/${relativePath}`;
36
+ let index = 0;
37
+ for (const char of relativePath) {
38
+ if (char !== "." && char !== "/")
39
+ return relativePath.slice(index - 1);
40
+ index++;
41
+ }
42
+ return relativePath;
43
+ }
26
44
  function toFilePath(id, root) {
27
45
  let absolute = id.startsWith("/@fs/") ? id.slice(4) : id.startsWith(root) ? id : id.startsWith("/") ? pathe.resolve(root, id.slice(1)) : id;
28
46
  if (absolute.startsWith("//"))
@@ -55,6 +73,7 @@ exports.isWindows = isWindows;
55
73
  exports.mergeSlashes = mergeSlashes;
56
74
  exports.normalizeModuleId = normalizeModuleId;
57
75
  exports.normalizeRequestId = normalizeRequestId;
76
+ exports.pathFromRoot = pathFromRoot;
58
77
  exports.slash = slash;
59
78
  exports.toArray = toArray;
60
79
  exports.toFilePath = toFilePath;
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { TransformResult } from 'vite';
2
- import { N as Nullable, A as Arrayable } from './types-24fd0349.js';
2
+ import { N as Nullable, A as Arrayable } from './types-dca976ee.js';
3
3
 
4
4
  declare const isWindows: boolean;
5
5
  declare function slash(str: string): string;
@@ -7,6 +7,7 @@ declare function mergeSlashes(str: string): string;
7
7
  declare function normalizeRequestId(id: string, base?: string): string;
8
8
  declare function normalizeModuleId(id: string): string;
9
9
  declare function isPrimitive(v: any): boolean;
10
+ declare function pathFromRoot(root: string, filename: string): string;
10
11
  declare function toFilePath(id: string, root: string): string;
11
12
  declare function withInlineSourcemap(result: TransformResult): Promise<TransformResult>;
12
13
  /**
@@ -16,4 +17,4 @@ declare function withInlineSourcemap(result: TransformResult): Promise<Transform
16
17
  */
17
18
  declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
18
19
 
19
- export { isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, slash, toArray, toFilePath, withInlineSourcemap };
20
+ export { isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, pathFromRoot, slash, toArray, toFilePath, withInlineSourcemap };
package/dist/utils.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  import { fileURLToPath, pathToFileURL } from 'url';
2
- import { resolve } from 'pathe';
2
+ import { relative, resolve } from 'pathe';
3
+ import { isNodeBuiltin } from 'mlly';
3
4
 
4
5
  const isWindows = process.platform === "win32";
5
6
  function slash(str) {
@@ -19,6 +20,23 @@ function normalizeModuleId(id) {
19
20
  function isPrimitive(v) {
20
21
  return v !== Object(v);
21
22
  }
23
+ function pathFromRoot(root, filename) {
24
+ if (isNodeBuiltin(filename))
25
+ return filename;
26
+ filename = filename.replace(/^\/@fs\//, isWindows ? "" : "/");
27
+ if (!filename.startsWith(root))
28
+ return filename;
29
+ const relativePath = relative(root, filename);
30
+ if (!relativePath.startsWith("/") && !relativePath.startsWith("."))
31
+ return `/${relativePath}`;
32
+ let index = 0;
33
+ for (const char of relativePath) {
34
+ if (char !== "." && char !== "/")
35
+ return relativePath.slice(index - 1);
36
+ index++;
37
+ }
38
+ return relativePath;
39
+ }
22
40
  function toFilePath(id, root) {
23
41
  let absolute = id.startsWith("/@fs/") ? id.slice(4) : id.startsWith(root) ? id : id.startsWith("/") ? resolve(root, id.slice(1)) : id;
24
42
  if (absolute.startsWith("//"))
@@ -46,4 +64,4 @@ function toArray(array) {
46
64
  return [array];
47
65
  }
48
66
 
49
- export { isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, slash, toArray, toFilePath, withInlineSourcemap };
67
+ export { isPrimitive, isWindows, mergeSlashes, normalizeModuleId, normalizeRequestId, pathFromRoot, slash, toArray, toFilePath, withInlineSourcemap };
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { DepsHandlingOptions, FetchFunction, FetchResult, ModuleCache, RawSourceMap, ResolveIdFunction, StartOfSourceMap, ViteNodeResolveId, ViteNodeRunnerOptions, ViteNodeServerOptions } from './types.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vite-node",
3
- "version": "0.22.0",
3
+ "version": "0.23.1",
4
4
  "description": "Vite as Node.js runtime",
5
5
  "author": "Anthony Fu <anthonyfu117@hotmail.com>",
6
6
  "license": "MIT",
@@ -65,15 +65,15 @@
65
65
  },
66
66
  "dependencies": {
67
67
  "debug": "^4.3.4",
68
- "mlly": "^0.5.12",
68
+ "mlly": "^0.5.14",
69
69
  "pathe": "^0.2.0",
70
70
  "vite": "^2.9.12 || ^3.0.0-0"
71
71
  },
72
72
  "devDependencies": {
73
73
  "@types/debug": "^4.1.7",
74
- "cac": "^6.7.12",
74
+ "cac": "^6.7.14",
75
75
  "picocolors": "^1.0.0",
76
- "rollup": "^2.77.3"
76
+ "rollup": "^2.78.1"
77
77
  },
78
78
  "scripts": {
79
79
  "build": "rimraf dist && rollup -c",
package/server.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { ViteDevServer, TransformResult } from 'vite';
2
+ import { DepsHandlingOptions, ViteNodeServerOptions, FetchResult, ViteNodeResolveId } from './types.js';
3
+
4
+ declare function guessCJSversion(id: string): string | undefined;
5
+ declare function shouldExternalize(id: string, options?: DepsHandlingOptions, cache?: Map<string, Promise<string | false>>): Promise<string | false>;
6
+
7
+ declare class ViteNodeServer {
8
+ server: ViteDevServer;
9
+ options: ViteNodeServerOptions;
10
+ private fetchPromiseMap;
11
+ private transformPromiseMap;
12
+ fetchCache: Map<string, {
13
+ timestamp: number;
14
+ result: FetchResult;
15
+ }>;
16
+ constructor(server: ViteDevServer, options?: ViteNodeServerOptions);
17
+ shouldExternalize(id: string): Promise<string | false>;
18
+ resolveId(id: string, importer?: string): Promise<ViteNodeResolveId | null>;
19
+ fetchModule(id: string): Promise<FetchResult>;
20
+ transformRequest(id: string): Promise<TransformResult | null | undefined>;
21
+ getTransformMode(id: string): "web" | "ssr";
22
+ private _fetchModule;
23
+ private _transformRequest;
24
+ }
25
+
26
+ export { ViteNodeServer, guessCJSversion, shouldExternalize };
package/types.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ interface DepsHandlingOptions {
2
+ external?: (string | RegExp)[];
3
+ inline?: (string | RegExp)[];
4
+ /**
5
+ * Try to guess the CJS version of a package when it's invalid ESM
6
+ * @default true
7
+ */
8
+ fallbackCJS?: boolean;
9
+ }
10
+ interface StartOfSourceMap {
11
+ file?: string;
12
+ sourceRoot?: string;
13
+ }
14
+ interface RawSourceMap extends StartOfSourceMap {
15
+ version: string;
16
+ sources: string[];
17
+ names: string[];
18
+ sourcesContent?: string[];
19
+ mappings: string;
20
+ }
21
+ interface FetchResult {
22
+ code?: string;
23
+ externalize?: string;
24
+ map?: RawSourceMap;
25
+ }
26
+ declare type FetchFunction = (id: string) => Promise<FetchResult>;
27
+ declare type ResolveIdFunction = (id: string, importer?: string) => Promise<ViteNodeResolveId | null>;
28
+ interface ModuleCache {
29
+ promise?: Promise<any>;
30
+ exports?: any;
31
+ code?: string;
32
+ }
33
+ interface ViteNodeRunnerOptions {
34
+ fetchModule: FetchFunction;
35
+ resolveId: ResolveIdFunction;
36
+ root: string;
37
+ base?: string;
38
+ moduleCache?: Map<string, ModuleCache>;
39
+ interopDefault?: boolean;
40
+ requestStubs?: Record<string, any>;
41
+ }
42
+ interface ViteNodeResolveId {
43
+ external?: boolean | 'absolute' | 'relative';
44
+ id: string;
45
+ meta?: Record<string, any> | null;
46
+ moduleSideEffects?: boolean | 'no-treeshake' | null;
47
+ syntheticNamedExports?: boolean | string | null;
48
+ }
49
+ interface ViteNodeServerOptions {
50
+ /**
51
+ * Inject inline sourcemap to modules
52
+ * @default 'inline'
53
+ */
54
+ sourcemap?: 'inline' | boolean;
55
+ /**
56
+ * Deps handling
57
+ */
58
+ deps?: DepsHandlingOptions;
59
+ /**
60
+ * Transform method for modules
61
+ */
62
+ transformMode?: {
63
+ ssr?: RegExp[];
64
+ web?: RegExp[];
65
+ };
66
+ }
67
+
68
+ export { DepsHandlingOptions, FetchFunction, FetchResult, ModuleCache, RawSourceMap, ResolveIdFunction, StartOfSourceMap, ViteNodeResolveId, ViteNodeRunnerOptions, ViteNodeServerOptions };
package/utils.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { TransformResult } from 'vite';
2
+
3
+ declare const isWindows: boolean;
4
+ declare function slash(str: string): string;
5
+ declare function normalizeId(id: string, base?: string): string;
6
+ declare function isPrimitive(v: any): boolean;
7
+ declare function toFilePath(id: string, root: string): string;
8
+ declare function withInlineSourcemap(result: TransformResult): Promise<TransformResult>;
9
+
10
+ export { isPrimitive, isWindows, normalizeId, slash, toFilePath, withInlineSourcemap };