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

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/helpers.js CHANGED
@@ -1,251 +1 @@
1
- /**
2
- * Get original stacktrace without source map support the most performant way.
3
- * - Create only 1 stack frame.
4
- * - Rewrite prepareStackTrace to bypass "support-stack-trace" (usually takes ~250ms).
5
- */
6
- function createSimpleStackTrace(options) {
7
- const { message = "$$stack trace error", stackTraceLimit = 1 } = options || {};
8
- const limit = Error.stackTraceLimit;
9
- const prepareStackTrace = Error.prepareStackTrace;
10
- Error.stackTraceLimit = stackTraceLimit;
11
- Error.prepareStackTrace = (e) => e.stack;
12
- const err = new Error(message);
13
- const stackTrace = err.stack || "";
14
- Error.prepareStackTrace = prepareStackTrace;
15
- Error.stackTraceLimit = limit;
16
- return stackTrace;
17
- }
18
- function notNullish(v) {
19
- return v != null;
20
- }
21
- function assertTypes(value, name, types) {
22
- const receivedType = typeof value;
23
- const pass = types.includes(receivedType);
24
- if (!pass) {
25
- throw new TypeError(`${name} value must be ${types.join(" or ")}, received "${receivedType}"`);
26
- }
27
- }
28
- function isPrimitive(value) {
29
- return value === null || typeof value !== "function" && typeof value !== "object";
30
- }
31
- function slash(path) {
32
- return path.replace(/\\/g, "/");
33
- }
34
- // convert RegExp.toString to RegExp
35
- function parseRegexp(input) {
36
- // Parse input
37
- // eslint-disable-next-line regexp/no-misleading-capturing-group
38
- const m = input.match(/(\/?)(.+)\1([a-z]*)/i);
39
- // match nothing
40
- if (!m) {
41
- return /$^/;
42
- }
43
- // Invalid flags
44
- // eslint-disable-next-line regexp/optimal-quantifier-concatenation
45
- if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3])) {
46
- return new RegExp(input);
47
- }
48
- // Create the regular expression
49
- return new RegExp(m[2], m[3]);
50
- }
51
- function toArray(array) {
52
- if (array === null || array === undefined) {
53
- array = [];
54
- }
55
- if (Array.isArray(array)) {
56
- return array;
57
- }
58
- return [array];
59
- }
60
- function isObject(item) {
61
- return item != null && typeof item === "object" && !Array.isArray(item);
62
- }
63
- function isFinalObj(obj) {
64
- return obj === Object.prototype || obj === Function.prototype || obj === RegExp.prototype;
65
- }
66
- function getType(value) {
67
- return Object.prototype.toString.apply(value).slice(8, -1);
68
- }
69
- function collectOwnProperties(obj, collector) {
70
- const collect = typeof collector === "function" ? collector : (key) => collector.add(key);
71
- Object.getOwnPropertyNames(obj).forEach(collect);
72
- Object.getOwnPropertySymbols(obj).forEach(collect);
73
- }
74
- function getOwnProperties(obj) {
75
- const ownProps = new Set();
76
- if (isFinalObj(obj)) {
77
- return [];
78
- }
79
- collectOwnProperties(obj, ownProps);
80
- return Array.from(ownProps);
81
- }
82
- const defaultCloneOptions = { forceWritable: false };
83
- function deepClone(val, options = defaultCloneOptions) {
84
- const seen = new WeakMap();
85
- return clone(val, seen, options);
86
- }
87
- function clone(val, seen, options = defaultCloneOptions) {
88
- let k, out;
89
- if (seen.has(val)) {
90
- return seen.get(val);
91
- }
92
- if (Array.isArray(val)) {
93
- out = Array.from({ length: k = val.length });
94
- seen.set(val, out);
95
- while (k--) {
96
- out[k] = clone(val[k], seen, options);
97
- }
98
- return out;
99
- }
100
- if (Object.prototype.toString.call(val) === "[object Object]") {
101
- out = Object.create(Object.getPrototypeOf(val));
102
- seen.set(val, out);
103
- // we don't need properties from prototype
104
- const props = getOwnProperties(val);
105
- for (const k of props) {
106
- const descriptor = Object.getOwnPropertyDescriptor(val, k);
107
- if (!descriptor) {
108
- continue;
109
- }
110
- const cloned = clone(val[k], seen, options);
111
- if (options.forceWritable) {
112
- Object.defineProperty(out, k, {
113
- enumerable: descriptor.enumerable,
114
- configurable: true,
115
- writable: true,
116
- value: cloned
117
- });
118
- } else if ("get" in descriptor) {
119
- Object.defineProperty(out, k, {
120
- ...descriptor,
121
- get() {
122
- return cloned;
123
- }
124
- });
125
- } else {
126
- Object.defineProperty(out, k, {
127
- ...descriptor,
128
- value: cloned
129
- });
130
- }
131
- }
132
- return out;
133
- }
134
- return val;
135
- }
136
- function noop() {}
137
- function objectAttr(source, path, defaultValue = undefined) {
138
- // a[3].b -> a.3.b
139
- const paths = path.replace(/\[(\d+)\]/g, ".$1").split(".");
140
- let result = source;
141
- for (const p of paths) {
142
- result = new Object(result)[p];
143
- if (result === undefined) {
144
- return defaultValue;
145
- }
146
- }
147
- return result;
148
- }
149
- function createDefer() {
150
- let resolve = null;
151
- let reject = null;
152
- const p = new Promise((_resolve, _reject) => {
153
- resolve = _resolve;
154
- reject = _reject;
155
- });
156
- p.resolve = resolve;
157
- p.reject = reject;
158
- return p;
159
- }
160
- /**
161
- * If code starts with a function call, will return its last index, respecting arguments.
162
- * This will return 25 - last ending character of toMatch ")"
163
- * Also works with callbacks
164
- * ```
165
- * toMatch({ test: '123' });
166
- * toBeAliased('123')
167
- * ```
168
- */
169
- function getCallLastIndex(code) {
170
- let charIndex = -1;
171
- let inString = null;
172
- let startedBracers = 0;
173
- let endedBracers = 0;
174
- let beforeChar = null;
175
- while (charIndex <= code.length) {
176
- beforeChar = code[charIndex];
177
- charIndex++;
178
- const char = code[charIndex];
179
- const isCharString = char === "\"" || char === "'" || char === "`";
180
- if (isCharString && beforeChar !== "\\") {
181
- if (inString === char) {
182
- inString = null;
183
- } else if (!inString) {
184
- inString = char;
185
- }
186
- }
187
- if (!inString) {
188
- if (char === "(") {
189
- startedBracers++;
190
- }
191
- if (char === ")") {
192
- endedBracers++;
193
- }
194
- }
195
- if (startedBracers && endedBracers && startedBracers === endedBracers) {
196
- return charIndex;
197
- }
198
- }
199
- return null;
200
- }
201
- function isNegativeNaN(val) {
202
- if (!Number.isNaN(val)) {
203
- return false;
204
- }
205
- const f64 = new Float64Array(1);
206
- f64[0] = val;
207
- const u32 = new Uint32Array(f64.buffer);
208
- const isNegative = u32[1] >>> 31 === 1;
209
- return isNegative;
210
- }
211
- function toString(v) {
212
- return Object.prototype.toString.call(v);
213
- }
214
- function isPlainObject(val) {
215
- return toString(val) === "[object Object]" && (!val.constructor || val.constructor.name === "Object");
216
- }
217
- function isMergeableObject(item) {
218
- return isPlainObject(item) && !Array.isArray(item);
219
- }
220
- /**
221
- * Deep merge :P
222
- *
223
- * Will merge objects only if they are plain
224
- *
225
- * Do not merge types - it is very expensive and usually it's better to case a type here
226
- */
227
- function deepMerge(target, ...sources) {
228
- if (!sources.length) {
229
- return target;
230
- }
231
- const source = sources.shift();
232
- if (source === undefined) {
233
- return target;
234
- }
235
- if (isMergeableObject(target) && isMergeableObject(source)) {
236
- Object.keys(source).forEach((key) => {
237
- const _source = source;
238
- if (isMergeableObject(_source[key])) {
239
- if (!target[key]) {
240
- target[key] = {};
241
- }
242
- deepMerge(target[key], _source[key]);
243
- } else {
244
- target[key] = _source[key];
245
- }
246
- });
247
- }
248
- return deepMerge(target, ...sources);
249
- }
250
-
251
- export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray };
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';
package/dist/index.d.ts CHANGED
@@ -1,8 +1,28 @@
1
1
  import { PrettyFormatOptions } from '@vitest/pretty-format';
