id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
1,800 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void | type ChildMessage =
| ChildMessageInitialize
| ChildMessageCall
| ChildMessageEnd
| ChildMessageMemUsage; |
1,801 | (listener: OnCustomMessage) => () => void | type OnCustomMessage = (message: Array<unknown> | unknown) => void; |
1,802 | enqueue(task: QueueChildMessage, workerId?: number): void | type QueueChildMessage = {
request: ChildMessageCall;
onStart: OnStart;
onEnd: OnEnd;
onCustomMessage: OnCustomMessage;
}; |
1,803 | (worker: WorkerInterface) => void | interface WorkerInterface {
get state(): WorkerStates;
send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void;
waitForExit(): Promise<void>;
forceExit(): void;
getWorkerId(): number;
getStderr(): NodeJS.ReadableStream | null;
getStdout(): NodeJS.ReadableStream | null;
/**
* Some system level identifier for the worker. IE, process id, thread id, etc.
*/
getWorkerSystemId(): number;
getMemoryUsage(): Promise<number | null>;
/**
* Checks to see if the child worker is actually running.
*/
isWorkerRunning(): boolean;
/**
* When the worker child is started and ready to start handling requests.
*
* @remarks
* This mostly exists to help with testing so that you don't check the status
* of things like isWorkerRunning before it actually is.
*/
waitForWorkerReady(): Promise<void>;
} |
1,804 | (listener: OnCustomMessage) => {
customMessageListeners.add(listener);
return () => {
customMessageListeners.delete(listener);
};
} | type OnCustomMessage = (message: Array<unknown> | unknown) => void; |
1,805 | (worker: WorkerInterface) => {
if (hash != null) {
this._cacheKeys[hash] = worker;
}
} | interface WorkerInterface {
get state(): WorkerStates;
send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void;
waitForExit(): Promise<void>;
forceExit(): void;
getWorkerId(): number;
getStderr(): NodeJS.ReadableStream | null;
getStdout(): NodeJS.ReadableStream | null;
/**
* Some system level identifier for the worker. IE, process id, thread id, etc.
*/
getWorkerSystemId(): number;
getMemoryUsage(): Promise<number | null>;
/**
* Checks to see if the child worker is actually running.
*/
isWorkerRunning(): boolean;
/**
* When the worker child is started and ready to start handling requests.
*
* @remarks
* This mostly exists to help with testing so that you don't check the status
* of things like isWorkerRunning before it actually is.
*/
waitForWorkerReady(): Promise<void>;
} |
1,806 | private _push(task: QueueChildMessage): Farm {
this._taskQueue.enqueue(task);
const offset = this._getNextWorkerOffset();
for (let i = 0; i < this._numOfWorkers; i++) {
this._process((offset + i) % this._numOfWorkers);
if (task.request[1]) {
break;
}
}
return this;
} | type QueueChildMessage = {
request: ChildMessageCall;
onStart: OnStart;
onEnd: OnEnd;
onCustomMessage: OnCustomMessage;
}; |
1,807 | constructor(private readonly _computePriority: ComputeTaskPriorityCallback) {} | type ComputeTaskPriorityCallback = (
method: string,
...args: Array<unknown>
) => number; |
1,808 | enqueue(task: QueueChildMessage, workerId?: number): void {
if (workerId == null) {
this._enqueue(task, this._sharedQueue);
} else {
const queue = this._getWorkerQueue(workerId);
this._enqueue(task, queue);
}
} | type QueueChildMessage = {
request: ChildMessageCall;
onStart: OnStart;
onEnd: OnEnd;
onCustomMessage: OnCustomMessage;
}; |
1,809 | _enqueue(task: QueueChildMessage, queue: MinHeap<QueueItem>): void {
const item = {
priority: this._computePriority(task.request[2], ...task.request[3]),
task,
};
queue.add(item);
} | type QueueChildMessage = {
request: ChildMessageCall;
onStart: OnStart;
onEnd: OnEnd;
onCustomMessage: OnCustomMessage;
}; |
1,810 | enqueue(task: QueueChildMessage, workerId?: number): void {
if (workerId == null) {
this._sharedQueue.enqueue(task);
return;
}
let workerQueue = this._workerQueues[workerId];
if (workerQueue == null) {
workerQueue = this._workerQueues[workerId] =
new InternalQueue<WorkerQueueValue>();
}
const sharedTop = this._sharedQueue.peekLast();
const item = {previousSharedTask: sharedTop, task};
workerQueue.enqueue(item);
} | type QueueChildMessage = {
request: ChildMessageCall;
onStart: OnStart;
onEnd: OnEnd;
onCustomMessage: OnCustomMessage;
}; |
1,811 | override createWorker(workerOptions: WorkerOptions): WorkerInterface {
let Worker;
if (this._options.enableWorkerThreads) {
Worker = require('./workers/NodeThreadsWorker').default;
} else {
Worker = require('./workers/ChildProcessWorker').default;
}
return new Worker(workerOptions);
} | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,812 | createWorker(_workerOptions: WorkerOptions): WorkerInterface {
throw Error('Missing method createWorker in WorkerPool');
} | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,813 | (workerOptions: WorkerOptions) => WorkerInterface | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,814 | override createWorker(workerOptions: WorkerOptions) {
return new Worker(workerOptions);
} | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,815 | constructor(options: WorkerOptions) {
super(options);
this._options = options;
this._request = null;
this._stdout = null;
this._stderr = null;
this._childIdleMemoryUsage = null;
this._childIdleMemoryUsageLimit = options.idleMemoryLimit || null;
this._childWorkerPath =
options.childWorkerPath || require.resolve('./processChild');
this.state = WorkerStates.STARTING;
this.initialize();
} | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,816 | private _onMessage(response: ParentMessage) {
// Ignore messages not intended for us
if (!Array.isArray(response)) return;
// TODO: Add appropriate type check
let error: any;
switch (response[0]) {
case PARENT_MESSAGE_OK:
this._onProcessEnd(null, response[1]);
break;
case PARENT_MESSAGE_CLIENT_ERROR:
error = response[4];
if (error != null && typeof error === 'object') {
const extra = error;
// @ts-expect-error: no index
const NativeCtor = globalThis[response[1]];
const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error;
error = new Ctor(response[2]);
error.type = response[1];
error.stack = response[3];
for (const key in extra) {
error[key] = extra[key];
}
}
this._onProcessEnd(error, null);
break;
case PARENT_MESSAGE_SETUP_ERROR:
error = new Error(`Error when calling setup: ${response[2]}`);
error.type = response[1];
error.stack = response[3];
this._onProcessEnd(error, null);
break;
case PARENT_MESSAGE_CUSTOM:
this._onCustomMessage(response[1]);
break;
case PARENT_MESSAGE_MEM_USAGE:
this._childIdleMemoryUsage = response[1];
if (this._resolveMemoryUsage) {
this._resolveMemoryUsage(response[1]);
this._resolveMemoryUsage = undefined;
this._memoryUsagePromise = undefined;
}
this._performRestartIfRequired();
break;
default:
// Ignore messages not intended for us
break;
}
} | type ParentMessage =
| ParentMessageOk
| ParentMessageError
| ParentMessageCustom
| ParentMessageMemUsage; |
1,817 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void {
this._stderrBuffer = [];
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (
this._childIdleMemoryUsageLimit &&
this._child.connected &&
hasRequest
) {
this.checkMemoryUsage();
}
return onProcessEnd(...args);
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
// eslint-disable-next-line @typescript-eslint/no-empty-function
this._child.send(request, () => {});
} | type OnStart = (worker: WorkerInterface) => void; |
1,818 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void {
this._stderrBuffer = [];
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (
this._childIdleMemoryUsageLimit &&
this._child.connected &&
hasRequest
) {
this.checkMemoryUsage();
}
return onProcessEnd(...args);
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
// eslint-disable-next-line @typescript-eslint/no-empty-function
this._child.send(request, () => {});
} | type OnCustomMessage = (message: Array<unknown> | unknown) => void; |
1,819 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void {
this._stderrBuffer = [];
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (
this._childIdleMemoryUsageLimit &&
this._child.connected &&
hasRequest
) {
this.checkMemoryUsage();
}
return onProcessEnd(...args);
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
// eslint-disable-next-line @typescript-eslint/no-empty-function
this._child.send(request, () => {});
} | type OnEnd = (err: Error | null, result: unknown) => void; |
1,820 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd,
onCustomMessage: OnCustomMessage,
): void {
this._stderrBuffer = [];
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (
this._childIdleMemoryUsageLimit &&
this._child.connected &&
hasRequest
) {
this.checkMemoryUsage();
}
return onProcessEnd(...args);
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
// eslint-disable-next-line @typescript-eslint/no-empty-function
this._child.send(request, () => {});
} | type ChildMessage =
| ChildMessageInitialize
| ChildMessageCall
| ChildMessageEnd
| ChildMessageMemUsage; |
1,821 | function reportError(error: Error, type: PARENT_MESSAGE_ERROR) {
if (isMainThread) {
throw new Error('Child can only be used on a forked process');
}
if (error == null) {
error = new Error('"null" or "undefined" thrown');
}
parentPort!.postMessage([
type,
error.constructor && error.constructor.name,
error.message,
error.stack,
typeof error === 'object' ? {...error} : error,
]);
} | type PARENT_MESSAGE_ERROR =
| typeof PARENT_MESSAGE_CLIENT_ERROR
| typeof PARENT_MESSAGE_SETUP_ERROR; |
1,822 | function execFunction(
fn: UnknownFunction,
ctx: unknown,
args: Array<unknown>,
onResult: (result: unknown) => void,
onError: (error: Error) => void,
): void {
let result: unknown;
try {
result = fn.apply(ctx, args);
} catch (err: any) {
onError(err);
return;
}
if (isPromise(result)) {
result.then(onResult, onError);
} else {
onResult(result);
}
} | type UnknownFunction = (...args: Array<unknown>) => unknown; |
1,823 | function execFunction(
fn: UnknownFunction,
ctx: unknown,
args: Array<unknown>,
onResult: (result: unknown) => void,
onError: (error: Error) => void,
): void {
let result: unknown;
try {
result = fn.apply(ctx, args);
} catch (err: any) {
onError(err);
return;
}
if (isPromise(result)) {
result.then(onResult, onError);
} else {
onResult(result);
}
} | type UnknownFunction = (...args: Array<unknown>) => unknown | Promise<unknown>; |
1,824 | function execFunction(
fn: UnknownFunction,
ctx: unknown,
args: Array<unknown>,
onResult: (result: unknown) => void,
onError: (error: Error) => void,
): void {
let result: unknown;
try {
result = fn.apply(ctx, args);
} catch (err: any) {
onError(err);
return;
}
if (isPromise(result)) {
result.then(onResult, onError);
} else {
onResult(result);
}
} | type UnknownFunction = (...args: Array<unknown>) => unknown | Promise<unknown>; |
1,825 | constructor(options: WorkerOptions) {
super();
if (typeof options.on === 'object') {
for (const [event, handlers] of Object.entries(options.on)) {
// Can't do Array.isArray on a ReadonlyArray<T>.
// https://github.com/microsoft/TypeScript/issues/17002
if (typeof handlers === 'function') {
super.on(event, handlers);
} else {
for (const handler of handlers) {
super.on(event, handler);
}
}
}
}
this._exitPromise = new Promise(resolve => {
this._resolveExitPromise = resolve;
});
this._exitPromise.then(() => {
this.state = WorkerStates.SHUT_DOWN;
});
} | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,826 | function reportError(error: Error, type: PARENT_MESSAGE_ERROR) {
if (!process || !process.send) {
throw new Error('Child can only be used on a forked process');
}
if (error == null) {
error = new Error('"null" or "undefined" thrown');
}
process.send([
type,
error.constructor && error.constructor.name,
error.message,
error.stack,
typeof error === 'object' ? {...error} : error,
]);
} | type PARENT_MESSAGE_ERROR =
| typeof PARENT_MESSAGE_CLIENT_ERROR
| typeof PARENT_MESSAGE_SETUP_ERROR; |
1,827 | constructor(options: WorkerOptions) {
super(options);
this._options = options;
this._request = null;
this._stdout = null;
this._stderr = null;
this._childWorkerPath =
options.childWorkerPath || require.resolve('./threadChild');
this._childIdleMemoryUsage = null;
this._childIdleMemoryUsageLimit = options.idleMemoryLimit || null;
this.initialize();
} | type WorkerOptions = {
forkOptions: ForkOptions;
resourceLimits: ResourceLimits;
setupArgs: Array<unknown>;
maxRetries: number;
workerId: number;
workerData?: unknown;
workerPath: string;
/**
* After a job has executed the memory usage it should return to.
*
* @remarks
* Note this is different from ResourceLimits in that it checks at idle, after
* a job is complete. So you could have a resource limit of 500MB but an idle
* limit of 50MB. The latter will only trigger if after a job has completed the
* memory usage hasn't returned back down under 50MB.
*/
idleMemoryLimit?: number;
/**
* This mainly exists so the path can be changed during testing.
* https://github.com/facebook/jest/issues/9543
*/
childWorkerPath?: string;
/**
* This is useful for debugging individual tests allowing you to see
* the raw output of the worker.
*/
silent?: boolean;
/**
* Used to immediately bind event handlers.
*/
on?: {
[WorkerEvents.STATE_CHANGE]:
| OnStateChangeHandler
| ReadonlyArray<OnStateChangeHandler>;
};
}; |
1,828 | private _onMessage(response: ParentMessage) {
// Ignore messages not intended for us
if (!Array.isArray(response)) return;
let error;
switch (response[0]) {
case PARENT_MESSAGE_OK:
this._onProcessEnd(null, response[1]);
break;
case PARENT_MESSAGE_CLIENT_ERROR:
error = response[4];
if (error != null && typeof error === 'object') {
const extra = error;
// @ts-expect-error: no index
const NativeCtor = globalThis[response[1]];
const Ctor = typeof NativeCtor === 'function' ? NativeCtor : Error;
error = new Ctor(response[2]);
error.type = response[1];
error.stack = response[3];
for (const key in extra) {
// @ts-expect-error: no index
error[key] = extra[key];
}
}
this._onProcessEnd(error, null);
break;
case PARENT_MESSAGE_SETUP_ERROR:
error = new Error(`Error when calling setup: ${response[2]}`);
// @ts-expect-error: adding custom properties to errors.
error.type = response[1];
error.stack = response[3];
this._onProcessEnd(error, null);
break;
case PARENT_MESSAGE_CUSTOM:
this._onCustomMessage(response[1]);
break;
case PARENT_MESSAGE_MEM_USAGE:
this._childIdleMemoryUsage = response[1];
if (this._resolveMemoryUsage) {
this._resolveMemoryUsage(response[1]);
this._resolveMemoryUsage = undefined;
this._memoryUsagePromise = undefined;
}
this._performRestartIfRequired();
break;
default:
// Ignore messages not intended for us
break;
}
} | type ParentMessage =
| ParentMessageOk
| ParentMessageError
| ParentMessageCustom
| ParentMessageMemUsage; |
1,829 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd | null,
onCustomMessage: OnCustomMessage,
): void {
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (this._childIdleMemoryUsageLimit && hasRequest) {
this.checkMemoryUsage();
}
const res = onProcessEnd?.(...args);
// Clean up the reference so related closures can be garbage collected.
onProcessEnd = null;
return res;
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
this._worker.postMessage(request);
} | type OnStart = (worker: WorkerInterface) => void; |
1,830 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd | null,
onCustomMessage: OnCustomMessage,
): void {
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (this._childIdleMemoryUsageLimit && hasRequest) {
this.checkMemoryUsage();
}
const res = onProcessEnd?.(...args);
// Clean up the reference so related closures can be garbage collected.
onProcessEnd = null;
return res;
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
this._worker.postMessage(request);
} | type OnCustomMessage = (message: Array<unknown> | unknown) => void; |
1,831 | send(
request: ChildMessage,
onProcessStart: OnStart,
onProcessEnd: OnEnd | null,
onCustomMessage: OnCustomMessage,
): void {
onProcessStart(this);
this._onProcessEnd = (...args) => {
const hasRequest = !!this._request;
// Clean the request to avoid sending past requests to workers that fail
// while waiting for a new request (timers, unhandled rejections...)
this._request = null;
if (this._childIdleMemoryUsageLimit && hasRequest) {
this.checkMemoryUsage();
}
const res = onProcessEnd?.(...args);
// Clean up the reference so related closures can be garbage collected.
onProcessEnd = null;
return res;
};
this._onCustomMessage = (...arg) => onCustomMessage(...arg);
this._request = request;
this._retries = 0;
this._worker.postMessage(request);
} | type ChildMessage =
| ChildMessageInitialize
| ChildMessageCall
| ChildMessageEnd
| ChildMessageMemUsage; |
1,832 | constructor(moduleMap: IModuleMap, options: ResolverConfig) {
this._options = {
defaultPlatform: options.defaultPlatform,
extensions: options.extensions,
hasCoreModules:
options.hasCoreModules === undefined ? true : options.hasCoreModules,
moduleDirectories: options.moduleDirectories || ['node_modules'],
moduleNameMapper: options.moduleNameMapper,
modulePaths: options.modulePaths,
platforms: options.platforms,
resolver: options.resolver,
rootDir: options.rootDir,
};
this._supportsNativePlatform = options.platforms
? options.platforms.includes(NATIVE_PLATFORM)
: false;
this._moduleMap = moduleMap;
this._moduleIDCache = new Map();
this._moduleNameCache = new Map();
this._modulePathCache = new Map();
} | interface IModuleMap<S = SerializableModuleMap> {
getModule(
name: string,
platform?: string | null,
supportsNativePlatform?: boolean | null,
type?: HTypeValue | null,
): string | null;
getPackage(
name: string,
platform: string | null | undefined,
_supportsNativePlatform: boolean | null,
): string | null;
getMockModule(name: string): string | undefined;
getRawModuleMap(): RawModuleMap;
toJSON(): S;
} |
1,833 | constructor(moduleMap: IModuleMap, options: ResolverConfig) {
this._options = {
defaultPlatform: options.defaultPlatform,
extensions: options.extensions,
hasCoreModules:
options.hasCoreModules === undefined ? true : options.hasCoreModules,
moduleDirectories: options.moduleDirectories || ['node_modules'],
moduleNameMapper: options.moduleNameMapper,
modulePaths: options.modulePaths,
platforms: options.platforms,
resolver: options.resolver,
rootDir: options.rootDir,
};
this._supportsNativePlatform = options.platforms
? options.platforms.includes(NATIVE_PLATFORM)
: false;
this._moduleMap = moduleMap;
this._moduleIDCache = new Map();
this._moduleNameCache = new Map();
this._modulePathCache = new Map();
} | type ResolverConfig = {
defaultPlatform?: string | null;
extensions: Array<string>;
hasCoreModules: boolean;
moduleDirectories: Array<string>;
moduleNameMapper?: Array<ModuleNameMapperConfig> | null;
modulePaths?: Array<string>;
platforms?: Array<string>;
resolver?: string | null;
rootDir: string;
}; |
1,834 | public static duckType(error: ModuleNotFoundError): ModuleNotFoundError {
error.buildMessage = ModuleNotFoundError.prototype.buildMessage;
return error;
} | class ModuleNotFoundError extends Error {
public code = 'MODULE_NOT_FOUND';
public hint?: string;
public requireStack?: Array<string>;
public siblingWithSimilarExtensionFound?: boolean;
public moduleName?: string;
private _originalMessage?: string;
constructor(message: string, moduleName?: string) {
super(message);
this._originalMessage = message;
this.moduleName = moduleName;
}
public buildMessage(rootDir: string): void {
if (!this._originalMessage) {
this._originalMessage = this.message || '';
}
let message = this._originalMessage;
if (this.requireStack?.length && this.requireStack.length > 1) {
message += `
Require stack:
${this.requireStack
.map(p => p.replace(`${rootDir}${path.sep}`, ''))
.map(slash)
.join('\n ')}
`;
}
if (this.hint) {
message += this.hint;
}
this.message = message;
}
public static duckType(error: ModuleNotFoundError): ModuleNotFoundError {
error.buildMessage = ModuleNotFoundError.prototype.buildMessage;
return error;
}
} |
1,835 | (
pkg: PackageJSON,
file: string,
dir: string,
) => PackageJSON | type PackageJSON = JSONObject; |
1,836 | (
pkg: PackageJSON,
path: string,
relativePath: string,
) => string | type PackageJSON = JSONObject; |
1,837 | (pkg: PackageJSON, file: string, dir: string) => pkg | type PackageJSON = JSONObject; |
1,838 | (pkg: PackageJSON, path: string, relativePath: string) =>
relativePath | type PackageJSON = JSONObject; |
1,839 | function getFormatOptions(
formatOptions: PrettyFormatOptions,
options?: DiffOptions,
): PrettyFormatOptions {
const {compareKeys} = normalizeDiffOptions(options);
return {
...formatOptions,
compareKeys,
};
} | type DiffOptions = {
aAnnotation?: string;
aColor?: DiffOptionsColor;
aIndicator?: string;
bAnnotation?: string;
bColor?: DiffOptionsColor;
bIndicator?: string;
changeColor?: DiffOptionsColor;
changeLineTrailingSpaceColor?: DiffOptionsColor;
commonColor?: DiffOptionsColor;
commonIndicator?: string;
commonLineTrailingSpaceColor?: DiffOptionsColor;
contextLines?: number;
emptyFirstOrLastLinePlaceholder?: string;
expand?: boolean;
includeChangeCounts?: boolean;
omitAnnotationLines?: boolean;
patchColor?: DiffOptionsColor;
compareKeys?: CompareKeys;
}; |
1,840 | function getFormatOptions(
formatOptions: PrettyFormatOptions,
options?: DiffOptions,
): PrettyFormatOptions {
const {compareKeys} = normalizeDiffOptions(options);
return {
...formatOptions,
compareKeys,
};
} | type DiffOptions = ImportDiffOptions; |
1,841 | function getFormatOptions(
formatOptions: PrettyFormatOptions,
options?: DiffOptions,
): PrettyFormatOptions {
const {compareKeys} = normalizeDiffOptions(options);
return {
...formatOptions,
compareKeys,
};
} | interface PrettyFormatOptions
extends Omit<SnapshotFormat, 'compareKeys'> {
compareKeys?: CompareKeys;
plugins?: Plugins;
} |
1,842 | (
{
aAnnotation,
aColor,
aIndicator,
bAnnotation,
bColor,
bIndicator,
includeChangeCounts,
omitAnnotationLines,
}: DiffOptionsNormalized,
changeCounts: ChangeCounts,
): string => {
if (omitAnnotationLines) {
return '';
}
let aRest = '';
let bRest = '';
if (includeChangeCounts) {
const aCount = String(changeCounts.a);
const bCount = String(changeCounts.b);
// Padding right aligns the ends of the annotations.
const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length;
const aAnnotationPadding = ' '.repeat(Math.max(0, baAnnotationLengthDiff));
const bAnnotationPadding = ' '.repeat(Math.max(0, -baAnnotationLengthDiff));
// Padding left aligns the ends of the counts.
const baCountLengthDiff = bCount.length - aCount.length;
const aCountPadding = ' '.repeat(Math.max(0, baCountLengthDiff));
const bCountPadding = ' '.repeat(Math.max(0, -baCountLengthDiff));
aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`;
bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`;
}
const a = `${aIndicator} ${aAnnotation}${aRest}`;
const b = `${bIndicator} ${bAnnotation}${bRest}`;
return `${aColor(a)}\n${bColor(b)}\n\n`;
} | type DiffOptionsNormalized = {
aAnnotation: string;
aColor: DiffOptionsColor;
aIndicator: string;
bAnnotation: string;
bColor: DiffOptionsColor;
bIndicator: string;
changeColor: DiffOptionsColor;
changeLineTrailingSpaceColor: DiffOptionsColor;
commonColor: DiffOptionsColor;
commonIndicator: string;
commonLineTrailingSpaceColor: DiffOptionsColor;
compareKeys: CompareKeys;
contextLines: number;
emptyFirstOrLastLinePlaceholder: string;
expand: boolean;
includeChangeCounts: boolean;
omitAnnotationLines: boolean;
patchColor: DiffOptionsColor;
}; |
1,843 | (
{
aAnnotation,
aColor,
aIndicator,
bAnnotation,
bColor,
bIndicator,
includeChangeCounts,
omitAnnotationLines,
}: DiffOptionsNormalized,
changeCounts: ChangeCounts,
): string => {
if (omitAnnotationLines) {
return '';
}
let aRest = '';
let bRest = '';
if (includeChangeCounts) {
const aCount = String(changeCounts.a);
const bCount = String(changeCounts.b);
// Padding right aligns the ends of the annotations.
const baAnnotationLengthDiff = bAnnotation.length - aAnnotation.length;
const aAnnotationPadding = ' '.repeat(Math.max(0, baAnnotationLengthDiff));
const bAnnotationPadding = ' '.repeat(Math.max(0, -baAnnotationLengthDiff));
// Padding left aligns the ends of the counts.
const baCountLengthDiff = bCount.length - aCount.length;
const aCountPadding = ' '.repeat(Math.max(0, baCountLengthDiff));
const bCountPadding = ' '.repeat(Math.max(0, -baCountLengthDiff));
aRest = `${aAnnotationPadding} ${aIndicator} ${aCountPadding}${aCount}`;
bRest = `${bAnnotationPadding} ${bIndicator} ${bCountPadding}${bCount}`;
}
const a = `${aIndicator} ${aAnnotation}${aRest}`;
const b = `${bIndicator} ${bAnnotation}${bRest}`;
return `${aColor(a)}\n${bColor(b)}\n\n`;
} | type ChangeCounts = {
a: number;
b: number;
}; |
1,844 | (diff: Diff) => {
switch (diff[0]) {
case DIFF_DELETE:
diff[1] = aLinesDisplay[aIndex];
aIndex += 1;
break;
case DIFF_INSERT:
diff[1] = bLinesDisplay[bIndex];
bIndex += 1;
break;
default:
diff[1] = bLinesDisplay[bIndex];
aIndex += 1;
bIndex += 1;
}
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,845 | (diff: Diff, i: number, diffs: Array<Diff>): string => {
const line = diff[1];
const isFirstOrLast = i === 0 || i === diffs.length - 1;
switch (diff[0]) {
case DIFF_DELETE:
return printDeleteLine(line, isFirstOrLast, options);
case DIFF_INSERT:
return printInsertLine(line, isFirstOrLast, options);
default:
return printCommonLine(line, isFirstOrLast, options);
}
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,846 | (compareKeys?: CompareKeys): CompareKeys =>
compareKeys && typeof compareKeys === 'function'
? compareKeys
: OPTIONS_DEFAULT.compareKeys | type CompareKeys = ((a: string, b: string) => number) | null | undefined; |
1,847 | (
options: DiffOptions = {},
): DiffOptionsNormalized => ({
...OPTIONS_DEFAULT,
...options,
compareKeys: getCompareKeys(options.compareKeys),
contextLines: getContextLines(options.contextLines),
}) | type DiffOptions = {
aAnnotation?: string;
aColor?: DiffOptionsColor;
aIndicator?: string;
bAnnotation?: string;
bColor?: DiffOptionsColor;
bIndicator?: string;
changeColor?: DiffOptionsColor;
changeLineTrailingSpaceColor?: DiffOptionsColor;
commonColor?: DiffOptionsColor;
commonIndicator?: string;
commonLineTrailingSpaceColor?: DiffOptionsColor;
contextLines?: number;
emptyFirstOrLastLinePlaceholder?: string;
expand?: boolean;
includeChangeCounts?: boolean;
omitAnnotationLines?: boolean;
patchColor?: DiffOptionsColor;
compareKeys?: CompareKeys;
}; |
1,848 | (
options: DiffOptions = {},
): DiffOptionsNormalized => ({
...OPTIONS_DEFAULT,
...options,
compareKeys: getCompareKeys(options.compareKeys),
contextLines: getContextLines(options.contextLines),
}) | type DiffOptions = ImportDiffOptions; |
1,849 | pushDiff(diff: Diff): void {
this.line.push(diff);
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,850 | align(diff: Diff): void {
const string = diff[1];
if (string.includes('\n')) {
const substrings = string.split('\n');
const iLast = substrings.length - 1;
substrings.forEach((substring, i) => {
if (i < iLast) {
// The first substring completes the current change line.
// A middle substring is a change line.
this.pushSubstring(substring);
this.pushLine();
} else if (substring.length !== 0) {
// The last substring starts a change line, if it is not empty.
// Important: This non-empty condition also automatically omits
// the newline appended to the end of expected and received strings.
this.pushSubstring(substring);
}
});
} else {
// Append non-multiline string to current change line.
this.pushDiff(diff);
}
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,851 | constructor(deleteBuffer: ChangeBuffer, insertBuffer: ChangeBuffer) {
this.deleteBuffer = deleteBuffer;
this.insertBuffer = insertBuffer;
this.lines = [];
} | class ChangeBuffer {
private readonly op: number;
private line: Array<Diff>; // incomplete line
private lines: Array<Diff>; // complete lines
private readonly changeColor: DiffOptionsColor;
constructor(op: number, changeColor: DiffOptionsColor) {
this.op = op;
this.line = [];
this.lines = [];
this.changeColor = changeColor;
}
private pushSubstring(substring: string): void {
this.pushDiff(new Diff(this.op, substring));
}
private pushLine(): void {
// Assume call only if line has at least one diff,
// therefore an empty line must have a diff which has an empty string.
// If line has multiple diffs, then assume it has a common diff,
// therefore change diffs have change color;
// otherwise then it has line color only.
this.lines.push(
this.line.length !== 1
? new Diff(
this.op,
concatenateRelevantDiffs(this.op, this.line, this.changeColor),
)
: this.line[0][0] === this.op
? this.line[0] // can use instance
: new Diff(this.op, this.line[0][1]), // was common diff
);
this.line.length = 0;
}
isLineEmpty() {
return this.line.length === 0;
}
// Minor input to buffer.
pushDiff(diff: Diff): void {
this.line.push(diff);
}
// Main input to buffer.
align(diff: Diff): void {
const string = diff[1];
if (string.includes('\n')) {
const substrings = string.split('\n');
const iLast = substrings.length - 1;
substrings.forEach((substring, i) => {
if (i < iLast) {
// The first substring completes the current change line.
// A middle substring is a change line.
this.pushSubstring(substring);
this.pushLine();
} else if (substring.length !== 0) {
// The last substring starts a change line, if it is not empty.
// Important: This non-empty condition also automatically omits
// the newline appended to the end of expected and received strings.
this.pushSubstring(substring);
}
});
} else {
// Append non-multiline string to current change line.
this.pushDiff(diff);
}
}
// Output from buffer.
moveLinesTo(lines: Array<Diff>): void {
if (!this.isLineEmpty()) {
this.pushLine();
}
lines.push(...this.lines);
this.lines.length = 0;
}
} |
1,852 | private pushDiffCommonLine(diff: Diff): void {
this.lines.push(diff);
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,853 | private pushDiffChangeLines(diff: Diff): void {
const isDiffEmpty = diff[1].length === 0;
// An empty diff string is redundant, unless a change line is empty.
if (!isDiffEmpty || this.deleteBuffer.isLineEmpty()) {
this.deleteBuffer.pushDiff(diff);
}
if (!isDiffEmpty || this.insertBuffer.isLineEmpty()) {
this.insertBuffer.pushDiff(diff);
}
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,854 | align(diff: Diff): void {
const op = diff[0];
const string = diff[1];
if (string.includes('\n')) {
const substrings = string.split('\n');
const iLast = substrings.length - 1;
substrings.forEach((substring, i) => {
if (i === 0) {
const subdiff = new Diff(op, substring);
if (
this.deleteBuffer.isLineEmpty() &&
this.insertBuffer.isLineEmpty()
) {
// If both current change lines are empty,
// then the first substring is a common line.
this.flushChangeLines();
this.pushDiffCommonLine(subdiff);
} else {
// If either current change line is non-empty,
// then the first substring completes the change lines.
this.pushDiffChangeLines(subdiff);
this.flushChangeLines();
}
} else if (i < iLast) {
// A middle substring is a common line.
this.pushDiffCommonLine(new Diff(op, substring));
} else if (substring.length !== 0) {
// The last substring starts a change line, if it is not empty.
// Important: This non-empty condition also automatically omits
// the newline appended to the end of expected and received strings.
this.pushDiffChangeLines(new Diff(op, substring));
}
});
} else {
// Append non-multiline string to current change lines.
// Important: It cannot be at the end following empty change lines,
// because newline appended to the end of expected and received strings.
this.pushDiffChangeLines(diff);
}
} | class Diff {
0: number;
1: string;
constructor(op: number, text: string) {
this[0] = op;
this[1] = text;
}
} |
1,855 | function getConsoleOutput(
buffer: ConsoleBuffer,
config: StackTraceConfig,
globalConfig: Config.GlobalConfig,
): string {
const TITLE_INDENT =
globalConfig.verbose === true ? ' '.repeat(2) : ' '.repeat(4);
const CONSOLE_INDENT = TITLE_INDENT + ' '.repeat(2);
const logEntries = buffer.reduce((output, {type, message, origin}) => {
message = message
.split(/\n/)
.map(line => CONSOLE_INDENT + line)
.join('\n');
let typeMessage = `console.${type}`;
let noStackTrace = true;
let noCodeFrame = true;
if (type === 'warn') {
message = chalk.yellow(message);
typeMessage = chalk.yellow(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
} else if (type === 'error') {
message = chalk.red(message);
typeMessage = chalk.red(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
}
const options: StackTraceOptions = {
noCodeFrame,
noStackTrace,
};
const formattedStackTrace = formatStackTrace(origin, config, options);
return `${
output + TITLE_INDENT + chalk.dim(typeMessage)
}\n${message.trimRight()}\n${chalk.dim(
formattedStackTrace.trimRight(),
)}\n\n`;
}, '');
return `${logEntries.trimRight()}\n`;
} | type StackTraceConfig = Pick<
Config.ProjectConfig,
'rootDir' | 'testMatch'
>; |
1,856 | function getConsoleOutput(
buffer: ConsoleBuffer,
config: StackTraceConfig,
globalConfig: Config.GlobalConfig,
): string {
const TITLE_INDENT =
globalConfig.verbose === true ? ' '.repeat(2) : ' '.repeat(4);
const CONSOLE_INDENT = TITLE_INDENT + ' '.repeat(2);
const logEntries = buffer.reduce((output, {type, message, origin}) => {
message = message
.split(/\n/)
.map(line => CONSOLE_INDENT + line)
.join('\n');
let typeMessage = `console.${type}`;
let noStackTrace = true;
let noCodeFrame = true;
if (type === 'warn') {
message = chalk.yellow(message);
typeMessage = chalk.yellow(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
} else if (type === 'error') {
message = chalk.red(message);
typeMessage = chalk.red(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
}
const options: StackTraceOptions = {
noCodeFrame,
noStackTrace,
};
const formattedStackTrace = formatStackTrace(origin, config, options);
return `${
output + TITLE_INDENT + chalk.dim(typeMessage)
}\n${message.trimRight()}\n${chalk.dim(
formattedStackTrace.trimRight(),
)}\n\n`;
}, '');
return `${logEntries.trimRight()}\n`;
} | type ConsoleBuffer = Array<LogEntry>; |
1,857 | (type: LogType, message: LogMessage) => string | type LogType =
| 'assert'
| 'count'
| 'debug'
| 'dir'
| 'dirxml'
| 'error'
| 'group'
| 'groupCollapsed'
| 'info'
| 'log'
| 'time'
| 'warn'; |
1,858 | (type: LogType, message: LogMessage) => string | type LogMessage = string; |
1,859 | private _log(type: LogType, message: string) {
clearLine(this._stdout);
super.log(
this._formatBuffer(type, ' '.repeat(this._groupDepth) + message),
);
} | type LogType =
| 'assert'
| 'count'
| 'debug'
| 'dir'
| 'dirxml'
| 'error'
| 'group'
| 'groupCollapsed'
| 'info'
| 'log'
| 'time'
| 'warn'; |
1,860 | private _logError(type: LogType, message: string) {
clearLine(this._stderr);
super.error(
this._formatBuffer(type, ' '.repeat(this._groupDepth) + message),
);
} | type LogType =
| 'assert'
| 'count'
| 'debug'
| 'dir'
| 'dirxml'
| 'error'
| 'group'
| 'groupCollapsed'
| 'info'
| 'log'
| 'time'
| 'warn'; |
1,861 | private _log(type: LogType, message: LogMessage) {
BufferedConsole.write(
this._buffer,
type,
' '.repeat(this._groupDepth) + message,
3,
);
} | type LogType =
| 'assert'
| 'count'
| 'debug'
| 'dir'
| 'dirxml'
| 'error'
| 'group'
| 'groupCollapsed'
| 'info'
| 'log'
| 'time'
| 'warn'; |
1,862 | private _log(type: LogType, message: LogMessage) {
BufferedConsole.write(
this._buffer,
type,
' '.repeat(this._groupDepth) + message,
3,
);
} | type LogMessage = string; |
1,863 | override onRunStart(
aggregatedResults: AggregatedResult,
options: ReporterOnStartOptions,
): void {
this._status.runStarted(aggregatedResults, options);
} | type ReporterOnStartOptions = {
estimatedTime: number;
showStatus: boolean;
}; |
1,864 | override onRunStart(
aggregatedResults: AggregatedResult,
options: ReporterOnStartOptions,
): void {
this._status.runStarted(aggregatedResults, options);
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,865 | override onTestStart(test: Test): void {
this._status.testStarted(test.path, test.context.config);
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,866 | override onTestStart(test: Test): void {
this._status.testStarted(test.path, test.context.config);
} | type Test = (arg0: any) => boolean; |
1,867 | override onTestCaseResult(test: Test, testCaseResult: TestCaseResult): void {
this._status.addTestCaseResult(test, testCaseResult);
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,868 | override onTestCaseResult(test: Test, testCaseResult: TestCaseResult): void {
this._status.addTestCaseResult(test, testCaseResult);
} | type Test = (arg0: any) => boolean; |
1,869 | override onTestCaseResult(test: Test, testCaseResult: TestCaseResult): void {
this._status.addTestCaseResult(test, testCaseResult);
} | type TestCaseResult = AssertionResult; |
1,870 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.testFinished(test.context.config, testResult, aggregatedResults);
if (!testResult.skipped) {
this.printTestFileHeader(
testResult.testFilePath,
test.context.config,
testResult,
);
this.printTestFileFailureMessage(
testResult.testFilePath,
test.context.config,
testResult,
);
}
this.forceFlushBufferedOutput();
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,871 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.testFinished(test.context.config, testResult, aggregatedResults);
if (!testResult.skipped) {
this.printTestFileHeader(
testResult.testFilePath,
test.context.config,
testResult,
);
this.printTestFileFailureMessage(
testResult.testFilePath,
test.context.config,
testResult,
);
}
this.forceFlushBufferedOutput();
} | type Test = (arg0: any) => boolean; |
1,872 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.testFinished(test.context.config, testResult, aggregatedResults);
if (!testResult.skipped) {
this.printTestFileHeader(
testResult.testFilePath,
test.context.config,
testResult,
);
this.printTestFileFailureMessage(
testResult.testFilePath,
test.context.config,
testResult,
);
}
this.forceFlushBufferedOutput();
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,873 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.testFinished(test.context.config, testResult, aggregatedResults);
if (!testResult.skipped) {
this.printTestFileHeader(
testResult.testFilePath,
test.context.config,
testResult,
);
this.printTestFileFailureMessage(
testResult.testFilePath,
test.context.config,
testResult,
);
}
this.forceFlushBufferedOutput();
} | type TestResult = {
console?: ConsoleBuffer;
coverage?: CoverageMapData;
displayName?: Config.DisplayName;
failureMessage?: string | null;
leaks: boolean;
memoryUsage?: number;
numFailingTests: number;
numPassingTests: number;
numPendingTests: number;
numTodoTests: number;
openHandles: Array<Error>;
perfStats: {
end: number;
runtime: number;
slow: boolean;
start: number;
};
skipped: boolean;
snapshot: {
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
};
testExecError?: SerializableError;
testFilePath: string;
testResults: Array<AssertionResult>;
v8Coverage?: V8CoverageResult;
}; |
1,874 | override onTestResult(
test: Test,
testResult: TestResult,
aggregatedResults: AggregatedResult,
): void {
this.testFinished(test.context.config, testResult, aggregatedResults);
if (!testResult.skipped) {
this.printTestFileHeader(
testResult.testFilePath,
test.context.config,
testResult,
);
this.printTestFileFailureMessage(
testResult.testFilePath,
test.context.config,
testResult,
);
}
this.forceFlushBufferedOutput();
} | type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {column: number; line: number} | null;
numPassingAsserts: number;
retryReasons: Array<FormattedError>;
testPath: Array<TestName | BlockName>;
}; |
1,875 | (
test: Test,
testResult: TestResult,
aggregatedResult: AggregatedResult,
) => Promise<void> | void | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,876 | (
test: Test,
testResult: TestResult,
aggregatedResult: AggregatedResult,
) => Promise<void> | void | type Test = (arg0: any) => boolean; |
1,877 | (
test: Test,
testResult: TestResult,
aggregatedResult: AggregatedResult,
) => Promise<void> | void | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,878 | (
test: Test,
testResult: TestResult,
aggregatedResult: AggregatedResult,
) => Promise<void> | void | type TestResult = {
console?: ConsoleBuffer;
coverage?: CoverageMapData;
displayName?: Config.DisplayName;
failureMessage?: string | null;
leaks: boolean;
memoryUsage?: number;
numFailingTests: number;
numPassingTests: number;
numPendingTests: number;
numTodoTests: number;
openHandles: Array<Error>;
perfStats: {
end: number;
runtime: number;
slow: boolean;
start: number;
};
skipped: boolean;
snapshot: {
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
};
testExecError?: SerializableError;
testFilePath: string;
testResults: Array<AssertionResult>;
v8Coverage?: V8CoverageResult;
}; |
1,879 | (
test: Test,
testResult: TestResult,
aggregatedResult: AggregatedResult,
) => Promise<void> | void | type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {column: number; line: number} | null;
numPassingAsserts: number;
retryReasons: Array<FormattedError>;
testPath: Array<TestName | BlockName>;
}; |
1,880 | (
test: Test,
testCaseResult: TestCaseResult,
) => Promise<void> | void | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,881 | (
test: Test,
testCaseResult: TestCaseResult,
) => Promise<void> | void | type Test = (arg0: any) => boolean; |
1,882 | (
test: Test,
testCaseResult: TestCaseResult,
) => Promise<void> | void | type TestCaseResult = AssertionResult; |
1,883 | (
results: AggregatedResult,
options: ReporterOnStartOptions,
) => Promise<void> | void | type ReporterOnStartOptions = {
estimatedTime: number;
showStatus: boolean;
}; |
1,884 | (
results: AggregatedResult,
options: ReporterOnStartOptions,
) => Promise<void> | void | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,885 | (test: Test) => Promise<void> | void | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,886 | (test: Test) => Promise<void> | void | type Test = (arg0: any) => boolean; |
1,887 | override onTestResult(_test: Test, testResult: TestResult): void {
if (testResult.v8Coverage) {
this._v8CoverageResults.push(testResult.v8Coverage);
return;
}
if (testResult.coverage) {
this._coverageMap.merge(testResult.coverage);
}
} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,888 | override onTestResult(_test: Test, testResult: TestResult): void {
if (testResult.v8Coverage) {
this._v8CoverageResults.push(testResult.v8Coverage);
return;
}
if (testResult.coverage) {
this._coverageMap.merge(testResult.coverage);
}
} | type Test = (arg0: any) => boolean; |
1,889 | override onTestResult(_test: Test, testResult: TestResult): void {
if (testResult.v8Coverage) {
this._v8CoverageResults.push(testResult.v8Coverage);
return;
}
if (testResult.coverage) {
this._coverageMap.merge(testResult.coverage);
}
} | type TestResult = {
console?: ConsoleBuffer;
coverage?: CoverageMapData;
displayName?: Config.DisplayName;
failureMessage?: string | null;
leaks: boolean;
memoryUsage?: number;
numFailingTests: number;
numPassingTests: number;
numPendingTests: number;
numTodoTests: number;
openHandles: Array<Error>;
perfStats: {
end: number;
runtime: number;
slow: boolean;
start: number;
};
skipped: boolean;
snapshot: {
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
};
testExecError?: SerializableError;
testFilePath: string;
testResults: Array<AssertionResult>;
v8Coverage?: V8CoverageResult;
}; |
1,890 | override onTestResult(_test: Test, testResult: TestResult): void {
if (testResult.v8Coverage) {
this._v8CoverageResults.push(testResult.v8Coverage);
return;
}
if (testResult.coverage) {
this._coverageMap.merge(testResult.coverage);
}
} | type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {column: number; line: number} | null;
numPassingAsserts: number;
retryReasons: Array<FormattedError>;
testPath: Array<TestName | BlockName>;
}; |
1,891 | function getResultHeader(
result: TestResult,
globalConfig: Config.GlobalConfig,
projectConfig?: Config.ProjectConfig,
): string {
const testPath = result.testFilePath;
const status =
result.numFailingTests > 0 || result.testExecError ? FAIL : PASS;
const testDetail = [];
if (result.perfStats?.slow) {
const runTime = result.perfStats.runtime / 1000;
testDetail.push(LONG_TEST_COLOR(formatTime(runTime, 0)));
}
if (result.memoryUsage) {
const toMB = (bytes: number) => Math.floor(bytes / 1024 / 1024);
testDetail.push(`${toMB(result.memoryUsage)} MB heap size`);
}
const projectDisplayName =
projectConfig && projectConfig.displayName
? `${printDisplayName(projectConfig)} `
: '';
return `${status} ${projectDisplayName}${formatTestPath(
projectConfig ?? globalConfig,
testPath,
)}${testDetail.length ? ` (${testDetail.join(', ')})` : ''}`;
} | type TestResult = {
console?: ConsoleBuffer;
coverage?: CoverageMapData;
displayName?: Config.DisplayName;
failureMessage?: string | null;
leaks: boolean;
memoryUsage?: number;
numFailingTests: number;
numPassingTests: number;
numPendingTests: number;
numTodoTests: number;
openHandles: Array<Error>;
perfStats: {
end: number;
runtime: number;
slow: boolean;
start: number;
};
skipped: boolean;
snapshot: {
added: number;
fileDeleted: boolean;
matched: number;
unchecked: number;
uncheckedKeys: Array<string>;
unmatched: number;
updated: number;
};
testExecError?: SerializableError;
testFilePath: string;
testResults: Array<AssertionResult>;
v8Coverage?: V8CoverageResult;
}; |
1,892 | function getResultHeader(
result: TestResult,
globalConfig: Config.GlobalConfig,
projectConfig?: Config.ProjectConfig,
): string {
const testPath = result.testFilePath;
const status =
result.numFailingTests > 0 || result.testExecError ? FAIL : PASS;
const testDetail = [];
if (result.perfStats?.slow) {
const runTime = result.perfStats.runtime / 1000;
testDetail.push(LONG_TEST_COLOR(formatTime(runTime, 0)));
}
if (result.memoryUsage) {
const toMB = (bytes: number) => Math.floor(bytes / 1024 / 1024);
testDetail.push(`${toMB(result.memoryUsage)} MB heap size`);
}
const projectDisplayName =
projectConfig && projectConfig.displayName
? `${printDisplayName(projectConfig)} `
: '';
return `${status} ${projectDisplayName}${formatTestPath(
projectConfig ?? globalConfig,
testPath,
)}${testDetail.length ? ` (${testDetail.join(', ')})` : ''}`;
} | type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {column: number; line: number} | null;
numPassingAsserts: number;
retryReasons: Array<FormattedError>;
testPath: Array<TestName | BlockName>;
}; |
1,893 | function getSummary(
aggregatedResults: AggregatedResult,
options?: SummaryOptions,
): string {
let runTime = (Date.now() - aggregatedResults.startTime) / 1000;
if (options && options.roundTime) {
runTime = Math.floor(runTime);
}
const valuesForCurrentTestCases = getValuesCurrentTestCases(
options?.currentTestCases,
);
const estimatedTime = (options && options.estimatedTime) || 0;
const snapshotResults = aggregatedResults.snapshot;
const snapshotsAdded = snapshotResults.added;
const snapshotsFailed = snapshotResults.unmatched;
const snapshotsOutdated = snapshotResults.unchecked;
const snapshotsFilesRemoved = snapshotResults.filesRemoved;
const snapshotsDidUpdate = snapshotResults.didUpdate;
const snapshotsPassed = snapshotResults.matched;
const snapshotsTotal = snapshotResults.total;
const snapshotsUpdated = snapshotResults.updated;
const suitesFailed = aggregatedResults.numFailedTestSuites;
const suitesPassed = aggregatedResults.numPassedTestSuites;
const suitesPending = aggregatedResults.numPendingTestSuites;
const suitesRun = suitesFailed + suitesPassed;
const suitesTotal = aggregatedResults.numTotalTestSuites;
const testsFailed = aggregatedResults.numFailedTests;
const testsPassed = aggregatedResults.numPassedTests;
const testsPending = aggregatedResults.numPendingTests;
const testsTodo = aggregatedResults.numTodoTests;
const testsTotal = aggregatedResults.numTotalTests;
const width = (options && options.width) || 0;
const optionalLines: Array<string> = [];
if (options?.showSeed === true) {
const {seed} = options;
if (seed === undefined) {
throw new Error('Attempted to display seed but seed value is undefined');
}
optionalLines.push(`${chalk.bold('Seed: ') + seed}`);
}
const suites = `${
chalk.bold('Test Suites: ') +
(suitesFailed ? `${chalk.bold.red(`${suitesFailed} failed`)}, ` : '') +
(suitesPending
? `${chalk.bold.yellow(`${suitesPending} skipped`)}, `
: '') +
(suitesPassed ? `${chalk.bold.green(`${suitesPassed} passed`)}, ` : '') +
(suitesRun !== suitesTotal ? `${suitesRun} of ${suitesTotal}` : suitesTotal)
} total`;
const updatedTestsFailed =
testsFailed + valuesForCurrentTestCases.numFailingTests;
const updatedTestsPending =
testsPending + valuesForCurrentTestCases.numPendingTests;
const updatedTestsTodo = testsTodo + valuesForCurrentTestCases.numTodoTests;
const updatedTestsPassed =
testsPassed + valuesForCurrentTestCases.numPassingTests;
const updatedTestsTotal =
testsTotal + valuesForCurrentTestCases.numTotalTests;
const tests = `${
chalk.bold('Tests: ') +
(updatedTestsFailed > 0
? `${chalk.bold.red(`${updatedTestsFailed} failed`)}, `
: '') +
(updatedTestsPending > 0
? `${chalk.bold.yellow(`${updatedTestsPending} skipped`)}, `
: '') +
(updatedTestsTodo > 0
? `${chalk.bold.magenta(`${updatedTestsTodo} todo`)}, `
: '') +
(updatedTestsPassed > 0
? `${chalk.bold.green(`${updatedTestsPassed} passed`)}, `
: '')
}${updatedTestsTotal} total`;
const snapshots = `${
chalk.bold('Snapshots: ') +
(snapshotsFailed
? `${chalk.bold.red(`${snapshotsFailed} failed`)}, `
: '') +
(snapshotsOutdated && !snapshotsDidUpdate
? `${chalk.bold.yellow(`${snapshotsOutdated} obsolete`)}, `
: '') +
(snapshotsOutdated && snapshotsDidUpdate
? `${chalk.bold.green(`${snapshotsOutdated} removed`)}, `
: '') +
(snapshotsFilesRemoved && !snapshotsDidUpdate
? `${chalk.bold.yellow(
`${pluralize('file', snapshotsFilesRemoved)} obsolete`,
)}, `
: '') +
(snapshotsFilesRemoved && snapshotsDidUpdate
? `${chalk.bold.green(
`${pluralize('file', snapshotsFilesRemoved)} removed`,
)}, `
: '') +
(snapshotsUpdated
? `${chalk.bold.green(`${snapshotsUpdated} updated`)}, `
: '') +
(snapshotsAdded
? `${chalk.bold.green(`${snapshotsAdded} written`)}, `
: '') +
(snapshotsPassed
? `${chalk.bold.green(`${snapshotsPassed} passed`)}, `
: '')
}${snapshotsTotal} total`;
const time = renderTime(runTime, estimatedTime, width);
return [...optionalLines, suites, tests, snapshots, time].join('\n');
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,894 | function getSummary(
aggregatedResults: AggregatedResult,
options?: SummaryOptions,
): string {
let runTime = (Date.now() - aggregatedResults.startTime) / 1000;
if (options && options.roundTime) {
runTime = Math.floor(runTime);
}
const valuesForCurrentTestCases = getValuesCurrentTestCases(
options?.currentTestCases,
);
const estimatedTime = (options && options.estimatedTime) || 0;
const snapshotResults = aggregatedResults.snapshot;
const snapshotsAdded = snapshotResults.added;
const snapshotsFailed = snapshotResults.unmatched;
const snapshotsOutdated = snapshotResults.unchecked;
const snapshotsFilesRemoved = snapshotResults.filesRemoved;
const snapshotsDidUpdate = snapshotResults.didUpdate;
const snapshotsPassed = snapshotResults.matched;
const snapshotsTotal = snapshotResults.total;
const snapshotsUpdated = snapshotResults.updated;
const suitesFailed = aggregatedResults.numFailedTestSuites;
const suitesPassed = aggregatedResults.numPassedTestSuites;
const suitesPending = aggregatedResults.numPendingTestSuites;
const suitesRun = suitesFailed + suitesPassed;
const suitesTotal = aggregatedResults.numTotalTestSuites;
const testsFailed = aggregatedResults.numFailedTests;
const testsPassed = aggregatedResults.numPassedTests;
const testsPending = aggregatedResults.numPendingTests;
const testsTodo = aggregatedResults.numTodoTests;
const testsTotal = aggregatedResults.numTotalTests;
const width = (options && options.width) || 0;
const optionalLines: Array<string> = [];
if (options?.showSeed === true) {
const {seed} = options;
if (seed === undefined) {
throw new Error('Attempted to display seed but seed value is undefined');
}
optionalLines.push(`${chalk.bold('Seed: ') + seed}`);
}
const suites = `${
chalk.bold('Test Suites: ') +
(suitesFailed ? `${chalk.bold.red(`${suitesFailed} failed`)}, ` : '') +
(suitesPending
? `${chalk.bold.yellow(`${suitesPending} skipped`)}, `
: '') +
(suitesPassed ? `${chalk.bold.green(`${suitesPassed} passed`)}, ` : '') +
(suitesRun !== suitesTotal ? `${suitesRun} of ${suitesTotal}` : suitesTotal)
} total`;
const updatedTestsFailed =
testsFailed + valuesForCurrentTestCases.numFailingTests;
const updatedTestsPending =
testsPending + valuesForCurrentTestCases.numPendingTests;
const updatedTestsTodo = testsTodo + valuesForCurrentTestCases.numTodoTests;
const updatedTestsPassed =
testsPassed + valuesForCurrentTestCases.numPassingTests;
const updatedTestsTotal =
testsTotal + valuesForCurrentTestCases.numTotalTests;
const tests = `${
chalk.bold('Tests: ') +
(updatedTestsFailed > 0
? `${chalk.bold.red(`${updatedTestsFailed} failed`)}, `
: '') +
(updatedTestsPending > 0
? `${chalk.bold.yellow(`${updatedTestsPending} skipped`)}, `
: '') +
(updatedTestsTodo > 0
? `${chalk.bold.magenta(`${updatedTestsTodo} todo`)}, `
: '') +
(updatedTestsPassed > 0
? `${chalk.bold.green(`${updatedTestsPassed} passed`)}, `
: '')
}${updatedTestsTotal} total`;
const snapshots = `${
chalk.bold('Snapshots: ') +
(snapshotsFailed
? `${chalk.bold.red(`${snapshotsFailed} failed`)}, `
: '') +
(snapshotsOutdated && !snapshotsDidUpdate
? `${chalk.bold.yellow(`${snapshotsOutdated} obsolete`)}, `
: '') +
(snapshotsOutdated && snapshotsDidUpdate
? `${chalk.bold.green(`${snapshotsOutdated} removed`)}, `
: '') +
(snapshotsFilesRemoved && !snapshotsDidUpdate
? `${chalk.bold.yellow(
`${pluralize('file', snapshotsFilesRemoved)} obsolete`,
)}, `
: '') +
(snapshotsFilesRemoved && snapshotsDidUpdate
? `${chalk.bold.green(
`${pluralize('file', snapshotsFilesRemoved)} removed`,
)}, `
: '') +
(snapshotsUpdated
? `${chalk.bold.green(`${snapshotsUpdated} updated`)}, `
: '') +
(snapshotsAdded
? `${chalk.bold.green(`${snapshotsAdded} written`)}, `
: '') +
(snapshotsPassed
? `${chalk.bold.green(`${snapshotsPassed} passed`)}, `
: '')
}${snapshotsTotal} total`;
const time = renderTime(runTime, estimatedTime, width);
return [...optionalLines, suites, tests, snapshots, time].join('\n');
} | type SummaryOptions = {
currentTestCases?: Array<{test: Test; testCaseResult: TestCaseResult}>;
estimatedTime?: number;
roundTime?: boolean;
width?: number;
showSeed?: boolean;
seed?: number;
}; |
1,895 | onRunStart(
_results?: AggregatedResult,
_options?: ReporterOnStartOptions,
): void {
preRunMessageRemove(process.stderr);
} | type ReporterOnStartOptions = {
estimatedTime: number;
showStatus: boolean;
}; |
1,896 | onRunStart(
_results?: AggregatedResult,
_options?: ReporterOnStartOptions,
): void {
preRunMessageRemove(process.stderr);
} | type AggregatedResult = AggregatedResultWithoutCoverage & {
coverageMap?: CoverageMap | null;
}; |
1,897 | onTestCaseResult(_test: Test, _testCaseResult: TestCaseResult): void {} | type Test = {
context: TestContext;
duration?: number;
path: string;
}; |
1,898 | onTestCaseResult(_test: Test, _testCaseResult: TestCaseResult): void {} | type Test = (arg0: any) => boolean; |
1,899 | onTestCaseResult(_test: Test, _testCaseResult: TestCaseResult): void {} | type TestCaseResult = AssertionResult; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.