@depup/vitest__utils 4.1.0-depup.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ import { D as DiffOptions } from './types.d-BCElaP-c.js';
2
+ import { TestError } from './types.js';
3
+ export { serializeValue as serializeError } from './serialize.js';
4
+ import '@vitest/pretty-format';
5
+
6
+ declare function processError(_err: any, diffOptions?: DiffOptions, seen?: WeakSet<WeakKey>): TestError;
7
+
8
+ export { processError };
package/dist/error.js ADDED
@@ -0,0 +1,41 @@
1
+ import { printDiffOrStringify } from './diff.js';
2
+ import { stringify } from './display.js';
3
+ import { serializeValue } from './serialize.js';
4
+ import '@vitest/pretty-format';
5
+ import 'tinyrainbow';
6
+ import './helpers.js';
7
+ import './constants.js';
8
+
9
+ function processError(_err, diffOptions, seen = new WeakSet()) {
10
+ if (!_err || typeof _err !== "object") {
11
+ return { message: String(_err) };
12
+ }
13
+ const err = _err;
14
+ if (err.showDiff || err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined) {
15
+ err.diff = printDiffOrStringify(err.actual, err.expected, {
16
+ ...diffOptions,
17
+ ...err.diffOptions
18
+ });
19
+ }
20
+ if ("expected" in err && typeof err.expected !== "string") {
21
+ err.expected = stringify(err.expected, 10);
22
+ }
23
+ if ("actual" in err && typeof err.actual !== "string") {
24
+ err.actual = stringify(err.actual, 10);
25
+ }
26
+ // some Error implementations may not allow rewriting cause
27
+ // in most cases, the assignment will lead to "err.cause = err.cause"
28
+ try {
29
+ if (!seen.has(err) && typeof err.cause === "object") {
30
+ seen.add(err);
31
+ err.cause = processError(err.cause, diffOptions, seen);
32
+ }
33
+ } catch {}
34
+ try {
35
+ return serializeValue(err);
36
+ } catch (e) {
37
+ return serializeValue(new Error(`Failed to fully serialize error: ${e?.message}\nInner error message: ${err?.message}`));
38
+ }
39
+ }
40
+
41
+ export { processError, serializeValue as serializeError };
@@ -0,0 +1,76 @@
1
+ import { Nullable, Arrayable } from './types.js';
2
+
3
+ declare function nanoid(size?: number): string;
4
+
5
+ declare function shuffle<T>(array: T[], seed?: number): T[];
6
+
7
+ interface CloneOptions {
8
+ forceWritable?: boolean;
9
+ }
10
+ interface ErrorOptions {
11
+ message?: string;
12
+ stackTraceLimit?: number;
13
+ }
14
+
15
+ /**
16
+ * Get original stacktrace without source map support the most performant way.
17
+ * - Create only 1 stack frame.
18
+ * - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
19
+ */
20
+ declare function createSimpleStackTrace(options?: ErrorOptions): string;
21
+ declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
22
+ declare function assertTypes(value: unknown, name: string, types: string[]): void;
23
+ declare function isPrimitive(value: unknown): boolean;
24
+ declare function slash(path: string): string;
25
+ declare function cleanUrl(url: string): string;
26
+ declare const isExternalUrl: (url: string) => boolean;
27
+ /**
28
+ * Prepend `/@id/` and replace null byte so the id is URL-safe.
29
+ * This is prepended to resolved ids that are not valid browser
30
+ * import specifiers by the importAnalysis plugin.
31
+ */
32
+ declare function wrapId(id: string): string;
33
+ /**
34
+ * Undo {@link wrapId}'s `/@id/` and null byte replacements.
35
+ */
36
+ declare function unwrapId(id: string): string;
37
+ declare function withTrailingSlash(path: string): string;
38
+ declare function filterOutComments(s: string): string;
39
+ declare function isBareImport(id: string): boolean;
40
+ declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
41
+ declare function isObject(item: unknown): boolean;
42
+ declare function getType(value: unknown): string;
43
+ declare function getOwnProperties(obj: any): (string | symbol)[];
44
+ declare function deepClone<T>(val: T, options?: CloneOptions): T;
45
+ declare function clone<T>(val: T, seen: WeakMap<any, any>, options?: CloneOptions): T;
46
+ declare function noop(): void;
47
+ declare function objectAttr(source: any, path: string, defaultValue?: undefined): any;
48
+ type DeferPromise<T> = Promise<T> & {
49
+ resolve: (value: T | PromiseLike<T>) => void;
50
+ reject: (reason?: any) => void;
51
+ };
52
+ declare function createDefer<T>(): DeferPromise<T>;
53
+ /**
54
+ * If code starts with a function call, will return its last index, respecting arguments.
55
+ * This will return 25 - last ending character of toMatch ")"
56
+ * Also works with callbacks
57
+ * ```
58
+ * toMatch({ test: '123' });
59
+ * toBeAliased('123')
60
+ * ```
61
+ */
62
+ declare function getCallLastIndex(code: string): number | null;
63
+ declare function isNegativeNaN(val: number): boolean;
64
+ declare function ordinal(i: number): string;
65
+ /**
66
+ * Deep merge :P
67
+ *
68
+ * Will merge objects only if they are plain
69
+ *
70
+ * Do not merge types - it is very expensive and usually it's better to case a type here
71
+ */
72
+ declare function deepMerge<T extends object = object>(target: T, ...sources: any[]): T;
73
+ declare function unique<T>(array: T[]): T[];
74
+
75
+ export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, toArray, unique, unwrapId, withTrailingSlash, wrapId };
76
+ export type { DeferPromise };
@@ -0,0 +1,337 @@
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
+ function filterOutComments(s) {
92
+ const result = [];
93
+ let commentState = "none";
94
+ for (let i = 0; i < s.length; ++i) {
95
+ if (commentState === "singleline") {
96
+ if (s[i] === "\n") {
97
+ commentState = "none";
98
+ }
99
+ } else if (commentState === "multiline") {
100
+ if (s[i - 1] === "*" && s[i] === "/") {
101
+ commentState = "none";
102
+ }
103
+ } else if (commentState === "none") {
104
+ if (s[i] === "/" && s[i + 1] === "/") {
105
+ commentState = "singleline";
106
+ } else if (s[i] === "/" && s[i + 1] === "*") {
107
+ commentState = "multiline";
108
+ i += 2;
109
+ } else {
110
+ result.push(s[i]);
111
+ }
112
+ }
113
+ }
114
+ return result.join("");
115
+ }
116
+ const bareImportRE = /^(?![a-z]:)[\w@](?!.*:\/\/)/i;
117
+ function isBareImport(id) {
118
+ return bareImportRE.test(id);
119
+ }
120
+ function toArray(array) {
121
+ if (array === null || array === undefined) {
122
+ array = [];
123
+ }
124
+ if (Array.isArray(array)) {
125
+ return array;
126
+ }
127
+ return [array];
128
+ }
129
+ function isObject(item) {
130
+ return item != null && typeof item === "object" && !Array.isArray(item);
131
+ }
132
+ function isFinalObj(obj) {
133
+ return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
134
+ }
135
+ function getType(value) {
136
+ return Object.prototype.toString.apply(value).slice(8, -1);
137
+ }
138
+ function collectOwnProperties(obj, collector) {
139
+ const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
140
+ Object.getOwnPropertyNames(obj).forEach(collect);
141
+ Object.getOwnPropertySymbols(obj).forEach(collect);
142
+ }
143
+ function getOwnProperties(obj) {
144
+ const ownProps = new Set();
145
+ if (isFinalObj(obj)) {
146
+ return [];
147
+ }
148
+ collectOwnProperties(obj, ownProps);
149
+ return Array.from(ownProps);
150
+ }
151
+ const defaultCloneOptions = { forceWritable: false };
152
+ function deepClone(val, options = defaultCloneOptions) {
153
+ const seen = new WeakMap();
154
+ return clone(val, seen, options);
155
+ }
156
+ function clone(val, seen, options = defaultCloneOptions) {
157
+ let k, out;
158
+ if (seen.has(val)) {
159
+ return seen.get(val);
160
+ }
161
+ if (Array.isArray(val)) {
162
+ out = Array.from({ length: k = val.length });
163
+ seen.set(val, out);
164
+ while (k--) {
165
+ out[k] = clone(val[k], seen, options);
166
+ }
167
+ return out;
168
+ }
169
+ if (Object.prototype.toString.call(val) === "[object Object]") {
170
+ out = Object.create(Object.getPrototypeOf(val));
171
+ seen.set(val, out);
172
+ // we don't need properties from prototype
173
+ const props = getOwnProperties(val);
174
+ for (const k of props) {
175
+ const descriptor = Object.getOwnPropertyDescriptor(val, k);
176
+ if (!descriptor) {
177
+ continue;
178
+ }
179
+ const cloned = clone(val[k], seen, options);
180
+ if (options.forceWritable) {
181
+ Object.defineProperty(out, k, {
182
+ enumerable: descriptor.enumerable,
183
+ configurable: true,
184
+ writable: true,
185
+ value: cloned
186
+ });
187
+ } else if ("get" in descriptor) {
188
+ Object.defineProperty(out, k, {
189
+ ...descriptor,
190
+ get() {
191
+ return cloned;
192
+ }
193
+ });
194
+ } else {
195
+ Object.defineProperty(out, k, {
196
+ ...descriptor,
197
+ value: cloned
198
+ });
199
+ }
200
+ }
201
+ return out;
202
+ }
203
+ return val;
204
+ }
205
+ function noop() {}
206
+ function objectAttr(source, path, defaultValue = undefined) {
207
+ // a[3].b -> a.3.b
208
+ const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
209
+ let result = source;
210
+ for (const p of paths) {
211
+ result = new Object(result)[p];
212
+ if (result === undefined) {
213
+ return defaultValue;
214
+ }
215
+ }
216
+ return result;
217
+ }
218
+ function createDefer() {
219
+ let resolve = null;
220
+ let reject = null;
221
+ const p = new Promise((_resolve, _reject) => {
222
+ resolve = _resolve;
223
+ reject = _reject;
224
+ });
225
+ p.resolve = resolve;
226
+ p.reject = reject;
227
+ return p;
228
+ }
229
+ /**
230
+ * If code starts with a function call, will return its last index, respecting arguments.
231
+ * This will return 25 - last ending character of toMatch ")"
232
+ * Also works with callbacks
233
+ * ```
234
+ * toMatch({ test: '123' });
235
+ * toBeAliased('123')
236
+ * ```
237
+ */
238
+ function getCallLastIndex(code) {
239
+ let charIndex = -1;
240
+ let inString = null;
241
+ let startedBracers = 0;
242
+ let endedBracers = 0;
243
+ let beforeChar = null;
244
+ while (charIndex <= code.length) {
245
+ beforeChar = code[charIndex];
246
+ charIndex++;
247
+ const char = code[charIndex];
248
+ const isCharString = char === "\"" || char === "'" || char === "`";
249
+ if (isCharString && beforeChar !== "\\") {
250
+ if (inString === char) {
251
+ inString = null;
252
+ } else if (!inString) {
253
+ inString = char;
254
+ }
255
+ }
256
+ if (!inString) {
257
+ if (char === "(") {
258
+ startedBracers++;
259
+ }
260
+ if (char === ")") {
261
+ endedBracers++;
262
+ }
263
+ }
264
+ if (startedBracers && endedBracers && startedBracers === endedBracers) {
265
+ return charIndex;
266
+ }
267
+ }
268
+ return null;
269
+ }
270
+ function isNegativeNaN(val) {
271
+ if (!Number.isNaN(val)) {
272
+ return false;
273
+ }
274
+ const f64 = new Float64Array(1);
275
+ f64[0] = val;
276
+ const u32 = new Uint32Array(f64.buffer);
277
+ const isNegative = u32[1] >>> 31 === 1;
278
+ return isNegative;
279
+ }
280
+ function toString(v) {
281
+ return Object.prototype.toString.call(v);
282
+ }
283
+ function isPlainObject(val) {
284
+ return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
285
+ }
286
+ function isMergeableObject(item) {
287
+ return isPlainObject(item) && !Array.isArray(item);
288
+ }
289
+ function ordinal(i) {
290
+ const j = i % 10;
291
+ const k = i % 100;
292
+ if (j === 1 && k !== 11) {
293
+ return `${i}st`;
294
+ }
295
+ if (j === 2 && k !== 12) {
296
+ return `${i}nd`;
297
+ }
298
+ if (j === 3 && k !== 13) {
299
+ return `${i}rd`;
300
+ }
301
+ return `${i}th`;
302
+ }
303
+ /**
304
+ * Deep merge :P
305
+ *
306
+ * Will merge objects only if they are plain
307
+ *
308
+ * Do not merge types - it is very expensive and usually it's better to case a type here
309
+ */
310
+ function deepMerge(target, ...sources) {
311
+ if (!sources.length) {
312
+ return target;
313
+ }
314
+ const source = sources.shift();
315
+ if (source === undefined) {
316
+ return target;
317
+ }
318
+ if (isMergeableObject(target) && isMergeableObject(source)) {
319
+ Object.keys(source).forEach((key) => {
320
+ const _source = source;
321
+ if (isMergeableObject(_source[key])) {
322
+ if (!target[key]) {
323
+ target[key] = {};
324
+ }
325
+ deepMerge(target[key], _source[key]);
326
+ } else {
327
+ target[key] = _source[key];
328
+ }
329
+ });
330
+ }
331
+ return deepMerge(target, ...sources);
332
+ }
333
+ function unique(array) {
334
+ return Array.from(new Set(array));
335
+ }
336
+
337
+ export { assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, filterOutComments, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, nanoid, noop, notNullish, objectAttr, ordinal, shuffle, slash, toArray, unique, unwrapId, withTrailingSlash, wrapId };
@@ -0,0 +1,5 @@
1
+ export { LoupeOptions, StringifyOptions } from './display.js';
2
+ export { DeferPromise } from './helpers.js';
3
+ export { SafeTimers } from './timers.js';
4
+ export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js';
5
+ import '@vitest/pretty-format';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,5 @@
1
+ declare const lineSplitRE: RegExp;
2
+ declare function positionToOffset(source: string, lineNumber: number, columnNumber: number): number;
3
+ declare function offsetToLineNumber(source: string, offset: number): number;
4
+
5
+ export { lineSplitRE, offsetToLineNumber, positionToOffset };
package/dist/offset.js ADDED
@@ -0,0 +1,32 @@
1
+ const lineSplitRE = /\r?\n/;
2
+ function positionToOffset(source, lineNumber, columnNumber) {
3
+ const lines = source.split(lineSplitRE);
4
+ const nl = /\r\n/.test(source) ? 2 : 1;
5
+ let start = 0;
6
+ if (lineNumber > lines.length) {
7
+ return source.length;
8
+ }
9
+ for (let i = 0; i < lineNumber - 1; i++) {
10
+ start += lines[i].length + nl;
11
+ }
12
+ return start + columnNumber;
13
+ }
14
+ function offsetToLineNumber(source, offset) {
15
+ if (offset > source.length) {
16
+ throw new Error(`offset is longer than source length! offset ${offset} > length ${source.length}`);
17
+ }
18
+ const lines = source.split(lineSplitRE);
19
+ const nl = /\r\n/.test(source) ? 2 : 1;
20
+ let counted = 0;
21
+ let line = 0;
22
+ for (; line < lines.length; line++) {
23
+ const lineLength = lines[line].length + nl;
24
+ if (counted + lineLength >= offset) {
25
+ break;
26
+ }
27
+ counted += lineLength;
28
+ }
29
+ return line + 1;
30
+ }
31
+
32
+ export { lineSplitRE, offsetToLineNumber, positionToOffset };
@@ -0,0 +1,7 @@
1
+ declare function findNearestPackageData(basedir: string): {
2
+ type?: "module" | "commonjs";
3
+ };
4
+ declare function getCachedData<T>(cache: Map<string, T>, basedir: string, originalBasedir: string): NonNullable<T> | undefined;
5
+ declare function setCacheData<T>(cache: Map<string, T>, data: T, basedir: string, originalBasedir: string): void;
6
+
7
+ export { findNearestPackageData, getCachedData, setCacheData };
@@ -0,0 +1,70 @@
1
+ import fs from 'node:fs';
2
+ import { j as join, d as dirname } from './chunk-pathe.M-eThtNZ.js';
3
+
4
+ const packageCache = new Map();
5
+ function findNearestPackageData(basedir) {
6
+ const originalBasedir = basedir;
7
+ while (basedir) {
8
+ const cached = getCachedData(packageCache, basedir, originalBasedir);
9
+ if (cached) {
10
+ return cached;
11
+ }
12
+ const pkgPath = join(basedir, "package.json");
13
+ if (tryStatSync(pkgPath)?.isFile()) {
14
+ const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
15
+ if (packageCache) {
16
+ setCacheData(packageCache, pkgData, basedir, originalBasedir);
17
+ }
18
+ return pkgData;
19
+ }
20
+ const nextBasedir = dirname(basedir);
21
+ if (nextBasedir === basedir) {
22
+ break;
23
+ }
24
+ basedir = nextBasedir;
25
+ }
26
+ return {};
27
+ }
28
+ function stripBomTag(content) {
29
+ if (content.charCodeAt(0) === 65279) {
30
+ return content.slice(1);
31
+ }
32
+ return content;
33
+ }
34
+ function tryStatSync(file) {
35
+ try {
36
+ // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
37
+ return fs.statSync(file, { throwIfNoEntry: false });
38
+ } catch {}
39
+ }
40
+ function getCachedData(cache, basedir, originalBasedir) {
41
+ const pkgData = cache.get(getFnpdCacheKey(basedir));
42
+ if (pkgData) {
43
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
44
+ cache.set(getFnpdCacheKey(dir), pkgData);
45
+ });
46
+ return pkgData;
47
+ }
48
+ }
49
+ function setCacheData(cache, data, basedir, originalBasedir) {
50
+ cache.set(getFnpdCacheKey(basedir), data);
51
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
52
+ cache.set(getFnpdCacheKey(dir), data);
53
+ });
54
+ }
55
+ function getFnpdCacheKey(basedir) {
56
+ return `fnpd_${basedir}`;
57
+ }
58
+ /**
59
+ * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
60
+ * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
61
+ * @param shorterDir Shorter dir path, e.g. `/User/foo`
62
+ */
63
+ function traverseBetweenDirs(longerDir, shorterDir, cb) {
64
+ while (longerDir !== shorterDir) {
65
+ cb(longerDir);
66
+ longerDir = dirname(longerDir);
67
+ }
68
+ }
69
+
70
+ export { findNearestPackageData, getCachedData, setCacheData };
@@ -0,0 +1,3 @@
1
+ declare function serializeValue(val: any, seen?: WeakMap<WeakKey, any>): any;
2
+
3
+ export { serializeValue };