2
- export { DeferPromise, assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray } from './helpers.js';
2
+ export { DeferPromise, assertTypes, cleanUrl, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isBareImport, isExternalUrl, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray, unwrapId, withTrailingSlash, wrapId } from './helpers.js';
3
3
  import { Colors } from 'tinyrainbow';
4
4
  export { ArgumentsType, Arrayable, Awaitable, Constructable, DeepMerge, MergeInsertions, Nullable, ParsedStack, SerializedError, TestError } from './types.js';
5
5
 
6
+ declare const KNOWN_ASSET_TYPES: string[];
7
+ declare const KNOWN_ASSET_RE: RegExp;
8
+ declare const CSS_LANGS_RE: RegExp;
9
+ /**
10
+ * Prefix for resolved Ids that are not valid browser import specifiers
11
+ */
12
+ declare const VALID_ID_PREFIX = "/@id/";
13
+ /**
14
+ * Plugins that use 'virtual modules' (e.g. for helper functions), prefix the
15
+ * module ID with `\0`, a convention from the rollup ecosystem.
16
+ * This prevents other plugins from trying to process the id (like node resolution),
17
+ * and core features like sourcemaps can use this info to differentiate between
18
+ * virtual modules and regular files.
19
+ * `\0` is not a permitted char in import URLs so we have to replace them during
20
+ * import analysis. The id will be decoded back before entering the plugins pipeline.
21
+ * These encoded virtual ids are also prefixed by the VALID_ID_PREFIX, so virtual
22
+ * modules in the browser end up encoded as `/@id/__x00__{id}`
23
+ */
24
+ declare const NULL_BYTE_PLACEHOLDER = "__x00__";
25
+
6
26
  type Inspect = (value: unknown, options: Options) => string;
