API Reference

Complete API documentation for the ComputeKit core library.

Table of contents

ComputeKit Class

The main entry point for using ComputeKit.

Constructor

new ComputeKit(options?: ComputeKitOptions)

ComputeKitOptions

PropertyTypeDefaultDescription
maxWorkersnumbernavigator.hardwareConcurrency \|\| 4Maximum number of workers in the pool
timeoutnumber30000Default timeout for operations (ms)
debugbooleanfalseEnable debug logging
workerPathstring''Custom path to worker script
useSharedMemorybooleantrueUse SharedArrayBuffer when available
remoteDependenciesstring[][]External scripts to load in workers

Methods

initialize()

Manually initialize the worker pool. Called automatically on first run().

const kit = new ComputeKit();
await kit.initialize(); // Optional: eager initialization

register()

Register a compute function.

register<TInput, TOutput>(
  name: string,
  fn: (input: TInput, context: ComputeContext) => TOutput | Promise<TOutput>
): this

Parameters:

  • name - Unique identifier for the function
  • fn - The function to execute (runs in a Web Worker)

Returns: this (for chaining)

kit.register('double', (n: number) => n * 2);

kit.register('asyncTask', async (data, { reportProgress }) => {
  // Report progress during long operations
  reportProgress({ percent: 50 });
  return await processData(data);
});

// Chaining
kit.register('add', (a, b) => a + b).register('multiply', (a, b) => a * b);

run()

Execute a registered function.

run<TInput, TOutput>(
  name: string,
  input: TInput,
  options?: ComputeOptions
): Promise<TOutput>

Parameters:

  • name - Name of the registered function
  • input - Input data (will be serialized)
  • options - Optional execution options
const result = await kit.run('double', 21);
console.log(result); // 42

runWithMetadata()

Execute a function and receive metadata about the execution.

runWithMetadata<TInput, TOutput>(
  name: string,
  input: TInput,
  options?: ComputeOptions
): Promise<ComputeResult<TOutput>>
const result = await kit.runWithMetadata('heavy', data);
console.log(`Took ${result.duration}ms on worker ${result.workerId}`);

getStats()

Get current worker pool statistics.

const stats = kit.getStats();
console.log(`Active workers: ${stats.activeWorkers}`);
console.log(`Queue length: ${stats.queueLength}`);

isWasmSupported()

Check if WebAssembly is supported in the current environment.

if (kit.isWasmSupported()) {
  // Load WASM module
}

terminate()

Terminate all workers and clean up resources.

await kit.terminate();

ComputeOptions

Options for individual compute operations.

PropertyTypeDescription
timeoutnumberOperation timeout in ms
transferArrayBuffer[]ArrayBuffers to transfer (not copy)
prioritynumberPriority level (0-10, higher = first)
signalAbortSignalAbort signal for cancellation
onProgress(progress: ComputeProgress) => voidProgress callback
const controller = new AbortController();

await kit.run('task', data, {
  timeout: 5000,
  priority: 10,
  signal: controller.signal,
  onProgress: (p) => console.log(`${p.percent}%`),
});

// Cancel the operation
controller.abort();

ComputeProgress

Progress information for long-running tasks.

PropertyTypeDescription
percentnumberProgress percentage (0-100)
phasestring?Current phase name
estimatedTimeRemainingnumber?Estimated ms remaining
dataunknown?Additional custom data

ComputeResult

Result wrapper with execution metadata.

PropertyTypeDescription
dataTThe computed result
durationnumberExecution time in ms
cachedbooleanWhether result was cached
workerIdstringID of the worker that processed this

PoolStats

Worker pool statistics.

PropertyTypeDescription
workersWorkerInfo[]Info about each worker
totalWorkersnumberTotal worker count
activeWorkersnumberCurrently busy workers
idleWorkersnumberCurrently idle workers
queueLengthnumberTasks waiting in queue
tasksCompletednumberTotal completed tasks
tasksFailednumberTotal failed tasks
averageTaskDurationnumberAverage task duration (ms)

Event Handling

ComputeKit extends EventEmitter and emits events:

kit.on('worker:created', (info) => {
  console.log('New worker:', info.id);
});

kit.on('worker:terminated', (info) => {
  console.log('Worker terminated:', info.id);
});

kit.on('task:start', (taskId, name) => {
  console.log(`Starting ${name}`);
});

kit.on('task:complete', (taskId, duration) => {
  console.log(`Done in ${duration}ms`);
});

kit.on('task:error', (taskId, error) => {
  console.error('Task failed:', error);
});

kit.on('task:progress', (taskId, progress) => {
  console.log(`${progress.percent}%`);
});

Utility Functions

isWasmSupported()

Check if WebAssembly is available.

import { isWasmSupported } from '@computekit/core';

if (isWasmSupported()) {
  // Use WASM
}

isSharedArrayBufferAvailable()

Check if SharedArrayBuffer is available.

import { isSharedArrayBufferAvailable } from '@computekit/core';

if (isSharedArrayBufferAvailable()) {
  // Use shared memory
}

getHardwareConcurrency()

Get the number of logical CPU cores.

import { getHardwareConcurrency } from '@computekit/core';

const cores = getHardwareConcurrency();
console.log(`${cores} CPU cores available`);

findTransferables()

Detect transferable objects in data for efficient worker communication.

import { findTransferables } from '@computekit/core';

const data = { buffer: new ArrayBuffer(1024), values: [1, 2, 3] };
const transferables = findTransferables(data);
// [ArrayBuffer(1024)]

Error Handling

ComputeKit throws errors in these cases:

try {
  await kit.run('unknown', data);
} catch (error) {
  if (error.message.includes('not registered')) {
    // Function not registered
  } else if (error.message.includes('timed out')) {
    // Timeout
  } else if (error.message.includes('aborted')) {
    // Cancelled via AbortSignal
  } else {
    // Worker error
  }
}

Back to top

Copyright © 2024-2025 Ghassen Lassoued. Distributed under the MIT license.