版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

source-map.mjs 29 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. import path from 'node:path';
  2. import fs from 'node:fs';
  3. const comma = ','.charCodeAt(0);
  4. const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  5. const intToChar = new Uint8Array(64); // 64 possible chars.
  6. const charToInt = new Uint8Array(128); // z is 122 in ASCII
  7. for (let i = 0; i < chars.length; i++) {
  8. const c = chars.charCodeAt(i);
  9. intToChar[i] = c;
  10. charToInt[c] = i;
  11. }
  12. function decode(mappings) {
  13. const state = new Int32Array(5);
  14. const decoded = [];
  15. let index = 0;
  16. do {
  17. const semi = indexOf(mappings, index);
  18. const line = [];
  19. let sorted = true;
  20. let lastCol = 0;
  21. state[0] = 0;
  22. for (let i = index; i < semi; i++) {
  23. let seg;
  24. i = decodeInteger(mappings, i, state, 0); // genColumn
  25. const col = state[0];
  26. if (col < lastCol)
  27. sorted = false;
  28. lastCol = col;
  29. if (hasMoreVlq(mappings, i, semi)) {
  30. i = decodeInteger(mappings, i, state, 1); // sourcesIndex
  31. i = decodeInteger(mappings, i, state, 2); // sourceLine
  32. i = decodeInteger(mappings, i, state, 3); // sourceColumn
  33. if (hasMoreVlq(mappings, i, semi)) {
  34. i = decodeInteger(mappings, i, state, 4); // namesIndex
  35. seg = [col, state[1], state[2], state[3], state[4]];
  36. }
  37. else {
  38. seg = [col, state[1], state[2], state[3]];
  39. }
  40. }
  41. else {
  42. seg = [col];
  43. }
  44. line.push(seg);
  45. }
  46. if (!sorted)
  47. sort(line);
  48. decoded.push(line);
  49. index = semi + 1;
  50. } while (index <= mappings.length);
  51. return decoded;
  52. }
  53. function indexOf(mappings, index) {
  54. const idx = mappings.indexOf(';', index);
  55. return idx === -1 ? mappings.length : idx;
  56. }
  57. function decodeInteger(mappings, pos, state, j) {
  58. let value = 0;
  59. let shift = 0;
  60. let integer = 0;
  61. do {
  62. const c = mappings.charCodeAt(pos++);
  63. integer = charToInt[c];
  64. value |= (integer & 31) << shift;
  65. shift += 5;
  66. } while (integer & 32);
  67. const shouldNegate = value & 1;
  68. value >>>= 1;
  69. if (shouldNegate) {
  70. value = -0x80000000 | -value;
  71. }
  72. state[j] += value;
  73. return pos;
  74. }
  75. function hasMoreVlq(mappings, i, length) {
  76. if (i >= length)
  77. return false;
  78. return mappings.charCodeAt(i) !== comma;
  79. }
  80. function sort(line) {
  81. line.sort(sortComparator$1);
  82. }
  83. function sortComparator$1(a, b) {
  84. return a[0] - b[0];
  85. }
  86. // Matches the scheme of a URL, eg "http://"
  87. const schemeRegex = /^[\w+.-]+:\/\//;
  88. /**
  89. * Matches the parts of a URL:
  90. * 1. Scheme, including ":", guaranteed.
  91. * 2. User/password, including "@", optional.
  92. * 3. Host, guaranteed.
  93. * 4. Port, including ":", optional.
  94. * 5. Path, including "/", optional.
  95. * 6. Query, including "?", optional.
  96. * 7. Hash, including "#", optional.
  97. */
  98. const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
  99. /**
  100. * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
  101. * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
  102. *
  103. * 1. Host, optional.
  104. * 2. Path, which may include "/", guaranteed.
  105. * 3. Query, including "?", optional.
  106. * 4. Hash, including "#", optional.
  107. */
  108. const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
  109. var UrlType;
  110. (function (UrlType) {
  111. UrlType[UrlType["Empty"] = 1] = "Empty";
  112. UrlType[UrlType["Hash"] = 2] = "Hash";
  113. UrlType[UrlType["Query"] = 3] = "Query";
  114. UrlType[UrlType["RelativePath"] = 4] = "RelativePath";
  115. UrlType[UrlType["AbsolutePath"] = 5] = "AbsolutePath";
  116. UrlType[UrlType["SchemeRelative"] = 6] = "SchemeRelative";
  117. UrlType[UrlType["Absolute"] = 7] = "Absolute";
  118. })(UrlType || (UrlType = {}));
  119. function isAbsoluteUrl(input) {
  120. return schemeRegex.test(input);
  121. }
  122. function isSchemeRelativeUrl(input) {
  123. return input.startsWith('//');
  124. }
  125. function isAbsolutePath(input) {
  126. return input.startsWith('/');
  127. }
  128. function isFileUrl(input) {
  129. return input.startsWith('file:');
  130. }
  131. function isRelative(input) {
  132. return /^[.?#]/.test(input);
  133. }
  134. function parseAbsoluteUrl(input) {
  135. const match = urlRegex.exec(input);
  136. return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
  137. }
  138. function parseFileUrl(input) {
  139. const match = fileRegex.exec(input);
  140. const path = match[2];
  141. return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
  142. }
  143. function makeUrl(scheme, user, host, port, path, query, hash) {
  144. return {
  145. scheme,
  146. user,
  147. host,
  148. port,
  149. path,
  150. query,
  151. hash,
  152. type: UrlType.Absolute,
  153. };
  154. }
  155. function parseUrl(input) {
  156. if (isSchemeRelativeUrl(input)) {
  157. const url = parseAbsoluteUrl('http:' + input);
  158. url.scheme = '';
  159. url.type = UrlType.SchemeRelative;
  160. return url;
  161. }
  162. if (isAbsolutePath(input)) {
  163. const url = parseAbsoluteUrl('http://foo.com' + input);
  164. url.scheme = '';
  165. url.host = '';
  166. url.type = UrlType.AbsolutePath;
  167. return url;
  168. }
  169. if (isFileUrl(input))
  170. return parseFileUrl(input);
  171. if (isAbsoluteUrl(input))
  172. return parseAbsoluteUrl(input);
  173. const url = parseAbsoluteUrl('http://foo.com/' + input);
  174. url.scheme = '';
  175. url.host = '';
  176. url.type = input
  177. ? input.startsWith('?')
  178. ? UrlType.Query
  179. : input.startsWith('#')
  180. ? UrlType.Hash
  181. : UrlType.RelativePath
  182. : UrlType.Empty;
  183. return url;
  184. }
  185. function stripPathFilename(path) {
  186. // If a path ends with a parent directory "..", then it's a relative path with excess parent
  187. // paths. It's not a file, so we can't strip it.
  188. if (path.endsWith('/..'))
  189. return path;
  190. const index = path.lastIndexOf('/');
  191. return path.slice(0, index + 1);
  192. }
  193. function mergePaths(url, base) {
  194. normalizePath(base, base.type);
  195. // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
  196. // path).
  197. if (url.path === '/') {
  198. url.path = base.path;
  199. }
  200. else {
  201. // Resolution happens relative to the base path's directory, not the file.
  202. url.path = stripPathFilename(base.path) + url.path;
  203. }
  204. }
  205. /**
  206. * The path can have empty directories "//", unneeded parents "foo/..", or current directory
  207. * "foo/.". We need to normalize to a standard representation.
  208. */
  209. function normalizePath(url, type) {
  210. const rel = type <= UrlType.RelativePath;
  211. const pieces = url.path.split('/');
  212. // We need to preserve the first piece always, so that we output a leading slash. The item at
  213. // pieces[0] is an empty string.
  214. let pointer = 1;
  215. // Positive is the number of real directories we've output, used for popping a parent directory.
  216. // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
  217. let positive = 0;
  218. // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
  219. // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
  220. // real directory, we won't need to append, unless the other conditions happen again.
  221. let addTrailingSlash = false;
  222. for (let i = 1; i < pieces.length; i++) {
  223. const piece = pieces[i];
  224. // An empty directory, could be a trailing slash, or just a double "//" in the path.
  225. if (!piece) {
  226. addTrailingSlash = true;
  227. continue;
  228. }
  229. // If we encounter a real directory, then we don't need to append anymore.
  230. addTrailingSlash = false;
  231. // A current directory, which we can always drop.
  232. if (piece === '.')
  233. continue;
  234. // A parent directory, we need to see if there are any real directories we can pop. Else, we
  235. // have an excess of parents, and we'll need to keep the "..".
  236. if (piece === '..') {
  237. if (positive) {
  238. addTrailingSlash = true;
  239. positive--;
  240. pointer--;
  241. }
  242. else if (rel) {
  243. // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
  244. // URL, protocol relative URL, or an absolute path, we don't need to keep excess.
  245. pieces[pointer++] = piece;
  246. }
  247. continue;
  248. }
  249. // We've encountered a real directory. Move it to the next insertion pointer, which accounts for
  250. // any popped or dropped directories.
  251. pieces[pointer++] = piece;
  252. positive++;
  253. }
  254. let path = '';
  255. for (let i = 1; i < pointer; i++) {
  256. path += '/' + pieces[i];
  257. }
  258. if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
  259. path += '/';
  260. }
  261. url.path = path;
  262. }
  263. /**
  264. * Attempts to resolve `input` URL/path relative to `base`.
  265. */
  266. function resolve$1(input, base) {
  267. if (!input && !base)
  268. return '';
  269. const url = parseUrl(input);
  270. let inputType = url.type;
  271. if (base && inputType !== UrlType.Absolute) {
  272. const baseUrl = parseUrl(base);
  273. const baseType = baseUrl.type;
  274. switch (inputType) {
  275. case UrlType.Empty:
  276. url.hash = baseUrl.hash;
  277. // fall through
  278. case UrlType.Hash:
  279. url.query = baseUrl.query;
  280. // fall through
  281. case UrlType.Query:
  282. case UrlType.RelativePath:
  283. mergePaths(url, baseUrl);
  284. // fall through
  285. case UrlType.AbsolutePath:
  286. // The host, user, and port are joined, you can't copy one without the others.
  287. url.user = baseUrl.user;
  288. url.host = baseUrl.host;
  289. url.port = baseUrl.port;
  290. // fall through
  291. case UrlType.SchemeRelative:
  292. // The input doesn't have a schema at least, so we need to copy at least that over.
  293. url.scheme = baseUrl.scheme;
  294. }
  295. if (baseType > inputType)
  296. inputType = baseType;
  297. }
  298. normalizePath(url, inputType);
  299. const queryHash = url.query + url.hash;
  300. switch (inputType) {
  301. // This is impossible, because of the empty checks at the start of the function.
  302. // case UrlType.Empty:
  303. case UrlType.Hash:
  304. case UrlType.Query:
  305. return queryHash;
  306. case UrlType.RelativePath: {
  307. // The first char is always a "/", and we need it to be relative.
  308. const path = url.path.slice(1);
  309. if (!path)
  310. return queryHash || '.';
  311. if (isRelative(base || input) && !isRelative(path)) {
  312. // If base started with a leading ".", or there is no base and input started with a ".",
  313. // then we need to ensure that the relative path starts with a ".". We don't know if
  314. // relative starts with a "..", though, so check before prepending.
  315. return './' + path + queryHash;
  316. }
  317. return path + queryHash;
  318. }
  319. case UrlType.AbsolutePath:
  320. return url.path + queryHash;
  321. default:
  322. return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
  323. }
  324. }
  325. function resolve(input, base) {
  326. // The base is always treated as a directory, if it's not empty.
  327. // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327
  328. // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401
  329. if (base && !base.endsWith('/'))
  330. base += '/';
  331. return resolve$1(input, base);
  332. }
  333. /**
  334. * Removes everything after the last "/", but leaves the slash.
  335. */
  336. function stripFilename(path) {
  337. if (!path)
  338. return '';
  339. const index = path.lastIndexOf('/');
  340. return path.slice(0, index + 1);
  341. }
  342. const COLUMN = 0;
  343. const SOURCES_INDEX = 1;
  344. const SOURCE_LINE = 2;
  345. const SOURCE_COLUMN = 3;
  346. const NAMES_INDEX = 4;
  347. function maybeSort(mappings, owned) {
  348. const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
  349. if (unsortedIndex === mappings.length)
  350. return mappings;
  351. // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If
  352. // not, we do not want to modify the consumer's input array.
  353. if (!owned)
  354. mappings = mappings.slice();
  355. for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
  356. mappings[i] = sortSegments(mappings[i], owned);
  357. }
  358. return mappings;
  359. }
  360. function nextUnsortedSegmentLine(mappings, start) {
  361. for (let i = start; i < mappings.length; i++) {
  362. if (!isSorted(mappings[i]))
  363. return i;
  364. }
  365. return mappings.length;
  366. }
  367. function isSorted(line) {
  368. for (let j = 1; j < line.length; j++) {
  369. if (line[j][COLUMN] < line[j - 1][COLUMN]) {
  370. return false;
  371. }
  372. }
  373. return true;
  374. }
  375. function sortSegments(line, owned) {
  376. if (!owned)
  377. line = line.slice();
  378. return line.sort(sortComparator);
  379. }
  380. function sortComparator(a, b) {
  381. return a[COLUMN] - b[COLUMN];
  382. }
  383. let found = false;
  384. /**
  385. * A binary search implementation that returns the index if a match is found.
  386. * If no match is found, then the left-index (the index associated with the item that comes just
  387. * before the desired index) is returned. To maintain proper sort order, a splice would happen at
  388. * the next index:
  389. *
  390. * ```js
  391. * const array = [1, 3];
  392. * const needle = 2;
  393. * const index = binarySearch(array, needle, (item, needle) => item - needle);
  394. *
  395. * assert.equal(index, 0);
  396. * array.splice(index + 1, 0, needle);
  397. * assert.deepEqual(array, [1, 2, 3]);
  398. * ```
  399. */
  400. function binarySearch(haystack, needle, low, high) {
  401. while (low <= high) {
  402. const mid = low + ((high - low) >> 1);
  403. const cmp = haystack[mid][COLUMN] - needle;
  404. if (cmp === 0) {
  405. found = true;
  406. return mid;
  407. }
  408. if (cmp < 0) {
  409. low = mid + 1;
  410. }
  411. else {
  412. high = mid - 1;
  413. }
  414. }
  415. found = false;
  416. return low - 1;
  417. }
  418. function upperBound(haystack, needle, index) {
  419. for (let i = index + 1; i < haystack.length; index = i++) {
  420. if (haystack[i][COLUMN] !== needle)
  421. break;
  422. }
  423. return index;
  424. }
  425. function lowerBound(haystack, needle, index) {
  426. for (let i = index - 1; i >= 0; index = i--) {
  427. if (haystack[i][COLUMN] !== needle)
  428. break;
  429. }
  430. return index;
  431. }
  432. function memoizedState() {
  433. return {
  434. lastKey: -1,
  435. lastNeedle: -1,
  436. lastIndex: -1,
  437. };
  438. }
  439. /**
  440. * This overly complicated beast is just to record the last tested line/column and the resulting
  441. * index, allowing us to skip a few tests if mappings are monotonically increasing.
  442. */
  443. function memoizedBinarySearch(haystack, needle, state, key) {
  444. const { lastKey, lastNeedle, lastIndex } = state;
  445. let low = 0;
  446. let high = haystack.length - 1;
  447. if (key === lastKey) {
  448. if (needle === lastNeedle) {
  449. found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
  450. return lastIndex;
  451. }
  452. if (needle >= lastNeedle) {
  453. // lastIndex may be -1 if the previous needle was not found.
  454. low = lastIndex === -1 ? 0 : lastIndex;
  455. }
  456. else {
  457. high = lastIndex;
  458. }
  459. }
  460. state.lastKey = key;
  461. state.lastNeedle = needle;
  462. return (state.lastIndex = binarySearch(haystack, needle, low, high));
  463. }
  464. const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)';
  465. const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)';
  466. const LEAST_UPPER_BOUND = -1;
  467. const GREATEST_LOWER_BOUND = 1;
  468. /**
  469. * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field.
  470. */
  471. let decodedMappings;
  472. /**
  473. * A higher-level API to find the source/line/column associated with a generated line/column
  474. * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in
  475. * `source-map` library.
  476. */
  477. let originalPositionFor;
  478. class TraceMap {
  479. constructor(map, mapUrl) {
  480. const isString = typeof map === 'string';
  481. if (!isString && map._decodedMemo)
  482. return map;
  483. const parsed = (isString ? JSON.parse(map) : map);
  484. const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
  485. this.version = version;
  486. this.file = file;
  487. this.names = names;
  488. this.sourceRoot = sourceRoot;
  489. this.sources = sources;
  490. this.sourcesContent = sourcesContent;
  491. const from = resolve(sourceRoot || '', stripFilename(mapUrl));
  492. this.resolvedSources = sources.map((s) => resolve(s || '', from));
  493. const { mappings } = parsed;
  494. if (typeof mappings === 'string') {
  495. this._encoded = mappings;
  496. this._decoded = undefined;
  497. }
  498. else {
  499. this._encoded = undefined;
  500. this._decoded = maybeSort(mappings, isString);
  501. }
  502. this._decodedMemo = memoizedState();
  503. this._bySources = undefined;
  504. this._bySourceMemos = undefined;
  505. }
  506. }
  507. (() => {
  508. decodedMappings = (map) => {
  509. return (map._decoded || (map._decoded = decode(map._encoded)));
  510. };
  511. originalPositionFor = (map, { line, column, bias }) => {
  512. line--;
  513. if (line < 0)
  514. throw new Error(LINE_GTR_ZERO);
  515. if (column < 0)
  516. throw new Error(COL_GTR_EQ_ZERO);
  517. const decoded = decodedMappings(map);
  518. // It's common for parent source maps to have pointers to lines that have no
  519. // mapping (like a "//# sourceMappingURL=") at the end of the child file.
  520. if (line >= decoded.length)
  521. return OMapping(null, null, null, null);
  522. const segments = decoded[line];
  523. const index = traceSegmentInternal(segments, map._decodedMemo, line, column, bias || GREATEST_LOWER_BOUND);
  524. if (index === -1)
  525. return OMapping(null, null, null, null);
  526. const segment = segments[index];
  527. if (segment.length === 1)
  528. return OMapping(null, null, null, null);
  529. const { names, resolvedSources } = map;
  530. return OMapping(resolvedSources[segment[SOURCES_INDEX]], segment[SOURCE_LINE] + 1, segment[SOURCE_COLUMN], segment.length === 5 ? names[segment[NAMES_INDEX]] : null);
  531. };
  532. })();
  533. function OMapping(source, line, column, name) {
  534. return { source, line, column, name };
  535. }
  536. function traceSegmentInternal(segments, memo, line, column, bias) {
  537. let index = memoizedBinarySearch(segments, column, memo, line);
  538. if (found) {
  539. index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
  540. }
  541. else if (bias === LEAST_UPPER_BOUND)
  542. index++;
  543. if (index === -1 || index === segments.length)
  544. return -1;
  545. return index;
  546. }
  547. let errorFormatterInstalled = false;
  548. let fileContentsCache = {};
  549. let sourceMapCache = {};
  550. const reSourceMap = /^data:application\/json[^,]+base64,/;
  551. let retrieveFileHandlers = [];
  552. let retrieveMapHandlers = [];
  553. function globalProcessVersion() {
  554. if (typeof process === "object" && process !== null)
  555. return process.version;
  556. else
  557. return "";
  558. }
  559. function handlerExec(list) {
  560. return function(arg) {
  561. for (let i = 0; i < list.length; i++) {
  562. const ret = list[i](arg);
  563. if (ret)
  564. return ret;
  565. }
  566. return null;
  567. };
  568. }
  569. let retrieveFile = handlerExec(retrieveFileHandlers);
  570. retrieveFileHandlers.push((path2) => {
  571. path2 = path2.trim();
  572. if (path2.startsWith("file:")) {
  573. path2 = path2.replace(/file:\/\/\/(\w:)?/, (protocol, drive) => {
  574. return drive ? "" : "/";
  575. });
  576. }
  577. if (path2 in fileContentsCache)
  578. return fileContentsCache[path2];
  579. let contents = "";
  580. try {
  581. if (fs.existsSync(path2))
  582. contents = fs.readFileSync(path2, "utf8");
  583. } catch (er) {
  584. }
  585. return fileContentsCache[path2] = contents;
  586. });
  587. function supportRelativeURL(file, url) {
  588. if (!file)
  589. return url;
  590. const dir = path.dirname(file);
  591. const match = /^\w+:\/\/[^\/]*/.exec(dir);
  592. let protocol = match ? match[0] : "";
  593. const startPath = dir.slice(protocol.length);
  594. if (protocol && /^\/\w\:/.test(startPath)) {
  595. protocol += "/";
  596. return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, "/");
  597. }
  598. return protocol + path.resolve(dir.slice(protocol.length), url);
  599. }
  600. function retrieveSourceMapURL(source) {
  601. const fileData = retrieveFile(source);
  602. if (!fileData)
  603. return null;
  604. const re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
  605. let lastMatch, match;
  606. while (match = re.exec(fileData))
  607. lastMatch = match;
  608. if (!lastMatch)
  609. return null;
  610. return lastMatch[1];
  611. }
  612. let retrieveSourceMap = handlerExec(retrieveMapHandlers);
  613. retrieveMapHandlers.push((source) => {
  614. let sourceMappingURL = retrieveSourceMapURL(source);
  615. if (!sourceMappingURL)
  616. return null;
  617. let sourceMapData;
  618. if (reSourceMap.test(sourceMappingURL)) {
  619. const rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
  620. sourceMapData = Buffer.from(rawData, "base64").toString();
  621. sourceMappingURL = source;
  622. } else {
  623. sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
  624. sourceMapData = retrieveFile(sourceMappingURL);
  625. }
  626. if (!sourceMapData)
  627. return null;
  628. return {
  629. url: sourceMappingURL,
  630. map: sourceMapData
  631. };
  632. });
  633. function mapSourcePosition(position) {
  634. var _a;
  635. if (!position.source)
  636. return position;
  637. let sourceMap = sourceMapCache[position.source];
  638. if (!sourceMap) {
  639. const urlAndMap = retrieveSourceMap(position.source);
  640. if (urlAndMap && urlAndMap.map) {
  641. sourceMap = sourceMapCache[position.source] = {
  642. url: urlAndMap.url,
  643. map: new TraceMap(urlAndMap.map)
  644. };
  645. if ((_a = sourceMap.map) == null ? void 0 : _a.sourcesContent) {
  646. sourceMap.map.sources.forEach((source, i) => {
  647. var _a2, _b;
  648. const contents = (_b = (_a2 = sourceMap.map) == null ? void 0 : _a2.sourcesContent) == null ? void 0 : _b[i];
  649. if (contents && source && sourceMap.url) {
  650. const url = supportRelativeURL(sourceMap.url, source);
  651. fileContentsCache[url] = contents;
  652. }
  653. });
  654. }
  655. } else {
  656. sourceMap = sourceMapCache[position.source] = {
  657. url: null,
  658. map: null
  659. };
  660. }
  661. }
  662. if (sourceMap && sourceMap.map && sourceMap.url) {
  663. const originalPosition = originalPositionFor(sourceMap.map, position);
  664. if (originalPosition.source !== null) {
  665. originalPosition.source = supportRelativeURL(
  666. sourceMap.url,
  667. originalPosition.source
  668. );
  669. return originalPosition;
  670. }
  671. }
  672. return position;
  673. }
  674. function mapEvalOrigin(origin) {
  675. let match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
  676. if (match) {
  677. const position = mapSourcePosition({
  678. name: null,
  679. source: match[2],
  680. line: +match[3],
  681. column: +match[4] - 1
  682. });
  683. return `eval at ${match[1]} (${position.source}:${position.line}:${position.column + 1})`;
  684. }
  685. match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
  686. if (match)
  687. return `eval at ${match[1]} (${mapEvalOrigin(match[2])})`;
  688. return origin;
  689. }
  690. function CallSiteToString() {
  691. let fileName;
  692. let fileLocation = "";
  693. if (this.isNative()) {
  694. fileLocation = "native";
  695. } else {
  696. fileName = this.getScriptNameOrSourceURL();
  697. if (!fileName && this.isEval()) {
  698. fileLocation = this.getEvalOrigin();
  699. fileLocation += ", ";
  700. }
  701. if (fileName) {
  702. fileLocation += fileName;
  703. } else {
  704. fileLocation += "<anonymous>";
  705. }
  706. const lineNumber = this.getLineNumber();
  707. if (lineNumber != null) {
  708. fileLocation += `:${lineNumber}`;
  709. const columnNumber = this.getColumnNumber();
  710. if (columnNumber)
  711. fileLocation += `:${columnNumber}`;
  712. }
  713. }
  714. let line = "";
  715. const functionName = this.getFunctionName();
  716. let addSuffix = true;
  717. const isConstructor = this.isConstructor();
  718. const isMethodCall = !(this.isToplevel() || isConstructor);
  719. if (isMethodCall) {
  720. let typeName = this.getTypeName();
  721. if (typeName === "[object Object]")
  722. typeName = "null";
  723. const methodName = this.getMethodName();
  724. if (functionName) {
  725. if (typeName && functionName.indexOf(typeName) !== 0)
  726. line += `${typeName}.`;
  727. line += functionName;
  728. if (methodName && functionName.indexOf(`.${methodName}`) !== functionName.length - methodName.length - 1)
  729. line += ` [as ${methodName}]`;
  730. } else {
  731. line += `${typeName}.${methodName || "<anonymous>"}`;
  732. }
  733. } else if (isConstructor) {
  734. line += `new ${functionName || "<anonymous>"}`;
  735. } else if (functionName) {
  736. line += functionName;
  737. } else {
  738. line += fileLocation;
  739. addSuffix = false;
  740. }
  741. if (addSuffix)
  742. line += ` (${fileLocation})`;
  743. return line;
  744. }
  745. function cloneCallSite(frame) {
  746. const object = {};
  747. Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach((name) => {
  748. const key = name;
  749. object[key] = /^(?:is|get)/.test(name) ? function() {
  750. return frame[key].call(frame);
  751. } : frame[key];
  752. });
  753. object.toString = CallSiteToString;
  754. return object;
  755. }
  756. function wrapCallSite(frame, state) {
  757. if (state === void 0)
  758. state = { nextPosition: null, curPosition: null };
  759. if (frame.isNative()) {
  760. state.curPosition = null;
  761. return frame;
  762. }
  763. const source = frame.getFileName() || frame.getScriptNameOrSourceURL();
  764. if (source) {
  765. const line = frame.getLineNumber();
  766. let column = frame.getColumnNumber() - 1;
  767. const noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
  768. const headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;
  769. if (line === 1 && column > headerLength && !frame.isEval())
  770. column -= headerLength;
  771. const position = mapSourcePosition({
  772. name: null,
  773. source,
  774. line,
  775. column
  776. });
  777. state.curPosition = position;
  778. frame = cloneCallSite(frame);
  779. const originalFunctionName = frame.getFunctionName;
  780. frame.getFunctionName = function() {
  781. if (state.nextPosition == null)
  782. return originalFunctionName();
  783. return state.nextPosition.name || originalFunctionName();
  784. };
  785. frame.getFileName = function() {
  786. return position.source;
  787. };
  788. frame.getLineNumber = function() {
  789. return position.line;
  790. };
  791. frame.getColumnNumber = function() {
  792. return position.column + 1;
  793. };
  794. frame.getScriptNameOrSourceURL = function() {
  795. return position.source;
  796. };
  797. return frame;
  798. }
  799. let origin = frame.isEval() && frame.getEvalOrigin();
  800. if (origin) {
  801. origin = mapEvalOrigin(origin);
  802. frame = cloneCallSite(frame);
  803. frame.getEvalOrigin = function() {
  804. return origin || void 0;
  805. };
  806. return frame;
  807. }
  808. return frame;
  809. }
  810. function prepareStackTrace(error, stack) {
  811. const name = error.name || "Error";
  812. const message = error.message || "";
  813. const errorString = `${name}: ${message}`;
  814. const state = { nextPosition: null, curPosition: null };
  815. const processedStack = [];
  816. for (let i = stack.length - 1; i >= 0; i--) {
  817. processedStack.push(`
  818. at ${wrapCallSite(stack[i], state)}`);
  819. state.nextPosition = state.curPosition;
  820. }
  821. state.curPosition = state.nextPosition = null;
  822. return errorString + processedStack.reverse().join("");
  823. }
  824. retrieveFileHandlers.slice(0);
  825. retrieveMapHandlers.slice(0);
  826. const install = function(options) {
  827. options = options || {};
  828. if (options.retrieveFile) {
  829. if (options.overrideRetrieveFile)
  830. retrieveFileHandlers.length = 0;
  831. retrieveFileHandlers.unshift(options.retrieveFile);
  832. }
  833. if (options.retrieveSourceMap) {
  834. if (options.overrideRetrieveSourceMap)
  835. retrieveMapHandlers.length = 0;
  836. retrieveMapHandlers.unshift(options.retrieveSourceMap);
  837. }
  838. if (!errorFormatterInstalled) {
  839. errorFormatterInstalled = true;
  840. Error.prepareStackTrace = prepareStackTrace;
  841. }
  842. };
  843. let SOURCEMAPPING_URL = "sourceMa";
  844. SOURCEMAPPING_URL += "ppingURL";
  845. const VITE_NODE_SOURCEMAPPING_SOURCE = "//# sourceMappingSource=vite-node";
  846. const VITE_NODE_SOURCEMAPPING_URL = `${SOURCEMAPPING_URL}=data:application/json;charset=utf-8`;
  847. const VITE_NODE_SOURCEMAPPING_REGEXP = new RegExp(`//# ${VITE_NODE_SOURCEMAPPING_URL};base64,(.+)`);
  848. function withInlineSourcemap(result) {
  849. const map = result.map;
  850. let code = result.code;
  851. if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
  852. return result;
  853. const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,(.+)`, "g");
  854. while (OTHER_SOURCE_MAP_REGEXP.test(code))
  855. code = code.replace(OTHER_SOURCE_MAP_REGEXP, "");
  856. const sourceMap = Buffer.from(JSON.stringify(map), "utf-8").toString("base64");
  857. result.code = `${code.trimEnd()}
  858. ${VITE_NODE_SOURCEMAPPING_SOURCE}
  859. //# ${VITE_NODE_SOURCEMAPPING_URL};base64,${sourceMap}
  860. `;
  861. return result;
  862. }
  863. function extractSourceMap(code) {
  864. var _a;
  865. const mapString = (_a = code.match(VITE_NODE_SOURCEMAPPING_REGEXP)) == null ? void 0 : _a[1];
  866. if (mapString)
  867. return JSON.parse(Buffer.from(mapString, "base64").toString("utf-8"));
  868. return null;
  869. }
  870. function installSourcemapsSupport(options) {
  871. install({
  872. retrieveSourceMap(source) {
  873. const map = options.getSourceMap(source);
  874. if (map) {
  875. return {
  876. url: source,
  877. map
  878. };
  879. }
  880. return null;
  881. }
  882. });
  883. }
  884. export { extractSourceMap, installSourcemapsSupport, withInlineSourcemap };