vitest 0.0.110 → 0.0.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { c, g as getNames, s as slash$1, a as getTests, i as isAbsolute, r as relative, d as dirname, b as basename, f as getSuites, h as resolve, n as noop$1, t as toArray, j as hasFailed } from './utils-d97bd6d9.js';
1
+ import { c, s as slash$1, i as isAbsolute, r as relative, d as dirname, b as basename, g as getFullName, a as getTests, f as getSuites, h as resolve, n as noop$1, t as toArray, j as hasFailed } from './utils-cb6b1266.js';
2
2
  import { createServer, mergeConfig } from 'vite';
3
3
  import path$a from 'path';
4
4
  import process$1 from 'process';
@@ -7,9 +7,9 @@ import require$$0 from 'os';
7
7
  import require$$0$1 from 'util';
8
8
  import require$$0$2 from 'stream';
9
9
  import require$$2 from 'events';
10
- import { d as defaultInclude, a as defaultExclude, b as defaultPort, c as distDir, e as configFiles } from './constants-e762cbc5.js';
10
+ import { d as defaultInclude, a as defaultExclude, b as defaultPort, c as distDir, e as configFiles } from './constants-2b0310b7.js';
11
11
  import { performance } from 'perf_hooks';
12
- import { s as stringWidth, a as ansiStyles, b as stripAnsi, c as sliceAnsi, F as F_POINTER, d as F_DOWN, e as F_LONG_DASH, f as F_DOWN_RIGHT, g as F_DOT, h as F_CHECK, i as F_CROSS, j as cliTruncate, k as F_RIGHT, p as printError } from './diff-46ee5d7d.js';
12
+ import { F as F_POINTER, a as F_DOWN, s as stripAnsi, b as F_LONG_DASH, c as F_DOWN_RIGHT, d as F_DOT, e as F_CHECK, f as F_CROSS, g as F_RIGHT, p as printError, h as stringWidth, i as ansiStyles, j as sliceAnsi, k as cliTruncate } from './diff-66d6bb83.js';
13
13
  import { o as onetime, s as signalExit } from './index-61c8686f.js';
14
14
  import { MessageChannel } from 'worker_threads';
15
15
  import { pathToFileURL } from 'url';
@@ -6750,2008 +6750,2135 @@ function addSnapshotResult(summary, result) {
6750
6750
  summary.total += result.added + result.matched + result.unmatched + result.updated;
6751
6751
  }
6752
6752
 
6753
- const ESC = '\u001B[';
6754
- const OSC = '\u001B]';
6755
- const BEL = '\u0007';
6756
- const SEP = ';';
6757
- const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
6758
-
6759
- const ansiEscapes = {};
6753
+ var charToInteger = {};
6754
+ var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
6755
+ for (var i = 0; i < chars.length; i++) {
6756
+ charToInteger[chars.charCodeAt(i)] = i;
6757
+ }
6758
+ function encode(decoded) {
6759
+ var sourceFileIndex = 0; // second field
6760
+ var sourceCodeLine = 0; // third field
6761
+ var sourceCodeColumn = 0; // fourth field
6762
+ var nameIndex = 0; // fifth field
6763
+ var mappings = '';
6764
+ for (var i = 0; i < decoded.length; i++) {
6765
+ var line = decoded[i];
6766
+ if (i > 0)
6767
+ mappings += ';';
6768
+ if (line.length === 0)
6769
+ continue;
6770
+ var generatedCodeColumn = 0; // first field
6771
+ var lineMappings = [];
6772
+ for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
6773
+ var segment = line_1[_i];
6774
+ var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
6775
+ generatedCodeColumn = segment[0];
6776
+ if (segment.length > 1) {
6777
+ segmentMappings +=
6778
+ encodeInteger(segment[1] - sourceFileIndex) +
6779
+ encodeInteger(segment[2] - sourceCodeLine) +
6780
+ encodeInteger(segment[3] - sourceCodeColumn);
6781
+ sourceFileIndex = segment[1];
6782
+ sourceCodeLine = segment[2];
6783
+ sourceCodeColumn = segment[3];
6784
+ }
6785
+ if (segment.length === 5) {
6786
+ segmentMappings += encodeInteger(segment[4] - nameIndex);
6787
+ nameIndex = segment[4];
6788
+ }
6789
+ lineMappings.push(segmentMappings);
6790
+ }
6791
+ mappings += lineMappings.join(',');
6792
+ }
6793
+ return mappings;
6794
+ }
6795
+ function encodeInteger(num) {
6796
+ var result = '';
6797
+ num = num < 0 ? (-num << 1) | 1 : num << 1;
6798
+ do {
6799
+ var clamped = num & 31;
6800
+ num >>>= 5;
6801
+ if (num > 0) {
6802
+ clamped |= 32;
6803
+ }
6804
+ result += chars[clamped];
6805
+ } while (num > 0);
6806
+ return result;
6807
+ }
6760
6808
 
