@vitest/utils 4.0.0-beta.10 → 4.0.0-beta.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/error.d.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  import { D as DiffOptions } from './types.d-BCElaP-c.js';
2
+ export { serializeValue as serializeError } from './serialize.js';
2
3
  import '@vitest/pretty-format';
3
4
 
4
- declare function serializeValue(val: any, seen?: WeakMap<WeakKey, any>): any;
5
-
6
5
  declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): any;
7
6
 
8
- export { processError, serializeValue as serializeError, serializeValue };
7
+ export { processError };
package/dist/error.js CHANGED
@@ -1,126 +1,12 @@
1
1
  import { printDiffOrStringify } from './diff.js';
2
- import { f as format, s as stringify } from './chunk-_commonjsHelpers.js';
2
+ import { stringify } from './display.js';
3
+ import { serializeValue } from './serialize.js';
3
4
  import '@vitest/pretty-format';
4
5
  import 'tinyrainbow';
5
- import './chunk-helpers.js';
6
- import 'loupe';
6
+ import './helpers.js';
7
+ import './constants.js';
8
+ import './chunk-_commonjsHelpers.js';
7
9
 
8
- const IS_RECORD_SYMBOL = "@@__IMMUTABLE_RECORD__@@";
9
- const IS_COLLECTION_SYMBOL = "@@__IMMUTABLE_ITERABLE__@@";
10
- function isImmutable(v) {
11
- return v && (v[IS_COLLECTION_SYMBOL] || v[IS_RECORD_SYMBOL]);
12
- }
13
- const OBJECT_PROTO = Object.getPrototypeOf({});
14
- function getUnserializableMessage(err) {
15
- if (err instanceof Error) {
16
- return `<unserializable>: ${err.message}`;
17
- }
18
- if (typeof err === "string") {
19
- return `<unserializable>: ${err}`;
20
- }
21
- return "<unserializable>";
22
- }
23
- // https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
24
- function serializeValue(val, seen = new WeakMap()) {
25
- if (!val || typeof val === "string") {
26
- return val;
27
- }
28
- if (val instanceof Error && "toJSON" in val && typeof val.toJSON === "function") {
29
- const jsonValue = val.toJSON();
30
- if (jsonValue && jsonValue !== val && typeof jsonValue === "object") {
31
- if (typeof val.message === "string") {
32
- safe(() => jsonValue.message ?? (jsonValue.message = val.message));
33
- }
34
- if (typeof val.stack === "string") {
35
- safe(() => jsonValue.stack ?? (jsonValue.stack = val.stack));
36
- }
37
- if (typeof val.name === "string") {
38
- safe(() => jsonValue.name ?? (jsonValue.name = val.name));
39
- }
40
- if (val.cause != null) {
41
- safe(() => jsonValue.cause ?? (jsonValue.cause = serializeValue(val.cause, seen)));
42
- }
43
- }
44
- return serializeValue(jsonValue, seen);
45
- }
46
- if (typeof val === "function") {
47
- return `Function<${val.name || "anonymous"}>`;
48
- }
49
- if (typeof val === "symbol") {
50
- return val.toString();
51
- }
52
- if (typeof val !== "object") {
53
- return val;
54
- }
55
- if (typeof Buffer !== "undefined" && val instanceof Buffer) {
56
- return `<Buffer(${val.length}) ...>`;
57
- }
58
- if (typeof Uint8Array !== "undefined" && val instanceof Uint8Array) {
59
- return `<Uint8Array(${val.length}) ...>`;
60
- }
61
- // cannot serialize immutables as immutables
62
- if (isImmutable(val)) {
63
- return serializeValue(val.toJSON(), seen);
64
- }
65
- if (val instanceof Promise || val.constructor && val.constructor.prototype === "AsyncFunction") {
66
- return "Promise";
67
- }
68
- if (typeof Element !== "undefined" && val instanceof Element) {
69
- return val.tagName;
70
- }
71
- if (typeof val.asymmetricMatch === "function") {
72
- return `${val.toString()} ${format(val.sample)}`;
73
- }
74
- if (typeof val.toJSON === "function") {
75
- return serializeValue(val.toJSON(), seen);
76
- }
77
- if (seen.has(val)) {
78
- return seen.get(val);
79
- }
80
- if (Array.isArray(val)) {
81
- // eslint-disable-next-line unicorn/no-new-array -- we need to keep sparse arrays ([1,,3])
82
- const clone = new Array(val.length);
83
- seen.set(val, clone);
84
- val.forEach((e, i) => {
85
- try {
86
- clone[i] = serializeValue(e, seen);
87
- } catch (err) {
88
- clone[i] = getUnserializableMessage(err);
89
- }
90
- });
91
- return clone;
92
- } else {
93
- // Objects with `Error` constructors appear to cause problems during worker communication
94
- // using `MessagePort`, so the serialized error object is being recreated as plain object.
95
- const clone = Object.create(null);
96
- seen.set(val, clone);
97
- let obj = val;
98
- while (obj && obj !== OBJECT_PROTO) {
99
- Object.getOwnPropertyNames(obj).forEach((key) => {
100
- if (key in clone) {
101
- return;
102
- }
103
- try {
104
- clone[key] = serializeValue(val[key], seen);
105
- } catch (err) {
106
- // delete in case it has a setter from prototype that might throw
107
- delete clone[key];
108
- clone[key] = getUnserializableMessage(err);
109
- }
110
- });
111
- obj = Object.getPrototypeOf(obj);
112
- }
113
- return clone;
114
- }
115
- }
116
- function safe(fn) {
117
- try {
118
- return fn();
119
- } catch {}
120
- }
121
- function normalizeErrorMessage(message) {
122
- return message.replace(/__(vite_ssr_import|vi_import)_\d+__\./g, "");
123
- }
124
10
  function processError(_err, diffOptions, seen = new WeakSet()) {
125
11
  if (!_err || typeof _err !== "object") {
126
12
  return { message: String(_err) };
@@ -138,12 +24,6 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
138
24
  if ("actual" in err && typeof err.actual !== "string") {
139
25
  err.actual = stringify(err.actual, 10);
140
26
  }
141
- // some Error implementations don't allow rewriting message
142
- try {
143
- if (typeof err.message === "string") {
144
- err.message = normalizeErrorMessage(err.message);
145
- }
146
- } catch {}
147
27
  // some Error implementations may not allow rewriting cause
148
28
  // in most cases, the assignment will lead to "err.cause = err.cause"
149
29
  try {
@@ -159,4 +39,4 @@ function processError(_err, diffOptions, seen = new WeakSet()) {
159
39
  }
160
40
  }
161
41
 
162
- export { processError, serializeValue as serializeError, serializeValue };
42
+ export { processError, serializeValue as serializeError };
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  import { Nullable, Arrayable } from './types.js';
2
2
 
3
+ declare function nanoid(size?: number): string;
4
+
5
+ declare function shuffle<T>(array: T[], seed?: number): T[];
6
+
3
7
  interface CloneOptions {
4
8
  forceWritable?: boolean;
5
9
  }
@@ -7,6 +11,7 @@ interface ErrorOptions {
7
11
  message?: string;
8
12
  stackTraceLimit?: number;
9
13
  }
14
+
10
15
  /**
11
16
  * Get original stacktrace without source map support the most performant way.
12
17
  * - Create only 1 stack frame.
@@ -31,7 +36,6 @@ declare function wrapId(id: string): string;
31
36
  declare function unwrapId(id: string): string;
32
37
  declare function withTrailingSlash(path: string): string;
33
38
  declare function isBareImport(id: string): boolean;
34
- declare function parseRegexp(input: string): RegExp;
35
39
  declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
36
40
  declare function isObject(item: unknown): boolean;
37
41
  declare function getType(value: unknown): string;
@@ -65,5 +69,5 @@ declare function isNegativeNaN(val: number): boolean;
65
69
  */
66
70
  declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): T;
67
71
 
68
- export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray, unwrapId, withTrailingSlash, wrapId };
72
+ export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
69
73
  export type { DeferPromise };