7
27
  interface Options {
8
28
  showHidden: boolean;
@@ -41,14 +61,12 @@ declare function offsetToLineNumber(source: string, offset: number): number;
41
61
  declare function shuffle<T>(array: T[], seed?: number): T[];
42
62
 
43
63
  interface SafeTimers {
44
- // node.js timers
45
64
  nextTick?: (cb: () => void) => void;
46
65
  setImmediate?: {
47
- <TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): any
48
- __promisify__: <T = void>(value?: T, options?: any) => Promise<T>
66
+ <TArgs extends any[]>(callback: (...args: TArgs) => void, ...args: TArgs): any;
67
+ __promisify__: <T = void>(value?: T, options?: any) => Promise<T>;
49
68
  };
50
69
  clearImmediate?: (immediateId: any) => void;
51
- // cross-platform timers
52
70
  setTimeout: typeof setTimeout;
53
71
  setInterval: typeof setInterval;
54
72
  clearInterval: typeof clearInterval;
@@ -58,5 +76,5 @@ interface SafeTimers {
58
76
  declare function getSafeTimers(): SafeTimers;
59
77
  declare function setSafeTimers(): void;
60
78
 
61
- export { format, getSafeTimers, highlight, inspect, lineSplitRE, nanoid, objDisplay, offsetToLineNumber, positionToOffset, setSafeTimers, shuffle, stringify };
79
+ export { CSS_LANGS_RE, KNOWN_ASSET_RE, KNOWN_ASSET_TYPES, NULL_BYTE_PLACEHOLDER, VALID_ID_PREFIX, format, getSafeTimers, highlight, inspect, lineSplitRE, nanoid, objDisplay, offsetToLineNumber, positionToOffset, setSafeTimers, shuffle, stringify };
62
80
  export type { LoupeOptions, SafeTimers, StringifyOptions };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
+ export { C as CSS_LANGS_RE, K as KNOWN_ASSET_RE, a as KNOWN_ASSET_TYPES, N as NULL_BYTE_PLACEHOLDER, V as VALID_ID_PREFIX, 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
2
  import { g as getDefaultExportFromCjs } from './chunk-_commonjsHelpers.js';
2
3
  export { f as format, i as inspect, o as objDisplay, s as stringify } from './chunk-_commonjsHelpers.js';
3
- export { assertTypes, clone, createDefer, createSimpleStackTrace, deepClone, deepMerge, getCallLastIndex, getOwnProperties, getType, isNegativeNaN, isObject, isPrimitive, noop, notNullish, objectAttr, parseRegexp, slash, toArray } from './helpers.js';
4
4
  import c from 'tinyrainbow';
5
5
  import '@vitest/pretty-format';
6
6
  import 'loupe';
@@ -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,71 @@
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
+ var _tryStatSync;
9
+ const cached = getCachedData(packageCache, basedir, originalBasedir);
10
+ if (cached) {
11
+ return cached;
12
+ }
13
+ const pkgPath = join(basedir, "package.json");
14
+ if ((_tryStatSync = tryStatSync(pkgPath)) === null || _tryStatSync === void 0 ? void 0 : _tryStatSync.isFile()) {
15
+ const pkgData = JSON.parse(stripBomTag(fs.readFileSync(pkgPath, "utf8")));
16
+ if (packageCache) {
17
+ setCacheData(packageCache, pkgData, basedir, originalBasedir);
18
+ }
19
+ return pkgData;
20
+ }
21
+ const nextBasedir = dirname(basedir);
22
+ if (nextBasedir === basedir) {
23
+ break;
24
+ }
25
+ basedir = nextBasedir;
26
+ }
27
+ return {};
28
+ }
29
+ function stripBomTag(content) {
30
+ if (content.charCodeAt(0) === 65279) {
31
+ return content.slice(1);
32
+ }
33
+ return content;
34
+ }
35
+ function tryStatSync(file) {
36
+ try {
37
+ // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
38
+ return fs.statSync(file, { throwIfNoEntry: false });
39
+ } catch {}
40
+ }
41
+ function getCachedData(cache, basedir, originalBasedir) {
42
+ const pkgData = cache.get(getFnpdCacheKey(basedir));
43
+ if (pkgData) {
44
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
45
+ cache.set(getFnpdCacheKey(dir), pkgData);
46
+ });
47
+ return pkgData;
48
+ }
49
+ }
50
+ function setCacheData(cache, data, basedir, originalBasedir) {
51
+ cache.set(getFnpdCacheKey(basedir), data);
52
+ traverseBetweenDirs(originalBasedir, basedir, (dir) => {
53
+ cache.set(getFnpdCacheKey(dir), data);
54
+ });
55
+ }
56
+ function getFnpdCacheKey(basedir) {
57
+ return `fnpd_${basedir}`;
58
+ }
59
+ /**
60
+ * Traverse between `longerDir` (inclusive) and `shorterDir` (exclusive) and call `cb` for each dir.
61
+ * @param longerDir Longer dir path, e.g. `/User/foo/bar/baz`
62
+ * @param shorterDir Shorter dir path, e.g. `/User/foo`
63
+ */
64
+ function traverseBetweenDirs(longerDir, shorterDir, cb) {
65
+ while (longerDir !== shorterDir) {
66
+ cb(longerDir);
67
+ longerDir = dirname(longerDir);
68
+ }
69
+ }
70
+
71
+ export { findNearestPackageData, getCachedData, setCacheData };
@@ -85,6 +85,11 @@ declare abstract class SourceMap {
85
85
  resolvedSources: SourceMapV3['sources'];
86
86
  ignoreList: SourceMapV3['ignoreList'];
87
87
  }