6761
- ansiEscapes.cursorTo = (x, y) => {
6762
- if (typeof x !== 'number') {
6763
- throw new TypeError('The `x` argument is required');
6764
- }
6809
+ var BitSet = function BitSet(arg) {
6810
+ this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
6811
+ };
6765
6812
 
6766
- if (typeof y !== 'number') {
6767
- return ESC + (x + 1) + 'G';
6768
- }
6813
+ BitSet.prototype.add = function add (n) {
6814
+ this.bits[n >> 5] |= 1 << (n & 31);
6815
+ };
6769
6816
 
6770
- return ESC + (y + 1) + ';' + (x + 1) + 'H';
6817
+ BitSet.prototype.has = function has (n) {
6818
+ return !!(this.bits[n >> 5] & (1 << (n & 31)));
6771
6819
  };
6772
6820
 
6773
- ansiEscapes.cursorMove = (x, y) => {
6774
- if (typeof x !== 'number') {
6775
- throw new TypeError('The `x` argument is required');
6776
- }
6821
+ var Chunk = function Chunk(start, end, content) {
6822
+ this.start = start;
6823
+ this.end = end;
6824
+ this.original = content;
6777
6825
 
6778
- let returnValue = '';
6826
+ this.intro = '';
6827
+ this.outro = '';
6779
6828
 
6780
- if (x < 0) {
6781
- returnValue += ESC + (-x) + 'D';
6782
- } else if (x > 0) {
6783
- returnValue += ESC + x + 'C';
6784
- }
6829
+ this.content = content;
6830
+ this.storeName = false;
6831
+ this.edited = false;
6785
6832
 
6786
- if (y < 0) {
6787
- returnValue += ESC + (-y) + 'A';
6788
- } else if (y > 0) {
6789
- returnValue += ESC + y + 'B';
6790
- }
6833
+ // we make these non-enumerable, for sanity while debugging
6834
+ Object.defineProperties(this, {
6835
+ previous: { writable: true, value: null },
6836
+ next: { writable: true, value: null }
6837
+ });
6838
+ };
6791
6839
 
6792
- return returnValue;
6840
+ Chunk.prototype.appendLeft = function appendLeft (content) {
6841
+ this.outro += content;
6793
6842
  };
6794
6843
 
6795
- ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
6796
- ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
6797
- ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
6798
- ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
6844
+ Chunk.prototype.appendRight = function appendRight (content) {
6845
+ this.intro = this.intro + content;
6846
+ };
6799
6847
 
6800
- ansiEscapes.cursorLeft = ESC + 'G';
6801
- ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's';
6802
- ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u';
6803
- ansiEscapes.cursorGetPosition = ESC + '6n';
6804
- ansiEscapes.cursorNextLine = ESC + 'E';
6805
- ansiEscapes.cursorPrevLine = ESC + 'F';
6806
- ansiEscapes.cursorHide = ESC + '?25l';
6807
- ansiEscapes.cursorShow = ESC + '?25h';
6848
+ Chunk.prototype.clone = function clone () {
6849
+ var chunk = new Chunk(this.start, this.end, this.original);
6808
6850
 
6809
- ansiEscapes.eraseLines = count => {
6810
- let clear = '';
6851
+ chunk.intro = this.intro;
6852
+ chunk.outro = this.outro;
6853
+ chunk.content = this.content;
6854
+ chunk.storeName = this.storeName;
6855
+ chunk.edited = this.edited;
6811
6856
 
6812
- for (let i = 0; i < count; i++) {
6813
- clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
6814
- }
6857
+ return chunk;
6858
+ };
6815
6859
 
6816
- if (count) {
6817
- clear += ansiEscapes.cursorLeft;
6860
+ Chunk.prototype.contains = function contains (index) {
6861
+ return this.start < index && index < this.end;
6862
+ };
6863
+
6864
+ Chunk.prototype.eachNext = function eachNext (fn) {
6865
+ var chunk = this;
6866
+ while (chunk) {
6867
+ fn(chunk);
6868
+ chunk = chunk.next;
6818
6869
  }
6870
+ };
6819
6871
 
6820
- return clear;
6872
+ Chunk.prototype.eachPrevious = function eachPrevious (fn) {
6873
+ var chunk = this;
6874
+ while (chunk) {
6875
+ fn(chunk);
6876
+ chunk = chunk.previous;
6877
+ }
6821
6878
  };
6822
6879
 
6823
- ansiEscapes.eraseEndLine = ESC + 'K';
6824
- ansiEscapes.eraseStartLine = ESC + '1K';
6825
- ansiEscapes.eraseLine = ESC + '2K';
6826
- ansiEscapes.eraseDown = ESC + 'J';
6827
- ansiEscapes.eraseUp = ESC + '1J';
6828
- ansiEscapes.eraseScreen = ESC + '2J';
6829
- ansiEscapes.scrollUp = ESC + 'S';
6830
- ansiEscapes.scrollDown = ESC + 'T';
6880
+ Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
6881
+ this.content = content;
6882
+ if (!contentOnly) {
6883
+ this.intro = '';
6884
+ this.outro = '';
6885
+ }
6886
+ this.storeName = storeName;
6831
6887
 
6832
- ansiEscapes.clearScreen = '\u001Bc';
6888
+ this.edited = true;
6833
6889
 
6834
- ansiEscapes.clearTerminal = process.platform === 'win32' ?
6835
- `${ansiEscapes.eraseScreen}${ESC}0f` :
6836
- // 1. Erases the screen (Only done in case `2` is not supported)
6837
- // 2. Erases the whole screen including scrollback buffer
6838
- // 3. Moves cursor to the top-left position
6839
- // More info: https://www.real-world-systems.com/docs/ANSIcode.html
6840
- `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
6890
+ return this;
6891
+ };
6841
6892
 
6842
- ansiEscapes.beep = BEL;
6893
+ Chunk.prototype.prependLeft = function prependLeft (content) {
6894
+ this.outro = content + this.outro;
6895
+ };
6843
6896
 
6844
- ansiEscapes.link = (text, url) => {
6845
- return [
6846
- OSC,
6847
- '8',
6848
- SEP,
6849
- SEP,
6850
- url,
6851
- BEL,
6852
- text,
6853
- OSC,
6854
- '8',
6855
- SEP,
6856
- SEP,
6857
- BEL
6858
- ].join('');
6897
+ Chunk.prototype.prependRight = function prependRight (content) {
6898
+ this.intro = content + this.intro;
6859
6899
  };
6860
6900
 
6861
- ansiEscapes.image = (buffer, options = {}) => {
6862
- let returnValue = `${OSC}1337;File=inline=1`;
6901
+ Chunk.prototype.split = function split (index) {
6902
+ var sliceIndex = index - this.start;
6863
6903
 
6864
- if (options.width) {
6865
- returnValue += `;width=${options.width}`;
6866
- }
6904
+ var originalBefore = this.original.slice(0, sliceIndex);
6905
+ var originalAfter = this.original.slice(sliceIndex);
6867
6906
 
6868
- if (options.height) {
6869
- returnValue += `;height=${options.height}`;
6870
- }
6907
+ this.original = originalBefore;
6871
6908
 
6872
- if (options.preserveAspectRatio === false) {
6873
- returnValue += ';preserveAspectRatio=0';
6909
+ var newChunk = new Chunk(index, this.end, originalAfter);
6910
+ newChunk.outro = this.outro;
6911
+ this.outro = '';
6912
+
6913
+ this.end = index;
6914
+
6915
+ if (this.edited) {
6916
+ // TODO is this block necessary?...
6917
+ newChunk.edit('', false);
6918
+ this.content = '';
6919
+ } else {
6920
+ this.content = originalBefore;
6874
6921
  }
6875
6922
 
6876
- return returnValue + ':' + buffer.toString('base64') + BEL;
6923
+ newChunk.next = this.next;
6924
+ if (newChunk.next) { newChunk.next.previous = newChunk; }
6925
+ newChunk.previous = this;
6926
+ this.next = newChunk;
6927
+
6928
+ return newChunk;
6877
6929
  };
6878
6930
 
6879
- ansiEscapes.iTerm = {
6880
- setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`,
6931
+ Chunk.prototype.toString = function toString () {
6932
+ return this.intro + this.content + this.outro;
6933
+ };
6881
6934
 
6882
- annotation: (message, options = {}) => {
6883
- let returnValue = `${OSC}1337;`;
6935
+ Chunk.prototype.trimEnd = function trimEnd (rx) {
6936
+ this.outro = this.outro.replace(rx, '');
6937
+ if (this.outro.length) { return true; }
6884
6938
 
6885
- const hasX = typeof options.x !== 'undefined';
6886
- const hasY = typeof options.y !== 'undefined';
6887
- if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) {
6888
- throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');
6889
- }
6939
+ var trimmed = this.content.replace(rx, '');
6890
6940
 
6891
- message = message.replace(/\|/g, '');
6892
-
6893
- returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';
6894
-
6895
- if (options.length > 0) {
6896
- returnValue +=
6897
- (hasX ?
6898
- [message, options.length, options.x, options.y] :
6899
- [options.length, message]).join('|');
6900
- } else {
6901
- returnValue += message;
6941
+ if (trimmed.length) {
6942
+ if (trimmed !== this.content) {
6943
+ this.split(this.start + trimmed.length).edit('', undefined, true);
6902
6944
  }
6945
+ return true;
6903
6946
 
6904
- return returnValue + BEL;
6947
+ } else {
6948
+ this.edit('', undefined, true);
6949
+
6950
+ this.intro = this.intro.replace(rx, '');
6951
+ if (this.intro.length) { return true; }
6905
6952
  }
6906
6953
  };
6907
6954
 
6908
- const restoreCursor = onetime(() => {
6909
- signalExit(() => {
6910
- process$1.stderr.write('\u001B[?25h');
6911
- }, {alwaysLast: true});
6912
- });
6955
+ Chunk.prototype.trimStart = function trimStart (rx) {
6956
+ this.intro = this.intro.replace(rx, '');
6957
+ if (this.intro.length) { return true; }
6913
6958
 
6914
- let isHidden = false;
6959
+ var trimmed = this.content.replace(rx, '');
6915
6960
 
6916
- const cliCursor = {};
6961
+ if (trimmed.length) {
6962
+ if (trimmed !== this.content) {
6963
+ this.split(this.end - trimmed.length);
6964
+ this.edit('', undefined, true);
6965
+ }
6966
+ return true;
6917
6967
 
6918
- cliCursor.show = (writableStream = process$1.stderr) => {
6919
- if (!writableStream.isTTY) {
6920
- return;
6968
+ } else {
6969
+ this.edit('', undefined, true);
6970
+
6971
+ this.outro = this.outro.replace(rx, '');
6972
+ if (this.outro.length) { return true; }
6921
6973
  }
6974
+ };
6922
6975
 
6923
- isHidden = false;
6924
- writableStream.write('\u001B[?25h');
6976
+ var btoa = function () {
6977
+ throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
6925
6978
  };
6979
+ if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
6980
+ btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
6981
+ } else if (typeof Buffer === 'function') {
6982
+ btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
6983
+ }
6926
6984
 
6927
- cliCursor.hide = (writableStream = process$1.stderr) => {
6928
- if (!writableStream.isTTY) {
6929
- return;
6930
- }
6985
+ var SourceMap = function SourceMap(properties) {
6986
+ this.version = 3;
6987
+ this.file = properties.file;
6988
+ this.sources = properties.sources;
6989
+ this.sourcesContent = properties.sourcesContent;
6990
+ this.names = properties.names;
6991
+ this.mappings = encode(properties.mappings);
6992
+ };
6931
6993
 
6932
- restoreCursor();
6933
- isHidden = true;
6934
- writableStream.write('\u001B[?25l');
6994
+ SourceMap.prototype.toString = function toString () {
6995
+ return JSON.stringify(this);
6935
6996
  };
6936
6997
 
6937
- cliCursor.toggle = (force, writableStream) => {
6938
- if (force !== undefined) {
6939
- isHidden = force;
6998
+ SourceMap.prototype.toUrl = function toUrl () {
6999
+ return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
7000
+ };
7001
+
7002
+ function guessIndent(code) {
7003
+ var lines = code.split('\n');
7004
+
7005
+ var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
7006
+ var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
7007
+
7008
+ if (tabbed.length === 0 && spaced.length === 0) {
7009
+ return null;
6940
7010
  }
6941
7011
 
6942
- if (isHidden) {
6943
- cliCursor.show(writableStream);
6944
- } else {
6945
- cliCursor.hide(writableStream);
7012
+ // More lines tabbed than spaced? Assume tabs, and
7013
+ // default to tabs in the case of a tie (or nothing
7014
+ // to go on)
7015
+ if (tabbed.length >= spaced.length) {
7016
+ return '\t';
6946
7017
  }
6947
- };
6948
7018
 
6949
- const ESCAPES = new Set([
6950
- '\u001B',
6951
- '\u009B',
6952
- ]);
7019
+ // Otherwise, we need to guess the multiple
7020
+ var min = spaced.reduce(function (previous, current) {
7021
+ var numSpaces = /^ +/.exec(current)[0].length;
7022
+ return Math.min(numSpaces, previous);
7023
+ }, Infinity);
6953
7024
 
6954
- const END_CODE = 39;
6955
- const ANSI_ESCAPE_BELL = '\u0007';
6956
- const ANSI_CSI = '[';
6957
- const ANSI_OSC = ']';
6958
- const ANSI_SGR_TERMINATOR = 'm';
6959
- const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
7025
+ return new Array(min + 1).join(' ');
7026
+ }
6960
7027
 
6961
- const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
6962
- const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
7028
+ function getRelativePath(from, to) {
7029
+ var fromParts = from.split(/[/\\]/);
7030
+ var toParts = to.split(/[/\\]/);
6963
7031
 
6964
- // Calculate the length of words split on ' ', ignoring
6965
- // the extra characters added by ansi escape codes
6966
- const wordLengths = string => string.split(' ').map(character => stringWidth(character));
7032
+ fromParts.pop(); // get dirname
6967
7033
 
6968
- // Wrap a long word across multiple rows
6969
- // Ansi escape codes do not count towards length
6970
- const wrapWord = (rows, word, columns) => {
6971
- const characters = [...word];
7034
+ while (fromParts[0] === toParts[0]) {
7035
+ fromParts.shift();
7036
+ toParts.shift();
7037
+ }
6972
7038
 
6973
- let isInsideEscape = false;
6974
- let isInsideLinkEscape = false;
6975
- let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
7039
+ if (fromParts.length) {
7040
+ var i = fromParts.length;
7041
+ while (i--) { fromParts[i] = '..'; }
7042
+ }
6976
7043
 
6977
- for (const [index, character] of characters.entries()) {
6978
- const characterLength = stringWidth(character);
7044
+ return fromParts.concat(toParts).join('/');
7045
+ }
6979
7046
 
6980
- if (visible + characterLength <= columns) {
6981
- rows[rows.length - 1] += character;
6982
- } else {
6983
- rows.push(character);
6984
- visible = 0;
6985
- }
7047
+ var toString = Object.prototype.toString;
6986
7048
 
6987
- if (ESCAPES.has(character)) {
6988
- isInsideEscape = true;
6989
- isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);
6990
- }
7049
+ function isObject(thing) {
7050
+ return toString.call(thing) === '[object Object]';
7051
+ }
6991
7052
 
6992
- if (isInsideEscape) {
6993
- if (isInsideLinkEscape) {
6994
- if (character === ANSI_ESCAPE_BELL) {
6995
- isInsideEscape = false;
6996
- isInsideLinkEscape = false;
6997
- }
6998
- } else if (character === ANSI_SGR_TERMINATOR) {
6999
- isInsideEscape = false;
7000
- }
7053
+ function getLocator(source) {
7054
+ var originalLines = source.split('\n');
7055
+ var lineOffsets = [];
7001
7056
 
7002
- continue;
7057
+ for (var i = 0, pos = 0; i < originalLines.length; i++) {
7058
+ lineOffsets.push(pos);
7059
+ pos += originalLines[i].length + 1;
7060
+ }
7061
+
7062
+ return function locate(index) {
7063
+ var i = 0;
7064
+ var j = lineOffsets.length;
7065
+ while (i < j) {
7066
+ var m = (i + j) >> 1;
7067
+ if (index < lineOffsets[m]) {
7068
+ j = m;
7069
+ } else {
7070
+ i = m + 1;
7071
+ }
7003
7072
  }
7073
+ var line = i - 1;
7074
+ var column = index - lineOffsets[line];
7075
+ return { line: line, column: column };
7076
+ };
7077
+ }
7004
7078
 
7005
- visible += characterLength;
7079
+ var Mappings = function Mappings(hires) {
7080
+ this.hires = hires;
7081
+ this.generatedCodeLine = 0;
7082
+ this.generatedCodeColumn = 0;
7083
+ this.raw = [];
7084
+ this.rawSegments = this.raw[this.generatedCodeLine] = [];
7085
+ this.pending = null;
7086
+ };
7006
7087
 
7007
- if (visible === columns && index < characters.length - 1) {
7008
- rows.push('');
7009
- visible = 0;
7088
+ Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
7089
+ if (content.length) {
7090
+ var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
7091
+ if (nameIndex >= 0) {
7092
+ segment.push(nameIndex);
7010
7093
  }
7094
+ this.rawSegments.push(segment);
7095
+ } else if (this.pending) {
7096
+ this.rawSegments.push(this.pending);
7011
7097
  }
7012
7098
 
7013
- // It's possible that the last row we copy over is only
7014
- // ansi escape characters, handle this edge-case
7015
- if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
7016
- rows[rows.length - 2] += rows.pop();
7017
- }
7099
+ this.advance(content);
7100
+ this.pending = null;
7018
7101
  };
7019
7102
 
7020
- // Trims spaces from a string ignoring invisible sequences
7021
- const stringVisibleTrimSpacesRight = string => {
7022
- const words = string.split(' ');
7023
- let last = words.length;
7103
+ Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
7104
+ var originalCharIndex = chunk.start;
7105
+ var first = true;
7024
7106
 
7025
- while (last > 0) {
7026
- if (stringWidth(words[last - 1]) > 0) {
7027
- break;
7107
+ while (originalCharIndex < chunk.end) {
7108
+ if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
7109
+ this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
7028
7110
  }
7029
7111
 
7030
- last--;
7031
- }
7112
+ if (original[originalCharIndex] === '\n') {
7113
+ loc.line += 1;
7114
+ loc.column = 0;
7115
+ this.generatedCodeLine += 1;
7116
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
7117
+ this.generatedCodeColumn = 0;
7118
+ first = true;
7119
+ } else {
7120
+ loc.column += 1;
7121
+ this.generatedCodeColumn += 1;
7122
+ first = false;
7123
+ }
7032
7124
 
7033
- if (last === words.length) {
7034
- return string;
7125
+ originalCharIndex += 1;
7035
7126
  }
7036
7127
 
7037
- return words.slice(0, last).join(' ') + words.slice(last).join('');
7128
+ this.pending = null;
7038
7129
  };
7039
7130
 
7040
- // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode
7041
- //
7042
- // 'hard' will never allow a string to take up more than columns characters
7043
- //
7044
- // 'soft' allows long words to expand past the column length
7045
- const exec = (string, columns, options = {}) => {
7046
- if (options.trim !== false && string.trim() === '') {
7047
- return '';
7048
- }
7049
-
7050
- let returnValue = '';
7051
- let escapeCode;
7052
- let escapeUrl;
7131
+ Mappings.prototype.advance = function advance (str) {
7132
+ if (!str) { return; }
7053
7133
 
7054
- const lengths = wordLengths(string);
7055
- let rows = [''];
7134
+ var lines = str.split('\n');
7056
7135
 
7057
- for (const [index, word] of string.split(' ').entries()) {
7058
- if (options.trim !== false) {
7059
- rows[rows.length - 1] = rows[rows.length - 1].trimStart();
7136
+ if (lines.length > 1) {
7137
+ for (var i = 0; i < lines.length - 1; i++) {
7138
+ this.generatedCodeLine++;
7139
+ this.raw[this.generatedCodeLine] = this.rawSegments = [];
7060
7140
  }
7141
+ this.generatedCodeColumn = 0;
7142
+ }
7061
7143
 
7062
- let rowLength = stringWidth(rows[rows.length - 1]);
7144
+ this.generatedCodeColumn += lines[lines.length - 1].length;
7145
+ };
7063
7146
 
7064
- if (index !== 0) {
7065
- if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
7066
- // If we start with a new word but the current row length equals the length of the columns, add a new row
7067
- rows.push('');
7068
- rowLength = 0;
7069
- }
7147
+ var n = '\n';
7070
7148
 
7071
- if (rowLength > 0 || options.trim === false) {
7072
- rows[rows.length - 1] += ' ';
7073
- rowLength++;
7074
- }
7075
- }
7149
+ var warned = {
7150
+ insertLeft: false,
7151
+ insertRight: false,
7152
+ storeName: false
7153
+ };
7076
7154
 
7077
- // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'
7078
- if (options.hard && lengths[index] > columns) {
7079
- const remainingColumns = (columns - rowLength);
7080
- const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
7081
- const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
7082
- if (breaksStartingNextLine < breaksStartingThisLine) {
7083
- rows.push('');
7084
- }
7155
+ var MagicString = function MagicString(string, options) {
7156
+ if ( options === void 0 ) options = {};
7085
7157
 
7086
- wrapWord(rows, word, columns);
7087
- continue;
7088
- }
7158
+ var chunk = new Chunk(0, string.length, string);
7089
7159
 
7090
- if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
7091
- if (options.wordWrap === false && rowLength < columns) {
7092
- wrapWord(rows, word, columns);
7093
- continue;
7094
- }
7160
+ Object.defineProperties(this, {
7161
+ original: { writable: true, value: string },
7162
+ outro: { writable: true, value: '' },
7163
+ intro: { writable: true, value: '' },
7164
+ firstChunk: { writable: true, value: chunk },
7165
+ lastChunk: { writable: true, value: chunk },
7166
+ lastSearchedChunk: { writable: true, value: chunk },
7167
+ byStart: { writable: true, value: {} },
7168
+ byEnd: { writable: true, value: {} },
7169
+ filename: { writable: true, value: options.filename },
7170
+ indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
7171
+ sourcemapLocations: { writable: true, value: new BitSet() },
7172
+ storedNames: { writable: true, value: {} },
7173
+ indentStr: { writable: true, value: guessIndent(string) }
7174
+ });
7095
7175
 
7096
- rows.push('');
7097
- }
7176
+ this.byStart[0] = chunk;
7177
+ this.byEnd[string.length] = chunk;
7178
+ };
7098
7179
 
7099
- if (rowLength + lengths[index] > columns && options.wordWrap === false) {
7100
- wrapWord(rows, word, columns);
7101
- continue;
7102
- }
7180
+ MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
7181
+ this.sourcemapLocations.add(char);
7182
+ };
7103
7183
 
7104
- rows[rows.length - 1] += word;
7105
- }
7184
+ MagicString.prototype.append = function append (content) {
7185
+ if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
7106
7186
 
7107
- if (options.trim !== false) {
7108
- rows = rows.map(row => stringVisibleTrimSpacesRight(row));
7109
- }
7187
+ this.outro += content;
7188
+ return this;
7189
+ };
7110
7190
 
7111
- const pre = [...rows.join('\n')];
7191
+ MagicString.prototype.appendLeft = function appendLeft (index, content) {
7192
+ if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
7112
7193
 
7113
- for (const [index, character] of pre.entries()) {
7114
- returnValue += character;
7194
+ this._split(index);
7115
7195
 
7116
- if (ESCAPES.has(character)) {
7117
- const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};
7118
- if (groups.code !== undefined) {
7119
- const code = Number.parseFloat(groups.code);
7120
- escapeCode = code === END_CODE ? undefined : code;
7121
- } else if (groups.uri !== undefined) {
7122
- escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
7123
- }
7124
- }
7196
+ var chunk = this.byEnd[index];
7125
7197
 
7126
- const code = ansiStyles.codes.get(Number(escapeCode));
7198
+ if (chunk) {
7199
+ chunk.appendLeft(content);
7200
+ } else {
7201
+ this.intro += content;
7202
+ }
7203
+ return this;
7204
+ };
7127
7205
 
7128
- if (pre[index + 1] === '\n') {
7129
- if (escapeUrl) {
7130
- returnValue += wrapAnsiHyperlink('');
7131
- }
7206
+ MagicString.prototype.appendRight = function appendRight (index, content) {
7207
+ if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
7132
7208
 
7133
- if (escapeCode && code) {
7134
- returnValue += wrapAnsiCode(code);
7135
- }
7136
- } else if (character === '\n') {
7137
- if (escapeCode && code) {
7138
- returnValue += wrapAnsiCode(escapeCode);
7139
- }
7209
+ this._split(index);
7140
7210
 
7141
- if (escapeUrl) {
7142
- returnValue += wrapAnsiHyperlink(escapeUrl);
7143
- }
7144
- }
7145
- }
7211
+ var chunk = this.byStart[index];
7146
7212
 
7147
- return returnValue;
7213
+ if (chunk) {
7214
+ chunk.appendRight(content);
7215
+ } else {
7216
+ this.outro += content;
7217
+ }
7218
+ return this;
7148
7219
  };
7149
7220
 
7150
- // For each newline, invoke the method separately
7151
- function wrapAnsi(string, columns, options) {
7152
- return String(string)
7153
- .normalize()
7154
- .replace(/\r\n/g, '\n')
7155
- .split('\n')
7156
- .map(line => exec(line, columns, options))
7157
- .join('\n');
7158
- }
7221
+ MagicString.prototype.clone = function clone () {
7222
+ var cloned = new MagicString(this.original, { filename: this.filename });
7159
7223
 
7160
- const defaultTerminalHeight = 24;
7224
+ var originalChunk = this.firstChunk;
7225
+ var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
7161
7226
 
7162
- const getWidth = stream => {
7163
- const {columns} = stream;
7227
+ while (originalChunk) {
7228
+ cloned.byStart[clonedChunk.start] = clonedChunk;
7229
+ cloned.byEnd[clonedChunk.end] = clonedChunk;
7164
7230
 
7165
- if (!columns) {
7166
- return 80;
7167
- }
7231
+ var nextOriginalChunk = originalChunk.next;
7232
+ var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
7168
7233
 
7169
- return columns;
7170
- };
7234
+ if (nextClonedChunk) {
7235
+ clonedChunk.next = nextClonedChunk;
7236
+ nextClonedChunk.previous = clonedChunk;
7171
7237
 
7172
- const fitToTerminalHeight = (stream, text) => {
7173
- const terminalHeight = stream.rows || defaultTerminalHeight;
7174
- const lines = text.split('\n');
7238
+ clonedChunk = nextClonedChunk;
7239
+ }
7175
7240
 
7176
- const toRemove = lines.length - terminalHeight;
7177
- if (toRemove <= 0) {
7178
- return text;
7241
+ originalChunk = nextOriginalChunk;
7179
7242
  }
7180
7243
 
7181
- return sliceAnsi(
7182
- text,
7183
- lines.slice(0, toRemove).join('\n').length + 1,
7184
- text.length);
7185
- };
7244
+ cloned.lastChunk = clonedChunk;
7186
7245
 
7187
- function createLogUpdate(stream, {showCursor = false} = {}) {
7188
- let previousLineCount = 0;
7189
- let previousWidth = getWidth(stream);
7190
- let previousOutput = '';
7246
+ if (this.indentExclusionRanges) {
7247
+ cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
7248
+ }
7191
7249
 
7192
- const render = (...arguments_) => {
7193
- if (!showCursor) {
7194
- cliCursor.hide();
7195
- }
7250
+ cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
7196
7251
 
7197
- let output = arguments_.join(' ') + '\n';
7198
- output = fitToTerminalHeight(stream, output);
7199
- const width = getWidth(stream);
7200
- if (output === previousOutput && previousWidth === width) {
7201
- return;
7202
- }
7252
+ cloned.intro = this.intro;
7253
+ cloned.outro = this.outro;
7203
7254
 
7204
- previousOutput = output;
7205
- previousWidth = width;
7206
- output = wrapAnsi(output, width, {
7207
- trim: false,
7208
- hard: true,
7209
- wordWrap: false,
7210
- });
7211
- stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
7212
- previousLineCount = output.split('\n').length;
7213
- };
7255
+ return cloned;
7256
+ };
7214
7257
 
7215
- render.clear = () => {
7216
- stream.write(ansiEscapes.eraseLines(previousLineCount));
7217
- previousOutput = '';
7218
- previousWidth = getWidth(stream);
7219
- previousLineCount = 0;
7220
- };
7258
+ MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
7259
+ var this$1$1 = this;
7221
7260
 
7222
- render.done = () => {
7223
- previousOutput = '';
7224
- previousWidth = getWidth(stream);
7225
- previousLineCount = 0;
7261
+ options = options || {};
7226
7262
 
7227
- if (!showCursor) {
7228
- cliCursor.show();
7229
- }
7230
- };
7263
+ var sourceIndex = 0;
7264
+ var names = Object.keys(this.storedNames);
7265
+ var mappings = new Mappings(options.hires);
7231
7266
 
7232
- return render;
7233
- }
7267
+ var locate = getLocator(this.original);
7234
7268
 
7235
- createLogUpdate(process$1.stdout);
7269
+ if (this.intro) {
7270
+ mappings.advance(this.intro);
7271
+ }
7236
7272
 
7237
- createLogUpdate(process$1.stderr);
7273
+ this.firstChunk.eachNext(function (chunk) {
7274
+ var loc = locate(chunk.start);
7238
7275
 
7239
- const DURATION_LONG = 300;
7240
- const MAX_HEIGHT = 20;
7241
- const spinnerMap = /* @__PURE__ */ new WeakMap();
7242
- const outputMap = /* @__PURE__ */ new WeakMap();
7243
- const pointer = c.yellow(F_POINTER);
7244
- const skipped = c.yellow(F_DOWN);
7245
- function getCols(delta = 0) {
7246
- let length = process.stdout.columns;
7247
- if (!length || isNaN(length))
7248
- length = 30;
7249
- return Math.max(length + delta, 0);
7250
- }
7251
- function divider(text, left, right) {
7252
- const cols = getCols();
7253
- if (text) {
7254
- const textLength = stripAnsi(text).length;
7255
- if (left == null && right != null) {
7256
- left = cols - textLength - right;
7257
- } else {
7258
- left = left ?? Math.floor((cols - textLength) / 2);
7259
- right = cols - textLength - left;
7260
- }
7261
- left = Math.max(0, left);
7262
- right = Math.max(0, right);
7263
- return `${F_LONG_DASH.repeat(left)}${text}${F_LONG_DASH.repeat(right)}`;
7264
- }
7265
- return F_LONG_DASH.repeat(cols);
7266
- }
7267
- function formatTestPath(root, path) {
7268
- var _a;
7269
- if (isAbsolute(path))
7270
- path = relative(root, path);
7271
- const dir = dirname(path);
7272
- const ext = ((_a = path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/)) == null ? void 0 : _a[0]) || "";
7273
- const base = basename(path, ext);
7274
- return slash$1(c.dim(`${dir}/`) + c.bold(base)) + c.dim(ext);
7275
- }
7276
- function renderSnapshotSummary(rootDir, snapshots) {
7277
- const summary = [];
7278
- if (snapshots.added)
7279
- summary.push(c.bold(c.green(`${snapshots.added} written`)));
7280
- if (snapshots.unmatched)
7281
- summary.push(c.bold(c.red(`${snapshots.unmatched} failed`)));
7282
- if (snapshots.updated)
7283
- summary.push(c.bold(c.green(`${snapshots.updated} updated `)));
7284
- if (snapshots.filesRemoved) {
7285
- if (snapshots.didUpdate)
7286
- summary.push(c.bold(c.green(`${snapshots.filesRemoved} files removed `)));
7287
- else
7288
- summary.push(c.bold(c.yellow(`${snapshots.filesRemoved} files obsolete `)));
7289
- }
7290
- if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
7291
- const [head, ...tail] = snapshots.filesRemovedList;
7292
- summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, head)}`);
7293
- tail.forEach((key) => {
7294
- summary.push(` ${c.gray(F_DOT)} ${formatTestPath(rootDir, key)}`);
7295
- });
7296
- }
7297
- if (snapshots.unchecked) {
7298
- if (snapshots.didUpdate)
7299
- summary.push(c.bold(c.green(`${snapshots.unchecked} removed`)));
7300
- else
7301
- summary.push(c.bold(c.yellow(`${snapshots.unchecked} obsolete`)));
7302
- snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => {
7303
- summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, uncheckedFile.filePath)}`);
7304
- uncheckedFile.keys.forEach((key) => summary.push(` ${c.gray(F_DOT)} ${key}`));
7305
- });
7306
- }
7307
- return summary;
7308
- }
7309
- function getStateString(tasks, name = "tests") {
7310
- if (tasks.length === 0)
7311
- return c.dim(`no ${name}`);
7312
- const passed = tasks.filter((i) => {
7313
- var _a;
7314
- return ((_a = i.result) == null ? void 0 : _a.state) === "pass";
7315
- });
7316
- const failed = tasks.filter((i) => {
7317
- var _a;
7318
- return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
7319
- });
7320
- const skipped2 = tasks.filter((i) => i.mode === "skip");
7321
- const todo = tasks.filter((i) => i.mode === "todo");
7322
- return [
7323
- failed.length ? c.bold(c.red(`${failed.length} failed`)) : null,
7324
- passed.length ? c.bold(c.green(`${passed.length} passed`)) : null,
7325
- skipped2.length ? c.yellow(`${skipped2.length} skipped`) : null,
7326
- todo.length ? c.gray(`${todo.length} todo`) : null
7327
- ].filter(Boolean).join(c.dim(" | ")) + c.gray(` (${tasks.length})`);
7328
- }
7329
- function getStateSymbol(task) {
7330
- if (task.mode === "skip" || task.mode === "todo")
7331
- return skipped;
7332
- if (!task.result)
7333
- return c.gray("\xB7");
7334
- if (task.result.state === "run") {
7335
- if (task.type === "suite")
7336
- return pointer;
7337
- let spinner = spinnerMap.get(task);
7338
- if (!spinner) {
7339
- spinner = elegantSpinner();
7340
- spinnerMap.set(task, spinner);
7341
- }
7342
- return c.yellow(spinner());
7343
- }
7344
- if (task.result.state === "pass")
7345
- return c.green(F_CHECK);
7346
- if (task.result.state === "fail") {
7347
- return task.type === "suite" ? pointer : c.red(F_CROSS);
7348
- }
7349
- return " ";
7350
- }
7351
- function formatFilepath(path) {
7352
- const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0);
7353
- const basename2 = path.slice(lastSlash);
7354
- let firstDot = basename2.indexOf(".");
7355
- if (firstDot < 0)
7356
- firstDot = basename2.length;
7357
- firstDot += lastSlash;
7358
- return c.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + c.dim(path.slice(firstDot));
7359
- }
7360
- function renderTree(tasks, level = 0) {
7361
- var _a, _b, _c, _d;
7362
- let output = [];
7363
- for (const task of tasks) {
7364
- let suffix = "";
7365
- const prefix = ` ${getStateSymbol(task)} `;
7366
- if (task.mode === "skip" || task.mode === "todo")
7367
- suffix += ` ${c.dim("[skipped]")}`;
7368
- if (task.type === "suite")
7369
- suffix += c.dim(` (${getTests(task).length})`);
7370
- if ((_a = task.result) == null ? void 0 : _a.end) {
7371
- const duration = task.result.end - task.result.start;
7372
- if (duration > DURATION_LONG)
7373
- suffix += c.yellow(` ${Math.round(duration)}${c.dim("ms")}`);
7374
- }
7375
- let name = task.name;
7376
- if (level === 0)
7377
- name = formatFilepath(name);
7378
- output.push(" ".repeat(level) + prefix + name + suffix);
7379
- if (((_b = task.result) == null ? void 0 : _b.state) !== "pass" && outputMap.get(task) != null) {
7380
- let data = outputMap.get(task);
7381
- if (typeof data === "string") {
7382
- data = stripAnsi(data.trim().split("\n").filter(Boolean).pop());
7383
- if (data === "")
7384
- data = void 0;
7385
- }
7386
- if (data != null) {
7387
- const out = `${" ".repeat(level)}${F_RIGHT} ${data}`;
7388
- output.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`);
7389
- }
7390
- }
7391
- if ((((_c = task.result) == null ? void 0 : _c.state) === "fail" || ((_d = task.result) == null ? void 0 : _d.state) === "run") && task.type === "suite" && task.tasks.length > 0)
7392
- output = output.concat(renderTree(task.tasks, level + 1));
7393
- }
7394
- return output.slice(0, MAX_HEIGHT).join("\n");
7395
- }
7396
- const createRenderer = (_tasks) => {
7397
- let tasks = _tasks;
7398
- let timer;
7399
- const stdout = process.stdout;
7400
- const log = createLogUpdate(stdout);
7401
- function update() {
7402
- log(renderTree(tasks));
7403
- }
7404
- return {
7405
- start() {
7406
- if (timer)
7407
- return this;
7408
- timer = setInterval(update, 200);
7409
- return this;
7410
- },
7411
- update(_tasks2) {
7412
- tasks = _tasks2;
7413
- update();
7414
- return this;
7415
- },
7416
- async stop() {
7417
- if (timer) {
7418
- clearInterval(timer);
7419
- timer = void 0;
7420
- }
7421
- log.clear();
7422
- stdout.write(`${renderTree(tasks)}
7423
- `);
7424
- return this;
7425
- },
7426
- clear() {
7427
- log.clear();
7428
- }
7429
- };
7430
- };
7431
- function getFullName(task) {
7432
- return getNames(task).join(c.dim(" > "));
7433
- }
7434
- const spinnerFrames = process.platform === "win32" ? ["-", "\\", "|", "/"] : ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
7435
- function elegantSpinner() {
7436
- let index = 0;
7437
- return () => {
7438
- index = ++index % spinnerFrames.length;
7439
- return spinnerFrames[index];
7440
- };
7441
- }
7276
+ if (chunk.intro.length) { mappings.advance(chunk.intro); }
7442
7277
 
7443
- const isTTY = process.stdout.isTTY && !process.env.CI;
7444
- class ConsoleReporter {
7445
- constructor(ctx) {
7446
- this.ctx = ctx;
7447
- this.start = 0;
7448
- this.end = 0;
7449
- this.isFirstWatchRun = true;
7450
- const mode = ctx.config.watch ? c.yellow(" DEV ") : c.cyan(" RUN ");
7451
- this.ctx.log(`
7452
- ${c.inverse(c.bold(mode))} ${c.gray(this.ctx.config.root)}
7453
- `);
7454
- this.start = performance.now();
7455
- }
7456
- relative(path) {
7457
- return relative(this.ctx.config.root, path);
7458
- }
7459
- onStart() {
7460
- if (isTTY) {
7461
- const files = this.ctx.state.getFiles(this.watchFilters);
7462
- if (!this.renderer)
7463
- this.renderer = createRenderer(files).start();
7464
- else
7465
- this.renderer.update(files);
7466
- }
7467
- }
7468
- onTaskUpdate(pack) {
7469
- var _a, _b, _c;
7470
- if (isTTY)
7471
- return;
7472
- const task = this.ctx.state.idMap[pack[0]];
7473
- if (task.type === "test" && ((_a = task.result) == null ? void 0 : _a.state) && ((_b = task.result) == null ? void 0 : _b.state) !== "run") {
7474
- this.ctx.log(` ${getStateSymbol(task)} ${getFullName(task)}`);
7475
- if (task.result.state === "fail")
7476
- this.ctx.log(c.red(` ${F_RIGHT} ${(_c = task.result.error) == null ? void 0 : _c.message}`));
7477
- }
7478
- }
7479
- async onFinished(files = this.ctx.state.getFiles()) {
7480
- var _a, _b;
7481
- this.end = performance.now();
7482
- await this.stopListRender();
7483
- this.ctx.log();
7484
- const suites = getSuites(files);
7485
- const tests = getTests(files);
7486
- const failedSuites = suites.filter((i) => {
7487
- var _a2;
7488
- return (_a2 = i.result) == null ? void 0 : _a2.error;
7489
- });
7490
- const failedTests = tests.filter((i) => {
7491
- var _a2;
7492
- return ((_a2 = i.result) == null ? void 0 : _a2.state) === "fail";
7493
- });
7494
- const failedTotal = failedSuites.length + failedTests.length;
7495
- let current = 1;
7496
- const errorDivider = () => this.ctx.error(`${c.red(c.dim(divider(`[${current++}/${failedTotal}]`, void 0, 1)))}
7497
- `);
7498
- if (failedSuites.length) {
7499
- this.ctx.error(c.red(divider(c.bold(c.inverse(` Failed Suites ${failedSuites.length} `)))));
7500
- this.ctx.error();
7501
- for (const suite of failedSuites) {
7502
- const filepath = (suite == null ? void 0 : suite.filepath) || "";
7503
- this.ctx.error(c.red(`
7504
- - ${getFullName(suite)} ${c.dim(`[ ${this.relative(filepath)} ]`)}`));
7505
- await printError((_a = suite.result) == null ? void 0 : _a.error, this.ctx);
7506
- errorDivider();
7507
- }
7508
- }
7509
- if (failedTests.length) {
7510
- this.ctx.error(c.red(divider(c.bold(c.inverse(` Failed Tests ${failedTests.length} `)))));
7511
- this.ctx.error();
7512
- for (const test of failedTests) {
7513
- this.ctx.error(`${c.red(c.bold(c.inverse(" FAIL ")))} ${getFullName(test)}`);
7514
- await printError((_b = test.result) == null ? void 0 : _b.error, this.ctx);
7515
- errorDivider();
7516
- }
7517
- }
7518
- const executionTime = this.end - this.start;
7519
- const threadTime = tests.reduce((acc, test) => {
7520
- var _a2;
7521
- return acc + (((_a2 = test.result) == null ? void 0 : _a2.end) ? test.result.end - test.result.start : 0);
7522
- }, 0);
7523
- const padTitle = (str) => c.dim(`${str.padStart(10)} `);
7524
- const time = (time2) => {
7525
- if (time2 > 1e3)
7526
- return `${(time2 / 1e3).toFixed(2)}s`;
7527
- return `${Math.round(time2)}ms`;
7528
- };
7529
- const snapshotOutput = renderSnapshotSummary(this.ctx.config.root, this.ctx.snapshot.summary);
7530
- if (snapshotOutput.length) {
7531
- this.ctx.log(snapshotOutput.map((t, i) => i === 0 ? `${padTitle("Snapshots")} ${t}` : `${padTitle("")} ${t}`).join("\n"));
7532
- if (snapshotOutput.length > 1)
7533
- this.ctx.log();
7534
- }
7535
- this.ctx.log(padTitle("Test Files"), getStateString(files));
7536
- this.ctx.log(padTitle("Tests"), getStateString(tests));
7537
- if (this.watchFilters)
7538
- this.ctx.log(padTitle("Time"), time(threadTime));
7539
- else
7540
- this.ctx.log(padTitle("Time"), time(executionTime) + c.gray(` (in thread ${time(threadTime)}, ${(executionTime / threadTime * 100).toFixed(2)}%)`));
7541
- this.ctx.log();
7542
- }
7543
- async onWatcherStart() {
7544
- await this.stopListRender();
7545
- const failed = getTests(this.ctx.state.getFiles()).filter((i) => {
7546
- var _a;
7547
- return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
7548
- });
7549
- if (failed.length)
7550
- this.ctx.log(`
7551
- ${c.bold(c.inverse(c.red(" FAIL ")))}${c.red(` ${failed.length} tests failed. Watching for file changes...`)}`);
7552
- else
7553
- this.ctx.log(`
7554
- ${c.bold(c.inverse(c.green(" PASS ")))}${c.green(" Waiting for file changes...")}`);
7555
- if (this.isFirstWatchRun) {
7556
- this.isFirstWatchRun = false;
7557
- this.ctx.log(c.gray("press any key to exit..."));
7558
- }
7559
- }
7560
- async onWatcherRerun(files, trigger) {
7561
- await this.stopListRender();
7562
- this.watchFilters = files;
7563
- if (!this.ctx.config.silent) {
7564
- this.ctx.console.clear();
7565
- this.ctx.log(c.blue("Re-running tests...") + c.dim(` [ ${this.relative(trigger)} ]
7566
- `));
7567
- }
7568
- }
7569
- async stopListRender() {
7570
- var _a;
7571
- (_a = this.renderer) == null ? void 0 : _a.stop();
7572
- this.renderer = void 0;
7573
- await new Promise((resolve) => setTimeout(resolve, 10));
7574
- }
7575
- onUserConsoleLog(log) {
7576
- var _a;
7577
- (_a = this.renderer) == null ? void 0 : _a.clear();
7578
- const task = log.taskId ? this.ctx.state.idMap[log.taskId] : void 0;
7579
- this.ctx.log(c.gray(log.type + c.dim(` | ${task ? getFullName(task) : "unknown test"}`)));
7580
- process[log.type].write(`${log.content}
7581
- `);
7582
- }
7583
- onServerRestart() {
7584
- this.ctx.log(c.cyan("Restarted due to config changes..."));
7585
- }
7586
- }
7278
+ if (chunk.edited) {
7279
+ mappings.addEdit(
7280
+ sourceIndex,
7281
+ chunk.content,
7282
+ loc,
7283
+ chunk.storeName ? names.indexOf(chunk.original) : -1
7284
+ );
7285
+ } else {
7286
+ mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
7287
+ }
7587
7288
 
7588
- var charToInteger = {};
7589
- var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
7590
- for (var i = 0; i < chars.length; i++) {
7591
- charToInteger[chars.charCodeAt(i)] = i;
7592
- }
7593
- function encode(decoded) {
7594
- var sourceFileIndex = 0; // second field
7595
- var sourceCodeLine = 0; // third field
7596
- var sourceCodeColumn = 0; // fourth field
7597
- var nameIndex = 0; // fifth field
7598
- var mappings = '';
7599
- for (var i = 0; i < decoded.length; i++) {
7600
- var line = decoded[i];
7601
- if (i > 0)
7602
- mappings += ';';
7603
- if (line.length === 0)
7604
- continue;
7605
- var generatedCodeColumn = 0; // first field
7606
- var lineMappings = [];
7607
- for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
7608
- var segment = line_1[_i];
7609
- var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
7610
- generatedCodeColumn = segment[0];
7611
- if (segment.length > 1) {
7612
- segmentMappings +=
7613
- encodeInteger(segment[1] - sourceFileIndex) +
7614
- encodeInteger(segment[2] - sourceCodeLine) +
7615
- encodeInteger(segment[3] - sourceCodeColumn);
7616
- sourceFileIndex = segment[1];
7617
- sourceCodeLine = segment[2];
7618
- sourceCodeColumn = segment[3];
7619
- }
7620
- if (segment.length === 5) {
7621
- segmentMappings += encodeInteger(segment[4] - nameIndex);
7622
- nameIndex = segment[4];
7623
- }
7624
- lineMappings.push(segmentMappings);
7625
- }
7626
- mappings += lineMappings.join(',');
7627
- }
7628
- return mappings;
7629
- }
7630
- function encodeInteger(num) {
7631
- var result = '';
7632
- num = num < 0 ? (-num << 1) | 1 : num << 1;
7633
- do {
7634
- var clamped = num & 31;
7635
- num >>>= 5;
7636
- if (num > 0) {
7637
- clamped |= 32;
7638
- }
7639
- result += chars[clamped];
7640
- } while (num > 0);
7641
- return result;
7642
- }
7289
+ if (chunk.outro.length) { mappings.advance(chunk.outro); }
7290
+ });
7643
7291
 
7644
- var BitSet = function BitSet(arg) {
7645
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
7292
+ return {
7293
+ file: options.file ? options.file.split(/[/\\]/).pop() : null,
7294
+ sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
7295
+ sourcesContent: options.includeContent ? [this.original] : [null],
7296
+ names: names,
7297
+ mappings: mappings.raw
7298
+ };
7646
7299
  };
7647
7300
 
7648
- BitSet.prototype.add = function add (n) {
7649
- this.bits[n >> 5] |= 1 << (n & 31);
7301
+ MagicString.prototype.generateMap = function generateMap (options) {
7302
+ return new SourceMap(this.generateDecodedMap(options));
7650
7303
  };
7651
7304
 
7652
- BitSet.prototype.has = function has (n) {
7653
- return !!(this.bits[n >> 5] & (1 << (n & 31)));
7305
+ MagicString.prototype.getIndentString = function getIndentString () {
7306
+ return this.indentStr === null ? '\t' : this.indentStr;
7654
7307
  };
7655
7308
 
7656
- var Chunk = function Chunk(start, end, content) {
7657
- this.start = start;
7658
- this.end = end;
7659
- this.original = content;
7309
+ MagicString.prototype.indent = function indent (indentStr, options) {
7310
+ var pattern = /^[^\r\n]/gm;
7311
+
7312
+ if (isObject(indentStr)) {
7313
+ options = indentStr;
7314
+ indentStr = undefined;
7315
+ }
7316
+
7317
+ indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
7318
+
7319
+ if (indentStr === '') { return this; } // noop
7320
+
7321
+ options = options || {};
7322
+
7323
+ // Process exclusion ranges
7324
+ var isExcluded = {};
7325
+
7326
+ if (options.exclude) {
7327
+ var exclusions =
7328
+ typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
7329
+ exclusions.forEach(function (exclusion) {
7330
+ for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
7331
+ isExcluded[i] = true;
7332
+ }
7333
+ });
7334
+ }
7335
+
7336
+ var shouldIndentNextCharacter = options.indentStart !== false;
7337
+ var replacer = function (match) {
7338
+ if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
7339
+ shouldIndentNextCharacter = true;
7340
+ return match;
7341
+ };
7342
+
7343
+ this.intro = this.intro.replace(pattern, replacer);
7344
+
7345
+ var charIndex = 0;
7346
+ var chunk = this.firstChunk;
7347
+
7348
+ while (chunk) {
7349
+ var end = chunk.end;
7660
7350
 
7661
- this.intro = '';
7662
- this.outro = '';
7351
+ if (chunk.edited) {
7352
+ if (!isExcluded[charIndex]) {
7353
+ chunk.content = chunk.content.replace(pattern, replacer);
7663
7354
 
7664
- this.content = content;
7665
- this.storeName = false;
7666
- this.edited = false;
7355
+ if (chunk.content.length) {
7356
+ shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
7357
+ }
7358
+ }
7359
+ } else {
7360
+ charIndex = chunk.start;
7667
7361
 
7668
- // we make these non-enumerable, for sanity while debugging
7669
- Object.defineProperties(this, {
7670
- previous: { writable: true, value: null },
7671
- next: { writable: true, value: null }
7672
- });
7673
- };
7362
+ while (charIndex < end) {
7363
+ if (!isExcluded[charIndex]) {
7364
+ var char = this.original[charIndex];
7674
7365
 
7675
- Chunk.prototype.appendLeft = function appendLeft (content) {
7676
- this.outro += content;
7677
- };
7366
+ if (char === '\n') {
7367
+ shouldIndentNextCharacter = true;
7368
+ } else if (char !== '\r' && shouldIndentNextCharacter) {
7369
+ shouldIndentNextCharacter = false;
7678
7370
 
7679
- Chunk.prototype.appendRight = function appendRight (content) {
7680
- this.intro = this.intro + content;
7681
- };
7371
+ if (charIndex === chunk.start) {
7372
+ chunk.prependRight(indentStr);
7373
+ } else {
7374
+ this._splitChunk(chunk, charIndex);
7375
+ chunk = chunk.next;
7376
+ chunk.prependRight(indentStr);
7377
+ }
7378
+ }
7379
+ }
7682
7380
 
7683
- Chunk.prototype.clone = function clone () {
7684
- var chunk = new Chunk(this.start, this.end, this.original);
7381
+ charIndex += 1;
7382
+ }
7383
+ }
7685
7384
 
7686
- chunk.intro = this.intro;
7687
- chunk.outro = this.outro;
7688
- chunk.content = this.content;
7689
- chunk.storeName = this.storeName;
7690
- chunk.edited = this.edited;
7385
+ charIndex = chunk.end;
7386
+ chunk = chunk.next;
7387
+ }
7691
7388
 
7692
- return chunk;
7693
- };
7389
+ this.outro = this.outro.replace(pattern, replacer);
7694
7390
 
7695
- Chunk.prototype.contains = function contains (index) {
7696
- return this.start < index && index < this.end;
7391
+ return this;
7697
7392
  };
7698
7393
 
7699
- Chunk.prototype.eachNext = function eachNext (fn) {
7700
- var chunk = this;
7701
- while (chunk) {
7702
- fn(chunk);
7703
- chunk = chunk.next;
7704
- }
7394
+ MagicString.prototype.insert = function insert () {
7395
+ throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
7705
7396
  };
7706
7397
 
7707
- Chunk.prototype.eachPrevious = function eachPrevious (fn) {
7708
- var chunk = this;
7709
- while (chunk) {
7710
- fn(chunk);
7711
- chunk = chunk.previous;
7398
+ MagicString.prototype.insertLeft = function insertLeft (index, content) {
7399
+ if (!warned.insertLeft) {
7400
+ console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
7401
+ warned.insertLeft = true;
7712
7402
  }
7403
+
7404
+ return this.appendLeft(index, content);
7713
7405
  };
7714
7406
 
7715
- Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
7716
- this.content = content;
7717
- if (!contentOnly) {
7718
- this.intro = '';
7719
- this.outro = '';
7407
+ MagicString.prototype.insertRight = function insertRight (index, content) {
7408
+ if (!warned.insertRight) {
7409
+ console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
7410
+ warned.insertRight = true;
7720
7411
  }
7721
- this.storeName = storeName;
7722
-
7723
- this.edited = true;
7724
7412
 
7725
- return this;
7413
+ return this.prependRight(index, content);
7726
7414
  };
7727
7415
 
7728
- Chunk.prototype.prependLeft = function prependLeft (content) {
7729
- this.outro = content + this.outro;
7730
- };
7416
+ MagicString.prototype.move = function move (start, end, index) {
7417
+ if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
7731
7418
 
7732
- Chunk.prototype.prependRight = function prependRight (content) {
7733
- this.intro = content + this.intro;
7734
- };
7419
+ this._split(start);
7420
+ this._split(end);
7421
+ this._split(index);
7735
7422
 
7736
- Chunk.prototype.split = function split (index) {
7737
- var sliceIndex = index - this.start;
7423
+ var first = this.byStart[start];
7424
+ var last = this.byEnd[end];
7738
7425
 
7739
- var originalBefore = this.original.slice(0, sliceIndex);
7740
- var originalAfter = this.original.slice(sliceIndex);
7426
+ var oldLeft = first.previous;
7427
+ var oldRight = last.next;
7741
7428
 
7742
- this.original = originalBefore;
7429
+ var newRight = this.byStart[index];
7430
+ if (!newRight && last === this.lastChunk) { return this; }
7431
+ var newLeft = newRight ? newRight.previous : this.lastChunk;
7743
7432
 
7744
- var newChunk = new Chunk(index, this.end, originalAfter);
7745
- newChunk.outro = this.outro;
7746
- this.outro = '';
7433
+ if (oldLeft) { oldLeft.next = oldRight; }
7434
+ if (oldRight) { oldRight.previous = oldLeft; }
7747
7435
 
7748
- this.end = index;
7436
+ if (newLeft) { newLeft.next = first; }
7437
+ if (newRight) { newRight.previous = last; }
7749
7438
 
7750
- if (this.edited) {
7751
- // TODO is this block necessary?...
7752
- newChunk.edit('', false);
7753
- this.content = '';
7754
- } else {
7755
- this.content = originalBefore;
7439
+ if (!first.previous) { this.firstChunk = last.next; }
7440
+ if (!last.next) {
7441
+ this.lastChunk = first.previous;
7442
+ this.lastChunk.next = null;
7756
7443
  }
7757
7444
 
7758
- newChunk.next = this.next;
7759
- if (newChunk.next) { newChunk.next.previous = newChunk; }
7760
- newChunk.previous = this;
7761
- this.next = newChunk;
7762
-
7763
- return newChunk;
7764
- };
7445
+ first.previous = newLeft;
7446
+ last.next = newRight || null;
7765
7447
 
7766
- Chunk.prototype.toString = function toString () {
7767
- return this.intro + this.content + this.outro;
7448
+ if (!newLeft) { this.firstChunk = first; }
7449
+ if (!newRight) { this.lastChunk = last; }
7450
+ return this;
7768
7451
  };
7769
7452
 
7770
- Chunk.prototype.trimEnd = function trimEnd (rx) {
7771
- this.outro = this.outro.replace(rx, '');
7772
- if (this.outro.length) { return true; }
7773
-
7774
- var trimmed = this.content.replace(rx, '');
7775
-
7776
- if (trimmed.length) {
7777
- if (trimmed !== this.content) {
7778
- this.split(this.start + trimmed.length).edit('', undefined, true);
7779
- }
7780
- return true;
7781
-
7782
- } else {
7783
- this.edit('', undefined, true);
7453
+ MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
7454
+ if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
7784
7455
 
7785
- this.intro = this.intro.replace(rx, '');
7786
- if (this.intro.length) { return true; }
7787
- }
7788
- };
7456
+ while (start < 0) { start += this.original.length; }
7457
+ while (end < 0) { end += this.original.length; }
7789
7458
 
7790
- Chunk.prototype.trimStart = function trimStart (rx) {
7791
- this.intro = this.intro.replace(rx, '');
7792
- if (this.intro.length) { return true; }
7459
+ if (end > this.original.length) { throw new Error('end is out of bounds'); }
7460
+ if (start === end)
7461
+ { throw new Error('Cannot overwrite a zero-length range use appendLeft or prependRight instead'); }
7793
7462
 
7794
- var trimmed = this.content.replace(rx, '');
7463
+ this._split(start);
7464
+ this._split(end);
7795
7465
 
7796
- if (trimmed.length) {
7797
- if (trimmed !== this.content) {
7798
- this.split(this.end - trimmed.length);
7799
- this.edit('', undefined, true);
7466
+ if (options === true) {
7467
+ if (!warned.storeName) {
7468
+ console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
7469
+ warned.storeName = true;
7800
7470
  }
7801
- return true;
7802
-
7803
- } else {
7804
- this.edit('', undefined, true);
7805
7471
 
7806
- this.outro = this.outro.replace(rx, '');
7807
- if (this.outro.length) { return true; }
7472
+ options = { storeName: true };
7808
7473
  }
7809
- };
7810
-
7811
- var btoa = function () {
7812
- throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
7813
- };
7814
- if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
7815
- btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
7816
- } else if (typeof Buffer === 'function') {
7817
- btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
7818
- }
7474
+ var storeName = options !== undefined ? options.storeName : false;
7475
+ var contentOnly = options !== undefined ? options.contentOnly : false;
7819
7476
 
7820
- var SourceMap = function SourceMap(properties) {
7821
- this.version = 3;
7822
- this.file = properties.file;
7823
- this.sources = properties.sources;
7824
- this.sourcesContent = properties.sourcesContent;
7825
- this.names = properties.names;
7826
- this.mappings = encode(properties.mappings);
7827
- };
7477
+ if (storeName) {
7478
+ var original = this.original.slice(start, end);
7479
+ this.storedNames[original] = true;
7480
+ }
7828
7481
 
7829
- SourceMap.prototype.toString = function toString () {
7830
- return JSON.stringify(this);
7831
- };
7482
+ var first = this.byStart[start];
7483
+ var last = this.byEnd[end];
7832
7484
 
7833
- SourceMap.prototype.toUrl = function toUrl () {
7834
- return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
7835
- };
7485
+ if (first) {
7486
+ if (end > first.end && first.next !== this.byStart[first.end]) {
7487
+ throw new Error('Cannot overwrite across a split point');
7488
+ }
7836
7489
 
7837
- function guessIndent(code) {
7838
- var lines = code.split('\n');
7490
+ first.edit(content, storeName, contentOnly);
7839
7491
 
7840
- var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
7841
- var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
7492
+ if (first !== last) {
7493
+ var chunk = first.next;
7494
+ while (chunk !== last) {
7495
+ chunk.edit('', false);
7496
+ chunk = chunk.next;
7497
+ }
7842
7498
 
7843
- if (tabbed.length === 0 && spaced.length === 0) {
7844
- return null;
7845
- }
7499
+ chunk.edit('', false);
7500
+ }
7501
+ } else {
7502
+ // must be inserting at the end
7503
+ var newChunk = new Chunk(start, end, '').edit(content, storeName);
7846
7504
 
7847
- // More lines tabbed than spaced? Assume tabs, and
7848
- // default to tabs in the case of a tie (or nothing
7849
- // to go on)
7850
- if (tabbed.length >= spaced.length) {
7851
- return '\t';
7505
+ // TODO last chunk in the array may not be the last chunk, if it's moved...
7506
+ last.next = newChunk;
7507
+ newChunk.previous = last;
7852
7508
  }
7509
+ return this;
7510
+ };
7853
7511
 
7854
- // Otherwise, we need to guess the multiple
7855
- var min = spaced.reduce(function (previous, current) {
7856
- var numSpaces = /^ +/.exec(current)[0].length;
7857
- return Math.min(numSpaces, previous);
7858
- }, Infinity);
7512
+ MagicString.prototype.prepend = function prepend (content) {
7513
+ if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
7859
7514
 
7860
- return new Array(min + 1).join(' ');
7861
- }
7515
+ this.intro = content + this.intro;
7516
+ return this;
7517
+ };
7862
7518
 
7863
- function getRelativePath(from, to) {
7864
- var fromParts = from.split(/[/\\]/);
7865
- var toParts = to.split(/[/\\]/);
7519
+ MagicString.prototype.prependLeft = function prependLeft (index, content) {
7520
+ if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
7866
7521
 
7867
- fromParts.pop(); // get dirname
7522
+ this._split(index);
7868
7523
 
7869
- while (fromParts[0] === toParts[0]) {
7870
- fromParts.shift();
7871
- toParts.shift();
7872
- }
7524
+ var chunk = this.byEnd[index];
7873
7525
 
7874
- if (fromParts.length) {
7875
- var i = fromParts.length;
7876
- while (i--) { fromParts[i] = '..'; }
7526
+ if (chunk) {
7527
+ chunk.prependLeft(content);
7528
+ } else {
7529
+ this.intro = content + this.intro;
7877
7530
  }
7531
+ return this;
7532
+ };
7878
7533
 
7879
- return fromParts.concat(toParts).join('/');
7880
- }
7881
-
7882
- var toString = Object.prototype.toString;
7534
+ MagicString.prototype.prependRight = function prependRight (index, content) {
7535
+ if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
7883
7536
 
7884
- function isObject(thing) {
7885
- return toString.call(thing) === '[object Object]';
7886
- }
7537
+ this._split(index);
7887
7538
 
7888
- function getLocator(source) {
7889
- var originalLines = source.split('\n');
7890
- var lineOffsets = [];
7539
+ var chunk = this.byStart[index];
7891
7540
 
7892
- for (var i = 0, pos = 0; i < originalLines.length; i++) {
7893
- lineOffsets.push(pos);
7894
- pos += originalLines[i].length + 1;
7541
+ if (chunk) {
7542
+ chunk.prependRight(content);
7543
+ } else {
7544
+ this.outro = content + this.outro;
7895
7545
  }
7546
+ return this;
7547
+ };
7896
7548
 
7897
- return function locate(index) {
7898
- var i = 0;
7899
- var j = lineOffsets.length;
7900
- while (i < j) {
7901
- var m = (i + j) >> 1;
7902
- if (index < lineOffsets[m]) {
7903
- j = m;
7904
- } else {
7905
- i = m + 1;
7906
- }
7907
- }
7908
- var line = i - 1;
7909
- var column = index - lineOffsets[line];
7910
- return { line: line, column: column };
7911
- };
7912
- }
7549
+ MagicString.prototype.remove = function remove (start, end) {
7550
+ while (start < 0) { start += this.original.length; }
7551
+ while (end < 0) { end += this.original.length; }
7913
7552
 
7914
- var Mappings = function Mappings(hires) {
7915
- this.hires = hires;
7916
- this.generatedCodeLine = 0;
7917
- this.generatedCodeColumn = 0;
7918
- this.raw = [];
7919
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
7920
- this.pending = null;
7921
- };
7553
+ if (start === end) { return this; }
7922
7554
 
7923
- Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
7924
- if (content.length) {
7925
- var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
7926
- if (nameIndex >= 0) {
7927
- segment.push(nameIndex);
7928
- }
7929
- this.rawSegments.push(segment);
7930
- } else if (this.pending) {
7931
- this.rawSegments.push(this.pending);
7932
- }
7555
+ if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
7556
+ if (start > end) { throw new Error('end must be greater than start'); }
7933
7557
 
7934
- this.advance(content);
7935
- this.pending = null;
7558
+ this._split(start);
7559
+ this._split(end);
7560
+
7561
+ var chunk = this.byStart[start];
7562
+
7563
+ while (chunk) {
7564
+ chunk.intro = '';
7565
+ chunk.outro = '';
7566
+ chunk.edit('');
7567
+
7568
+ chunk = end > chunk.end ? this.byStart[chunk.end] : null;
7569
+ }
7570
+ return this;
7936
7571
  };
7937
7572
 
7938
- Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
7939
- var originalCharIndex = chunk.start;
7940
- var first = true;
7573
+ MagicString.prototype.lastChar = function lastChar () {
7574
+ if (this.outro.length)
7575
+ { return this.outro[this.outro.length - 1]; }
7576
+ var chunk = this.lastChunk;
7577
+ do {
7578
+ if (chunk.outro.length)
7579
+ { return chunk.outro[chunk.outro.length - 1]; }
7580
+ if (chunk.content.length)
7581
+ { return chunk.content[chunk.content.length - 1]; }
7582
+ if (chunk.intro.length)
7583
+ { return chunk.intro[chunk.intro.length - 1]; }
7584
+ } while (chunk = chunk.previous);
7585
+ if (this.intro.length)
7586
+ { return this.intro[this.intro.length - 1]; }
7587
+ return '';
7588
+ };
7941
7589
 
7942
- while (originalCharIndex < chunk.end) {
7943
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
7944
- this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
7590
+ MagicString.prototype.lastLine = function lastLine () {
7591
+ var lineIndex = this.outro.lastIndexOf(n);
7592
+ if (lineIndex !== -1)
7593
+ { return this.outro.substr(lineIndex + 1); }
7594
+ var lineStr = this.outro;
7595
+ var chunk = this.lastChunk;
7596
+ do {
7597
+ if (chunk.outro.length > 0) {
7598
+ lineIndex = chunk.outro.lastIndexOf(n);
7599
+ if (lineIndex !== -1)
7600
+ { return chunk.outro.substr(lineIndex + 1) + lineStr; }
7601
+ lineStr = chunk.outro + lineStr;
7945
7602
  }
7946
7603
 
7947
- if (original[originalCharIndex] === '\n') {
7948
- loc.line += 1;
7949
- loc.column = 0;
7950
- this.generatedCodeLine += 1;
7951
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
7952
- this.generatedCodeColumn = 0;
7953
- first = true;
7954
- } else {
7955
- loc.column += 1;
7956
- this.generatedCodeColumn += 1;
7957
- first = false;
7604
+ if (chunk.content.length > 0) {
7605
+ lineIndex = chunk.content.lastIndexOf(n);
7606
+ if (lineIndex !== -1)
7607
+ { return chunk.content.substr(lineIndex + 1) + lineStr; }
7608
+ lineStr = chunk.content + lineStr;
7958
7609
  }
7959
7610
 
7960
- originalCharIndex += 1;
7961
- }
7962
-
7963
- this.pending = null;
7611
+ if (chunk.intro.length > 0) {
7612
+ lineIndex = chunk.intro.lastIndexOf(n);
7613
+ if (lineIndex !== -1)
7614
+ { return chunk.intro.substr(lineIndex + 1) + lineStr; }
7615
+ lineStr = chunk.intro + lineStr;
7616
+ }
7617
+ } while (chunk = chunk.previous);
7618
+ lineIndex = this.intro.lastIndexOf(n);
7619
+ if (lineIndex !== -1)
7620
+ { return this.intro.substr(lineIndex + 1) + lineStr; }
7621
+ return this.intro + lineStr;
7964
7622
  };
7965
7623
 
7966
- Mappings.prototype.advance = function advance (str) {
7967
- if (!str) { return; }
7624
+ MagicString.prototype.slice = function slice (start, end) {
7625
+ if ( start === void 0 ) start = 0;
7626
+ if ( end === void 0 ) end = this.original.length;
7968
7627
 
7969
- var lines = str.split('\n');
7628
+ while (start < 0) { start += this.original.length; }
7629
+ while (end < 0) { end += this.original.length; }
7970
7630
 
7971
- if (lines.length > 1) {
7972
- for (var i = 0; i < lines.length - 1; i++) {
7973
- this.generatedCodeLine++;
7974
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
7631
+ var result = '';
7632
+
7633
+ // find start chunk
7634
+ var chunk = this.firstChunk;
7635
+ while (chunk && (chunk.start > start || chunk.end <= start)) {
7636
+ // found end chunk before start
7637
+ if (chunk.start < end && chunk.end >= end) {
7638
+ return result;
7975
7639
  }
7976
- this.generatedCodeColumn = 0;
7640
+
7641
+ chunk = chunk.next;
7977
7642
  }
7978
7643
 
7979
- this.generatedCodeColumn += lines[lines.length - 1].length;
7980
- };
7644
+ if (chunk && chunk.edited && chunk.start !== start)
7645
+ { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
7981
7646
 
7982
- var n = '\n';
7647
+ var startChunk = chunk;
7648
+ while (chunk) {
7649
+ if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
7650
+ result += chunk.intro;
7651
+ }
7983
7652
 
7984
- var warned = {
7985
- insertLeft: false,
7986
- insertRight: false,
7987
- storeName: false
7988
- };
7653
+ var containsEnd = chunk.start < end && chunk.end >= end;
7654
+ if (containsEnd && chunk.edited && chunk.end !== end)
7655
+ { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
7989
7656
 
7990
- var MagicString = function MagicString(string, options) {
7991
- if ( options === void 0 ) options = {};
7657
+ var sliceStart = startChunk === chunk ? start - chunk.start : 0;
7658
+ var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
7992
7659
 
7993
- var chunk = new Chunk(0, string.length, string);
7660
+ result += chunk.content.slice(sliceStart, sliceEnd);
7994
7661
 
7995
- Object.defineProperties(this, {
7996
- original: { writable: true, value: string },
7997
- outro: { writable: true, value: '' },
7998
- intro: { writable: true, value: '' },
7999
- firstChunk: { writable: true, value: chunk },
8000
- lastChunk: { writable: true, value: chunk },
8001
- lastSearchedChunk: { writable: true, value: chunk },
8002
- byStart: { writable: true, value: {} },
8003
- byEnd: { writable: true, value: {} },
8004
- filename: { writable: true, value: options.filename },
8005
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
8006
- sourcemapLocations: { writable: true, value: new BitSet() },
8007
- storedNames: { writable: true, value: {} },
8008
- indentStr: { writable: true, value: guessIndent(string) }
8009
- });
7662
+ if (chunk.outro && (!containsEnd || chunk.end === end)) {
7663
+ result += chunk.outro;
7664
+ }
8010
7665
 
8011
- this.byStart[0] = chunk;
8012
- this.byEnd[string.length] = chunk;
8013
- };
7666
+ if (containsEnd) {
7667
+ break;
7668
+ }
8014
7669
 
8015
- MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
8016
- this.sourcemapLocations.add(char);
7670
+ chunk = chunk.next;
7671
+ }
7672
+
7673
+ return result;
8017
7674
  };
8018
7675
 
8019
- MagicString.prototype.append = function append (content) {
8020
- if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
7676
+ // TODO deprecate this? not really very useful
7677
+ MagicString.prototype.snip = function snip (start, end) {
7678
+ var clone = this.clone();
7679
+ clone.remove(0, start);
7680
+ clone.remove(end, clone.original.length);
8021
7681
 
8022
- this.outro += content;
8023
- return this;
7682
+ return clone;
8024
7683
  };
8025
7684
 
8026
- MagicString.prototype.appendLeft = function appendLeft (index, content) {
8027
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
7685
+ MagicString.prototype._split = function _split (index) {
7686
+ if (this.byStart[index] || this.byEnd[index]) { return; }
8028
7687
 
8029
- this._split(index);
7688
+ var chunk = this.lastSearchedChunk;
7689
+ var searchForward = index > chunk.end;
8030
7690
 
8031
- var chunk = this.byEnd[index];
7691
+ while (chunk) {
7692
+ if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
8032
7693
 
8033
- if (chunk) {
8034
- chunk.appendLeft(content);
8035
- } else {
8036
- this.intro += content;
7694
+ chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
8037
7695
  }
8038
- return this;
8039
7696
  };
8040
7697
 
8041
- MagicString.prototype.appendRight = function appendRight (index, content) {
8042
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
7698
+ MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
7699
+ if (chunk.edited && chunk.content.length) {
7700
+ // zero-length edited chunks are a special case (overlapping replacements)
7701
+ var loc = getLocator(this.original)(index);
7702
+ throw new Error(
7703
+ ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
7704
+ );
7705
+ }
8043
7706
 
8044
- this._split(index);
7707
+ var newChunk = chunk.split(index);
8045
7708
 
8046
- var chunk = this.byStart[index];
7709
+ this.byEnd[index] = chunk;
7710
+ this.byStart[index] = newChunk;
7711
+ this.byEnd[newChunk.end] = newChunk;
8047
7712
 
8048
- if (chunk) {
8049
- chunk.appendRight(content);
8050
- } else {
8051
- this.outro += content;
7713
+ if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
7714
+
7715
+ this.lastSearchedChunk = chunk;
7716
+ return true;
7717
+ };
7718
+
7719
+ MagicString.prototype.toString = function toString () {
7720
+ var str = this.intro;
7721
+
7722
+ var chunk = this.firstChunk;
7723
+ while (chunk) {
7724
+ str += chunk.toString();
7725
+ chunk = chunk.next;
8052
7726
  }
8053
- return this;
7727
+
7728
+ return str + this.outro;
8054
7729
  };
8055
7730
 
8056
- MagicString.prototype.clone = function clone () {
8057
- var cloned = new MagicString(this.original, { filename: this.filename });
7731
+ MagicString.prototype.isEmpty = function isEmpty () {
7732
+ var chunk = this.firstChunk;
7733
+ do {
7734
+ if (chunk.intro.length && chunk.intro.trim() ||
7735
+ chunk.content.length && chunk.content.trim() ||
7736
+ chunk.outro.length && chunk.outro.trim())
7737
+ { return false; }
7738
+ } while (chunk = chunk.next);
7739
+ return true;
7740
+ };
8058
7741
 
8059
- var originalChunk = this.firstChunk;
8060
- var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
7742
+ MagicString.prototype.length = function length () {
7743
+ var chunk = this.firstChunk;
7744
+ var length = 0;
7745
+ do {
7746
+ length += chunk.intro.length + chunk.content.length + chunk.outro.length;
7747
+ } while (chunk = chunk.next);
7748
+ return length;
7749
+ };
8061
7750
 
8062
- while (originalChunk) {
8063
- cloned.byStart[clonedChunk.start] = clonedChunk;
8064
- cloned.byEnd[clonedChunk.end] = clonedChunk;
7751
+ MagicString.prototype.trimLines = function trimLines () {
7752
+ return this.trim('[\\r\\n]');
7753
+ };
8065
7754
 
8066
- var nextOriginalChunk = originalChunk.next;
8067
- var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
7755
+ MagicString.prototype.trim = function trim (charType) {
7756
+ return this.trimStart(charType).trimEnd(charType);
7757
+ };
8068
7758
 
8069
- if (nextClonedChunk) {
8070
- clonedChunk.next = nextClonedChunk;
8071
- nextClonedChunk.previous = clonedChunk;
7759
+ MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
7760
+ var rx = new RegExp((charType || '\\s') + '+$');
8072
7761
 
8073
- clonedChunk = nextClonedChunk;
8074
- }
7762
+ this.outro = this.outro.replace(rx, '');
7763
+ if (this.outro.length) { return true; }
8075
7764
 
8076
- originalChunk = nextOriginalChunk;
8077
- }
7765
+ var chunk = this.lastChunk;
8078
7766
 
8079
- cloned.lastChunk = clonedChunk;
7767
+ do {
7768
+ var end = chunk.end;
7769
+ var aborted = chunk.trimEnd(rx);
8080
7770
 
8081
- if (this.indentExclusionRanges) {
8082
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
8083
- }
7771
+ // if chunk was trimmed, we have a new lastChunk
7772
+ if (chunk.end !== end) {
7773
+ if (this.lastChunk === chunk) {
7774
+ this.lastChunk = chunk.next;
7775
+ }
8084
7776
 
8085
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
7777
+ this.byEnd[chunk.end] = chunk;
7778
+ this.byStart[chunk.next.start] = chunk.next;
7779
+ this.byEnd[chunk.next.end] = chunk.next;
7780
+ }
8086
7781
 
8087
- cloned.intro = this.intro;
8088
- cloned.outro = this.outro;
7782
+ if (aborted) { return true; }
7783
+ chunk = chunk.previous;
7784
+ } while (chunk);
8089
7785
 
8090
- return cloned;
7786
+ return false;
8091
7787
  };
8092
7788
 
8093
- MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
8094
- var this$1$1 = this;
7789
+ MagicString.prototype.trimEnd = function trimEnd (charType) {
7790
+ this.trimEndAborted(charType);
7791
+ return this;
7792
+ };
7793
+ MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
7794
+ var rx = new RegExp('^' + (charType || '\\s') + '+');
8095
7795
 
8096
- options = options || {};
7796
+ this.intro = this.intro.replace(rx, '');
7797
+ if (this.intro.length) { return true; }
8097
7798
 
8098
- var sourceIndex = 0;
8099
- var names = Object.keys(this.storedNames);
8100
- var mappings = new Mappings(options.hires);
7799
+ var chunk = this.firstChunk;
8101
7800
 
8102
- var locate = getLocator(this.original);
7801
+ do {
7802
+ var end = chunk.end;
7803
+ var aborted = chunk.trimStart(rx);
8103
7804
 
8104
- if (this.intro) {
8105
- mappings.advance(this.intro);
8106
- }
7805
+ if (chunk.end !== end) {
7806
+ // special case...
7807
+ if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
8107
7808
 
8108
- this.firstChunk.eachNext(function (chunk) {
8109
- var loc = locate(chunk.start);
7809
+ this.byEnd[chunk.end] = chunk;
7810
+ this.byStart[chunk.next.start] = chunk.next;
7811
+ this.byEnd[chunk.next.end] = chunk.next;
7812
+ }
8110
7813
 
8111
- if (chunk.intro.length) { mappings.advance(chunk.intro); }
7814
+ if (aborted) { return true; }
7815
+ chunk = chunk.next;
7816
+ } while (chunk);
8112
7817
 
8113
- if (chunk.edited) {
8114
- mappings.addEdit(
8115
- sourceIndex,
8116
- chunk.content,
8117
- loc,
8118
- chunk.storeName ? names.indexOf(chunk.original) : -1
8119
- );
8120
- } else {
8121
- mappings.addUneditedChunk(sourceIndex, chunk, this$1$1.original, loc, this$1$1.sourcemapLocations);
8122
- }
7818
+ return false;
7819
+ };
8123
7820
 
8124
- if (chunk.outro.length) { mappings.advance(chunk.outro); }
8125
- });
7821
+ MagicString.prototype.trimStart = function trimStart (charType) {
7822
+ this.trimStartAborted(charType);
7823
+ return this;
7824
+ };
8126
7825
 
8127
- return {
8128
- file: options.file ? options.file.split(/[/\\]/).pop() : null,
8129
- sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
8130
- sourcesContent: options.includeContent ? [this.original] : [null],
8131
- names: names,
8132
- mappings: mappings.raw
8133
- };
7826
+ const mockRegexp = /\b((?:vitest|vi)\s*.\s*mock\(["`'\s](.*[@\w_-]+)["`'\s])[),]{1}/;
7827
+ const pathRegexp = /\b(?:vitest|vi)\s*.\s*(unmock|importActual|importMock)\(["`'\s](.*[@\w_-]+)["`'\s]\);?/mg;
7828
+ const isComment = (line) => {
7829
+ const commentStarts = ["//", "/*", "*"];
7830
+ line = line.trim();
7831
+ return commentStarts.some((cmt) => line.startsWith(cmt));
7832
+ };
7833
+ const parseMocks = (code) => {
7834
+ const splitted = code.split("\n");
7835
+ const mockCalls = {};
7836
+ let mockCall = 0;
7837
+ let lineIndex = -1;
7838
+ while (lineIndex < splitted.length) {
7839
+ lineIndex++;
7840
+ const line = splitted[lineIndex];
7841
+ if (!line)
7842
+ break;
7843
+ const mock = mockCalls[mockCall] || {
7844
+ code: "",
7845
+ declaraton: "",
7846
+ path: ""
7847
+ };
7848
+ if (!mock.code) {
7849
+ const started = mockRegexp.exec(line);
7850
+ if (!started || isComment(line))
7851
+ continue;
7852
+ mock.code += `${line}
7853
+ `;
7854
+ mock.declaraton = started[1];
7855
+ mock.path = started[2];
7856
+ mockCalls[mockCall] = mock;
7857
+ if (line.includes(");")) {
7858
+ mockCall++;
7859
+ continue;
7860
+ }
7861
+ continue;
7862
+ }
7863
+ mock.code += `${line}
7864
+ `;
7865
+ mockCalls[mockCall] = mock;
7866
+ const startNumber = (mock.code.match(/{/g) || []).length;
7867
+ const endNumber = (mock.code.match(/}/g) || []).length;
7868
+ if (line.includes(");")) {
7869
+ if (startNumber === endNumber || startNumber === 0 && endNumber === 0)
7870
+ mockCall++;
7871
+ }
7872
+ }
7873
+ return Object.values(mockCalls);
7874
+ };
7875
+ const getMethodCall = (method, actualPath, importPath) => {
7876
+ let nodeModule = "null";
7877
+ if (actualPath.includes("/node_modules/"))
7878
+ nodeModule = `"${importPath}"`;
7879
+ return `__vitest__${method}__("${actualPath}", ${nodeModule}`;
7880
+ };
7881
+ const MocksPlugin = () => {
7882
+ return {
7883
+ name: "vitest:mock-plugin",
7884
+ enforce: "post",
7885
+ async transform(code, id) {
7886
+ let m;
7887
+ const matchAll = code.matchAll(pathRegexp);
7888
+ for (const match of matchAll) {
7889
+ const [line, method, modulePath] = match;
7890
+ const filepath = await this.resolve(modulePath, id);
7891
+ if (filepath) {
7892
+ m ?? (m = new MagicString(code));
7893
+ const start = match.index || 0;
7894
+ const end = start + line.length;
7895
+ const overwrite = `${getMethodCall(method, filepath.id, modulePath)});`;
7896
+ m.overwrite(start, end, overwrite);
7897
+ }
7898
+ }
7899
+ if (mockRegexp.exec(code)) {
7900
+ const mocks = parseMocks((m == null ? void 0 : m.toString()) || code);
7901
+ for (const mock of mocks) {
7902
+ const filepath = await this.resolve(mock.path, id);
7903
+ if (!filepath)
7904
+ continue;
7905
+ m ?? (m = new MagicString(code));
7906
+ const overwrite = getMethodCall("mock", filepath.id, mock.path);
7907
+ m.prepend(mock.code.replace(mock.declaraton, overwrite));
7908
+ }
7909
+ }
7910
+ if (m) {
7911
+ return {
7912
+ code: m.toString(),
7913
+ map: m.generateMap()
7914
+ };
7915
+ }
7916
+ }
7917
+ };
8134
7918
  };
8135
7919
 
8136
- MagicString.prototype.generateMap = function generateMap (options) {
8137
- return new SourceMap(this.generateDecodedMap(options));
8138
- };
7920
+ const spinnerMap = /* @__PURE__ */ new WeakMap();
7921
+ const pointer = c.yellow(F_POINTER);
7922
+ const skipped = c.yellow(F_DOWN);
7923
+ function getCols(delta = 0) {
7924
+ let length = process.stdout.columns;
7925
+ if (!length || isNaN(length))
7926
+ length = 30;
7927
+ return Math.max(length + delta, 0);
7928
+ }
7929
+ function divider(text, left, right) {
7930
+ const cols = getCols();
7931
+ if (text) {
7932
+ const textLength = stripAnsi(text).length;
7933
+ if (left == null && right != null) {
7934
+ left = cols - textLength - right;
7935
+ } else {
7936
+ left = left ?? Math.floor((cols - textLength) / 2);
7937
+ right = cols - textLength - left;
7938
+ }
7939
+ left = Math.max(0, left);
7940
+ right = Math.max(0, right);
7941
+ return `${F_LONG_DASH.repeat(left)}${text}${F_LONG_DASH.repeat(right)}`;
7942
+ }
7943
+ return F_LONG_DASH.repeat(cols);
7944
+ }
7945
+ function formatTestPath(root, path) {
7946
+ var _a;
7947
+ if (isAbsolute(path))
7948
+ path = relative(root, path);
7949
+ const dir = dirname(path);
7950
+ const ext = ((_a = path.match(/(\.(spec|test)\.[cm]?[tj]sx?)$/)) == null ? void 0 : _a[0]) || "";
7951
+ const base = basename(path, ext);
7952
+ return slash$1(c.dim(`${dir}/`) + c.bold(base)) + c.dim(ext);
7953
+ }
7954
+ function renderSnapshotSummary(rootDir, snapshots) {
7955
+ const summary = [];
7956
+ if (snapshots.added)
7957
+ summary.push(c.bold(c.green(`${snapshots.added} written`)));
7958
+ if (snapshots.unmatched)
7959
+ summary.push(c.bold(c.red(`${snapshots.unmatched} failed`)));
7960
+ if (snapshots.updated)
7961
+ summary.push(c.bold(c.green(`${snapshots.updated} updated `)));
7962
+ if (snapshots.filesRemoved) {
7963
+ if (snapshots.didUpdate)
7964
+ summary.push(c.bold(c.green(`${snapshots.filesRemoved} files removed `)));
7965
+ else
7966
+ summary.push(c.bold(c.yellow(`${snapshots.filesRemoved} files obsolete `)));
7967
+ }
7968
+ if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
7969
+ const [head, ...tail] = snapshots.filesRemovedList;
7970
+ summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, head)}`);
7971
+ tail.forEach((key) => {
7972
+ summary.push(` ${c.gray(F_DOT)} ${formatTestPath(rootDir, key)}`);
7973
+ });
7974
+ }
7975
+ if (snapshots.unchecked) {
7976
+ if (snapshots.didUpdate)
7977
+ summary.push(c.bold(c.green(`${snapshots.unchecked} removed`)));
7978
+ else
7979
+ summary.push(c.bold(c.yellow(`${snapshots.unchecked} obsolete`)));
7980
+ snapshots.uncheckedKeysByFile.forEach((uncheckedFile) => {
7981
+ summary.push(`${c.gray(F_DOWN_RIGHT)} ${formatTestPath(rootDir, uncheckedFile.filePath)}`);
7982
+ uncheckedFile.keys.forEach((key) => summary.push(` ${c.gray(F_DOT)} ${key}`));
7983
+ });
7984
+ }
7985
+ return summary;
7986
+ }
7987
+ function getStateString(tasks, name = "tests") {
7988
+ if (tasks.length === 0)
7989
+ return c.dim(`no ${name}`);
7990
+ const passed = tasks.filter((i) => {
7991
+ var _a;
7992
+ return ((_a = i.result) == null ? void 0 : _a.state) === "pass";
7993
+ });
7994
+ const failed = tasks.filter((i) => {
7995
+ var _a;
7996
+ return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
7997
+ });
7998
+ const skipped2 = tasks.filter((i) => i.mode === "skip");
7999
+ const todo = tasks.filter((i) => i.mode === "todo");
8000
+ return [
8001
+ failed.length ? c.bold(c.red(`${failed.length} failed`)) : null,
8002
+ passed.length ? c.bold(c.green(`${passed.length} passed`)) : null,
8003
+ skipped2.length ? c.yellow(`${skipped2.length} skipped`) : null,
8004
+ todo.length ? c.gray(`${todo.length} todo`) : null
8005
+ ].filter(Boolean).join(c.dim(" | ")) + c.gray(` (${tasks.length})`);
8006
+ }
8007
+ function getStateSymbol(task) {
8008
+ if (task.mode === "skip" || task.mode === "todo")
8009
+ return skipped;
8010
+ if (!task.result)
8011
+ return c.gray("\xB7");
8012
+ if (task.result.state === "run") {
8013
+ if (task.type === "suite")
8014
+ return pointer;
8015
+ let spinner = spinnerMap.get(task);
8016
+ if (!spinner) {
8017
+ spinner = elegantSpinner();
8018
+ spinnerMap.set(task, spinner);
8019
+ }
8020
+ return c.yellow(spinner());
8021
+ }
8022
+ if (task.result.state === "pass")
8023
+ return c.green(F_CHECK);
8024
+ if (task.result.state === "fail") {
8025
+ return task.type === "suite" ? pointer : c.red(F_CROSS);
8026
+ }
8027
+ return " ";
8028
+ }
8029
+ const spinnerFrames = process.platform === "win32" ? ["-", "\\", "|", "/"] : ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
8030
+ function elegantSpinner() {
8031
+ let index = 0;
8032
+ return () => {
8033
+ index = ++index % spinnerFrames.length;
8034
+ return spinnerFrames[index];
8035
+ };
8036
+ }
8037
+
8038
+ class BaseReporter {
8039
+ constructor(ctx) {
8040
+ this.ctx = ctx;
8041
+ this.start = 0;
8042
+ this.end = 0;
8043
+ this.isTTY = process.stdout.isTTY && !process.env.CI;
8044
+ this.isFirstWatchRun = true;
8045
+ const mode = ctx.config.watch ? c.yellow(" DEV ") : c.cyan(" RUN ");
8046
+ this.ctx.log(`
8047
+ ${c.inverse(c.bold(mode))} ${c.gray(this.ctx.config.root)}
8048
+ `);
8049
+ this.start = performance.now();
8050
+ }
8051
+ relative(path) {
8052
+ return relative(this.ctx.config.root, path);
8053
+ }
8054
+ async onFinished(files = this.ctx.state.getFiles()) {
8055
+ this.end = performance.now();
8056
+ await this.reportSummary(files);
8057
+ }
8058
+ onTaskUpdate(pack) {
8059
+ var _a, _b, _c;
8060
+ if (this.isTTY)
8061
+ return;
8062
+ const task = this.ctx.state.idMap[pack[0]];
8063
+ if (task.type === "test" && ((_a = task.result) == null ? void 0 : _a.state) && ((_b = task.result) == null ? void 0 : _b.state) !== "run") {
8064
+ this.ctx.log(` ${getStateSymbol(task)} ${getFullName(task)}`);
8065
+ if (task.result.state === "fail")
8066
+ this.ctx.log(c.red(` ${F_RIGHT} ${(_c = task.result.error) == null ? void 0 : _c.message}`));
8067
+ }
8068
+ }
8069
+ async onWatcherStart() {
8070
+ const failed = getTests(this.ctx.state.getFiles()).filter((i) => {
8071
+ var _a;
8072
+ return ((_a = i.result) == null ? void 0 : _a.state) === "fail";
8073
+ });
8074
+ if (failed.length)
8075
+ this.ctx.log(`
8076
+ ${c.bold(c.inverse(c.red(" FAIL ")))}${c.red(` ${failed.length} tests failed. Watching for file changes...`)}`);
8077
+ else
8078
+ this.ctx.log(`
8079
+ ${c.bold(c.inverse(c.green(" PASS ")))}${c.green(" Waiting for file changes...")}`);
8080
+ if (this.isFirstWatchRun) {
8081
+ this.isFirstWatchRun = false;
8082
+ this.ctx.log(c.gray("press any key to exit..."));
8083
+ }
8084
+ }
8085
+ async onWatcherRerun(files, trigger) {
8086
+ this.watchFilters = files;
8087
+ if (!this.ctx.config.silent) {
8088
+ this.ctx.console.clear();
8089
+ this.ctx.log(c.blue("Re-running tests...") + c.dim(` [ ${this.relative(trigger)} ]
8090
+ `));
8091
+ }
8092
+ }
8093
+ onUserConsoleLog(log) {
8094
+ const task = log.taskId ? this.ctx.state.idMap[log.taskId] : void 0;
8095
+ this.ctx.log(c.gray(log.type + c.dim(` | ${task ? getFullName(task) : "unknown test"}`)));
8096
+ process[log.type].write(`${log.content}
8097
+ `);
8098
+ }
8099
+ onServerRestart() {
8100
+ this.ctx.log(c.cyan("Restarted due to config changes..."));
8101
+ }
8102
+ async reportSummary(files) {
8103
+ var _a, _b;
8104
+ const suites = getSuites(files);
8105
+ const tests = getTests(files);
8106
+ const failedSuites = suites.filter((i) => {
8107
+ var _a2;
8108
+ return (_a2 = i.result) == null ? void 0 : _a2.error;
8109
+ });
8110
+ const failedTests = tests.filter((i) => {
8111
+ var _a2;
8112
+ return ((_a2 = i.result) == null ? void 0 : _a2.state) === "fail";
8113
+ });
8114
+ const failedTotal = failedSuites.length + failedTests.length;
8115
+ let current = 1;
8116
+ const errorDivider = () => this.ctx.error(`${c.red(c.dim(divider(`[${current++}/${failedTotal}]`, void 0, 1)))}
8117
+ `);
8118
+ if (failedSuites.length) {
8119
+ this.ctx.error(c.red(divider(c.bold(c.inverse(` Failed Suites ${failedSuites.length} `)))));
8120
+ this.ctx.error();
8121
+ for (const suite of failedSuites) {
8122
+ const filepath = (suite == null ? void 0 : suite.filepath) || "";
8123
+ this.ctx.error(c.red(`
8124
+ - ${getFullName(suite)} ${c.dim(`[ ${this.relative(filepath)} ]`)}`));
8125
+ await printError((_a = suite.result) == null ? void 0 : _a.error, this.ctx);
8126
+ errorDivider();
8127
+ }
8128
+ }
8129
+ if (failedTests.length) {
8130
+ this.ctx.error(c.red(divider(c.bold(c.inverse(` Failed Tests ${failedTests.length} `)))));
8131
+ this.ctx.error();
8132
+ for (const test of failedTests) {
8133
+ this.ctx.error(`${c.red(c.bold(c.inverse(" FAIL ")))} ${getFullName(test)}`);
8134
+ await printError((_b = test.result) == null ? void 0 : _b.error, this.ctx);
8135
+ errorDivider();
8136
+ }
8137
+ }
8138
+ const executionTime = this.end - this.start;
8139
+ const threadTime = tests.reduce((acc, test) => {
8140
+ var _a2;
8141
+ return acc + (((_a2 = test.result) == null ? void 0 : _a2.end) ? test.result.end - test.result.start : 0);
8142
+ }, 0);
8143
+ const padTitle = (str) => c.dim(`${str.padStart(10)} `);
8144
+ const time = (time2) => {
8145
+ if (time2 > 1e3)
8146
+ return `${(time2 / 1e3).toFixed(2)}s`;
8147
+ return `${Math.round(time2)}ms`;
8148
+ };
8149
+ const snapshotOutput = renderSnapshotSummary(this.ctx.config.root, this.ctx.snapshot.summary);
8150
+ if (snapshotOutput.length) {
8151
+ this.ctx.log(snapshotOutput.map((t, i) => i === 0 ? `${padTitle("Snapshots")} ${t}` : `${padTitle("")} ${t}`).join("\n"));
8152
+ if (snapshotOutput.length > 1)
8153
+ this.ctx.log();
8154
+ }
8155
+ this.ctx.log(padTitle("Test Files"), getStateString(files));
8156
+ this.ctx.log(padTitle("Tests"), getStateString(tests));
8157
+ if (this.watchFilters)
8158
+ this.ctx.log(padTitle("Time"), time(threadTime));
8159
+ else
8160
+ this.ctx.log(padTitle("Time"), time(executionTime) + c.gray(` (in thread ${time(threadTime)}, ${(executionTime / threadTime * 100).toFixed(2)}%)`));
8161
+ this.ctx.log();
8162
+ }
8163
+ }
8139
8164
 
8140
- MagicString.prototype.getIndentString = function getIndentString () {
8141
- return this.indentStr === null ? '\t' : this.indentStr;
8142
- };
8165
+ const ESC = '\u001B[';
8166
+ const OSC = '\u001B]';
8167
+ const BEL = '\u0007';
8168
+ const SEP = ';';
8169
+ const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal';
8143
8170
 
8144
- MagicString.prototype.indent = function indent (indentStr, options) {
8145
- var pattern = /^[^\r\n]/gm;
8171
+ const ansiEscapes = {};
8146
8172
 
8147
- if (isObject(indentStr)) {
8148
- options = indentStr;
8149
- indentStr = undefined;
8173
+ ansiEscapes.cursorTo = (x, y) => {
8174
+ if (typeof x !== 'number') {
8175
+ throw new TypeError('The `x` argument is required');
8150
8176
  }
8151
8177
 
8152
- indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
8153
-
8154
- if (indentStr === '') { return this; } // noop
8155
-
8156
- options = options || {};
8157
-
8158
- // Process exclusion ranges
8159
- var isExcluded = {};
8160
-
8161
- if (options.exclude) {
8162
- var exclusions =
8163
- typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
8164
- exclusions.forEach(function (exclusion) {
8165
- for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
8166
- isExcluded[i] = true;
8167
- }
8168
- });
8178
+ if (typeof y !== 'number') {
8179
+ return ESC + (x + 1) + 'G';
8169
8180
  }
8170
8181
 
8171
- var shouldIndentNextCharacter = options.indentStart !== false;
8172
- var replacer = function (match) {
8173
- if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
8174
- shouldIndentNextCharacter = true;
8175
- return match;
8176
- };
8177
-
8178
- this.intro = this.intro.replace(pattern, replacer);
8179
-
8180
- var charIndex = 0;
8181
- var chunk = this.firstChunk;
8182
-
8183
- while (chunk) {
8184
- var end = chunk.end;
8185
-
8186
- if (chunk.edited) {
8187
- if (!isExcluded[charIndex]) {
8188
- chunk.content = chunk.content.replace(pattern, replacer);
8189
-
8190
- if (chunk.content.length) {
8191
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
8192
- }
8193
- }
8194
- } else {
8195
- charIndex = chunk.start;
8196
-
8197
- while (charIndex < end) {
8198
- if (!isExcluded[charIndex]) {
8199
- var char = this.original[charIndex];
8200
-
8201
- if (char === '\n') {
8202
- shouldIndentNextCharacter = true;
8203
- } else if (char !== '\r' && shouldIndentNextCharacter) {
8204
- shouldIndentNextCharacter = false;
8182
+ return ESC + (y + 1) + ';' + (x + 1) + 'H';
8183
+ };
8205
8184
 
8206
- if (charIndex === chunk.start) {
8207
- chunk.prependRight(indentStr);
8208
- } else {
8209
- this._splitChunk(chunk, charIndex);
8210
- chunk = chunk.next;
8211
- chunk.prependRight(indentStr);
8212
- }
8213
- }
8214
- }
8185
+ ansiEscapes.cursorMove = (x, y) => {
8186
+ if (typeof x !== 'number') {
8187
+ throw new TypeError('The `x` argument is required');
8188
+ }
8215
8189
 
8216
- charIndex += 1;
8217
- }
8218
- }
8190
+ let returnValue = '';
8219
8191
 
8220
- charIndex = chunk.end;
8221
- chunk = chunk.next;
8192
+ if (x < 0) {
8193
+ returnValue += ESC + (-x) + 'D';
8194
+ } else if (x > 0) {
8195
+ returnValue += ESC + x + 'C';
8222
8196
  }
8223
8197
 
8224
- this.outro = this.outro.replace(pattern, replacer);
8198
+ if (y < 0) {
8199
+ returnValue += ESC + (-y) + 'A';
8200
+ } else if (y > 0) {
8201
+ returnValue += ESC + y + 'B';
8202
+ }
8225
8203
 
8226
- return this;
8204
+ return returnValue;
8227
8205
  };
8228
8206
 
8229
- MagicString.prototype.insert = function insert () {
8230
- throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
8231
- };
8207
+ ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A';
8208
+ ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B';
8209
+ ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C';
8210
+ ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D';
8232
8211
 
8233
- MagicString.prototype.insertLeft = function insertLeft (index, content) {
8234
- if (!warned.insertLeft) {
8235
- console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
8236
- warned.insertLeft = true;
8237
- }
8212
+ ansiEscapes.cursorLeft = ESC + 'G';
8213
+ ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's';
8214
+ ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u';
8215
+ ansiEscapes.cursorGetPosition = ESC + '6n';
8216
+ ansiEscapes.cursorNextLine = ESC + 'E';
8217
+ ansiEscapes.cursorPrevLine = ESC + 'F';
8218
+ ansiEscapes.cursorHide = ESC + '?25l';
8219
+ ansiEscapes.cursorShow = ESC + '?25h';
8238
8220
 
8239
- return this.appendLeft(index, content);
8240
- };
8221
+ ansiEscapes.eraseLines = count => {
8222
+ let clear = '';
8241
8223
 
8242
- MagicString.prototype.insertRight = function insertRight (index, content) {
8243
- if (!warned.insertRight) {
8244
- console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
8245
- warned.insertRight = true;
8224
+ for (let i = 0; i < count; i++) {
8225
+ clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : '');
8246
8226
  }
8247
8227
 
8248
- return this.prependRight(index, content);
8228
+ if (count) {
8229
+ clear += ansiEscapes.cursorLeft;
8230
+ }
8231
+
8232
+ return clear;
8249
8233
  };
8250
8234
 
8251
- MagicString.prototype.move = function move (start, end, index) {
8252
- if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
8235
+ ansiEscapes.eraseEndLine = ESC + 'K';
8236
+ ansiEscapes.eraseStartLine = ESC + '1K';
8237
+ ansiEscapes.eraseLine = ESC + '2K';
8238
+ ansiEscapes.eraseDown = ESC + 'J';
8239
+ ansiEscapes.eraseUp = ESC + '1J';
8240
+ ansiEscapes.eraseScreen = ESC + '2J';
8241
+ ansiEscapes.scrollUp = ESC + 'S';
8242
+ ansiEscapes.scrollDown = ESC + 'T';
8253
8243
 
8254
- this._split(start);
8255
- this._split(end);
8256
- this._split(index);
8244
+ ansiEscapes.clearScreen = '\u001Bc';
8257
8245
 
8258
- var first = this.byStart[start];
8259
- var last = this.byEnd[end];
8246
+ ansiEscapes.clearTerminal = process.platform === 'win32' ?
8247
+ `${ansiEscapes.eraseScreen}${ESC}0f` :
8248
+ // 1. Erases the screen (Only done in case `2` is not supported)
8249
+ // 2. Erases the whole screen including scrollback buffer
8250
+ // 3. Moves cursor to the top-left position
8251
+ // More info: https://www.real-world-systems.com/docs/ANSIcode.html
8252
+ `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`;
8260
8253
 
8261
- var oldLeft = first.previous;
8262
- var oldRight = last.next;
8254
+ ansiEscapes.beep = BEL;
8263
8255
 
8264
- var newRight = this.byStart[index];
8265
- if (!newRight && last === this.lastChunk) { return this; }
8266
- var newLeft = newRight ? newRight.previous : this.lastChunk;
8256
+ ansiEscapes.link = (text, url) => {
8257
+ return [
8258
+ OSC,
8259
+ '8',
8260
+ SEP,
8261
+ SEP,
8262
+ url,
8263
+ BEL,
8264
+ text,
8265
+ OSC,
8266
+ '8',
8267
+ SEP,
8268
+ SEP,
8269
+ BEL
8270
+ ].join('');
8271
+ };
8267
8272
 
8268
- if (oldLeft) { oldLeft.next = oldRight; }
8269
- if (oldRight) { oldRight.previous = oldLeft; }
8273
+ ansiEscapes.image = (buffer, options = {}) => {
8274
+ let returnValue = `${OSC}1337;File=inline=1`;
8270
8275
 
8271
- if (newLeft) { newLeft.next = first; }
8272
- if (newRight) { newRight.previous = last; }
8276
+ if (options.width) {
8277
+ returnValue += `;width=${options.width}`;
8278
+ }
8273
8279
 
8274
- if (!first.previous) { this.firstChunk = last.next; }
8275
- if (!last.next) {
8276
- this.lastChunk = first.previous;
8277
- this.lastChunk.next = null;
8280
+ if (options.height) {
8281
+ returnValue += `;height=${options.height}`;
8278
8282
  }
8279
8283
 
8280
- first.previous = newLeft;
8281
- last.next = newRight || null;
8284
+ if (options.preserveAspectRatio === false) {
8285
+ returnValue += ';preserveAspectRatio=0';
8286
+ }
8282
8287
 
8283
- if (!newLeft) { this.firstChunk = first; }
8284
- if (!newRight) { this.lastChunk = last; }
8285
- return this;
8288
+ return returnValue + ':' + buffer.toString('base64') + BEL;
8286
8289
  };
8287
8290
 
8288
- MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
8289
- if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
8290
-
8291
- while (start < 0) { start += this.original.length; }
8292
- while (end < 0) { end += this.original.length; }
8293
-
8294
- if (end > this.original.length) { throw new Error('end is out of bounds'); }
8295
- if (start === end)
8296
- { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
8297
-
8298
- this._split(start);
8299
- this._split(end);
8300
-
8301
- if (options === true) {
8302
- if (!warned.storeName) {
8303
- console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
8304
- warned.storeName = true;
8305
- }
8306
-
8307
- options = { storeName: true };
8308
- }
8309
- var storeName = options !== undefined ? options.storeName : false;
8310
- var contentOnly = options !== undefined ? options.contentOnly : false;
8311
-
8312
- if (storeName) {
8313
- var original = this.original.slice(start, end);
8314
- this.storedNames[original] = true;
8315
- }
8291
+ ansiEscapes.iTerm = {
8292
+ setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`,
8316
8293
 
8317
- var first = this.byStart[start];
8318
- var last = this.byEnd[end];
8294
+ annotation: (message, options = {}) => {
8295
+ let returnValue = `${OSC}1337;`;
8319
8296
 
8320
- if (first) {
8321
- if (end > first.end && first.next !== this.byStart[first.end]) {
8322
- throw new Error('Cannot overwrite across a split point');
8297
+ const hasX = typeof options.x !== 'undefined';
8298
+ const hasY = typeof options.y !== 'undefined';
8299
+ if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) {
8300
+ throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined');
8323
8301
  }
8324
8302
 
8325
- first.edit(content, storeName, contentOnly);
8303
+ message = message.replace(/\|/g, '');
8326
8304
 
8327
- if (first !== last) {
8328
- var chunk = first.next;
8329
- while (chunk !== last) {
8330
- chunk.edit('', false);
8331
- chunk = chunk.next;
8332
- }
8305
+ returnValue += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation=';
8333
8306
 
8334
- chunk.edit('', false);
8307
+ if (options.length > 0) {
8308
+ returnValue +=
8309
+ (hasX ?
8310
+ [message, options.length, options.x, options.y] :
8311
+ [options.length, message]).join('|');
8312
+ } else {
8313
+ returnValue += message;
8335
8314
  }
8336
- } else {
8337
- // must be inserting at the end
8338
- var newChunk = new Chunk(start, end, '').edit(content, storeName);
8339
8315
 
8340
- // TODO last chunk in the array may not be the last chunk, if it's moved...
8341
- last.next = newChunk;
8342
- newChunk.previous = last;
8316
+ return returnValue + BEL;
8343
8317
  }
8344
- return this;
8345
8318
  };
8346
8319
 
8347
- MagicString.prototype.prepend = function prepend (content) {
8348
- if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
8320
+ const restoreCursor = onetime(() => {
8321
+ signalExit(() => {
8322
+ process$1.stderr.write('\u001B[?25h');
8323
+ }, {alwaysLast: true});
8324
+ });
8349
8325
 
8350
- this.intro = content + this.intro;
8351
- return this;
8326
+ let isHidden = false;
8327
+
8328
+ const cliCursor = {};
8329
+
8330
+ cliCursor.show = (writableStream = process$1.stderr) => {
8331
+ if (!writableStream.isTTY) {
8332
+ return;
8333
+ }
8334
+
8335
+ isHidden = false;
8336
+ writableStream.write('\u001B[?25h');
8352
8337
  };
8353
8338
 
8354
- MagicString.prototype.prependLeft = function prependLeft (index, content) {
8355
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
8339
+ cliCursor.hide = (writableStream = process$1.stderr) => {
8340
+ if (!writableStream.isTTY) {
8341
+ return;
8342
+ }
8356
8343
 
8357
- this._split(index);
8344
+ restoreCursor();
8345
+ isHidden = true;
8346
+ writableStream.write('\u001B[?25l');
8347
+ };
8358
8348
 
8359
- var chunk = this.byEnd[index];
8349
+ cliCursor.toggle = (force, writableStream) => {
8350
+ if (force !== undefined) {
8351
+ isHidden = force;
8352
+ }
8360
8353
 
8361
- if (chunk) {
8362
- chunk.prependLeft(content);
8354
+ if (isHidden) {
8355
+ cliCursor.show(writableStream);
8363
8356
  } else {
8364
- this.intro = content + this.intro;
8357
+ cliCursor.hide(writableStream);
8365
8358
  }
8366
- return this;
8367
8359
  };
8368
8360
 
8369
- MagicString.prototype.prependRight = function prependRight (index, content) {
8370
- if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
8361
+ const ESCAPES = new Set([
8362
+ '\u001B',
8363
+ '\u009B',
8364
+ ]);
8371
8365
 
8372
- this._split(index);
8366
+ const END_CODE = 39;
8367
+ const ANSI_ESCAPE_BELL = '\u0007';
8368
+ const ANSI_CSI = '[';
8369
+ const ANSI_OSC = ']';
8370
+ const ANSI_SGR_TERMINATOR = 'm';
8371
+ const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
8373
8372
 
8374
- var chunk = this.byStart[index];
8373
+ const wrapAnsiCode = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
8374
+ const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`;
8375
8375
 
8376
- if (chunk) {
8377
- chunk.prependRight(content);
8378
- } else {
8379
- this.outro = content + this.outro;
8380
- }
8381
- return this;
8382
- };
8376
+ // Calculate the length of words split on ' ', ignoring
8377
+ // the extra characters added by ansi escape codes
8378
+ const wordLengths = string => string.split(' ').map(character => stringWidth(character));
8383
8379
 
8384
- MagicString.prototype.remove = function remove (start, end) {
8385
- while (start < 0) { start += this.original.length; }
8386
- while (end < 0) { end += this.original.length; }
8380
+ // Wrap a long word across multiple rows
8381
+ // Ansi escape codes do not count towards length
8382
+ const wrapWord = (rows, word, columns) => {
8383
+ const characters = [...word];
8387
8384
 
8388
- if (start === end) { return this; }
8385
+ let isInsideEscape = false;
8386
+ let isInsideLinkEscape = false;
8387
+ let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
8389
8388
 
8390
- if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
8391
- if (start > end) { throw new Error('end must be greater than start'); }
8389
+ for (const [index, character] of characters.entries()) {
8390
+ const characterLength = stringWidth(character);
8392
8391
 
8393
- this._split(start);
8394
- this._split(end);
8392
+ if (visible + characterLength <= columns) {
8393
+ rows[rows.length - 1] += character;
8394
+ } else {
8395
+ rows.push(character);
8396
+ visible = 0;
8397
+ }
8395
8398
 
8396
- var chunk = this.byStart[start];
8399
+ if (ESCAPES.has(character)) {
8400
+ isInsideEscape = true;
8401
+ isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK);
8402
+ }
8397
8403
 
8398
- while (chunk) {
8399
- chunk.intro = '';
8400
- chunk.outro = '';
8401
- chunk.edit('');
8404
+ if (isInsideEscape) {
8405
+ if (isInsideLinkEscape) {
8406
+ if (character === ANSI_ESCAPE_BELL) {
8407
+ isInsideEscape = false;
8408
+ isInsideLinkEscape = false;
8409
+ }
8410
+ } else if (character === ANSI_SGR_TERMINATOR) {
8411
+ isInsideEscape = false;
8412
+ }
8402
8413
 
8403
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
8414
+ continue;
8415
+ }
8416
+
8417
+ visible += characterLength;
8418
+
8419
+ if (visible === columns && index < characters.length - 1) {
8420
+ rows.push('');
8421
+ visible = 0;
8422
+ }
8404
8423
  }
8405
- return this;
8406
- };
8407
8424
 
8408
- MagicString.prototype.lastChar = function lastChar () {
8409
- if (this.outro.length)
8410
- { return this.outro[this.outro.length - 1]; }
8411
- var chunk = this.lastChunk;
8412
- do {
8413
- if (chunk.outro.length)
8414
- { return chunk.outro[chunk.outro.length - 1]; }
8415
- if (chunk.content.length)
8416
- { return chunk.content[chunk.content.length - 1]; }
8417
- if (chunk.intro.length)
8418
- { return chunk.intro[chunk.intro.length - 1]; }
8419
- } while (chunk = chunk.previous);
8420
- if (this.intro.length)
8421
- { return this.intro[this.intro.length - 1]; }
8422
- return '';
8425
+ // It's possible that the last row we copy over is only
8426
+ // ansi escape characters, handle this edge-case
8427
+ if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
8428
+ rows[rows.length - 2] += rows.pop();
8429
+ }
8423
8430
  };
8424
8431
 
8425
- MagicString.prototype.lastLine = function lastLine () {
8426
- var lineIndex = this.outro.lastIndexOf(n);
8427
- if (lineIndex !== -1)
8428
- { return this.outro.substr(lineIndex + 1); }
8429
- var lineStr = this.outro;
8430
- var chunk = this.lastChunk;
8431
- do {
8432
- if (chunk.outro.length > 0) {
8433
- lineIndex = chunk.outro.lastIndexOf(n);
8434
- if (lineIndex !== -1)
8435
- { return chunk.outro.substr(lineIndex + 1) + lineStr; }
8436
- lineStr = chunk.outro + lineStr;
8437
- }
8432
+ // Trims spaces from a string ignoring invisible sequences
8433
+ const stringVisibleTrimSpacesRight = string => {
8434
+ const words = string.split(' ');
8435
+ let last = words.length;
8438
8436
 
8439
- if (chunk.content.length > 0) {
8440
- lineIndex = chunk.content.lastIndexOf(n);
8441
- if (lineIndex !== -1)
8442
- { return chunk.content.substr(lineIndex + 1) + lineStr; }
8443
- lineStr = chunk.content + lineStr;
8437
+ while (last > 0) {
8438
+ if (stringWidth(words[last - 1]) > 0) {
8439
+ break;
8444
8440
  }
8445
8441
 
8446
- if (chunk.intro.length > 0) {
8447
- lineIndex = chunk.intro.lastIndexOf(n);
8448
- if (lineIndex !== -1)
8449
- { return chunk.intro.substr(lineIndex + 1) + lineStr; }
8450
- lineStr = chunk.intro + lineStr;
8451
- }
8452
- } while (chunk = chunk.previous);
8453
- lineIndex = this.intro.lastIndexOf(n);
8454
- if (lineIndex !== -1)
8455
- { return this.intro.substr(lineIndex + 1) + lineStr; }
8456
- return this.intro + lineStr;
8442
+ last--;
8443
+ }
8444
+
8445
+ if (last === words.length) {
8446
+ return string;
8447
+ }
8448
+
8449
+ return words.slice(0, last).join(' ') + words.slice(last).join('');
8457
8450
  };
8458
8451
 
8459
- MagicString.prototype.slice = function slice (start, end) {
8460
- if ( start === void 0 ) start = 0;
8461
- if ( end === void 0 ) end = this.original.length;
8452
+ // The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode
8453
+ //
8454
+ // 'hard' will never allow a string to take up more than columns characters
8455
+ //
8456
+ // 'soft' allows long words to expand past the column length
8457
+ const exec = (string, columns, options = {}) => {
8458
+ if (options.trim !== false && string.trim() === '') {
8459
+ return '';
8460
+ }
8462
8461
 
8463
- while (start < 0) { start += this.original.length; }
8464
- while (end < 0) { end += this.original.length; }
8462
+ let returnValue = '';
8463
+ let escapeCode;
8464
+ let escapeUrl;
8465
8465
 
8466
- var result = '';
8466
+ const lengths = wordLengths(string);
8467
+ let rows = [''];
8467
8468
 
8468
- // find start chunk
8469
- var chunk = this.firstChunk;
8470
- while (chunk && (chunk.start > start || chunk.end <= start)) {
8471
- // found end chunk before start
8472
- if (chunk.start < end && chunk.end >= end) {
8473
- return result;
8469
+ for (const [index, word] of string.split(' ').entries()) {
8470
+ if (options.trim !== false) {
8471
+ rows[rows.length - 1] = rows[rows.length - 1].trimStart();
8474
8472
  }
8475
8473
 
8476
- chunk = chunk.next;
8477
- }
8474
+ let rowLength = stringWidth(rows[rows.length - 1]);
8478
8475
 
8479
- if (chunk && chunk.edited && chunk.start !== start)
8480
- { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
8476
+ if (index !== 0) {
8477
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
8478
+ // If we start with a new word but the current row length equals the length of the columns, add a new row
8479
+ rows.push('');
8480
+ rowLength = 0;
8481
+ }
8481
8482
 
8482
- var startChunk = chunk;
8483
- while (chunk) {
8484
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
8485
- result += chunk.intro;
8483
+ if (rowLength > 0 || options.trim === false) {
8484
+ rows[rows.length - 1] += ' ';
8485
+ rowLength++;
8486
+ }
8486
8487
  }
8487
8488
 
8488
- var containsEnd = chunk.start < end && chunk.end >= end;
8489
- if (containsEnd && chunk.edited && chunk.end !== end)
8490
- { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
8489
+ // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns'
8490
+ if (options.hard && lengths[index] > columns) {
8491
+ const remainingColumns = (columns - rowLength);
8492
+ const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
8493
+ const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
8494
+ if (breaksStartingNextLine < breaksStartingThisLine) {
8495
+ rows.push('');
8496
+ }
8491
8497
 
8492
- var sliceStart = startChunk === chunk ? start - chunk.start : 0;
8493
- var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
8498
+ wrapWord(rows, word, columns);
8499
+ continue;
8500
+ }
8494
8501
 
8495
- result += chunk.content.slice(sliceStart, sliceEnd);
8502
+ if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
8503
+ if (options.wordWrap === false && rowLength < columns) {
8504
+ wrapWord(rows, word, columns);
8505
+ continue;
8506
+ }
8496
8507
 
8497
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
8498
- result += chunk.outro;
8508
+ rows.push('');
8499
8509
  }
8500
8510
 
8501
- if (containsEnd) {
8502
- break;
8511
+ if (rowLength + lengths[index] > columns && options.wordWrap === false) {
8512
+ wrapWord(rows, word, columns);
8513
+ continue;
8503
8514
  }
8504
8515
 
8505
- chunk = chunk.next;
8516
+ rows[rows.length - 1] += word;
8506
8517
  }
8507
8518
 
8508
- return result;
8509
- };
8519
+ if (options.trim !== false) {
8520
+ rows = rows.map(row => stringVisibleTrimSpacesRight(row));
8521
+ }
8510
8522
 
8511
- // TODO deprecate this? not really very useful
8512
- MagicString.prototype.snip = function snip (start, end) {
8513
- var clone = this.clone();
8514
- clone.remove(0, start);
8515
- clone.remove(end, clone.original.length);
8523
+ const pre = [...rows.join('\n')];
8516
8524
 
8517
- return clone;
8518
- };
8525
+ for (const [index, character] of pre.entries()) {
8526
+ returnValue += character;
8519
8527
 
8520
- MagicString.prototype._split = function _split (index) {
8521
- if (this.byStart[index] || this.byEnd[index]) { return; }
8528
+ if (ESCAPES.has(character)) {
8529
+ const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}};
8530
+ if (groups.code !== undefined) {
8531
+ const code = Number.parseFloat(groups.code);
8532
+ escapeCode = code === END_CODE ? undefined : code;
8533
+ } else if (groups.uri !== undefined) {
8534
+ escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;
8535
+ }
8536
+ }
8522
8537
 
8523
- var chunk = this.lastSearchedChunk;
8524
- var searchForward = index > chunk.end;
8538
+ const code = ansiStyles.codes.get(Number(escapeCode));
8525
8539
 
8526
- while (chunk) {
8527
- if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
8540
+ if (pre[index + 1] === '\n') {
8541
+ if (escapeUrl) {
8542
+ returnValue += wrapAnsiHyperlink('');
8543
+ }
8528
8544
 
8529
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
8530
- }
8531
- };
8545
+ if (escapeCode && code) {
8546
+ returnValue += wrapAnsiCode(code);
8547
+ }
8548
+ } else if (character === '\n') {
8549
+ if (escapeCode && code) {
8550
+ returnValue += wrapAnsiCode(escapeCode);
8551
+ }
8532
8552
 
8533
- MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
8534
- if (chunk.edited && chunk.content.length) {
8535
- // zero-length edited chunks are a special case (overlapping replacements)
8536
- var loc = getLocator(this.original)(index);
8537
- throw new Error(
8538
- ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
8539
- );
8553
+ if (escapeUrl) {
8554
+ returnValue += wrapAnsiHyperlink(escapeUrl);
8555
+ }
8556
+ }
8540
8557
  }
8541
8558
 
8542
- var newChunk = chunk.split(index);
8543
-
8544
- this.byEnd[index] = chunk;
8545
- this.byStart[index] = newChunk;
8546
- this.byEnd[newChunk.end] = newChunk;
8559
+ return returnValue;
8560
+ };
8547
8561
 
8548
- if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
8562
+ // For each newline, invoke the method separately
8563
+ function wrapAnsi(string, columns, options) {
8564
+ return String(string)
8565
+ .normalize()
8566
+ .replace(/\r\n/g, '\n')
8567
+ .split('\n')
8568
+ .map(line => exec(line, columns, options))
8569
+ .join('\n');
8570
+ }
8549
8571
 
8550
- this.lastSearchedChunk = chunk;
8551
- return true;
8552
- };
8572
+ const defaultTerminalHeight = 24;
8553
8573
 
8554
- MagicString.prototype.toString = function toString () {
8555
- var str = this.intro;
8574
+ const getWidth = stream => {
8575
+ const {columns} = stream;
8556
8576
 
8557
- var chunk = this.firstChunk;
8558
- while (chunk) {
8559
- str += chunk.toString();
8560
- chunk = chunk.next;
8577
+ if (!columns) {
8578
+ return 80;
8561
8579
  }
8562
8580
 
8563
- return str + this.outro;
8564
- };
8565
-
8566
- MagicString.prototype.isEmpty = function isEmpty () {
8567
- var chunk = this.firstChunk;
8568
- do {
8569
- if (chunk.intro.length && chunk.intro.trim() ||
8570
- chunk.content.length && chunk.content.trim() ||
8571
- chunk.outro.length && chunk.outro.trim())
8572
- { return false; }
8573
- } while (chunk = chunk.next);
8574
- return true;
8581
+ return columns;
8575
8582
  };
8576
8583
 
8577
- MagicString.prototype.length = function length () {
8578
- var chunk = this.firstChunk;
8579
- var length = 0;
8580
- do {
8581
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
8582
- } while (chunk = chunk.next);
8583
- return length;
8584
- };
8584
+ const fitToTerminalHeight = (stream, text) => {
8585
+ const terminalHeight = stream.rows || defaultTerminalHeight;
8586
+ const lines = text.split('\n');
8585
8587
 
8586
- MagicString.prototype.trimLines = function trimLines () {
8587
- return this.trim('[\\r\\n]');
8588
- };
8588
+ const toRemove = lines.length - terminalHeight;
8589
+ if (toRemove <= 0) {
8590
+ return text;
8591
+ }
8589
8592
 
8590
- MagicString.prototype.trim = function trim (charType) {
8591
- return this.trimStart(charType).trimEnd(charType);
8593
+ return sliceAnsi(
8594
+ text,
8595
+ lines.slice(0, toRemove).join('\n').length + 1,
8596
+ text.length);
8592
8597
  };
8593
8598
 
8594
- MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
8595
- var rx = new RegExp((charType || '\\s') + '+$');
8596
-
8597
- this.outro = this.outro.replace(rx, '');
8598
- if (this.outro.length) { return true; }
8599
-
8600
- var chunk = this.lastChunk;
8601
-
8602
- do {
8603
- var end = chunk.end;
8604
- var aborted = chunk.trimEnd(rx);
8605
-
8606
- // if chunk was trimmed, we have a new lastChunk
8607
- if (chunk.end !== end) {
8608
- if (this.lastChunk === chunk) {
8609
- this.lastChunk = chunk.next;
8610
- }
8599
+ function createLogUpdate(stream, {showCursor = false} = {}) {
8600
+ let previousLineCount = 0;
8601
+ let previousWidth = getWidth(stream);
8602
+ let previousOutput = '';
8611
8603
 
8612
- this.byEnd[chunk.end] = chunk;
8613
- this.byStart[chunk.next.start] = chunk.next;
8614
- this.byEnd[chunk.next.end] = chunk.next;
8604
+ const render = (...arguments_) => {
8605
+ if (!showCursor) {
8606
+ cliCursor.hide();
8615
8607
  }
8616
8608
 
8617
- if (aborted) { return true; }
8618
- chunk = chunk.previous;
8619
- } while (chunk);
8620
-
8621
- return false;
8622
- };
8623
-
8624
- MagicString.prototype.trimEnd = function trimEnd (charType) {
8625
- this.trimEndAborted(charType);
8626
- return this;
8627
- };
8628
- MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
8629
- var rx = new RegExp('^' + (charType || '\\s') + '+');
8630
-
8631
- this.intro = this.intro.replace(rx, '');
8632
- if (this.intro.length) { return true; }
8609
+ let output = arguments_.join(' ') + '\n';
8610
+ output = fitToTerminalHeight(stream, output);
8611
+ const width = getWidth(stream);
8612
+ if (output === previousOutput && previousWidth === width) {
8613
+ return;
8614
+ }
8633
8615
 
8634
- var chunk = this.firstChunk;
8616
+ previousOutput = output;
8617
+ previousWidth = width;
8618
+ output = wrapAnsi(output, width, {
8619
+ trim: false,
8620
+ hard: true,
8621
+ wordWrap: false,
8622
+ });
8623
+ stream.write(ansiEscapes.eraseLines(previousLineCount) + output);
8624
+ previousLineCount = output.split('\n').length;
8625
+ };
8635
8626
 
8636
- do {
8637
- var end = chunk.end;
8638
- var aborted = chunk.trimStart(rx);
8627
+ render.clear = () => {
8628
+ stream.write(ansiEscapes.eraseLines(previousLineCount));
8629
+ previousOutput = '';
8630
+ previousWidth = getWidth(stream);
8631
+ previousLineCount = 0;
8632
+ };
8639
8633
 
8640
- if (chunk.end !== end) {
8641
- // special case...
8642
- if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
8634
+ render.done = () => {
8635
+ previousOutput = '';
8636
+ previousWidth = getWidth(stream);
8637
+ previousLineCount = 0;
8643
8638
 
8644
- this.byEnd[chunk.end] = chunk;
8645
- this.byStart[chunk.next.start] = chunk.next;
8646
- this.byEnd[chunk.next.end] = chunk.next;
8639
+ if (!showCursor) {
8640
+ cliCursor.show();
8647
8641
  }
8642
+ };
8648
8643
 
8649
- if (aborted) { return true; }
8650
- chunk = chunk.next;
8651
- } while (chunk);
8652
-
8653
- return false;
8654
- };
8644
+ return render;
8645
+ }
8655
8646
 
8656
- MagicString.prototype.trimStart = function trimStart (charType) {
8657
- this.trimStartAborted(charType);
8658
- return this;
8659
- };
8647
+ createLogUpdate(process$1.stdout);
8660
8648
 
8661
- const mockRegexp = /\b((?:vitest|vi)\s*.\s*mock\(["`'\s](.*[@\w_-]+)["`'\s])[),]{1}/;
8662
- const pathRegexp = /\b(?:vitest|vi)\s*.\s*(unmock|importActual|importMock)\(["`'\s](.*[@\w_-]+)["`'\s]\);?/mg;
8663
- const isComment = (line) => {
8664
- const commentStarts = ["//", "/*", "*"];
8665
- line = line.trim();
8666
- return commentStarts.some((cmt) => line.startsWith(cmt));
8667
- };
8668
- const parseMocks = (code) => {
8669
- const splitted = code.split("\n");
8670
- const mockCalls = {};
8671
- let mockCall = 0;
8672
- let lineIndex = -1;
8673
- while (lineIndex < splitted.length) {
8674
- lineIndex++;
8675
- const line = splitted[lineIndex];
8676
- if (!line)
8677
- break;
8678
- const mock = mockCalls[mockCall] || {
8679
- code: "",
8680
- declaraton: "",
8681
- path: ""
8682
- };
8683
- if (!mock.code) {
8684
- const started = mockRegexp.exec(line);
8685
- if (!started || isComment(line))
8686
- continue;
8687
- mock.code += `${line}
8688
- `;
8689
- mock.declaraton = started[1];
8690
- mock.path = started[2];
8691
- mockCalls[mockCall] = mock;
8692
- if (line.includes(");")) {
8693
- mockCall++;
8694
- continue;
8649
+ createLogUpdate(process$1.stderr);
8650
+
8651
+ const DURATION_LONG = 300;
8652
+ const MAX_HEIGHT = 20;
8653
+ const outputMap = /* @__PURE__ */ new WeakMap();
8654
+ function formatFilepath(path) {
8655
+ const lastSlash = Math.max(path.lastIndexOf("/") + 1, 0);
8656
+ const basename = path.slice(lastSlash);
8657
+ let firstDot = basename.indexOf(".");
8658
+ if (firstDot < 0)
8659
+ firstDot = basename.length;
8660
+ firstDot += lastSlash;
8661
+ return c.dim(path.slice(0, lastSlash)) + path.slice(lastSlash, firstDot) + c.dim(path.slice(firstDot));
8662
+ }
8663
+ function renderTree(tasks, options, level = 0) {
8664
+ var _a, _b, _c, _d;
8665
+ let output = [];
8666
+ for (const task of tasks) {
8667
+ let suffix = "";
8668
+ const prefix = ` ${getStateSymbol(task)} `;
8669
+ if (task.mode === "skip" || task.mode === "todo")
8670
+ suffix += ` ${c.dim("[skipped]")}`;
8671
+ if (task.type === "suite")
8672
+ suffix += c.dim(` (${getTests(task).length})`);
8673
+ if ((_a = task.result) == null ? void 0 : _a.end) {
8674
+ const duration = task.result.end - task.result.start;
8675
+ if (duration > DURATION_LONG)
8676
+ suffix += c.yellow(` ${Math.round(duration)}${c.dim("ms")}`);
8677
+ }
8678
+ let name = task.name;
8679
+ if (level === 0)
8680
+ name = formatFilepath(name);
8681
+ output.push(" ".repeat(level) + prefix + name + suffix);
8682
+ if (((_b = task.result) == null ? void 0 : _b.state) !== "pass" && outputMap.get(task) != null) {
8683
+ let data = outputMap.get(task);
8684
+ if (typeof data === "string") {
8685
+ data = stripAnsi(data.trim().split("\n").filter(Boolean).pop());
8686
+ if (data === "")
8687
+ data = void 0;
8688
+ }
8689
+ if (data != null) {
8690
+ const out = `${" ".repeat(level)}${F_RIGHT} ${data}`;
8691
+ output.push(` ${c.gray(cliTruncate(out, getCols(-3)))}`);
8695
8692
  }
8696
- continue;
8697
8693
  }
8698
- mock.code += `${line}
8699
- `;
8700
- mockCalls[mockCall] = mock;
8701
- const startNumber = (mock.code.match(/{/g) || []).length;
8702
- const endNumber = (mock.code.match(/}/g) || []).length;
8703
- if (line.includes(");")) {
8704
- if (startNumber === endNumber || startNumber === 0 && endNumber === 0)
8705
- mockCall++;
8694
+ if (task.type === "suite" && task.tasks.length > 0) {
8695
+ if (((_c = task.result) == null ? void 0 : _c.state) === "fail" || ((_d = task.result) == null ? void 0 : _d.state) === "run" || options.renderSucceed)
8696
+ output = output.concat(renderTree(task.tasks, options, level + 1));
8706
8697
  }
8707
8698
  }
8708
- return Object.values(mockCalls);
8709
- };
8710
- const getMethodCall = (method, actualPath, importPath) => {
8711
- let nodeModule = "null";
8712
- if (actualPath.includes("/node_modules/"))
8713
- nodeModule = `"${importPath}"`;
8714
- return `__vitest__${method}__("${actualPath}", ${nodeModule}`;
8715
- };
8716
- const MocksPlugin = () => {
8699
+ return output.slice(0, MAX_HEIGHT).join("\n");
8700
+ }
8701
+ const createListRenderer = (_tasks, options = {}) => {
8702
+ let tasks = _tasks;
8703
+ let timer;
8704
+ const stdout = process.stdout;
8705
+ const log = createLogUpdate(stdout);
8706
+ function update() {
8707
+ log(renderTree(tasks, options));
8708
+ }
8717
8709
  return {
8718
- name: "vitest:mock-plugin",
8719
- enforce: "post",
8720
- async transform(code, id) {
8721
- let m;
8722
- const matchAll = code.matchAll(pathRegexp);
8723
- for (const match of matchAll) {
8724
- const [line, method, modulePath] = match;
8725
- const filepath = await this.resolve(modulePath, id);
8726
- if (filepath) {
8727
- m ?? (m = new MagicString(code));
8728
- const start = match.index || 0;
8729
- const end = start + line.length;
8730
- const overwrite = `${getMethodCall(method, filepath.id, modulePath)});`;
8731
- m.overwrite(start, end, overwrite);
8732
- }
8733
- }
8734
- if (mockRegexp.exec(code)) {
8735
- const mocks = parseMocks((m == null ? void 0 : m.toString()) || code);
8736
- for (const mock of mocks) {
8737
- const filepath = await this.resolve(mock.path, id);
8738
- if (!filepath)
8739
- continue;
8740
- m ?? (m = new MagicString(code));
8741
- const overwrite = getMethodCall("mock", filepath.id, mock.path);
8742
- m.prepend(mock.code.replace(mock.declaraton, overwrite));
8743
- }
8710
+ start() {
8711
+ if (timer)
8712
+ return this;
8713
+ timer = setInterval(update, 200);
8714
+ return this;
8715
+ },
8716
+ update(_tasks2) {
8717
+ tasks = _tasks2;
8718
+ update();
8719
+ return this;
8720
+ },
8721
+ async stop() {
8722
+ if (timer) {
8723
+ clearInterval(timer);
8724
+ timer = void 0;
8744
8725
  }
8745
- if (m) {
8746
- return {
8747
- code: m.toString(),
8748
- map: m.generateMap()
8749
- };
8726
+ log.clear();
8727
+ stdout.write(`${renderTree(tasks, options)}
8728
+ `);
8729
+ return this;
8730
+ },
8731
+ clear() {
8732
+ log.clear();
8733
+ }
8734
+ };
8735
+ };
8736
+
8737
+ class DefaultReporter extends BaseReporter {
8738
+ constructor() {
8739
+ super(...arguments);
8740
+ this.rendererOptions = {};
8741
+ }
8742
+ onStart() {
8743
+ if (this.isTTY) {
8744
+ const files = this.ctx.state.getFiles(this.watchFilters);
8745
+ if (!this.renderer)
8746
+ this.renderer = createListRenderer(files, this.rendererOptions).start();
8747
+ else
8748
+ this.renderer.update(files);
8749
+ }
8750
+ }
8751
+ async onFinished(files = this.ctx.state.getFiles()) {
8752
+ await this.stopListRender();
8753
+ this.ctx.log();
8754
+ await super.onFinished(files);
8755
+ }
8756
+ async onWatcherStart() {
8757
+ await this.stopListRender();
8758
+ super.onWatcherStart();
8759
+ }
8760
+ async stopListRender() {
8761
+ var _a;
8762
+ (_a = this.renderer) == null ? void 0 : _a.stop();
8763
+ this.renderer = void 0;
8764
+ await new Promise((resolve) => setTimeout(resolve, 10));
8765
+ }
8766
+ async onWatcherRerun(files, trigger) {
8767
+ await this.stopListRender();
8768
+ await super.onWatcherRerun(files, trigger);
8769
+ }
8770
+ onUserConsoleLog(log) {
8771
+ var _a;
8772
+ (_a = this.renderer) == null ? void 0 : _a.clear();
8773
+ super.onUserConsoleLog(log);
8774
+ }
8775
+ }
8776
+
8777
+ const check = c.green("\xB7");
8778
+ const cross = c.red("x");
8779
+ const pending = c.yellow("*");
8780
+ const skip = c.dim(c.gray("-"));
8781
+ function render(tasks) {
8782
+ const all = getTests(tasks);
8783
+ return all.map((i) => {
8784
+ var _a;
8785
+ if (i.mode === "skip" || i.mode === "todo")
8786
+ return skip;
8787
+ switch ((_a = i.result) == null ? void 0 : _a.state) {
8788
+ case "pass":
8789
+ return check;
8790
+ case "fail":
8791
+ return cross;
8792
+ default:
8793
+ return pending;
8794
+ }
8795
+ }).join("");
8796
+ }
8797
+ const createDotRenderer = (_tasks) => {
8798
+ let tasks = _tasks;
8799
+ let timer;
8800
+ const stdout = process.stdout;
8801
+ const log = createLogUpdate(stdout);
8802
+ function update() {
8803
+ log(render(tasks));
8804
+ }
8805
+ return {
8806
+ start() {
8807
+ if (timer)
8808
+ return this;
8809
+ timer = setInterval(update, 200);
8810
+ return this;
8811
+ },
8812
+ update(_tasks2) {
8813
+ tasks = _tasks2;
8814
+ update();
8815
+ return this;
8816
+ },
8817
+ async stop() {
8818
+ if (timer) {
8819
+ clearInterval(timer);
8820
+ timer = void 0;
8750
8821
  }
8822
+ log.clear();
8823
+ stdout.write(`${render(tasks)}
8824
+ `);
8825
+ return this;
8826
+ },
8827
+ clear() {
8828
+ log.clear();
8751
8829
  }
8752
8830
  };
8753
8831
  };
8754
8832
 
8833
+ class DotReporter extends BaseReporter {
8834
+ onStart() {
8835
+ if (this.isTTY) {
8836
+ const files = this.ctx.state.getFiles(this.watchFilters);
8837
+ if (!this.renderer)
8838
+ this.renderer = createDotRenderer(files).start();
8839
+ else
8840
+ this.renderer.update(files);
8841
+ }
8842
+ }
8843
+ async onFinished(files = this.ctx.state.getFiles()) {
8844
+ await this.stopListRender();
8845
+ this.ctx.log();
8846
+ await super.onFinished(files);
8847
+ }
8848
+ async onWatcherStart() {
8849
+ await this.stopListRender();
8850
+ super.onWatcherStart();
8851
+ }
8852
+ async stopListRender() {
8853
+ var _a;
8854
+ (_a = this.renderer) == null ? void 0 : _a.stop();
8855
+ this.renderer = void 0;
8856
+ await new Promise((resolve) => setTimeout(resolve, 10));
8857
+ }
8858
+ async onWatcherRerun(files, trigger) {
8859
+ await this.stopListRender();
8860
+ await super.onWatcherRerun(files, trigger);
8861
+ }
8862
+ onUserConsoleLog(log) {
8863
+ var _a;
8864
+ (_a = this.renderer) == null ? void 0 : _a.clear();
8865
+ super.onUserConsoleLog(log);
8866
+ }
8867
+ }
8868
+
8869
+ class VerboseReporter extends DefaultReporter {
8870
+ constructor(ctx) {
8871
+ super(ctx);
8872
+ this.rendererOptions.renderSucceed = true;
8873
+ }
8874
+ }
8875
+
8876
+ const ReportersMap = {
8877
+ default: DefaultReporter,
8878
+ verbose: VerboseReporter,
8879
+ dot: DotReporter
8880
+ };
8881
+
8755
8882
  class StateManager {
8756
8883
  constructor() {
8757
8884
  this.filesMap = {};
@@ -9015,9 +9142,17 @@ class Vitest {
9015
9142
  this.config = resolved;
9016
9143
  this.state = new StateManager();
9017
9144
  this.snapshot = new SnapshotManager(resolved);
9018
- this.reporters = toArray(resolved.reporters);
9145
+ this.reporters = toArray(resolved.reporters || resolved.reporter).map((i) => {
9146
+ if (typeof i === "string") {
9147
+ const Reporter = ReportersMap[i];
9148
+ if (!Reporter)
9149
+ throw new Error(`Unknown reporter: ${i}`);
9150
+ return new Reporter(this);
9151
+ }
9152
+ return i;
9153
+ });
9019
9154
  if (!this.reporters.length && !this.config.silent)
9020
- this.reporters.push(new ConsoleReporter(this));
9155
+ this.reporters.push(new DefaultReporter(this));
9021
9156
  if (this.config.watch)
9022
9157
  this.registerWatcher();
9023
9158
  this.runningPromise = void 0;
@@ -9183,7 +9318,7 @@ async function createVitest(options, viteOverrides = {}) {
9183
9318
  ctx.setServer(options, server2);
9184
9319
  haveStarted = true;
9185
9320
  if (options.api)
9186
- server2.middlewares.use((await import('./middleware-093a3bde.js')).default(ctx));
9321
+ server2.middlewares.use((await import('./middleware-2028dfa0.js')).default(ctx));
9187
9322
  }
9188
9323
  },
9189
9324
  MocksPlugin()