vite-node 5.0.0 → 5.2.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.
Files changed (43) hide show
  1. package/dist/cli.d.mts +21 -0
  2. package/dist/cli.mjs +145 -0
  3. package/dist/{client.js → client-CyS7w_FB.mjs} +54 -87
  4. package/dist/client.d.mts +2 -0
  5. package/dist/client.mjs +5 -0
  6. package/dist/{constants.js → constants-DRkacFwN.mjs} +3 -1
  7. package/dist/{constants.d.ts → constants.d.mts} +3 -2
  8. package/dist/constants.mjs +3 -0
  9. package/dist/dist-B2ebky9O.mjs +85 -0
  10. package/dist/{chunk-hmr.js → hmr-qEG3qSgW.mjs} +17 -29
  11. package/dist/hmr.d.mts +57 -0
  12. package/dist/hmr.mjs +5 -0
  13. package/dist/index.d.mts +2 -0
  14. package/dist/index.mjs +3 -0
  15. package/dist/{server.js → server-BWywEVuB.mjs} +52 -87
  16. package/dist/server.d.mts +60 -0
  17. package/dist/server.mjs +7 -0
  18. package/dist/source-map-DQLD3K8K.mjs +737 -0
  19. package/dist/{source-map.d.ts → source-map.d.mts} +9 -8
  20. package/dist/source-map.mjs +4 -0
  21. package/dist/types-55T_-8KG.mjs +1 -0
  22. package/dist/types-Dtew7m7O.d.mts +212 -0
  23. package/dist/types.d.mts +2 -0
  24. package/dist/types.mjs +3 -0
  25. package/dist/{utils.js → utils-ExLpYVUV.mjs} +10 -18
  26. package/dist/{utils.d.ts → utils.d.mts} +7 -7
  27. package/dist/utils.mjs +3 -0
  28. package/package.json +25 -32
  29. package/dist/chunk-index.js +0 -82
  30. package/dist/cli.d.ts +0 -19
  31. package/dist/cli.js +0 -156
  32. package/dist/client.d.ts +0 -2
  33. package/dist/hmr.d.ts +0 -55
  34. package/dist/hmr.js +0 -10
  35. package/dist/index.d-D6Pqey3g.d.ts +0 -367
  36. package/dist/index.d.ts +0 -2
  37. package/dist/index.js +0 -1
  38. package/dist/server.d.ts +0 -58
  39. package/dist/source-map.js +0 -919
  40. package/dist/trace-mapping.d-BWFx6tPc.d.ts +0 -62
  41. package/dist/types.d.ts +0 -2
  42. package/dist/types.js +0 -1
  43. package/vite-node.js +0 -2
