import { MapOptions, SerializableData, SerializableFunction, TaskResult, ThreadConfig, ThreadOptions, ThreadTask } from '../types'; import { ArrayOperations } from './array-operations'; import { Pipeline, TerminalPipeline } from './pipeline'; /** * Event map for ThreadTS event system. * Defines all events that can be emitted by the ThreadTS instance. */ interface ThreadEventMap { /** Emitted when a task completes successfully */ 'task-complete': { taskId: string; result: SerializableData; duration: number; }; /** Emitted when a task fails with an error */ 'task-error': { taskId: string; error: string; duration: number; }; /** Emitted when the worker pool size changes */ 'pool-resize': { oldSize: number; newSize: number; }; /** Emitted when a new worker is spawned */ 'worker-spawn': { workerId: string; poolSize: number; }; /** Emitted when a worker is terminated */ 'worker-terminate': { workerId: string; poolSize: number; }; } /** Type for event listener functions */ type ThreadEventListener = (detail: ThreadEventMap[K]) => void; /** Internal key used to identify args payloads */ declare const INTERNAL_ARGS_KEY: "__THREADTS_ARGS__"; /** Internal type for passing multiple arguments to workers */ type InternalArgsPayload = { [INTERNAL_ARGS_KEY]: unknown[]; }; /** * Legacy task format for backwards compatibility. * Supports both 'fn' and 'func' property names. */ type LegacyTask = { fn?: SerializableFunction; func?: SerializableFunction; data?: SerializableData; options?: ThreadOptions; }; /** * ThreadTS - The main class for parallel computing. * * Implements a singleton pattern for resource sharing while allowing * configuration customization. Provides methods for executing functions * in parallel, including map, filter, reduce, and batch operations. * * @extends EventTarget - Enables event-based communication * * @example * ```typescript * // Get the singleton instance * const instance = ThreadTS.getInstance(); * * // Execute a function in parallel * const result = await instance.run((x) => x * 2, 21); * * // Process arrays in parallel * const doubled = await instance.map([1, 2, 3], (x) => x * 2); * ``` */ export declare class ThreadTS extends EventTarget { private static _instance; private config; private isReady; private taskCounter; private completedTasks; private failedTasks; private totalExecutionTime; private eventListeners; /** Extended array operations */ private arrayOps; constructor(config?: Partial); private mergeConfig; static getInstance(config?: Partial): ThreadTS; private initialize; /** * Returns the extended array operations module. * Provides additional array methods like indexOf, lastIndexOf, at, slice, etc. * * @returns The ArrayOperations object with extended methods * * @example * ```typescript * const ops = threadts.getArrayOps(); * const index = await ops.indexOf([1, 2, 3], 2); * const chunk = await ops.chunk([1, 2, 3, 4, 5], 2); * ``` */ getArrayOps(): ArrayOperations; /** * Finds the index of the first occurrence of a value in the array. * @see ArrayOperations.indexOf */ indexOf(array: T[], searchElement: T, fromIndex?: number): Promise; /** * Finds the index of the last occurrence of a value in the array. * @see ArrayOperations.lastIndexOf */ lastIndexOf(array: T[], searchElement: T, fromIndex?: number): Promise; /** * Returns the element at the specified index. * @see ArrayOperations.at */ at(array: T[], index: number): Promise; /** * Creates a new array with elements from startIndex to endIndex. * @see ArrayOperations.slice */ slice(array: T[], start?: number, end?: number): Promise; /** * Concatenates multiple arrays into one. * @see ArrayOperations.concat */ concat(array: T[], ...items: (T | T[])[]): Promise; /** * Creates an array containing a range of numbers. * @see ArrayOperations.range */ range(start: number, end: number, step?: number): Promise; /** * Creates an array by repeating a value. * @see ArrayOperations.repeat */ repeat(value: T, count: number): Promise; /** * Removes duplicate values from an array. * @see ArrayOperations.unique */ unique(array: T[]): Promise; /** * Removes duplicate values using a key function. * @see ArrayOperations.uniqueBy */ uniqueBy(array: T[], keyFn: (item: T) => K): Promise; /** * Splits an array into chunks of the specified size. * @see ArrayOperations.chunk */ chunk(array: T[], size: number): Promise; /** * Zips multiple arrays together into an array of tuples. * @see ArrayOperations.zip */ zip(...arrays: T): Promise<{ [K in keyof T]: T[K] extends (infer U)[] ? U : never; }[]>; /** * Finds the last element that satisfies the predicate. * @see ArrayOperations.findLast */ findLast(array: T[], predicate: (value: T, index: number, array: T[]) => boolean): Promise; /** * Finds the index of the last element that satisfies the predicate. * @see ArrayOperations.findLastIndex */ findLastIndex(array: T[], predicate: (value: T, index: number, array: T[]) => boolean): Promise; /** * Returns a new sorted array (immutable). * @see ArrayOperations.toSorted */ toSorted(array: T[], compareFn?: (a: T, b: T) => number): Promise; /** * Returns a new reversed array (immutable). * @see ArrayOperations.toReversed */ toReversed(array: T[]): Promise; /** * Returns a new array with the element at the given index replaced. * @see ArrayOperations.withElement */ withElement(array: T[], index: number, value: T): Promise; /** * Returns a new array with elements removed/replaced/added at a given index. * @see ArrayOperations.toSpliced */ toSpliced(array: T[], start: number, deleteCount?: number, ...items: T[]): Promise; /** * Groups elements of an array based on a callback function. * @see ArrayOperations.groupByObject */ groupByObject(array: T[], keyFn: (item: T, index: number) => K): Promise>>; private emitEvent; on(event: K, listener: ThreadEventListener): void; off(event: K, listener: ThreadEventListener): void; private isArgsPayload; private createArgsPayload; private prepareArguments; private executeWithControls; private wrapWithAbort; private withTimeout; private normalizeTask; run(func: SerializableFunction, data?: SerializableData | InternalArgsPayload, options?: ThreadOptions): Promise; map(array: T[], func: SerializableFunction, options?: MapOptions): Promise; filter(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; reduce(array: T[], reducer: SerializableFunction, initialValue: R, options?: ThreadOptions): Promise; /** * Iterates over an array, executing the function for each element. * Similar to Array.prototype.forEach but runs in parallel. * * @template T - The type of array elements * @param array - The array to iterate over * @param func - Function to execute for each element: (item, index, array) => void * @param options - Execution options including batchSize * * @example * ```typescript * await threadts.forEach([1, 2, 3], (item) => { * console.log(item); * }); * ``` */ forEach(array: T[], func: SerializableFunction, options?: MapOptions): Promise; /** * Finds the first element that satisfies the predicate function. * Similar to Array.prototype.find but processes elements in parallel batches. * * Note: Due to parallel processing, this may check more elements than * a sequential find, but returns the first matching element by index. * * @template T - The type of array elements * @param array - The array to search * @param predicate - Function to test each element: (item, index, array) => boolean * @param options - Execution options including batchSize * @returns The first element that satisfies the predicate, or undefined * * @example * ```typescript * const found = await threadts.find( * [1, 2, 3, 4, 5], * (x) => x > 3 * ); * console.log(found); // 4 * ``` */ find(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Finds the index of the first element that satisfies the predicate. * Similar to Array.prototype.findIndex but processes in parallel batches. * * @template T - The type of array elements * @param array - The array to search * @param predicate - Function to test each element: (item, index, array) => boolean * @param options - Execution options including batchSize * @returns The index of the first matching element, or -1 if not found * * @example * ```typescript * const index = await threadts.findIndex( * [1, 2, 3, 4, 5], * (x) => x > 3 * ); * console.log(index); // 3 * ``` */ findIndex(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Tests whether at least one element satisfies the predicate. * Similar to Array.prototype.some but processes in parallel batches. * * @template T - The type of array elements * @param array - The array to test * @param predicate - Function to test each element: (item, index, array) => boolean * @param options - Execution options including batchSize * @returns true if at least one element passes the test * * @example * ```typescript * const hasEven = await threadts.some( * [1, 3, 5, 6, 7], * (x) => x % 2 === 0 * ); * console.log(hasEven); // true * ``` */ some(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Tests whether all elements satisfy the predicate. * Similar to Array.prototype.every but processes in parallel batches. * * @template T - The type of array elements * @param array - The array to test * @param predicate - Function to test each element: (item, index, array) => boolean * @param options - Execution options including batchSize * @returns true if all elements pass the test * * @example * ```typescript * const allPositive = await threadts.every( * [1, 2, 3, 4, 5], * (x) => x > 0 * ); * console.log(allPositive); // true * ``` */ every(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Maps each element to an array and flattens the result. * Similar to Array.prototype.flatMap but processes in parallel. * * @template T - The type of array elements * @template R - The type of result array elements * @param array - The array to process * @param func - Function that returns an array for each element: (item, index, array) => R[] * @param options - Execution options including batchSize * @returns Flattened array of results * * @example * ```typescript * const result = await threadts.flatMap( * [1, 2, 3], * (x) => [x, x * 2] * ); * console.log(result); // [1, 2, 2, 4, 3, 6] * ``` */ flatMap(array: T[], func: SerializableFunction, options?: MapOptions): Promise; /** * Reduces an array from right to left. * Similar to Array.prototype.reduceRight but processes in parallel where possible. * * @template T - The type of array elements * @template R - The type of the accumulator * @param array - The array to reduce * @param reducer - Function to execute on each element: (acc, item, index, array) => R * @param initialValue - Initial value for the accumulator * @param options - Execution options * @returns The final accumulated value * * @example * ```typescript * const result = await threadts.reduceRight( * ['a', 'b', 'c'], * (acc, item) => acc + item, * '' * ); * console.log(result); // 'cba' * ``` */ reduceRight(array: T[], reducer: SerializableFunction, initialValue: R, options?: ThreadOptions): Promise; /** * Groups array elements by a key returned from the function. * Processes the grouping function in parallel for performance. * * @template T - The type of array elements * @template K - The type of the grouping key * @param array - The array to group * @param keyFn - Function that returns the group key: (item, index, array) => K * @param options - Execution options including batchSize * @returns Map of grouped elements * * @example * ```typescript * const grouped = await threadts.groupBy( * [{ type: 'a', value: 1 }, { type: 'b', value: 2 }, { type: 'a', value: 3 }], * (item) => item.type * ); * // Map { 'a' => [{type: 'a', value: 1}, {type: 'a', value: 3}], 'b' => [{type: 'b', value: 2}] } * ``` */ groupBy(array: T[], keyFn: SerializableFunction, options?: MapOptions): Promise>; /** * Partitions an array into two arrays based on a predicate. * Elements that satisfy the predicate go to the first array, * elements that don't go to the second array. * * @template T - The type of array elements * @param array - The array to partition * @param predicate - Function to test each element: (item, index, array) => boolean * @param options - Execution options including batchSize * @returns Tuple of [matching elements, non-matching elements] * * @example * ```typescript * const [evens, odds] = await threadts.partition( * [1, 2, 3, 4, 5], * (x) => x % 2 === 0 * ); * console.log(evens); // [2, 4] * console.log(odds); // [1, 3, 5] * ``` */ partition(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise<[T[], T[]]>; /** * Counts elements that satisfy a predicate. * Like filter().length but more efficient as it doesn't store filtered elements. * * @template T - The type of array elements * @param array - The array to count * @param predicate - Function to test each element: (item, index, array) => boolean * @param options - Execution options including batchSize * @returns The count of matching elements * * @example * ```typescript * const count = await threadts.count( * [1, 2, 3, 4, 5], * (x) => x > 2 * ); * console.log(count); // 3 * ``` */ count(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Creates a pipeline for chaining parallel operations. * Returns a fluent interface for building complex data transformations. * * @template T - The type of initial array elements * @param array - The initial array to process * @returns A Pipeline instance for chaining operations * * @example * ```typescript * const result = await threadts.pipe([1, 2, 3, 4, 5]) * .map((x) => x * 2) * .filter((x) => x > 4) * .reduce((acc, x) => acc + x, 0) * .execute(); * console.log(result); // 24 (6 + 8 + 10) * ``` */ pipe(array: T[]): Pipeline; /** * Executes multiple tasks as a batch with configurable batch size. * Tasks within a batch run in parallel, batches run sequentially. * * @param tasks - Array of tasks to execute * @param batchSize - Number of tasks to run in parallel (default: all) * @returns Array of task results with success/error information * * @example * ```typescript * const results = await threadts.batch([ * { fn: (x) => x * 2, data: 5 }, * { fn: (x) => x + 1, data: 10 } * ], 2); * ``` */ batch(tasks: Array, batchSize?: number): Promise; parallel(tasks: Array): Promise; resize(newSize: number): Promise; getPoolSize(): number; getActiveWorkers(): number; getQueueLength(): number; isInitialized(): boolean; getConfig(): ThreadConfig; updateConfig(newConfig: Partial): void; getStats(): { activeWorkers: number; idleWorkers: number; queuedTasks: number; completedTasks: number; averageExecutionTime: number; }; getPlatform(): string; isSupported(): boolean; private generateTaskId; terminate(): Promise; static terminateAll(): Promise; static run(func: SerializableFunction, data?: SerializableData, options?: ThreadOptions): Promise; static map(array: T[], func: SerializableFunction, options?: MapOptions): Promise; static filter(array: T[], func: SerializableFunction, options?: MapOptions): Promise; static reduce(array: T[], func: SerializableFunction, initialValue: R, options?: ThreadOptions): Promise; static forEach(array: T[], func: SerializableFunction, options?: MapOptions): Promise; /** * Static method to find the first element satisfying the predicate. * @see {@link ThreadTS.find} for instance method documentation */ static find(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Static method to find the index of the first element satisfying the predicate. * @see {@link ThreadTS.findIndex} for instance method documentation */ static findIndex(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Static method to test if any element satisfies the predicate. * @see {@link ThreadTS.some} for instance method documentation */ static some(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Static method to test if all elements satisfy the predicate. * @see {@link ThreadTS.every} for instance method documentation */ static every(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; static batch(tasks: Array, batchSize?: number): Promise; static parallel(tasks: Array): Promise; static resize(newSize: number): Promise; static getPoolSize(): number; static getActiveWorkers(): number; static getQueueLength(): number; static isInitialized(): boolean; static getConfig(): ThreadConfig; static updateConfig(newConfig: Partial): void; static getStats(): { activeWorkers: number; idleWorkers: number; queuedTasks: number; completedTasks: number; averageExecutionTime: number; }; static getPlatform(): string; static isSupported(): boolean; /** * Static method to create a flatMap operation. * @see {@link ThreadTS.flatMap} for instance method documentation */ static flatMap(array: T[], func: SerializableFunction, options?: MapOptions): Promise; /** * Static method to reduce an array from right to left. * @see {@link ThreadTS.reduceRight} for instance method documentation */ static reduceRight(array: T[], reducer: SerializableFunction, initialValue: R, options?: ThreadOptions): Promise; /** * Static method to group array elements by a key. * @see {@link ThreadTS.groupBy} for instance method documentation */ static groupBy(array: T[], keyFn: SerializableFunction, options?: MapOptions): Promise>; /** * Static method to partition an array into two arrays. * @see {@link ThreadTS.partition} for instance method documentation */ static partition(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise<[T[], T[]]>; /** * Static method to count elements matching a predicate. * @see {@link ThreadTS.count} for instance method documentation */ static count(array: T[], predicate: SerializableFunction, options?: MapOptions): Promise; /** * Static method to create a pipeline for chaining operations. * @see {@link ThreadTS.pipe} for instance method documentation */ static pipe(array: T[]): Pipeline; /** * Static method to find the index of an element. * @see {@link ThreadTS.indexOf} for instance method documentation */ static indexOf(array: T[], searchElement: T, fromIndex?: number): Promise; /** * Static method to find the last index of an element. * @see {@link ThreadTS.lastIndexOf} for instance method documentation */ static lastIndexOf(array: T[], searchElement: T, fromIndex?: number): Promise; /** * Static method to get an element at a specific index. * @see {@link ThreadTS.at} for instance method documentation */ static at(array: T[], index: number): Promise; /** * Static method to slice an array. * @see {@link ThreadTS.slice} for instance method documentation */ static slice(array: T[], start?: number, end?: number): Promise; /** * Static method to concatenate arrays. * @see {@link ThreadTS.concat} for instance method documentation */ static concat(array: T[], ...items: (T | T[])[]): Promise; /** * Static method to create a range of numbers. * @see {@link ThreadTS.range} for instance method documentation */ static range(start: number, end: number, step?: number): Promise; /** * Static method to repeat a value. * @see {@link ThreadTS.repeat} for instance method documentation */ static repeat(value: T, count: number): Promise; /** * Static method to get unique values. * @see {@link ThreadTS.unique} for instance method documentation */ static unique(array: T[]): Promise; /** * Static method to get unique values by key. * @see {@link ThreadTS.uniqueBy} for instance method documentation */ static uniqueBy(array: T[], keyFn: (item: T) => K): Promise; /** * Static method to chunk an array. * @see {@link ThreadTS.chunk} for instance method documentation */ static chunk(array: T[], size: number): Promise; /** * Static method to zip arrays. * @see {@link ThreadTS.zip} for instance method documentation */ static zip(...arrays: T): Promise<{ [K in keyof T]: T[K] extends (infer U)[] ? U : never; }[]>; /** * Static method to get the array operations module. * @see {@link ThreadTS.getArrayOps} for instance method documentation */ static getArrayOps(): ArrayOperations; } export { Pipeline, TerminalPipeline }; export default ThreadTS; //# sourceMappingURL=threadts.d.ts.map