package/dist/helpers.js CHANGED
@@ -1 +1,295 @@
1
- export { b as assertTypes, c as cleanUrl, d as clone, e as createDefer, f as createSimpleStackTrace, g as deepClone, h as deepMerge, j as getCallLastIndex, k as getOwnProperties, l as getType, m as isBareImport, o as isExternalUrl, p as isNegativeNaN, q as isObject, i as isPrimitive, r as noop, n as notNullish, s as objectAttr, t as parseRegexp, u as slash, v as toArray, w as unwrapId, x as withTrailingSlash, y as wrapId } from './chunk-helpers.js';
1
+ import { VALID_ID_PREFIX, NULL_BYTE_PLACEHOLDER } from './constants.js';
2
+
3
+ // port from nanoid
4
+ // https://github.com/ai/nanoid
5
+ const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
6
+ function nanoid(size = 21) {
7
+ let id = "";
8
+ let i = size;
9
+ while (i--) {
10
+ id += urlAlphabet[Math.random() * 64 | 0];
11
+ }
12
+ return id;
13
+ }
14
+
15
+ const RealDate = Date;
16
+ function random(seed) {
17
+ const x = Math.sin(seed++) * 1e4;
18
+ return x - Math.floor(x);
19
+ }
20
+ function shuffle(array, seed = RealDate.now()) {
21
+ let length = array.length;
22
+ while (length) {
23
+ const index = Math.floor(random(seed) * length--);
24
+ const previous = array[length];
25
+ array[length] = array[index];
26
+ array[index] = previous;
27
+ ++seed;
28
+ }
29
+ return array;
30
+ }
31
+
32
+ /**
33
+ * Get original stacktrace without source map support the most performant way.
34
+ * - Create only 1 stack frame.
35
+ * - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
36
+ */
37
+ function createSimpleStackTrace(options) {
38
+ const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
39
+ const limit = Error.stackTraceLimit;
40
+ const prepareStackTrace = Error.prepareStackTrace;
41
+ Error.stackTraceLimit = stackTraceLimit;
42
+ Error.prepareStackTrace = (e) => e.stack;
43
+ const err = new Error(message);
44
+ const stackTrace = err.stack || "";
45
+ Error.prepareStackTrace = prepareStackTrace;
46
+ Error.stackTraceLimit = limit;
47
+ return stackTrace;
48
+ }
49
+ function notNullish(v) {
50
+ return v != null;
51
+ }
52
+ function assertTypes(value, name, types) {
53
+ const receivedType = typeof value;
54
+ const pass = types.includes(receivedType);
55
+ if (!pass) {
56
+ throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
57
+ }
58
+ }
59
+ function isPrimitive(value) {
60
+ return value === null || typeof value !== "function" && typeof value !== "object";
61
+ }
62
+ function slash(path) {
63
+ return path.replace(/\\/g, "/");
64
+ }
65
+ const postfixRE = /[?#].*$/;
66
+ function cleanUrl(url) {
67
+ return url.replace(postfixRE, "");
68
+ }
69
+ const externalRE = /^(?:[a-z]+:)?\/\//;
70
+ const isExternalUrl = (url) => externalRE.test(url);
71
+ /**
72
+ * Prepend `/@id/` and replace null byte so the id is URL-safe.
73
+ * This is prepended to resolved ids that are not valid browser
74
+ * import specifiers by the importAnalysis plugin.
75
+ */
76
+ function wrapId(id) {
77
+ return id.startsWith(VALID_ID_PREFIX) ? id : VALID_ID_PREFIX + id.replace("\0", NULL_BYTE_PLACEHOLDER);
78
+ }
79
+ /**
80
+ * Undo {@link wrapId}'s `/@id/` and null byte replacements.
81
+ */
82
+ function unwrapId(id) {
83
+ return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length).replace(NULL_BYTE_PLACEHOLDER, "\0") : id;
84
+ }
85
+ function withTrailingSlash(path) {
86
+ if (path.at(-1) !== "/") {
87
+ return `${path}/`;
88
+ }
89
+ return path;
90
+ }
91
+ const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
92
+ function isBareImport(id) {
93
+ return bareImportRE.test(id);
94
+ }
95
+ function toArray(array) {
96
+ if (array === null || array === undefined) {
97
+ array = [];
98
+ }
99
+ if (Array.isArray(array)) {
100
+ return array;
101
+ }
102
+ return [array];
103
+ }
104
+ function isObject(item) {
105
+ return item != null && typeof item === "object" && !Array.isArray(item);
106
+ }
107
+ function isFinalObj(obj) {
108
+ return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
109
+ }
110
+ function getType(value) {
111
+ return Object.prototype.toString.apply(value).slice(8, -1);
112
+ }
113
+ function collectOwnProperties(obj, collector) {
114
+ const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
115
+ Object.getOwnPropertyNames(obj).forEach(collect);
116
+ Object.getOwnPropertySymbols(obj).forEach(collect);
117
+ }
118
+ function getOwnProperties(obj) {
119
+ const ownProps = new Set();
120
+ if (isFinalObj(obj)) {
121
+ return [];
122
+ }
123
+ collectOwnProperties(obj, ownProps);
124
+ return Array.from(ownProps);
125
+ }
126
+ const defaultCloneOptions = { forceWritable: false };
127
+ function deepClone(val, options = defaultCloneOptions) {
128
+ const seen = new WeakMap();
129
+ return clone(val, seen, options);
130
+ }
131
+ function clone(val, seen, options = defaultCloneOptions) {
132
+ let k, out;
133
+ if (seen.has(val)) {
134
+ return seen.get(val);
135
+ }
136
+ if (Array.isArray(val)) {
137
+ out = Array.from({ length: k = val.length });
138
+ seen.set(val, out);
139
+ while (k--) {
140
+ out[k] = clone(val[k], seen, options);
141
+ }
142
+ return out;
143
+ }
144
+ if (Object.prototype.toString.call(val) === "[object Object]") {
145
+ out = Object.create(Object.getPrototypeOf(val));
146
+ seen.set(val, out);
147
+ // we don't need properties from prototype
148
+ const props = getOwnProperties(val);
149
+ for (const k of props) {
150
+ const descriptor = Object.getOwnPropertyDescriptor(val, k);
151
+ if (!descriptor) {
152
+ continue;
153
+ }
154
+ const cloned = clone(val[k], seen, options);
155
+ if (options.forceWritable) {
156
+ Object.defineProperty(out, k, {
157
+ enumerable: descriptor.enumerable,
158
+ configurable: true,
159
+ writable: true,
160
+ value: cloned
161
+ });
162
+ } else if ("get" in descriptor) {
163
+ Object.defineProperty(out, k, {
164
+ ...descriptor,
165
+ get() {
166
+ return cloned;
167
+ }
168
+ });
169
+ } else {
170
+ Object.defineProperty(out, k, {
171
+ ...descriptor,
172
+ value: cloned
173
+ });
174
+ }
175
+ }
176
+ return out;
177
+ }
178
+ return val;
179
+ }
180
+ function noop() {}
181
+ function objectAttr(source, path, defaultValue = undefined) {
182
+ // a[3].b -> a.3.b
183
+ const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
184
+ let result = source;
185
+ for (const p of paths) {
186
+ result = new Object(result)[p];
187
+ if (result === undefined) {
188
+ return defaultValue;
189
+ }
190
+ }
191
+ return result;
192
+ }
193
+ function createDefer() {
194
+ let resolve = null;
195
+ let reject = null;
196
+ const p = new Promise((_resolve, _reject) => {
197
+ resolve = _resolve;
198
+ reject = _reject;
199
+ });
200
+ p.resolve = resolve;
201
+ p.reject = reject;
202
+ return p;
203
+ }
204
+ /**
205
+ * If code starts with a function call, will return its last index, respecting arguments.
206
+ * This will return 25 - last ending character of toMatch ")"
207
+ * Also works with callbacks
208
+ * ```
209
+ * toMatch({ test: '123' });
210
+ * toBeAliased('123')
211
+ * ```
212
+ */
213
+ function getCallLastIndex(code) {
214
+ let charIndex = -1;
215
+ let inString = null;
216
+ let startedBracers = 0;
217
+ let endedBracers = 0;
218
+ let beforeChar = null;
219
+ while (charIndex <= code.length) {
220
+ beforeChar = code[charIndex];
221
+ charIndex++;
222
+ const char = code[charIndex];
223
+ const isCharString = char === "\"" || char === "'" || char === "`";
224
+ if (isCharString && beforeChar !== "\\") {
225
+ if (inString === char) {
226
+ inString = null;
227
+ } else if (!inString) {
228
+ inString = char;
229
+ }
230
+ }
231
+ if (!inString) {
232
+ if (char === "(") {
233
+ startedBracers++;
234
+ }
235
+ if (char === ")") {
236
+ endedBracers++;
237
+ }
238
+ }
239
+ if (startedBracers && endedBracers && startedBracers === endedBracers) {
240
+ return charIndex;
241
+ }
242
+ }
243
+ return null;
244
+ }
245
+ function isNegativeNaN(val) {
246
+ if (!Number.isNaN(val)) {
247
+ return false;
248
+ }
249
+ const f64 = new Float64Array(1);
250
+ f64[0] = val;
251
+ const u32 = new Uint32Array(f64.buffer);
252
+ const isNegative = u32[1] >>> 31 === 1;
253
+ return isNegative;
254
+ }
255
+ function toString(v) {
256
+ return Object.prototype.toString.call(v);
257
+ }
258
+ function isPlainObject(val) {
259
+ return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
260
+ }
261
+ function isMergeableObject(item) {
262
+ return isPlainObject(item) && !Array.isArray(item);
263
+ }
264
+ /**
265
+ * Deep merge :P
266
+ *
267
+ * Will merge objects only if they are plain
268
+ *
269
+ * Do not merge types - it is very expensive and usually it's better to case a type here
270
+ */
271
+ function deepMerge(target, ...sources) {
272
+ if (!sources.length) {
273
+ return target;
274
+ }
275
+ const source = sources.shift();
276
+ if (source === undefined) {
277
+ return target;
278
+ }
279
+ if (isMergeableObject(target) && isMergeableObject(source)) {
280
+ Object.keys(source).forEach((key) => {
281
+ const _source = source;
282
+ if (isMergeableObject(_source[key])) {
283
+ if (!target[key]) {
284
+ target[key] = {};
285
+ }
286
+ deepMerge(target[key], _source[key]);
287
+ } else {
288
+ target[key] = _source[key];
289
+ }
290
+ });
291
+ }
292
+ return deepMerge(target, ...sources);
293
+ }
294
+
295
+ export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, shuffle, slash, toArray, unwrapId, withTrailingSlash, wrapId };
@@ -0,0 +1,9 @@
1
+ import { Colors } from 'tinyrainbow';
2
+
3
+ interface HighlightOptions {
4
+ jsx?: boolean;
5
+ colors?: Colors;
6
+ }
7
+ declare function highlight(code: string, options?: HighlightOptions): string;
8
+
9
+ export { highlight };