@@ -1,919 +0,0 @@
1
- import { Buffer } from 'node:buffer';
2
- import { isAbsolute, resolve as resolve$1, relative, dirname } from 'pathe';
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import process from 'node:process';
6
- import { withTrailingSlash } from './utils.js';
7
- import 'node:module';
8
- import 'node:url';
9
-
10
- // src/vlq.ts
11
- var comma = ",".charCodeAt(0);
12
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
13
- var intToChar = new Uint8Array(64);
14
- var charToInt = new Uint8Array(128);
15
- for (let i = 0; i < chars.length; i++) {
16
- const c = chars.charCodeAt(i);
17
- intToChar[i] = c;
18
- charToInt[c] = i;
19
- }
20
- function decodeInteger(reader, relative) {
21
- let value = 0;
22
- let shift = 0;
23
- let integer = 0;
24
- do {
25
- const c = reader.next();
26
- integer = charToInt[c];
27
- value |= (integer & 31) << shift;
28
- shift += 5;
29
- } while (integer & 32);
30
- const shouldNegate = value & 1;
31
- value >>>= 1;
32
- if (shouldNegate) {
33
- value = -2147483648 | -value;
34
- }
35
- return relative + value;
36
- }
37
- function hasMoreVlq(reader, max) {
38
- if (reader.pos >= max) return false;
39
- return reader.peek() !== comma;
40
- }
41
- var StringReader = class {
42
- constructor(buffer) {
43
- this.pos = 0;
44
- this.buffer = buffer;
45
- }
46
- next() {
47
- return this.buffer.charCodeAt(this.pos++);
48
- }
49
- peek() {
50
- return this.buffer.charCodeAt(this.pos);
51
- }
52
- indexOf(char) {
53
- const { buffer, pos } = this;
54
- const idx = buffer.indexOf(char, pos);
55
- return idx === -1 ? buffer.length : idx;
56
- }
57
- };
58
-
59
- // src/sourcemap-codec.ts
60
- function decode(mappings) {
61
- const { length } = mappings;
62
- const reader = new StringReader(mappings);
63
- const decoded = [];
64
- let genColumn = 0;
65
- let sourcesIndex = 0;
66
- let sourceLine = 0;
67
- let sourceColumn = 0;
68
- let namesIndex = 0;
69
- do {
70
- const semi = reader.indexOf(";");
71
- const line = [];
72
- let sorted = true;
73
- let lastCol = 0;
74
- genColumn = 0;
75
- while (reader.pos < semi) {
76
- let seg;
77
- genColumn = decodeInteger(reader, genColumn);
78
- if (genColumn < lastCol) sorted = false;
79
- lastCol = genColumn;
80
- if (hasMoreVlq(reader, semi)) {
81
- sourcesIndex = decodeInteger(reader, sourcesIndex);
82
- sourceLine = decodeInteger(reader, sourceLine);
83
- sourceColumn = decodeInteger(reader, sourceColumn);
84
- if (hasMoreVlq(reader, semi)) {
85
- namesIndex = decodeInteger(reader, namesIndex);
86
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
87
- } else {
88
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
89
- }
90
- } else {
91
- seg = [genColumn];
92
- }
93
- line.push(seg);
94
- reader.pos++;
95
- }
96
- if (!sorted) sort(line);
97
- decoded.push(line);
98
- reader.pos = semi + 1;
99
- } while (reader.pos <= length);
100
- return decoded;
101
- }
102
- function sort(line) {
103
- line.sort(sortComparator$1);
104
- }
105
- function sortComparator$1(a, b) {
106
- return a[0] - b[0];
107
- }
108
-
109
- // Matches the scheme of a URL, eg "http://"
110
- const schemeRegex = /^[\w+.-]+:\/\//;
111
- /**
112
- * Matches the parts of a URL:
113
- * 1. Scheme, including ":", guaranteed.
114
- * 2. User/password, including "@", optional.
115
- * 3. Host, guaranteed.
116
- * 4. Port, including ":", optional.
117
- * 5. Path, including "/", optional.
118
- * 6. Query, including "?", optional.
119
- * 7. Hash, including "#", optional.
120
- */
121
- const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
122
- /**
123
- * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
124
- * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
125
- *
126
- * 1. Host, optional.
127
- * 2. Path, which may include "/", guaranteed.
128
- * 3. Query, including "?", optional.
129
- * 4. Hash, including "#", optional.
130
- */
131
- const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
132
- function isAbsoluteUrl(input) {
133
- return schemeRegex.test(input);
134
- }
135
- function isSchemeRelativeUrl(input) {
136
- return input.startsWith('//');
137
- }
138
- function isAbsolutePath(input) {
139
- return input.startsWith('/');
140
- }
141
- function isFileUrl(input) {
142
- return input.startsWith('file:');
143
- }
144
- function isRelative(input) {
145
- return /^[.?#]/.test(input);
146
- }
147
- function parseAbsoluteUrl(input) {
148
- const match = urlRegex.exec(input);
149
- return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
150
- }
151
- function parseFileUrl(input) {
152
- const match = fileRegex.exec(input);
153
- const path = match[2];
154
- return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
155
- }
156
- function makeUrl(scheme, user, host, port, path, query, hash) {
157
- return {
158
- scheme,
159
- user,
160
- host,
161
- port,
162
- path,
163
- query,
164
- hash,
165
- type: 7 /* Absolute */,
166
- };
167
- }
168
- function parseUrl(input) {
169
- if (isSchemeRelativeUrl(input)) {
170
- const url = parseAbsoluteUrl('http:' + input);
171
- url.scheme = '';
172
- url.type = 6 /* SchemeRelative */;
173
- return url;
174
- }
175
- if (isAbsolutePath(input)) {
176
- const url = parseAbsoluteUrl('http://foo.com' + input);
177
- url.scheme = '';
178
- url.host = '';
179
- url.type = 5 /* AbsolutePath */;
180
- return url;
181
- }
182
- if (isFileUrl(input))
183
- return parseFileUrl(input);
184
- if (isAbsoluteUrl(input))
185
- return parseAbsoluteUrl(input);
186
- const url = parseAbsoluteUrl('http://foo.com/' + input);
187
- url.scheme = '';
188
- url.host = '';
189
- url.type = input
190
- ? input.startsWith('?')
191
- ? 3 /* Query */
192
- : input.startsWith('#')
193
- ? 2 /* Hash */
194
- : 4 /* RelativePath */
195
- : 1 /* Empty */;
196
- return url;
197
- }
198
- function stripPathFilename(path) {
199
- // If a path ends with a parent directory "..", then it's a relative path with excess parent
200
- // paths. It's not a file, so we can't strip it.
201
- if (path.endsWith('/..'))
202
- return path;
203
- const index = path.lastIndexOf('/');
204
- return path.slice(0, index + 1);
205
- }
206
- function mergePaths(url, base) {
207
- normalizePath(base, base.type);
208
- // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
209
- // path).
210
- if (url.path === '/') {
211
- url.path = base.path;
212
- }
213
- else {
214
- // Resolution happens relative to the base path's directory, not the file.
215
- url.path = stripPathFilename(base.path) + url.path;
216
- }
217
- }
218
- /**
219
- * The path can have empty directories "//", unneeded parents "foo/..", or current directory
220
- * "foo/.". We need to normalize to a standard representation.
221
- */
222
- function normalizePath(url, type) {
223
- const rel = type <= 4 /* RelativePath */;
224
- const pieces = url.path.split('/');
225
- // We need to preserve the first piece always, so that we output a leading slash. The item at
226
- // pieces[0] is an empty string.
227
- let pointer = 1;
228
- // Positive is the number of real directories we've output, used for popping a parent directory.
229
- // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
230
- let positive = 0;
231
- // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
232
- // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
233
- // real directory, we won't need to append, unless the other conditions happen again.
234
- let addTrailingSlash = false;
235
- for (let i = 1; i < pieces.length; i++) {
236
- const piece = pieces[i];
237
- // An empty directory, could be a trailing slash, or just a double "//" in the path.
238
- if (!piece) {
239
- addTrailingSlash = true;
240
- continue;
241
- }
242
- // If we encounter a real directory, then we don't need to append anymore.
243
- addTrailingSlash = false;
244
- // A current directory, which we can always drop.
245
- if (piece === '.')
246
- continue;
247
- // A parent directory, we need to see if there are any real directories we can pop. Else, we
248
- // have an excess of parents, and we'll need to keep the "..".
249
- if (piece === '..') {
250
- if (positive) {
251
- addTrailingSlash = true;
252
- positive--;
253
- pointer--;
254
- }
255
- else if (rel) {
256
- // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
257
- // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
258
- pieces[pointer++] = piece;
259
- }
260
- continue;
261
- }
262
- // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
263
- // any popped or dropped directories.
264
- pieces[pointer++] = piece;
265
- positive++;
266
- }
267
- let path = '';
268
- for (let i = 1; i < pointer; i++) {
269
- path += '/' + pieces[i];
270
- }
271
- if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
272
- path += '/';
273
- }
274
- url.path = path;
275
- }
276
- /**
277
- * Attempts to resolve `input` URL/path relative to `base`.
278
- */
279
- function resolve(input, base) {
280
- if (!input && !base)
281
- return '';
282
- const url = parseUrl(input);
283
- let inputType = url.type;
284
- if (base && inputType !== 7 /* Absolute */) {
285
- const baseUrl = parseUrl(base);
286
- const baseType = baseUrl.type;
287
- switch (inputType) {
288
- case 1 /* Empty */:
289
- url.hash = baseUrl.hash;
290
- // fall through
291
- case 2 /* Hash */:
292
- url.query = baseUrl.query;
293
- // fall through
294
- case 3 /* Query */:
295
- case 4 /* RelativePath */:
296
- mergePaths(url, baseUrl);
297
- // fall through
298
- case 5 /* AbsolutePath */:
299
- // The host, user, and port are joined, you can't copy one without the others.
300
- url.user = baseUrl.user;
301
- url.host = baseUrl.host;
302
- url.port = baseUrl.port;
303
- // fall through
304
- case 6 /* SchemeRelative */:
305
- // The input doesn't have a schema at least, so we need to copy at least that over.
306
- url.scheme = baseUrl.scheme;
307
- }
308
- if (baseType > inputType)
309
- inputType = baseType;
310
- }
311
- normalizePath(url, inputType);
312
- const queryHash = url.query + url.hash;
313
- switch (inputType) {
314
- // This is impossible, because of the empty checks at the start of the function.
315
- // case UrlType.Empty:
316
- case 2 /* Hash */:
317
- case 3 /* Query */:
318
- return queryHash;
319
- case 4 /* RelativePath */: {
320
- // The first char is always a "/", and we need it to be relative.
321
- const path = url.path.slice(1);
322
- if (!path)
323
- return queryHash || '.';
324
- if (isRelative(base || input) && !isRelative(path)) {
325
- // If base started with a leading ".", or there is no base and input started with a ".",
326
- // then we need to ensure that the relative path starts with a ".". We don't know if
327
- // relative starts with a "..", though, so check before prepending.
328
- return './' + path + queryHash;
329
- }
330
- return path + queryHash;
331
- }
332
- case 5 /* AbsolutePath */:
333
- return url.path + queryHash;
334
- default:
335
- return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
336
- }
337
- }
338
-
339
- // src/trace-mapping.ts
340
-
341
- // src/strip-filename.ts
342
- function stripFilename(path) {
343
- if (!path) return "";
344
- const index = path.lastIndexOf("/");
345
- return path.slice(0, index + 1);
346
- }
347
-
348
- // src/resolve.ts
349
- function resolver(mapUrl, sourceRoot) {
350
- const from = stripFilename(mapUrl);
351
- const prefix = sourceRoot ? sourceRoot + "/" : "";
352
- return (source) => resolve(prefix + (source || ""), from);
353
- }
354
-
355
- // src/sourcemap-segment.ts
356
- var COLUMN = 0;
357
- var SOURCES_INDEX = 1;
358
- var SOURCE_LINE = 2;
359
- var SOURCE_COLUMN = 3;
360
- var NAMES_INDEX = 4;
361
-
362
- // src/sort.ts
363
- function maybeSort(mappings, owned) {
364
- const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
365
- if (unsortedIndex === mappings.length) return mappings;
366
- if (!owned) mappings = mappings.slice();
367
- for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
368
- mappings[i] = sortSegments(mappings[i], owned);
369
- }
370
- return mappings;
371
- }
372
- function nextUnsortedSegmentLine(mappings, start) {
373
- for (let i = start; i < mappings.length; i++) {
374
- if (!isSorted(mappings[i])) return i;
375
- }
376
- return mappings.length;
377
- }
378
- function isSorted(line) {
379
- for (let j = 1; j < line.length; j++) {
380
- if (line[j][COLUMN] < line[j - 1][COLUMN]) {
381
- return false;
382
- }
383
- }
384
- return true;
385
- }
386
- function sortSegments(line, owned) {
387
- if (!owned) line = line.slice();
388
- return line.sort(sortComparator);
389
- }
390
- function sortComparator(a, b) {
391
- return a[COLUMN] - b[COLUMN];
392
- }
393
-
394
- // src/binary-search.ts
395
- var found = false;
396
- function binarySearch(haystack, needle, low, high) {
397
- while (low <= high) {
398
- const mid = low + (high - low >> 1);
399
- const cmp = haystack[mid][COLUMN] - needle;
400
- if (cmp === 0) {
401
- found = true;
402
- return mid;
403
- }
404
- if (cmp < 0) {
405
- low = mid + 1;
406
- } else {
407
- high = mid - 1;
408
- }
409
- }
410
- found = false;
411
- return low - 1;
412
- }
413
- function upperBound(haystack, needle, index) {
414
- for (let i = index + 1; i < haystack.length; index = i++) {
415
- if (haystack[i][COLUMN] !== needle) break;
416
- }
417
- return index;
418
- }
419
- function lowerBound(haystack, needle, index) {
420
- for (let i = index - 1; i >= 0; index = i--) {
421
- if (haystack[i][COLUMN] !== needle) break;
422
- }
423
- return index;
424
- }
425
- function memoizedState() {
426
- return {
427
- lastKey: -1,
428
- lastNeedle: -1,
429
- lastIndex: -1
430
- };
431
- }
432
- function memoizedBinarySearch(haystack, needle, state, key) {
433
- const { lastKey, lastNeedle, lastIndex } = state;
434
- let low = 0;
435
- let high = haystack.length - 1;
436
- if (key === lastKey) {
437
- if (needle === lastNeedle) {
438
- found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
439
- return lastIndex;
440
- }
441
- if (needle >= lastNeedle) {
442
- low = lastIndex === -1 ? 0 : lastIndex;
443
- } else {
444
- high = lastIndex;
445
- }
446
- }
447
- state.lastKey = key;
448
- state.lastNeedle = needle;
449
- return state.lastIndex = binarySearch(haystack, needle, low, high);
450
- }
451
-
452
- // src/types.ts
453
- function parse(map) {
454
- return typeof map === "string" ? JSON.parse(map) : map;
455
- }
456
-
457
- // src/trace-mapping.ts
458
- var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
459
- var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
460
- var LEAST_UPPER_BOUND = -1;
461
- var GREATEST_LOWER_BOUND = 1;
462
- var TraceMap = class {
463
- constructor(map, mapUrl) {
464
- const isString = typeof map === "string";
465
- if (!isString && map._decodedMemo) return map;
466
- const parsed = parse(map);
467
- const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
468
- this.version = version;
469
- this.file = file;
470
- this.names = names || [];
471
- this.sourceRoot = sourceRoot;
472
- this.sources = sources;
473
- this.sourcesContent = sourcesContent;
474
- this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
475
- const resolve = resolver(mapUrl, sourceRoot);
476
- this.resolvedSources = sources.map(resolve);
477
- const { mappings } = parsed;
478
- if (typeof mappings === "string") {
479
- this._encoded = mappings;
480
- this._decoded = void 0;
481
- } else if (Array.isArray(mappings)) {
482
- this._encoded = void 0;
483
- this._decoded = maybeSort(mappings, isString);
484
- } else if (parsed.sections) {
485
- throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
486
- } else {
487
- throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
488
- }
489
- this._decodedMemo = memoizedState();
490
- this._bySources = void 0;
491
- this._bySourceMemos = void 0;
492
- }
493
- };
494
- function cast(map) {
495
- return map;
496
- }
497
- function decodedMappings(map) {
498
- var _a;
499
- return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
500
- }
501
- function originalPositionFor(map, needle) {
502
- let { line, column, bias } = needle;
503
- line--;
504
- if (line < 0) throw new Error(LINE_GTR_ZERO);
505
- if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
506
- const decoded = decodedMappings(map);
507
- if (line >= decoded.length) return OMapping(null, null, null, null);
508
- const segments = decoded[line];
509
- const index = traceSegmentInternal(
510
- segments,
511
- cast(map)._decodedMemo,
512
- line,
513
- column,
514
- bias || GREATEST_LOWER_BOUND
515
- );
516
- if (index === -1) return OMapping(null, null, null, null);
517
- const segment = segments[index];
518
- if (segment.length === 1) return OMapping(null, null, null, null);
519
- const { names, resolvedSources } = map;
520
- return OMapping(
521
- resolvedSources[segment[SOURCES_INDEX]],
522
- segment[SOURCE_LINE] + 1,
523
- segment[SOURCE_COLUMN],
524
- segment.length === 5 ? names[segment[NAMES_INDEX]] : null
525
- );
526
- }
527
- function OMapping(source, line, column, name) {
528
- return { source, line, column, name };
529
- }
530
- function traceSegmentInternal(segments, memo, line, column, bias) {
531
- let index = memoizedBinarySearch(segments, column, memo, line);
532
- if (found) {
533
- index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
534
- } else if (bias === LEAST_UPPER_BOUND) index++;
535
- if (index === -1 || index === segments.length) return -1;
536
- return index;
537
- }
538
-
539
- // Only install once if called multiple times
540
- let errorFormatterInstalled = false;
541
- // Maps a file path to a string containing the file contents
542
- const fileContentsCache = {};
543
- // Maps a file path to a source map for that file
544
- const sourceMapCache = {};
545
- // Regex for detecting source maps
546
- const reSourceMap = /^data:application\/json[^,]+base64,/;
547
- // Priority list of retrieve handlers
548
- let retrieveFileHandlers = [];
549
- let retrieveMapHandlers = [];
550
- function globalProcessVersion() {
551
- if (typeof process === "object" && process !== null) return process.version;
552
- else return "";
553
- }
554
- function handlerExec(list) {
555
- return function(arg) {
556
- for (let i = 0; i < list.length; i++) {
557
- const ret = list[i](arg);
558
- if (ret) return ret;
559
- }
560
- return null;
561
- };
562
- }
563
- let retrieveFile = handlerExec(retrieveFileHandlers);
564
- retrieveFileHandlers.push((path) => {
565
- // Trim the path to make sure there is no extra whitespace.
566
- path = path.trim();
567
- if (path.startsWith("file:"))
568
- // existsSync/readFileSync can't handle file protocol, but once stripped, it works
569
- path = path.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
570
- return drive ? "" : "/";
571
- });
572
- if (path in fileContentsCache) return fileContentsCache[path];
573
- let contents = "";
574
- try {
575
- if (fs.existsSync(path)) contents = fs.readFileSync(path, "utf8");
576
- } catch {}
577
- return fileContentsCache[path] = contents;
578
- });
579
- // Support URLs relative to a directory, but be careful about a protocol prefix
580
- function supportRelativeURL(file, url) {
581
- if (!file) return url;
582
- const dir = path.dirname(file);
583
- const match = /^\w+:\/\/[^/]*/.exec(dir);
584
- let protocol = match ? match[0] : "";
585
- const startPath = dir.slice(protocol.length);
586
- if (protocol && /^\/\w:/.test(startPath)) {
587
- // handle file:///C:/ paths
588
- protocol += "/";
589
- return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
590
- }
591
- return protocol + path.resolve(dir.slice(protocol.length), url);
592
- }
593
- function retrieveSourceMapURL(source) {
594
- // Get the URL of the source map
595
- const fileData = retrieveFile(source);
596
- if (!fileData) return null;
597
- const re = /\/\/[@#]\s*sourceMappingURL=([^\s'"]+)\s*$|\/\*[@#]\s*sourceMappingURL=[^\s*'"]+\s*\*\/\s*$/gm;
598
- // Keep executing the search to find the *last* sourceMappingURL to avoid
599
- // picking up sourceMappingURLs from comments, strings, etc.
600
- let lastMatch, match;
601
- // eslint-disable-next-line no-cond-assign
602
- while (match = re.exec(fileData)) lastMatch = match;
603
- if (!lastMatch) return null;
604
- return lastMatch[1];
605
- }
606
- // Can be overridden by the retrieveSourceMap option to install. Takes a
607
- // generated source filename; returns a {map, optional url} object, or null if
608
- // there is no source map. The map field may be either a string or the parsed
609
- // JSON object (ie, it must be a valid argument to the SourceMapConsumer
610
- // constructor).
611
- let retrieveSourceMap = handlerExec(retrieveMapHandlers);
612
- retrieveMapHandlers.push((source) => {
613
- let sourceMappingURL = retrieveSourceMapURL(source);
614
- if (!sourceMappingURL) return null;
615
- // Read the contents of the source map
616
- let sourceMapData;
617
- if (reSourceMap.test(sourceMappingURL)) {
618
- // Support source map URL as a data url
619
- const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
620
- sourceMapData = Buffer.from(rawData, "base64").toString();
621
- sourceMappingURL = source;
622
- } else {
623
- // Support source map URLs relative to the source URL
624
- sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
625
- sourceMapData = retrieveFile(sourceMappingURL);
626
- }
627
- if (!sourceMapData) return null;
628
- return {
629
- url: sourceMappingURL,
630
- map: sourceMapData
631
- };
632
- });
633
- // interface Position {
634
- // source: string
635
- // line: number
636
- // column: number
637
- // }
638
- function mapSourcePosition(position) {
639
- if (!position.source) return position;
640
- let sourceMap = sourceMapCache[position.source];
641
- if (!sourceMap) {
642
- // Call the (overridable) retrieveSourceMap function to get the source map.
643
- const urlAndMap = retrieveSourceMap(position.source);
644
- const map = urlAndMap && urlAndMap.map;
645
- if (map && !(typeof map === "object" && "mappings" in map && map.mappings === "")) {
646
- var _sourceMap$map;
647
- sourceMap = sourceMapCache[position.source] = {
648
- url: urlAndMap.url,
649
- map: new TraceMap(map)
650
- };
651
- // Load all sources stored inline with the source map into the file cache
652
- // to pretend like they are already loaded. They may not exist on disk.
653
- if ((_sourceMap$map = sourceMap.map) === null || _sourceMap$map === void 0 ? void 0 : _sourceMap$map.sourcesContent) sourceMap.map.sources.forEach((source, i) => {
654
- var _sourceMap$map2;
655
- const contents = (_sourceMap$map2 = sourceMap.map) === null || _sourceMap$map2 === void 0 || (_sourceMap$map2 = _sourceMap$map2.sourcesContent) === null || _sourceMap$map2 === void 0 ? void 0 : _sourceMap$map2[i];
656
- if (contents && source && sourceMap.url) {
657
- const url = supportRelativeURL(sourceMap.url, source);
658
- fileContentsCache[url] = contents;
659
- }
660
- });
661
- } else sourceMap = sourceMapCache[position.source] = {
662
- url: null,
663
- map: null
664
- };
665
- }
666
- // Resolve the source URL relative to the URL of the source map
667
- if (sourceMap && sourceMap.map && sourceMap.url) {
668
- const originalPosition = originalPositionFor(sourceMap.map, position);
669
- // Only return the original position if a matching line was found. If no
670
- // matching line is found then we return position instead, which will cause
671
- // the stack trace to print the path and line for the compiled file. It is
672
- // better to give a precise location in the compiled file than a vague
673
- // location in the original file.
674
- if (originalPosition.source !== null) {
675
- originalPosition.source = supportRelativeURL(sourceMap.url, originalPosition.source);
676
- return originalPosition;
677
- }
678
- }
679
- return position;
680
- }
681
- // Parses code generated by FormatEvalOrigin(), a function inside V8:
682
- // https://code.google.com/p/v8/source/browse/trunk/src/messages.js
683
- function mapEvalOrigin(origin) {
684
- // Most eval() calls are in this format
685
- let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
686
- if (match) {
687
- const position = mapSourcePosition({
688
- name: null,
689
- source: match[2],
690
- line: +match[3],
691
- column: +match[4] - 1
692
- });
693
- return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
694
- }
695
- // Parse nested eval() calls using recursion
696
- match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
697
- if (match) return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`;
698
- // Make sure we still return useful information if we didn't find anything
699
- return origin;
700
- }
701
- // This is copied almost verbatim from the V8 source code at
702
- // https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
703
- // implementation of wrapCallSite() used to just forward to the actual source
704
- // code of CallSite.prototype.toString but unfortunately a new release of V8
705
- // did something to the prototype chain and broke the shim. The only fix I
706
- // could find was copy/paste.
707
- function CallSiteToString() {
708
- let fileName;
709
- let fileLocation = "";
710
- if (this.isNative()) fileLocation = "native";
711
- else {
712
- fileName = this.getScriptNameOrSourceURL();
713
- if (!fileName && this.isEval()) {
714
- fileLocation = this.getEvalOrigin();
715
- fileLocation += ", ";
716
- }
717
- if (fileName) fileLocation += fileName;
718
- else
719
- // Source code does not originate from a file and is not native, but we
720
- // can still get the source position inside the source string, e.g. in
721
- // an eval string.
722
- fileLocation += "<anonymous>";
723
- const lineNumber = this.getLineNumber();
724
- if (lineNumber != null) {
725
- fileLocation += `:${lineNumber}`;
726
- const columnNumber = this.getColumnNumber();
727
- if (columnNumber) fileLocation += `:${columnNumber}`;
728
- }
729
- }
730
- let line = "";
731
- const functionName = this.getFunctionName();
732
- let addSuffix = true;
733
- const isConstructor = this.isConstructor();
734
- if (!(this.isToplevel() || isConstructor)) {
735
- let typeName = this.getTypeName();
736
- // Fixes shim to be backward compatible with Node v0 to v4
737
- if (typeName === "[object Object]") typeName = "null";
738
- const methodName = this.getMethodName();
739
- if (functionName) {
740
- if (typeName && functionName.indexOf(typeName) !== 0) line += `${typeName}.`;
741
- line += functionName;
742
- if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1) line += ` [as ${methodName}]`;
743
- } else line += `${typeName}.${methodName || "<anonymous>"}`;
744
- } else if (isConstructor) line += `new ${functionName || "<anonymous>"}`;
745
- else if (functionName) line += functionName;
746
- else {
747
- line += fileLocation;
748
- addSuffix = false;
749
- }
750
- if (addSuffix) line += ` (${fileLocation})`;
751
- return line;
752
- }
753
- function cloneCallSite(frame) {
754
- const object = {};
755
- Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
756
- const key = name;
757
- // @ts-expect-error difficult to type
758
- object[key] = /^(?:is|get)/.test(name) ? function() {
759
- // eslint-disable-next-line no-useless-call
760
- return frame[key].call(frame);
761
- } : frame[key];
762
- });
763
- object.toString = CallSiteToString;
764
- return object;
765
- }
766
- function wrapCallSite(frame, state) {
767
- // provides interface backward compatibility
768
- if (state === void 0) state = {
769
- nextPosition: null,
770
- curPosition: null
771
- };
772
- if (frame.isNative()) {
773
- state.curPosition = null;
774
- return frame;
775
- }
776
- // Most call sites will return the source file from getFileName(), but code
777
- // passed to eval() ending in "//# sourceURL=..." will return the source file
778
- // from getScriptNameOrSourceURL() instead
779
- const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
780
- if (source) {
781
- const line = frame.getLineNumber();
782
- let column = frame.getColumnNumber() - 1;
783
- const headerLength = /^v(?:10\.1[6-9]|10\.[2-9]\d|10\.\d{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/.test(globalProcessVersion()) ? 0 : 62;
784
- if (line === 1 && column > headerLength && !frame.isEval()) column -= headerLength;
785
- const position = mapSourcePosition({
786
- name: null,
787
- source,
788
- line,
789
- column
790
- });
791
- state.curPosition = position;
792
- frame = cloneCallSite(frame);
793
- const originalFunctionName = frame.getFunctionName;
794
- frame.getFunctionName = function() {
795
- if (state.nextPosition == null) return originalFunctionName();
796
- return state.nextPosition.name || originalFunctionName();
797
- };
798
- frame.getFileName = function() {
799
- return position.source ?? null;
800
- };
801
- frame.getLineNumber = function() {
802
- return position.line;
803
- };
804
- frame.getColumnNumber = function() {
805
- return position.column + 1;
806
- };
807
- frame.getScriptNameOrSourceURL = function() {
808
- return position.source;
809
- };
810
- return frame;
811
- }
812
- // Code called using eval() needs special handling
813
- let origin = frame.isEval() && frame.getEvalOrigin();
814
- if (origin) {
815
- origin = mapEvalOrigin(origin);
816
- frame = cloneCallSite(frame);
817
- frame.getEvalOrigin = function() {
818
- return origin || void 0;
819
- };
820
- return frame;
821
- }
822
- // If we get here then we were unable to change the source position
823
- return frame;
824
- }
825
- // This function is part of the V8 stack trace API, for more info see:
826
- // https://v8.dev/docs/stack-trace-api
827
- function prepareStackTrace(error, stack) {
828
- const errorString = `${error.name || "Error"}: ${error.message || ""}`;
829
- const state = {
830
- nextPosition: null,
831
- curPosition: null
832
- };
833
- const processedStack = [];
834
- for (let i = stack.length - 1; i >= 0; i--) {
835
- processedStack.push(`\n at ${wrapCallSite(stack[i], state)}`);
836
- state.nextPosition = state.curPosition;
837
- }
838
- state.curPosition = state.nextPosition = null;
839
- return errorString + processedStack.reverse().join("");
840
- }
841
- retrieveFileHandlers.slice(0);
842
- retrieveMapHandlers.slice(0);
843
- function install(options) {
844
- options = options || {};
845
- // Allow sources to be found by methods other than reading the files
846
- // directly from disk.
847
- if (options.retrieveFile) {
848
- if (options.overrideRetrieveFile) retrieveFileHandlers.length = 0;
849
- retrieveFileHandlers.unshift(options.retrieveFile);
850
- }
851
- // Allow source maps to be found by methods other than reading the files
852
- // directly from disk.
853
- if (options.retrieveSourceMap) {
854
- if (options.overrideRetrieveSourceMap) retrieveMapHandlers.length = 0;
855
- retrieveMapHandlers.unshift(options.retrieveSourceMap);
856
- }
857
- // Install the error reformatter
858
- if (!errorFormatterInstalled) {
859
- errorFormatterInstalled = true;
860
- Error.prepareStackTrace = prepareStackTrace;
861
- }
862
- }
863
-
864
- let SOURCEMAPPING_URL = "sourceMa";
865
- SOURCEMAPPING_URL += "ppingURL";
866
- const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
867
- const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
868
- function withInlineSourcemap(result, options) {
869
- const map = result.map;
870
- let code = result.code;
871
- if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE)) return result;
872
- if ("sources" in map) {
873
- var _map$sources;
874
- map.sources = (_map$sources = map.sources) === null || _map$sources === void 0 ? void 0 : _map$sources.map((source) => {
875
- if (!source) return source;
876
- // sometimes files here are absolute,
877
- // but they are considered absolute to the server url, not the file system
878
- // this is a bug in Vite
879
- // all files should be either absolute to the file system or relative to the source map file
880
- if (isAbsolute(source)) {
881
- const actualPath = !source.startsWith(withTrailingSlash(options.root)) && source.startsWith("/") ? resolve$1(options.root, source.slice(1)) : source;
882
- return relative(dirname(options.filepath), actualPath);
883
- }
884
- return source;
885
- });
886
- }
887
- // to reduce the payload size, we only inline vite node source map, because it's also the only one we use
888
- const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, "gm");
889
- while (OTHER_SOURCE_MAP_REGEXP.test(code)) code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
890
- // If the first line is not present on source maps, add simple 1:1 mapping ([0,0,0,0], [1,0,0,0])
891
- // so that debuggers can be set to break on first line
892
- // Since Vite 6, import statements at the top of the file are preserved correctly,
893
- // so we don't need to add this mapping anymore.
894
- if (!options.noFirstLineMapping && map.mappings.startsWith(";")) map.mappings = `AAAA,CAAA${map.mappings}`;
895
- const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
896
- result.code = `${code.trimEnd()}\n\n${VITE_NODE_SOURCEMAPPING_SOURCE}\n//# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}\n`;
897
- return result;
898
- }
899
- function extractSourceMap(code) {
900
- const regexp = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`, "gm");
901
- let lastMatch, match;
902
- // eslint-disable-next-line no-cond-assign
903
- while (match = regexp.exec(code)) lastMatch = match;
904
- // pick only the last source map keeping user strings that look like maps
905
- if (lastMatch) return JSON.parse(Buffer.from(lastMatch[1], "base64").toString("utf-8"));
906
- return null;
907
- }
908
- function installSourcemapsSupport(options) {
909
- install({ retrieveSourceMap(source) {
910
- const map = options.getSourceMap(source);
911
- if (map) return {
912
- url: source,
913
- map
914
- };
915
- return null;
916
- } });
917
- }
918
-
919
- export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };