vite-node 0.34.3 → 0.34.5

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/hmr.mjs CHANGED
@@ -1,9 +1,241 @@
1
- export { a as createHmrEmitter, c as createHotContext, g as getCache, h as handleMessage, r as reload, s as sendMessageBuffer, v as viteNodeHmrPlugin } from './chunk-hmr.mjs';
2
- import 'node:events';
3
- import 'picocolors';
4
- import 'debug';
5
- import './utils.mjs';
1
+ import { EventEmitter } from 'node:events';
2
+ import c from 'picocolors';
3
+ import createDebug from 'debug';
4
+ import { normalizeRequestId } from './utils.mjs';
6
5
  import 'node:url';
7
6
  import 'node:module';
8
7
  import 'node:fs';
9
8
  import 'pathe';
9
+
10
+ function createHmrEmitter() {
11
+ const emitter = new EventEmitter();
12
+ return emitter;
13
+ }
14
+ function viteNodeHmrPlugin() {
15
+ const emitter = createHmrEmitter();
16
+ return {
17
+ name: "vite-node:hmr",
18
+ config() {
19
+ if (process.platform === "darwin" && process.env.VITE_TEST_WATCHER_DEBUG) {
20
+ return {
21
+ server: {
22
+ watch: {
23
+ useFsEvents: false,
24
+ usePolling: false
25
+ }
26
+ }
27
+ };
28
+ }
29
+ },
30
+ configureServer(server) {
31
+ const _send = server.ws.send;
32
+ server.emitter = emitter;
33
+ server.ws.send = function(payload) {
34
+ _send(payload);
35
+ emitter.emit("message", payload);
36
+ };
37
+ if (process.env.VITE_TEST_WATCHER_DEBUG) {
38
+ server.watcher.on("ready", () => {
39
+ console.log("[debug] watcher is ready");
40
+ });
41
+ }
42
+ }
43
+ };
44
+ }
45
+
46
+ const debugHmr = createDebug("vite-node:hmr");
47
+ const cache = /* @__PURE__ */ new WeakMap();
48
+ function getCache(runner) {
49
+ if (!cache.has(runner)) {
50
+ cache.set(runner, {
51
+ hotModulesMap: /* @__PURE__ */ new Map(),
52
+ dataMap: /* @__PURE__ */ new Map(),
53
+ disposeMap: /* @__PURE__ */ new Map(),
54
+ pruneMap: /* @__PURE__ */ new Map(),
55
+ customListenersMap: /* @__PURE__ */ new Map(),
56
+ ctxToListenersMap: /* @__PURE__ */ new Map(),
57
+ messageBuffer: [],
58
+ isFirstUpdate: false,
59
+ pending: false,
60
+ queued: []
61
+ });
62
+ }
63
+ return cache.get(runner);
64
+ }
65
+ function sendMessageBuffer(runner, emitter) {
66
+ const maps = getCache(runner);
67
+ maps.messageBuffer.forEach((msg) => emitter.emit("custom", msg));
68
+ maps.messageBuffer.length = 0;
69
+ }
70
+ async function reload(runner, files) {
71
+ Array.from(runner.moduleCache.keys()).forEach((fsPath) => {
72
+ if (!fsPath.includes("node_modules"))
73
+ runner.moduleCache.delete(fsPath);
74
+ });
75
+ return Promise.all(files.map((file) => runner.executeId(file)));
76
+ }
77
+ async function notifyListeners(runner, event, data) {
78
+ const maps = getCache(runner);
79
+ const cbs = maps.customListenersMap.get(event);
80
+ if (cbs)
81
+ await Promise.all(cbs.map((cb) => cb(data)));
82
+ }
83
+ async function queueUpdate(runner, p) {
84
+ const maps = getCache(runner);
85
+ maps.queued.push(p);
86
+ if (!maps.pending) {
87
+ maps.pending = true;
88
+ await Promise.resolve();
89
+ maps.pending = false;
90
+ const loading = [...maps.queued];
91
+ maps.queued = [];
92
+ (await Promise.all(loading)).forEach((fn) => fn && fn());
93
+ }
94
+ }
95
+ async function fetchUpdate(runner, { path, acceptedPath }) {
96
+ path = normalizeRequestId(path);
97
+ acceptedPath = normalizeRequestId(acceptedPath);
98
+ const maps = getCache(runner);
99
+ const mod = maps.hotModulesMap.get(path);
100
+ if (!mod) {
101
+ return;
102
+ }
103
+ const isSelfUpdate = path === acceptedPath;
104
+ let fetchedModule;
105
+ const qualifiedCallbacks = mod.callbacks.filter(
106
+ ({ deps }) => deps.includes(acceptedPath)
107
+ );
108
+ if (isSelfUpdate || qualifiedCallbacks.length > 0) {
109
+ const disposer = maps.disposeMap.get(acceptedPath);
110
+ if (disposer)
111
+ await disposer(maps.dataMap.get(acceptedPath));
112
+ try {
113
+ [fetchedModule] = await reload(runner, [acceptedPath]);
114
+ } catch (e) {
115
+ warnFailedFetch(e, acceptedPath);
116
+ }
117
+ }
118
+ return () => {
119
+ for (const { deps, fn } of qualifiedCallbacks)
120
+ fn(deps.map((dep) => dep === acceptedPath ? fetchedModule : void 0));
121
+ const loggedPath = isSelfUpdate ? path : `${acceptedPath} via ${path}`;
122
+ console.log(`${c.cyan("[vite-node]")} hot updated: ${loggedPath}`);
123
+ };
124
+ }
125
+ function warnFailedFetch(err, path) {
126
+ if (!err.message.match("fetch"))
127
+ console.error(err);
128
+ console.error(
129
+ `[hmr] Failed to reload ${path}. This could be due to syntax errors or importing non-existent modules. (see errors above)`
130
+ );
131
+ }
132
+ async function handleMessage(runner, emitter, files, payload) {
133
+ const maps = getCache(runner);
134
+ switch (payload.type) {
135
+ case "connected":
136
+ sendMessageBuffer(runner, emitter);
137
+ break;
138
+ case "update":
139
+ await notifyListeners(runner, "vite:beforeUpdate", payload);
140
+ await Promise.all(payload.updates.map((update) => {
141
+ if (update.type === "js-update")
142
+ return queueUpdate(runner, fetchUpdate(runner, update));
143
+ console.error(`${c.cyan("[vite-node]")} no support css hmr.}`);
144
+ return null;
145
+ }));
146
+ await notifyListeners(runner, "vite:afterUpdate", payload);
147
+ break;
148
+ case "full-reload":
149
+ await notifyListeners(runner, "vite:beforeFullReload", payload);
150
+ maps.customListenersMap.delete("vite:beforeFullReload");
151
+ await reload(runner, files);
152
+ break;
153
+ case "custom":
154
+ await notifyListeners(runner, payload.event, payload.data);
155
+ break;
156
+ case "prune":
157
+ await notifyListeners(runner, "vite:beforePrune", payload);
158
+ payload.paths.forEach((path) => {
159
+ const fn = maps.pruneMap.get(path);
160
+ if (fn)
161
+ fn(maps.dataMap.get(path));
162
+ });
163
+ break;
164
+ case "error": {
165
+ await notifyListeners(runner, "vite:error", payload);
166
+ const err = payload.err;
167
+ console.error(`${c.cyan("[vite-node]")} Internal Server Error
168
+ ${err.message}
169
+ ${err.stack}`);
170
+ break;
171
+ }
172
+ }
173
+ }
174
+ function createHotContext(runner, emitter, files, ownerPath) {
175
+ debugHmr("createHotContext", ownerPath);
176
+ const maps = getCache(runner);
177
+ if (!maps.dataMap.has(ownerPath))
178
+ maps.dataMap.set(ownerPath, {});
179
+ const mod = maps.hotModulesMap.get(ownerPath);
180
+ if (mod)
181
+ mod.callbacks = [];
182
+ const newListeners = /* @__PURE__ */ new Map();
183
+ maps.ctxToListenersMap.set(ownerPath, newListeners);
184
+ function acceptDeps(deps, callback = () => {
185
+ }) {
186
+ const mod2 = maps.hotModulesMap.get(ownerPath) || {
187
+ id: ownerPath,
188
+ callbacks: []
189
+ };
190
+ mod2.callbacks.push({
191
+ deps,
192
+ fn: callback
193
+ });
194
+ maps.hotModulesMap.set(ownerPath, mod2);
195
+ }
196
+ const hot = {
197
+ get data() {
198
+ return maps.dataMap.get(ownerPath);
199
+ },
200
+ acceptExports(_, callback) {
201
+ acceptDeps([ownerPath], callback && (([mod2]) => callback(mod2)));
202
+ },
203
+ accept(deps, callback) {
204
+ if (typeof deps === "function" || !deps) {
205
+ acceptDeps([ownerPath], ([mod2]) => deps && deps(mod2));
206
+ } else if (typeof deps === "string") {
207
+ acceptDeps([deps], ([mod2]) => callback && callback(mod2));
208
+ } else if (Array.isArray(deps)) {
209
+ acceptDeps(deps, callback);
210
+ } else {
211
+ throw new TypeError("invalid hot.accept() usage.");
212
+ }
213
+ },
214
+ dispose(cb) {
215
+ maps.disposeMap.set(ownerPath, cb);
216
+ },
217
+ prune(cb) {
218
+ maps.pruneMap.set(ownerPath, cb);
219
+ },
220
+ invalidate() {
221
+ notifyListeners(runner, "vite:invalidate", { path: ownerPath, message: void 0 });
222
+ return reload(runner, files);
223
+ },
224
+ on(event, cb) {
225
+ const addToMap = (map) => {
226
+ const existing = map.get(event) || [];
227
+ existing.push(cb);
228
+ map.set(event, existing);
229
+ };
230
+ addToMap(maps.customListenersMap);
231
+ addToMap(newListeners);
232
+ },
233
+ send(event, data) {
234
+ maps.messageBuffer.push(JSON.stringify({ type: "custom", event, data }));
235
+ sendMessageBuffer(runner, emitter);
236
+ }
237
+ };
238
+ return hot;
239
+ }
240
+
241
+ export { createHmrEmitter, createHotContext, getCache, handleMessage, reload, sendMessageBuffer, viteNodeHmrPlugin };
@@ -1,4 +1,4 @@
1
- import { E as EncodedSourceMap } from './types.d-7442d07f.js';
1
+ import { E as EncodedSourceMap } from './trace-mapping.d-e677e8f4.js';
2
2
 
3
3
  type HMRPayload =
4
4
  | ConnectedPayload
@@ -69,6 +69,18 @@ interface CustomEventMap {
69
69
  'vite:beforeFullReload': FullReloadPayload
70
70
  'vite:error': ErrorPayload
71
71
  'vite:invalidate': InvalidatePayload
72
+ 'vite:ws:connect': WebSocketConnectionPayload
73
+ 'vite:ws:disconnect': WebSocketConnectionPayload
74
+ }
75
+
76
+ interface WebSocketConnectionPayload {
77
+ /**
78
+ * @experimental
79
+ * We expose this instance experimentally to see potential usage.
80
+ * This might be removed in the future if we didn't find reasonable use cases.
81
+ * If you find this useful, please open an issue with details so we can discuss and make it stable API.
82
+ */
83
+ webSocket: WebSocket
72
84
  }
73
85
 
74
86
  interface InvalidatePayload {
@@ -283,4 +295,4 @@ interface DebuggerOptions {
283
295
  loadDumppedModules?: boolean;
284
296
  }
285
297
 
286
- export { Arrayable as A, CreateHotContextFunction as C, DepsHandlingOptions as D, FetchResult as F, HotContext as H, ModuleCacheMap as M, Nullable as N, RawSourceMap as R, StartOfSourceMap as S, ViteNodeRunnerOptions as V, Awaitable as a, FetchFunction as b, ResolveIdFunction as c, ModuleCache as d, ViteNodeResolveId as e, ViteNodeServerOptions as f, DebuggerOptions as g, CustomEventMap as h, ViteNodeRunner as i, HMRPayload as j, DEFAULT_REQUEST_STUBS as k };
298
+ export { Arrayable as A, CustomEventMap as C, DebuggerOptions as D, FetchResult as F, HMRPayload as H, ModuleCacheMap as M, Nullable as N, RawSourceMap as R, StartOfSourceMap as S, ViteNodeServerOptions as V, ViteNodeRunner as a, HotContext as b, DepsHandlingOptions as c, ViteNodeResolveId as d, DEFAULT_REQUEST_STUBS as e, Awaitable as f, FetchFunction as g, ResolveIdFunction as h, CreateHotContextFunction as i, ModuleCache as j, ViteNodeRunnerOptions as k };
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { A as Arrayable, a as Awaitable, C as CreateHotContextFunction, g as DebuggerOptions, D as DepsHandlingOptions, b as FetchFunction, F as FetchResult, H as HotContext, d as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, c as ResolveIdFunction, S as StartOfSourceMap, e as ViteNodeResolveId, V as ViteNodeRunnerOptions, f as ViteNodeServerOptions } from './types-2dc895bd.js';
2
- export { D as DecodedSourceMap, E as EncodedSourceMap } from './types.d-7442d07f.js';
1
+ export { A as Arrayable, f as Awaitable, i as CreateHotContextFunction, D as DebuggerOptions, c as DepsHandlingOptions, g as FetchFunction, F as FetchResult, b as HotContext, j as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, h as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, k as ViteNodeRunnerOptions, V as ViteNodeServerOptions } from './index-6fb787b2.js';
2
+ export { D as DecodedSourceMap, E as EncodedSourceMap, S as SourceMapInput } from './trace-mapping.d-e677e8f4.js';
package/dist/server.cjs CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var perf_hooks = require('perf_hooks');
6
4
  var fs = require('fs');
7
5
  var pathe = require('pathe');
@@ -15,11 +13,6 @@ require('node:url');
15
13
  require('module');
16
14
  require('path');
17
15
 
18
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
19
-
20
- var createDebug__default = /*#__PURE__*/_interopDefaultLegacy(createDebug);
21
- var c__default = /*#__PURE__*/_interopDefaultLegacy(c);
22
-
23
16
  const ESM_EXT_RE = /\.(es|esm|esm-browser|esm-bundler|es6|module)\.js$/;
24
17
  const ESM_FOLDER_RE = /\/(es|esm)\/(.*\.js)$/;
25
18
  const defaultInline = [
@@ -126,9 +119,9 @@ class Debugger {
126
119
  this.dumpDir = pathe.resolve(root, options.dumpModules === true ? ".vite-node/dump" : options.dumpModules);
127
120
  if (this.dumpDir) {
128
121
  if (options.loadDumppedModules)
129
- console.info(c__default["default"].gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
122
+ console.info(c.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`));
130
123
  else
131
- console.info(c__default["default"].gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
124
+ console.info(c.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`));
132
125
  }
133
126
  this.initPromise = this.clearDump();
134
127
  }
@@ -184,7 +177,7 @@ ${result.code}`, "utf-8");
184
177
  }
185
178
  }
186
179
 
187
- const debugRequest = createDebug__default["default"]("vite-node:server:request");
180
+ const debugRequest = createDebug("vite-node:server:request");
188
181
  class ViteNodeServer {
189
182
  constructor(server, options = {}) {
190
183
  this.server = server;
@@ -249,7 +242,7 @@ class ViteNodeServer {
249
242
  });
250
243
  }
251
244
  async resolveId(id, importer, transformMode) {
252
- if (importer && !importer.startsWith(this.server.config.root))
245
+ if (importer && !importer.startsWith(utils.withTrailingSlash(this.server.config.root)))
253
246
  importer = pathe.resolve(this.server.config.root, importer);
254
247
  const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr");
255
248
  return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
@@ -313,7 +306,7 @@ class ViteNodeServer {
313
306
  let result;
314
307
  const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir;
315
308
  if (cacheDir && id.includes(cacheDir)) {
316
- if (!id.startsWith(this.server.config.root))
309
+ if (!id.startsWith(utils.withTrailingSlash(this.server.config.root)))
317
310
  id = pathe.join(this.server.config.root, id);
318
311
  const timeout = setTimeout(() => {
319
312
  throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { TransformResult, ViteDevServer } from 'vite';
2
- import { E as EncodedSourceMap } from './types.d-7442d07f.js';
3
- import { g as DebuggerOptions, D as DepsHandlingOptions, f as ViteNodeServerOptions, F as FetchResult, e as ViteNodeResolveId } from './types-2dc895bd.js';
2
+ import { D as DebuggerOptions, c as DepsHandlingOptions, V as ViteNodeServerOptions, F as FetchResult, d as ViteNodeResolveId } from './index-6fb787b2.js';
3
+ import { E as EncodedSourceMap } from './trace-mapping.d-e677e8f4.js';
4
4
 
5
5
  declare class Debugger {
6
6
  options: DebuggerOptions;
package/dist/server.mjs CHANGED
@@ -3,7 +3,7 @@ import { existsSync, promises } from 'node:fs';
3
3
  import { join, resolve, relative, normalize } from 'pathe';
4
4
  import createDebug from 'debug';
5
5
  import { isValidNodeImport } from 'mlly';
6
- import { isNodeBuiltin, slash, toArray, normalizeModuleId, toFilePath } from './utils.mjs';
6
+ import { isNodeBuiltin, slash, toArray, withTrailingSlash, normalizeModuleId, toFilePath } from './utils.mjs';
7
7
  import { KNOWN_ASSET_TYPES } from './constants.mjs';
8
8
  import c from 'picocolors';
9
9
  import { withInlineSourcemap } from './source-map.mjs';
@@ -240,7 +240,7 @@ class ViteNodeServer {
240
240
  });
241
241
  }
242
242
  async resolveId(id, importer, transformMode) {
243
- if (importer && !importer.startsWith(this.server.config.root))
243
+ if (importer && !importer.startsWith(withTrailingSlash(this.server.config.root)))
244
244
  importer = resolve(this.server.config.root, importer);
245
245
  const mode = transformMode ?? (importer && this.getTransformMode(importer) || "ssr");
246
246
  return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === "ssr" });
@@ -304,7 +304,7 @@ class ViteNodeServer {
304
304
  let result;
305
305
  const cacheDir = (_a = this.options.deps) == null ? void 0 : _a.cacheDir;
306
306
  if (cacheDir && id.includes(cacheDir)) {
307
- if (!id.startsWith(this.server.config.root))
307
+ if (!id.startsWith(withTrailingSlash(this.server.config.root)))
308
308
  id = join(this.server.config.root, id);
309
309
  const timeout = setTimeout(() => {
310
310
  throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`);
@@ -1,15 +1,11 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var pathe = require('pathe');
4
+ var utils = require('./utils.cjs');
6
5
  var path = require('path');
7
6
  var fs = require('fs');
8
-
9
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
10
-
11
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
12
- var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
7
+ require('node:url');
8
+ require('module');
13
9
 
14
10
  const comma = ','.charCodeAt(0);
15
11
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
@@ -597,8 +593,8 @@ retrieveFileHandlers.push((path2) => {
597
593
  return fileContentsCache[path2];
598
594
  let contents = "";
599
595
  try {
600
- if (fs__default["default"].existsSync(path2))
601
- contents = fs__default["default"].readFileSync(path2, "utf8");
596
+ if (fs.existsSync(path2))
597
+ contents = fs.readFileSync(path2, "utf8");
602
598
  } catch (er) {
603
599
  }
604
600
  return fileContentsCache[path2] = contents;
@@ -606,15 +602,15 @@ retrieveFileHandlers.push((path2) => {
606
602
  function supportRelativeURL(file, url) {
607
603
  if (!file)
608
604
  return url;
609
- const dir = path__default["default"].dirname(file);
605
+ const dir = path.dirname(file);
610
606
  const match = /^\w+:\/\/[^\/]*/.exec(dir);
611
607
  let protocol = match ? match[0] : "";
612
608
  const startPath = dir.slice(protocol.length);
613
609
  if (protocol && /^\/\w\:/.test(startPath)) {
614
610
  protocol += "/";
615
- return protocol + path__default["default"].resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
611
+ return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
616
612
  }
617
- return protocol + path__default["default"].resolve(dir.slice(protocol.length), url);
613
+ return protocol + path.resolve(dir.slice(protocol.length), url);
618
614
  }
619
615
  function retrieveSourceMapURL(source) {
620
616
  const fileData = retrieveFile(source);
@@ -871,15 +867,17 @@ function withInlineSourcemap(result, options) {
871
867
  let code = result.code;
872
868
  if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
873
869
  return result;
874
- map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => {
875
- if (!source)
870
+ if ("sources" in map) {
871
+ map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => {
872
+ if (!source)
873
+ return source;
874
+ if (pathe.isAbsolute(source)) {
875
+ const actualPath = !source.startsWith(utils.withTrailingSlash(options.root)) && source.startsWith("/") ? pathe.resolve(options.root, source.slice(1)) : source;
876
+ return pathe.relative(pathe.dirname(options.filepath), actualPath);
877
+ }
876
878
  return source;
877
- if (pathe.isAbsolute(source)) {
878
- const actualPath = !source.startsWith(options.root) && source.startsWith("/") ? pathe.resolve(options.root, source.slice(1)) : source;
879
- return pathe.relative(pathe.dirname(options.filepath), actualPath);
880
- }
881
- return source;
882
- });
879
+ });
880
+ }
883
881
  const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
884
882
  while (OTHER_SOURCE_MAP_REGEXP.test(code))
885
883
  code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
@@ -1,5 +1,5 @@
1
1
  import { TransformResult } from 'vite';
2
- import { E as EncodedSourceMap } from './types.d-7442d07f.js';
2
+ import { E as EncodedSourceMap } from './trace-mapping.d-e677e8f4.js';
3
3
 
4
4
  interface InstallSourceMapSupportOptions {
5
5
  getSourceMap: (source: string) => EncodedSourceMap | null | undefined;
@@ -1,6 +1,9 @@
1
1
  import { isAbsolute, resolve as resolve$2, relative, dirname } from 'pathe';
2
+ import { withTrailingSlash } from './utils.mjs';
2
3
  import path from 'node:path';
3
4
  import fs from 'node:fs';
5
+ import 'node:url';
6
+ import 'node:module';
4
7
 
5
8
  const comma = ','.charCodeAt(0);
6
9
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
@@ -862,15 +865,17 @@ function withInlineSourcemap(result, options) {
862
865
  let code = result.code;
863
866
  if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
864
867
  return result;
865
- map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => {
866
- if (!source)
868
+ if ("sources" in map) {
869
+ map.sources = (_a = map.sources) == null ? void 0 : _a.map((source) => {
870
+ if (!source)
871
+ return source;
872
+ if (isAbsolute(source)) {
873
+ const actualPath = !source.startsWith(withTrailingSlash(options.root)) && source.startsWith("/") ? resolve$2(options.root, source.slice(1)) : source;
874
+ return relative(dirname(options.filepath), actualPath);
875
+ }
867
876
  return source;
868
- if (isAbsolute(source)) {
869
- const actualPath = !source.startsWith(options.root) && source.startsWith("/") ? resolve$2(options.root, source.slice(1)) : source;
870
- return relative(dirname(options.filepath), actualPath);
871
- }
872
- return source;
873
- });
877
+ });
878
+ }
874
879
  const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
875
880
  while (OTHER_SOURCE_MAP_REGEXP.test(code))
876
881
  code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
@@ -0,0 +1,54 @@
1
+ declare type GeneratedColumn = number;
2
+ declare type SourcesIndex = number;
3
+ declare type SourceLine = number;
4
+ declare type SourceColumn = number;
5
+ declare type NamesIndex = number;
6
+ declare type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex];
7
+
8
+ interface SourceMapV3 {
9
+ file?: string | null;
10
+ names: string[];
11
+ sourceRoot?: string;
12
+ sources: (string | null)[];
13
+ sourcesContent?: (string | null)[];
14
+ version: 3;
15
+ }
16
+ interface EncodedSourceMap extends SourceMapV3 {
17
+ mappings: string;
18
+ }
19
+ interface DecodedSourceMap extends SourceMapV3 {
20
+ mappings: SourceMapSegment[][];
21
+ }
22
+ declare type SourceMapInput = string | Ro<EncodedSourceMap> | Ro<DecodedSourceMap> | TraceMap;
23
+ declare abstract class SourceMap {
24
+ version: SourceMapV3['version'];
25
+ file: SourceMapV3['file'];
26
+ names: SourceMapV3['names'];
27
+ sourceRoot: SourceMapV3['sourceRoot'];
28
+ sources: SourceMapV3['sources'];
29
+ sourcesContent: SourceMapV3['sourcesContent'];
30
+ resolvedSources: SourceMapV3['sources'];
31
+ }
32
+ declare type Ro<T> = T extends Array<infer V> ? V[] | Readonly<V[]> | RoArray<V> | Readonly<RoArray<V>> : T extends object ? T | Readonly<T> | RoObject<T> | Readonly<RoObject<T>> : T;
33
+ declare type RoArray<T> = Ro<T>[];
34
+ declare type RoObject<T> = {
35
+ [K in keyof T]: T[K] | Ro<T[K]>;
36
+ };
37
+
38
+ declare class TraceMap implements SourceMap {
39
+ version: SourceMapV3['version'];
40
+ file: SourceMapV3['file'];
41
+ names: SourceMapV3['names'];
42
+ sourceRoot: SourceMapV3['sourceRoot'];
43
+ sources: SourceMapV3['sources'];
44
+ sourcesContent: SourceMapV3['sourcesContent'];
45
+ resolvedSources: string[];
46
+ private _encoded;
47
+ private _decoded;
48
+ private _decodedMemo;
49
+ private _bySources;
50
+ private _bySourceMemos;
51
+ constructor(map: SourceMapInput, mapUrl?: string | null);
52
+ }
53
+
54
+ export { DecodedSourceMap as D, EncodedSourceMap as E, SourceMapInput as S };
package/dist/types.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { A as Arrayable, a as Awaitable, C as CreateHotContextFunction, g as DebuggerOptions, D as DepsHandlingOptions, b as FetchFunction, F as FetchResult, H as HotContext, d as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, c as ResolveIdFunction, S as StartOfSourceMap, e as ViteNodeResolveId, V as ViteNodeRunnerOptions, f as ViteNodeServerOptions } from './types-2dc895bd.js';
2
- export { D as DecodedSourceMap, E as EncodedSourceMap } from './types.d-7442d07f.js';
1
+ export { A as Arrayable, f as Awaitable, i as CreateHotContextFunction, D as DebuggerOptions, c as DepsHandlingOptions, g as FetchFunction, F as FetchResult, b as HotContext, j as ModuleCache, M as ModuleCacheMap, N as Nullable, R as RawSourceMap, h as ResolveIdFunction, S as StartOfSourceMap, d as ViteNodeResolveId, k as ViteNodeRunnerOptions, V as ViteNodeServerOptions } from './index-6fb787b2.js';
2
+ export { D as DecodedSourceMap, E as EncodedSourceMap, S as SourceMapInput } from './trace-mapping.d-e677e8f4.js';
package/dist/utils.cjs CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
3
  var node_url = require('node:url');
6
4
  var module$1 = require('module');
7
5
  var fs = require('fs');
@@ -17,7 +15,7 @@ function slash(str) {
17
15
  }
18
16
  const VALID_ID_PREFIX = "/@id/";
19
17
  function normalizeRequestId(id, base) {
20
- if (base && id.startsWith(base))
18
+ if (base && id.startsWith(withTrailingSlash(base)))
21
19
  id = `/${id.slice(base.length)}`;
22
20
  if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id)))
23
21
  id = id.replace(driveOppositeRegext, `${drive}$1`);
@@ -67,11 +65,11 @@ function toFilePath(id, root) {
67
65
  let { absolute, exists } = (() => {
68
66
  if (id.startsWith("/@fs/"))
69
67
  return { absolute: id.slice(4), exists: true };
70
- if (!id.startsWith(root) && id.startsWith("/")) {
68
+ if (!id.startsWith(withTrailingSlash(root)) && id.startsWith("/")) {
71
69
  const resolved = pathe.resolve(root, id.slice(1));
72
70
  if (fs.existsSync(cleanUrl(resolved)))
73
71
  return { absolute: resolved, exists: true };
74
- } else if (id.startsWith(root) && fs.existsSync(cleanUrl(id))) {
72
+ } else if (id.startsWith(withTrailingSlash(root)) && fs.existsSync(cleanUrl(id))) {
75
73
  return { absolute: id, exists: true };
76
74
  }
77
75
  return { absolute: id, exists: false };
@@ -122,6 +120,11 @@ function traverseBetweenDirs(longerDir, shorterDir, cb) {
122
120
  longerDir = pathe.dirname(longerDir);
123
121
  }
124
122
  }
123
+ function withTrailingSlash(path) {
124
+ if (path[path.length - 1] !== "/")
125
+ return `${path}/`;
126
+ return path;
127
+ }
125
128
  function createImportMetaEnvProxy() {
126
129
  const booleanKeys = [
127
130
  "DEV",
@@ -164,3 +167,4 @@ exports.setCacheData = setCacheData;
164
167
  exports.slash = slash;
165
168
  exports.toArray = toArray;
166
169
  exports.toFilePath = toFilePath;
170
+ exports.withTrailingSlash = withTrailingSlash;
package/dist/utils.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { N as Nullable, A as Arrayable } from './types-2dc895bd.js';
2
- import './types.d-7442d07f.js';
1
+ import { N as Nullable, A as Arrayable } from './index-6fb787b2.js';
2
+ import './trace-mapping.d-e677e8f4.js';
3
3
 
4
4
  declare const isWindows: boolean;
5
5
  declare function slash(str: string): string;
@@ -24,6 +24,7 @@ declare function isNodeBuiltin(id: string): boolean;
24
24
  declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
25
25
  declare function getCachedData<T>(cache: Map<string, T>, basedir: string, originalBasedir: string): NonNullable<T> | undefined;
26
26
  declare function setCacheData<T>(cache: Map<string, T>, data: T, basedir: string, originalBasedir: string): void;
27
+ declare function withTrailingSlash(path: string): string;
27
28
  declare function createImportMetaEnvProxy(): NodeJS.ProcessEnv;
28
29
 
29
- export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath };
30
+ export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath, withTrailingSlash };
package/dist/utils.mjs CHANGED
@@ -13,7 +13,7 @@ function slash(str) {
13
13
  }
14
14
  const VALID_ID_PREFIX = "/@id/";
15
15
  function normalizeRequestId(id, base) {
16
- if (base && id.startsWith(base))
16
+ if (base && id.startsWith(withTrailingSlash(base)))
17
17
  id = `/${id.slice(base.length)}`;
18
18
  if (driveRegexp && !(driveRegexp == null ? void 0 : driveRegexp.test(id)) && (driveOppositeRegext == null ? void 0 : driveOppositeRegext.test(id)))
19
19
  id = id.replace(driveOppositeRegext, `${drive}$1`);
@@ -63,11 +63,11 @@ function toFilePath(id, root) {
63
63
  let { absolute, exists } = (() => {
64
64
  if (id.startsWith("/@fs/"))
65
65
  return { absolute: id.slice(4), exists: true };
66
- if (!id.startsWith(root) && id.startsWith("/")) {
66
+ if (!id.startsWith(withTrailingSlash(root)) && id.startsWith("/")) {
67
67
  const resolved = resolve(root, id.slice(1));
68
68
  if (existsSync(cleanUrl(resolved)))
69
69
  return { absolute: resolved, exists: true };
70
- } else if (id.startsWith(root) && existsSync(cleanUrl(id))) {
70
+ } else if (id.startsWith(withTrailingSlash(root)) && existsSync(cleanUrl(id))) {
71
71
  return { absolute: id, exists: true };
72
72
  }
73
73
  return { absolute: id, exists: false };
@@ -118,6 +118,11 @@ function traverseBetweenDirs(longerDir, shorterDir, cb) {
118
118
  longerDir = dirname(longerDir);
119
119
  }
120
120
  }
121
+ function withTrailingSlash(path) {
122
+ if (path[path.length - 1] !== "/")
123
+ return `${path}/`;
124
+ return path;
125
+ }
121
126
  function createImportMetaEnvProxy() {
122
127
  const booleanKeys = [
123
128
  "DEV",
@@ -144,4 +149,4 @@ function createImportMetaEnvProxy() {
144
149
  });
145
150
  }
146
151
 
147
- export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath };
152
+ export { VALID_ID_PREFIX, cleanUrl, createImportMetaEnvProxy, getCachedData, hashRE, isInternalRequest, isNodeBuiltin, isPrimitive, isWindows, normalizeModuleId, normalizeRequestId, queryRE, setCacheData, slash, toArray, toFilePath, withTrailingSlash };