88
+ type Ro<T> = T extends Array<infer V> ? V[] | Readonly<V[]> | RoArray<V> | Readonly<RoArray<V>> : T extends object ? T | Readonly<T> | RoObject<T> | Readonly<RoObject<T>> : T;
89
+ type RoArray<T> = Ro<T>[];
90
+ type RoObject<T> = {
91
+ [K in keyof T]: T[K] | Ro<T[K]>;
92
+ };
88
93
 
89
94
  declare const LEAST_UPPER_BOUND = -1;
90
95
  declare const GREATEST_LOWER_BOUND = 1;
@@ -103,7 +108,7 @@ declare class TraceMap implements SourceMap {
103
108
  private _decodedMemo;
104
109
  private _bySources;
105
110
  private _bySourceMemos;
106
- constructor(map: SourceMapInput, mapUrl?: string | null);
111
+ constructor(map: Ro<SourceMapInput>, mapUrl?: string | null);
107
112
  }
108
113
  /**
109
114
  * A higher-level API to find the source/line/column associated with a generated line/column
@@ -126,14 +131,14 @@ interface StackTraceParserOptions {
126
131
  getUrlId?: (id: string) => string;
127
132
  frameFilter?: (error: TestError, frame: ParsedStack) => boolean | void;
128
133
  }
134
+ declare const stackIgnorePatterns: (string | RegExp)[];
135
+
129
136
  declare function parseSingleFFOrSafariStack(raw: string): ParsedStack | null;
130
137
  declare function parseSingleStack(raw: string): ParsedStack | null;
131
- // Based on https://github.com/stacktracejs/error-stack-parser
132
- // Credit to stacktracejs
133
138
  declare function parseSingleV8Stack(raw: string): ParsedStack | null;
134
139
  declare function createStackString(stacks: ParsedStack[]): string;
135
140
  declare function parseStacktrace(stack: string, options?: StackTraceParserOptions): ParsedStack[];
136
141
  declare function parseErrorStacktrace(e: TestError | Error, options?: StackTraceParserOptions): ParsedStack[];
137
142
 
138
- export { TraceMap, createStackString, eachMapping, generatedPositionFor, originalPositionFor, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace };
143
+ export { TraceMap, createStackString, stackIgnorePatterns as defaultStackIgnorePatterns, eachMapping, generatedPositionFor, originalPositionFor, parseErrorStacktrace, parseSingleFFOrSafariStack, parseSingleStack, parseSingleV8Stack, parseStacktrace };
139
144
  export type { EachMapping, SourceMapInput, StackTraceParserOptions };