New:Socket for Asana Is Now Available.Learn more
Sign In

asyncbox

Package Overview
Dependencies
Maintainers
4
Versions
55
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

asyncbox - npm Package Compare versions

Comparing version
6.3.5
to
6.4.0
+103
build/cjs/lib/asyncbox.d.ts
import type { CancellablePromise, LongSleepOptions, MapFilterOptions, SleepOptions, WaitForConditionOptions } from './types.js';
/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
export declare class TimeoutError extends Error {
constructor(message?: string);
}
/** Thrown when a promise is cancelled via `cancel`. */
export declare class PromiseCancellationError extends Error {
constructor(message?: string);
}
/**
* An async/await version of `setTimeout`. The returned promise has a `cancel()` method that clears
* the timer and usually rejects with {@link PromiseCancellationError} unless you use the object form with
* `cancelError: null` to resolve on cancel.
*
* @param ms - Milliseconds to wait
* @returns A thenable you can `await`; call `.cancel()` to abort early.
*/
export declare function sleep(ms: number): CancellablePromise<void>;
/**
* Object form: `ms` plus optional `cancelError` (non-empty string or `Error`, `null` to resolve on
* cancel, or omitted / `undefined` / `''` for default {@link PromiseCancellationError}). Any non-array
* object with a finite `ms` is accepted at runtime (including class instances), matching structural typing.
*
* @param options - Duration and optional cancellation behavior
* @returns A thenable you can `await`; call `.cancel()` to abort early.
*/
export declare function sleep(options: SleepOptions): CancellablePromise<void>;
/**
* Resolves with `promise` or rejects if it does not settle before `timeoutMs`.
*
* If the deadline passes first: with no third argument (or a falsy non-error value), rejects
* with {@link TimeoutError} whose message includes `timeoutMs`; with a non-empty string,
* rejects with {@link TimeoutError} using that message; with an `Error` instance, rejects
* with that same instance.
*
* @param promise - Promise to race against the timeout.
* @param timeoutMs - Maximum time in milliseconds before rejecting if `promise` has not settled.
* @param messageOrError - Optional override for the timeout rejection: custom {@link TimeoutError}
* message when the string is non-empty, or an existing `Error` to reject with verbatim.
* Omitted, `undefined`, or other falsy non-error values use the default timeout message (includes `timeoutMs`).
*/
export declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, messageOrError?: string | Error): Promise<T>;
/**
* Sometimes `Promise.delay` or `setTimeout` are inaccurate for large wait
* times. To safely wait for these long times (e.g. in the 5+ minute range), you
* can use `longSleep`.
*
* You can also pass a `progressCb` option which is a callback function that
* receives an object with the properties `elapsedMs`, `timeLeft`, and
* `progress`. This will be called on every wait interval so you can do your
* wait logging or whatever.
* @param ms - The number of milliseconds to wait
* @param options - Options for controlling the long sleep behavior
*/
export declare function longSleep(ms: number, { thresholdMs, intervalMs, progressCb }?: LongSleepOptions): Promise<void>;
/**
* An async/await way of running a method until it doesn't throw an error
* @param times - The maximum number of times to retry the function
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export declare function retry<T = any>(times: number, fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T | null>;
/**
* You can also use `retryInterval` to add a sleep in between retries. This can
* be useful if you want to throttle how fast we retry.
* @param times - The maximum number of times to retry the function
* @param sleepMs - The number of milliseconds to wait between retries
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export declare function retryInterval<T = any>(times: number, sleepMs: number, fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T | null>;
/**
* Similar to `Array.prototype.map`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to map over
* @param mapper - The function to apply to each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export declare function asyncmap<T, R>(coll: T[], mapper: (value: T) => R | Promise<R>, options?: MapFilterOptions): Promise<R[]>;
/**
* Similar to `Array.prototype.filter`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to filter
* @param filter - The function to test each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export declare function asyncfilter<T>(coll: T[], filter: (value: T) => boolean | Promise<boolean>, options?: MapFilterOptions): Promise<T[]>;
/**
* Takes a condition (a function returning a boolean or boolean promise), and
* waits until the condition is true.
*
* Throws a `/Condition unmet/` error if the condition has not been satisfied
* within the allocated time, unless an error is provided in the options, as the
* `error` property, which is either thrown itself, or used as the message.
*
* The condition result is returned if it is not falsy. If the condition throws an
* error then this exception will be immediately passed through.
*
* The default options are: `{ waitMs: 5000, intervalMs: 500 }`
* @param condFn - The condition function to evaluate
* @param options - Options for controlling the wait behavior
*/
export declare function waitForCondition<T>(condFn: () => Promise<T> | T, options?: WaitForConditionOptions): Promise<T>;
export type { CancellablePromise, Progress, ProgressCallback, LongSleepOptions, SleepArg, SleepOptions, WaitForConditionOptions, } from './types.js';
//# sourceMappingURL=asyncbox.d.ts.map
{"version":3,"file":"asyncbox.d.ts","sourceRoot":"","sources":["../../../lib/asyncbox.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAEhB,YAAY,EACZ,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAIpB,yEAAyE;AACzE,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,CAAC,EAAE,MAAM;CAI7B;AAED,uDAAuD;AACvD,qBAAa,wBAAyB,SAAQ,KAAK;gBACrC,OAAO,GAAE,MAA4B;CAIlD;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAC5D;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAsCvE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EACnB,SAAS,EAAE,MAAM,EACjB,cAAc,CAAC,EAAE,MAAM,GAAG,KAAK,GAC9B,OAAO,CAAC,CAAC,CAAC,CAsBZ;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,SAAS,CAC7B,EAAE,EAAE,MAAM,EACV,EAAC,WAAkC,EAAE,UAAiB,EAAE,UAAiB,EAAC,GAAE,gBAAqB,GAChG,OAAO,CAAC,IAAI,CAA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Q,EACR,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,YAAY,EACZ,uBAAuB,GACxB,MAAM,YAAY,CAAC"}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseCancellationError = exports.TimeoutError = void 0;
exports.sleep = sleep;
exports.withTimeout = withTimeout;
exports.longSleep = longSleep;
exports.retry = retry;
exports.retryInterval = retryInterval;
exports.asyncmap = asyncmap;
exports.asyncfilter = asyncfilter;
exports.waitForCondition = waitForCondition;
const p_limit_1 = require("p-limit");
const LONG_SLEEP_THRESHOLD = 5000; // anything over 5000ms will turn into a spin
/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
class TimeoutError extends Error {
constructor(message) {
super(message ?? 'Operation timed out');
this.name = 'TimeoutError';
}
}
exports.TimeoutError = TimeoutError;
/** Thrown when a promise is cancelled via `cancel`. */
class PromiseCancellationError extends Error {
constructor(message = 'Promise cancelled') {
super(message);
this.name = 'PromiseCancellationError';
}
}
exports.PromiseCancellationError = PromiseCancellationError;
function sleep(arg) {
const { ms, cancelError } = parseSleepArg(arg);
let timeoutId;
let resolveFn;
let rejectFn;
const promise = new Promise((resolve, reject) => {
resolveFn = resolve;
rejectFn = reject;
timeoutId = setTimeout(resolve, ms);
});
promise.cancel = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
if (cancelError === null) {
resolveFn?.(undefined);
}
else {
let err;
if (typeof cancelError === 'string' && cancelError) {
err = new PromiseCancellationError(cancelError);
}
else if (cancelError instanceof Error) {
err = cancelError;
}
else {
err = new PromiseCancellationError();
}
rejectFn?.(err);
}
resolveFn = undefined;
rejectFn = undefined;
};
return promise;
}
/**
* Resolves with `promise` or rejects if it does not settle before `timeoutMs`.
*
* If the deadline passes first: with no third argument (or a falsy non-error value), rejects
* with {@link TimeoutError} whose message includes `timeoutMs`; with a non-empty string,
* rejects with {@link TimeoutError} using that message; with an `Error` instance, rejects
* with that same instance.
*
* @param promise - Promise to race against the timeout.
* @param timeoutMs - Maximum time in milliseconds before rejecting if `promise` has not settled.
* @param messageOrError - Optional override for the timeout rejection: custom {@link TimeoutError}
* message when the string is non-empty, or an existing `Error` to reject with verbatim.
* Omitted, `undefined`, or other falsy non-error values use the default timeout message (includes `timeoutMs`).
*/
async function withTimeout(promise, timeoutMs, messageOrError) {
let timer = null;
try {
return await Promise.race([
promise,
new Promise((_resolve, reject) => {
timer = setTimeout(() => {
if (typeof messageOrError === 'string' && messageOrError) {
reject(new TimeoutError(messageOrError));
}
else if (!messageOrError) {
reject(new TimeoutError(`Operation timed out after ${timeoutMs}ms`));
}
else {
reject(messageOrError);
}
}, timeoutMs);
}),
]);
}
finally {
if (timer) {
clearTimeout(timer);
}
}
}
/**
* Sometimes `Promise.delay` or `setTimeout` are inaccurate for large wait
* times. To safely wait for these long times (e.g. in the 5+ minute range), you
* can use `longSleep`.
*
* You can also pass a `progressCb` option which is a callback function that
* receives an object with the properties `elapsedMs`, `timeLeft`, and
* `progress`. This will be called on every wait interval so you can do your
* wait logging or whatever.
* @param ms - The number of milliseconds to wait
* @param options - Options for controlling the long sleep behavior
*/
async function longSleep(ms, { thresholdMs = LONG_SLEEP_THRESHOLD, intervalMs = 1000, progressCb = null } = {}) {
if (ms < thresholdMs) {
return await sleep(ms);
}
const endAt = Date.now() + ms;
let timeLeft;
let elapsedMs = 0;
do {
const pre = Date.now();
await sleep(intervalMs);
const post = Date.now();
timeLeft = endAt - post;
elapsedMs = elapsedMs + (post - pre);
if (typeof progressCb === 'function') {
progressCb({ elapsedMs, timeLeft, progress: elapsedMs / ms });
}
} while (timeLeft > 0);
}
/**
* An async/await way of running a method until it doesn't throw an error
* @param times - The maximum number of times to retry the function
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
async function retry(times, fn, ...args) {
let tries = 0;
let done = false;
let res = null;
while (!done && tries < times) {
tries++;
try {
res = await fn(...args);
done = true;
}
catch (err) {
if (tries >= times) {
throw err;
}
}
}
return res;
}
/**
* You can also use `retryInterval` to add a sleep in between retries. This can
* be useful if you want to throttle how fast we retry.
* @param times - The maximum number of times to retry the function
* @param sleepMs - The number of milliseconds to wait between retries
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
async function retryInterval(times, sleepMs, fn, ...args) {
let count = 0;
const wrapped = async () => {
count++;
let res;
try {
res = await fn(...args);
}
catch (e) {
// do not pause when finished the last retry
if (count !== times) {
await sleep(sleepMs);
}
throw e;
}
return res;
};
return await retry(times, wrapped);
}
/**
* Similar to `Array.prototype.map`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to map over
* @param mapper - The function to apply to each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
async function asyncmap(coll, mapper, options = true) {
if (options === null) {
throw new Error('Options cannot be null');
}
// limitFunction requires the mapper to always return a promise
const mapperAsync = async (value) => mapper(value);
if (options === false) {
return coll.reduce(async (acc, item) => [...(await acc), await mapperAsync(item)], Promise.resolve([]));
}
const adjustedMapper = options === true ? mapperAsync : (0, p_limit_1.limitFunction)(mapperAsync, { concurrency: options.concurrency });
return Promise.all(coll.map(adjustedMapper));
}
/**
* Similar to `Array.prototype.filter`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to filter
* @param filter - The function to test each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
async function asyncfilter(coll, filter, options = true) {
if (options === null) {
throw new Error('Options cannot be null');
}
// limitFunction requires the filter to always return a promise
const filterAsync = async (value) => filter(value);
if (options === false) {
return coll.reduce(async (accP, item) => {
const acc = await accP;
if (await filterAsync(item)) {
acc.push(item);
}
return acc;
}, Promise.resolve([]));
}
const adjustedFilter = options === true ? filterAsync : (0, p_limit_1.limitFunction)(filterAsync, { concurrency: options.concurrency });
const bools = await Promise.all(coll.map(adjustedFilter));
return coll.reduce((acc, item, i) => {
if (bools[i]) {
acc.push(item);
}
return acc;
}, []);
}
/**
* Takes a condition (a function returning a boolean or boolean promise), and
* waits until the condition is true.
*
* Throws a `/Condition unmet/` error if the condition has not been satisfied
* within the allocated time, unless an error is provided in the options, as the
* `error` property, which is either thrown itself, or used as the message.
*
* The condition result is returned if it is not falsy. If the condition throws an
* error then this exception will be immediately passed through.
*
* The default options are: `{ waitMs: 5000, intervalMs: 500 }`
* @param condFn - The condition function to evaluate
* @param options - Options for controlling the wait behavior
*/
async function waitForCondition(condFn, options = {}) {
const opts = {
...options,
waitMs: typeof options.waitMs === 'number' ? options.waitMs : 5000,
intervalMs: typeof options.intervalMs === 'number' ? options.intervalMs : 500,
};
const debug = opts.logger ? opts.logger.debug.bind(opts.logger) : () => undefined;
const error = opts.error;
const begunAt = Date.now();
const endAt = begunAt + opts.waitMs;
const spin = async function spin() {
const result = await condFn();
if (result) {
return result;
}
const now = Date.now();
const waited = now - begunAt;
const remainingTime = endAt - now;
if (now < endAt) {
debug(`Waited for ${waited} ms so far`);
await sleep(Math.min(opts.intervalMs, remainingTime));
return await spin();
}
// if there is an error option, it is either a string message or an error itself
if (error) {
throw typeof error === 'string' ? new Error(error) : error;
}
throw new Error(`Condition unmet after ${waited} ms. Timing out.`);
};
return await spin();
}
/** Non-array object values (including class instances); excludes `null` and arrays. */
function isSleepArgObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function parseSleepArg(arg) {
if (typeof arg === 'number') {
if (!Number.isFinite(arg)) {
throw new TypeError('sleep: expected a finite number or an object with ms');
}
return { ms: arg };
}
if (isSleepArgObject(arg)) {
const ms = arg.ms;
if (typeof ms !== 'number' || !Number.isFinite(ms)) {
throw new TypeError('sleep: options.ms must be a finite number');
}
return { ms, cancelError: arg.cancelError };
}
throw new TypeError('sleep: expected a finite number or an object with ms');
}
//# sourceMappingURL=asyncbox.js.map
{"version":3,"file":"asyncbox.js","sourceRoot":"","sources":["../../../lib/asyncbox.ts"],"names":[],"mappings":";;;AA8CA,sBAmCC;AAgBD,kCA0BC;AAcD,8BAoBC;AAQD,sBAoBC;AAUD,sCAsBC;AAQD,4BAmBC;AAQD,kCA4BC;AAiBD,4CAiCC;AA1UD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AAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC;YACnD,MAAM,IAAI,SAAS,CAAC,2CAA2C,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,EAAC,EAAE,EAAE,WAAW,EAAE,GAAG,CAAC,WAAgD,EAAC,CAAC;IACjF,CAAC;IACD,MAAM,IAAI,SAAS,CAAC,sDAAsD,CAAC,CAAC;AAC9E,CAAC"}
/**
* Parameter provided to a progress callback
*/
export interface Progress {
/** Elapsed time in milliseconds since the operation started */
elapsedMs: number;
/** Remaining time in milliseconds until the operation completes */
timeLeft: number;
/** Progress as a number between 0 and 1 (0 = not started, 1 = complete) */
progress: number;
}
/**
* Progress callback for {@link longSleep}
*/
export type ProgressCallback = (progress: Progress) => void;
/**
* Options for {@link longSleep}
*/
export interface LongSleepOptions {
/** Minimum duration in milliseconds before using long sleep behavior.
* @default 5000
*/
thresholdMs?: number;
/** Interval in milliseconds between progress callbacks.
* @default 1000
*/
intervalMs?: number;
/** Optional callback function to receive progress updates during the sleep */
progressCb?: ProgressCallback | null;
}
/**
* Options for {@link asyncmap} and {@link asyncfilter}
*/
export type MapFilterOptions = boolean | {
concurrency: number;
};
/**
* Object form of {@link sleep}'s argument: duration plus optional cancellation rejection override.
* Structural typing allows class instances; {@link sleep} accepts any non-array object with a finite `ms`.
*/
export interface SleepOptions {
/** Duration in milliseconds */
ms: number;
/**
* When {@link sleep}'s `cancel` runs: a non-empty string becomes {@link PromiseCancellationError}
* with that message; an `Error` rejects with that same instance; `null` resolves the promise
* instead of rejecting; omitted, `undefined`, or `''` use the default {@link PromiseCancellationError}.
*/
cancelError?: string | Error | null;
}
/**
* Argument to {@link sleep}: either milliseconds or an options object (see {@link SleepOptions}).
*/
export type SleepArg = number | SleepOptions;
/**
* A promise with a {@linkcode cancel} method (e.g. from {@link sleep}).
*
* @typeParam T - Resolved value type; {@link sleep} uses `void`.
*/
export type CancellablePromise<T = void> = Promise<T> & {
cancel: () => void;
};
/**
* Options for {@link waitForCondition}
*/
export interface WaitForConditionOptions {
/** Maximum time to wait in milliseconds.
* @default 5000
*/
waitMs?: number;
/** Interval in milliseconds between condition checks.
* @default 500
*/
intervalMs?: number;
/** Optional logger object with a debug method for logging wait progress */
logger?: {
debug: (...args: any[]) => void;
};
/** Custom error message (string) or Error object to throw if condition is not met.
* If not provided, a default error is thrown
*/
error?: string | Error;
}
//# sourceMappingURL=types.d.ts.map
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../lib/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG;IAAC,WAAW,EAAE,MAAM,CAAA;CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,YAAY,CAAC;AAE7C;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,CAAC,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG;IACtD,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,MAAM,CAAC,EAAE;QACP,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;KACjC,CAAC;IACF;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACxB"}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/types.ts"],"names":[],"mappings":""}
{
"type": "commonjs"
}
import type { CancellablePromise, LongSleepOptions, MapFilterOptions, SleepOptions, WaitForConditionOptions } from './types.js';
/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
export declare class TimeoutError extends Error {
constructor(message?: string);
}
/** Thrown when a promise is cancelled via `cancel`. */
export declare class PromiseCancellationError extends Error {
constructor(message?: string);
}
/**
* An async/await version of `setTimeout`. The returned promise has a `cancel()` method that clears
* the timer and usually rejects with {@link PromiseCancellationError} unless you use the object form with
* `cancelError: null` to resolve on cancel.
*
* @param ms - Milliseconds to wait
* @returns A thenable you can `await`; call `.cancel()` to abort early.
*/
export declare function sleep(ms: number): CancellablePromise<void>;
/**
* Object form: `ms` plus optional `cancelError` (non-empty string or `Error`, `null` to resolve on
* cancel, or omitted / `undefined` / `''` for default {@link PromiseCancellationError}). Any non-array
* object with a finite `ms` is accepted at runtime (including class instances), matching structural typing.
*
* @param options - Duration and optional cancellation behavior
* @returns A thenable you can `await`; call `.cancel()` to abort early.
*/
export declare function sleep(options: SleepOptions): CancellablePromise<void>;
/**
* Resolves with `promise` or rejects if it does not settle before `timeoutMs`.
*
* If the deadline passes first: with no third argument (or a falsy non-error value), rejects
* with {@link TimeoutError} whose message includes `timeoutMs`; with a non-empty string,
* rejects with {@link TimeoutError} using that message; with an `Error` instance, rejects
* with that same instance.
*
* @param promise - Promise to race against the timeout.
* @param timeoutMs - Maximum time in milliseconds before rejecting if `promise` has not settled.
* @param messageOrError - Optional override for the timeout rejection: custom {@link TimeoutError}
* message when the string is non-empty, or an existing `Error` to reject with verbatim.
* Omitted, `undefined`, or other falsy non-error values use the default timeout message (includes `timeoutMs`).
*/
export declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, messageOrError?: string | Error): Promise<T>;
/**
* Sometimes `Promise.delay` or `setTimeout` are inaccurate for large wait
* times. To safely wait for these long times (e.g. in the 5+ minute range), you
* can use `longSleep`.
*
* You can also pass a `progressCb` option which is a callback function that
* receives an object with the properties `elapsedMs`, `timeLeft`, and
* `progress`. This will be called on every wait interval so you can do your
* wait logging or whatever.
* @param ms - The number of milliseconds to wait
* @param options - Options for controlling the long sleep behavior
*/
export declare function longSleep(ms: number, { thresholdMs, intervalMs, progressCb }?: LongSleepOptions): Promise<void>;
/**
* An async/await way of running a method until it doesn't throw an error
* @param times - The maximum number of times to retry the function
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export declare function retry<T = any>(times: number, fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T | null>;
/**
* You can also use `retryInterval` to add a sleep in between retries. This can
* be useful if you want to throttle how fast we retry.
* @param times - The maximum number of times to retry the function
* @param sleepMs - The number of milliseconds to wait between retries
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export declare function retryInterval<T = any>(times: number, sleepMs: number, fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T | null>;
/**
* Similar to `Array.prototype.map`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to map over
* @param mapper - The function to apply to each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export declare function asyncmap<T, R>(coll: T[], mapper: (value: T) => R | Promise<R>, options?: MapFilterOptions): Promise<R[]>;
/**
* Similar to `Array.prototype.filter`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to filter
* @param filter - The function to test each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export declare function asyncfilter<T>(coll: T[], filter: (value: T) => boolean | Promise<boolean>, options?: MapFilterOptions): Promise<T[]>;
/**
* Takes a condition (a function returning a boolean or boolean promise), and
* waits until the condition is true.
*
* Throws a `/Condition unmet/` error if the condition has not been satisfied
* within the allocated time, unless an error is provided in the options, as the
* `error` property, which is either thrown itself, or used as the message.
*
* The condition result is returned if it is not falsy. If the condition throws an
* error then this exception will be immediately passed through.
*
* The default options are: `{ waitMs: 5000, intervalMs: 500 }`
* @param condFn - The condition function to evaluate
* @param options - Options for controlling the wait behavior
*/
export declare function waitForCondition<T>(condFn: () => Promise<T> | T, options?: WaitForConditionOptions): Promise<T>;
export type { CancellablePromise, Progress, ProgressCallback, LongSleepOptions, SleepArg, SleepOptions, WaitForConditionOptions, } from './types.js';
//# sourceMappingURL=asyncbox.d.ts.map
{"version":3,"file":"asyncbox.d.ts","sourceRoot":"","sources":["../../../lib/asyncbox.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAEhB,YAAY,EACZ,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAIpB,yEAAyE;AACzE,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,CAAC,EAAE,MAAM;CAI7B;AAED,uDAAuD;AACvD,qBAAa,wBAAyB,SAAQ,KAAK;gBACrC,OAAO,GAAE,MAA4B;CAIlD;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAC5D;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAsCvE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAAC,C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O,CAAC,OAAO,CAAC,EAChD,OAAO,GAAE,gBAAuB,GAC/B,OAAO,CAAC,CAAC,EAAE,CAAC,CAwBd;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,gBAAgB,CAAC,CAAC,EACtC,MAAM,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,EAC5B,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,CAAC,CAAC,CA8BZ;AAGD,YAAY,EACV,kBAAkB,EAClB,QAAQ,EACR,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,YAAY,EACZ,uBAAuB,GACxB,MAAM,YAAY,CAAC"}
import { limitFunction } from 'p-limit';
const LONG_SLEEP_THRESHOLD = 5000; // anything over 5000ms will turn into a spin
/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
export class TimeoutError extends Error {
constructor(message) {
super(message ?? 'Operation timed out');
this.name = 'TimeoutError';
}
}
/** Thrown when a promise is cancelled via `cancel`. */
export class PromiseCancellationError extends Error {
constructor(message = 'Promise cancelled') {
super(message);
this.name = 'PromiseCancellationError';
}
}
export function sleep(arg) {
const { ms, cancelError } = parseSleepArg(arg);
let timeoutId;
let resolveFn;
let rejectFn;
const promise = new Promise((resolve, reject) => {
resolveFn = resolve;
rejectFn = reject;
timeoutId = setTimeout(resolve, ms);
});
promise.cancel = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
if (cancelError === null) {
resolveFn?.(undefined);
}
else {
let err;
if (typeof cancelError === 'string' && cancelError) {
err = new PromiseCancellationError(cancelError);
}
else if (cancelError instanceof Error) {
err = cancelError;
}
else {
err = new PromiseCancellationError();
}
rejectFn?.(err);
}
resolveFn = undefined;
rejectFn = undefined;
};
return promise;
}
/**
* Resolves with `promise` or rejects if it does not settle before `timeoutMs`.
*
* If the deadline passes first: with no third argument (or a falsy non-error value), rejects
* with {@link TimeoutError} whose message includes `timeoutMs`; with a non-empty string,
* rejects with {@link TimeoutError} using that message; with an `Error` instance, rejects
* with that same instance.
*
* @param promise - Promise to race against the timeout.
* @param timeoutMs - Maximum time in milliseconds before rejecting if `promise` has not settled.
* @param messageOrError - Optional override for the timeout rejection: custom {@link TimeoutError}
* message when the string is non-empty, or an existing `Error` to reject with verbatim.
* Omitted, `undefined`, or other falsy non-error values use the default timeout message (includes `timeoutMs`).
*/
export async function withTimeout(promise, timeoutMs, messageOrError) {
let timer = null;
try {
return await Promise.race([
promise,
new Promise((_resolve, reject) => {
timer = setTimeout(() => {
if (typeof messageOrError === 'string' && messageOrError) {
reject(new TimeoutError(messageOrError));
}
else if (!messageOrError) {
reject(new TimeoutError(`Operation timed out after ${timeoutMs}ms`));
}
else {
reject(messageOrError);
}
}, timeoutMs);
}),
]);
}
finally {
if (timer) {
clearTimeout(timer);
}
}
}
/**
* Sometimes `Promise.delay` or `setTimeout` are inaccurate for large wait
* times. To safely wait for these long times (e.g. in the 5+ minute range), you
* can use `longSleep`.
*
* You can also pass a `progressCb` option which is a callback function that
* receives an object with the properties `elapsedMs`, `timeLeft`, and
* `progress`. This will be called on every wait interval so you can do your
* wait logging or whatever.
* @param ms - The number of milliseconds to wait
* @param options - Options for controlling the long sleep behavior
*/
export async function longSleep(ms, { thresholdMs = LONG_SLEEP_THRESHOLD, intervalMs = 1000, progressCb = null } = {}) {
if (ms < thresholdMs) {
return await sleep(ms);
}
const endAt = Date.now() + ms;
let timeLeft;
let elapsedMs = 0;
do {
const pre = Date.now();
await sleep(intervalMs);
const post = Date.now();
timeLeft = endAt - post;
elapsedMs = elapsedMs + (post - pre);
if (typeof progressCb === 'function') {
progressCb({ elapsedMs, timeLeft, progress: elapsedMs / ms });
}
} while (timeLeft > 0);
}
/**
* An async/await way of running a method until it doesn't throw an error
* @param times - The maximum number of times to retry the function
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export async function retry(times, fn, ...args) {
let tries = 0;
let done = false;
let res = null;
while (!done && tries < times) {
tries++;
try {
res = await fn(...args);
done = true;
}
catch (err) {
if (tries >= times) {
throw err;
}
}
}
return res;
}
/**
* You can also use `retryInterval` to add a sleep in between retries. This can
* be useful if you want to throttle how fast we retry.
* @param times - The maximum number of times to retry the function
* @param sleepMs - The number of milliseconds to wait between retries
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export async function retryInterval(times, sleepMs, fn, ...args) {
let count = 0;
const wrapped = async () => {
count++;
let res;
try {
res = await fn(...args);
}
catch (e) {
// do not pause when finished the last retry
if (count !== times) {
await sleep(sleepMs);
}
throw e;
}
return res;
};
return await retry(times, wrapped);
}
/**
* Similar to `Array.prototype.map`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to map over
* @param mapper - The function to apply to each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export async function asyncmap(coll, mapper, options = true) {
if (options === null) {
throw new Error('Options cannot be null');
}
// limitFunction requires the mapper to always return a promise
const mapperAsync = async (value) => mapper(value);
if (options === false) {
return coll.reduce(async (acc, item) => [...(await acc), await mapperAsync(item)], Promise.resolve([]));
}
const adjustedMapper = options === true ? mapperAsync : limitFunction(mapperAsync, { concurrency: options.concurrency });
return Promise.all(coll.map(adjustedMapper));
}
/**
* Similar to `Array.prototype.filter`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to filter
* @param filter - The function to test each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export async function asyncfilter(coll, filter, options = true) {
if (options === null) {
throw new Error('Options cannot be null');
}
// limitFunction requires the filter to always return a promise
const filterAsync = async (value) => filter(value);
if (options === false) {
return coll.reduce(async (accP, item) => {
const acc = await accP;
if (await filterAsync(item)) {
acc.push(item);
}
return acc;
}, Promise.resolve([]));
}
const adjustedFilter = options === true ? filterAsync : limitFunction(filterAsync, { concurrency: options.concurrency });
const bools = await Promise.all(coll.map(adjustedFilter));
return coll.reduce((acc, item, i) => {
if (bools[i]) {
acc.push(item);
}
return acc;
}, []);
}
/**
* Takes a condition (a function returning a boolean or boolean promise), and
* waits until the condition is true.
*
* Throws a `/Condition unmet/` error if the condition has not been satisfied
* within the allocated time, unless an error is provided in the options, as the
* `error` property, which is either thrown itself, or used as the message.
*
* The condition result is returned if it is not falsy. If the condition throws an
* error then this exception will be immediately passed through.
*
* The default options are: `{ waitMs: 5000, intervalMs: 500 }`
* @param condFn - The condition function to evaluate
* @param options - Options for controlling the wait behavior
*/
export async function waitForCondition(condFn, options = {}) {
const opts = {
...options,
waitMs: typeof options.waitMs === 'number' ? options.waitMs : 5000,
intervalMs: typeof options.intervalMs === 'number' ? options.intervalMs : 500,
};
const debug = opts.logger ? opts.logger.debug.bind(opts.logger) : () => undefined;
const error = opts.error;
const begunAt = Date.now();
const endAt = begunAt + opts.waitMs;
const spin = async function spin() {
const result = await condFn();
if (result) {
return result;
}
const now = Date.now();
const waited = now - begunAt;
const remainingTime = endAt - now;
if (now < endAt) {
debug(`Waited for ${waited} ms so far`);
await sleep(Math.min(opts.intervalMs, remainingTime));
return await spin();
}
// if there is an error option, it is either a string message or an error itself
if (error) {
throw typeof error === 'string' ? new Error(error) : error;
}
throw new Error(`Condition unmet after ${waited} ms. Timing out.`);
};
return await spin();
}
/** Non-array object values (including class instances); excludes `null` and arrays. */
function isSleepArgObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function parseSleepArg(arg) {
if (typeof arg === 'number') {
if (!Number.isFinite(arg)) {
throw new TypeError('sleep: expected a finite number or an object with ms');
}
return { ms: arg };
}
if (isSleepArgObject(arg)) {
const ms = arg.ms;
if (typeof ms !== 'number' || !Number.isFinite(ms)) {
throw new TypeError('sleep: options.ms must be a finite number');
}
return { ms, cancelError: arg.cancelError };
}
throw new TypeError('sleep: expected a finite number or an object with ms');
}
//# sourceMappingURL=asyncbox.js.map
{"version":3,"file":"asyncbox.js","sourceRoot":"","sources":["../../../lib/asyncbox.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,SAAS,CAAC;AAUtC,MAAM,oBAAoB,GAAG,IAAI,CAAC,CAAC,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IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC;YACnD,MAAM,IAAI,SAAS,CAAC,2CAA2C,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,EAAC,EAAE,EAAE,WAAW,EAAE,GAAG,CAAC,WAAgD,EAAC,CAAC;IACjF,CAAC;IACD,MAAM,IAAI,SAAS,CAAC,sDAAsD,CAAC,CAAC;AAC9E,CAAC"}
/**
* Parameter provided to a progress callback
*/
export interface Progress {
/** Elapsed time in milliseconds since the operation started */
elapsedMs: number;
/** Remaining time in milliseconds until the operation completes */
timeLeft: number;
/** Progress as a number between 0 and 1 (0 = not started, 1 = complete) */
progress: number;
}
/**
* Progress callback for {@link longSleep}
*/
export type ProgressCallback = (progress: Progress) => void;
/**
* Options for {@link longSleep}
*/
export interface LongSleepOptions {
/** Minimum duration in milliseconds before using long sleep behavior.
* @default 5000
*/
thresholdMs?: number;
/** Interval in milliseconds between progress callbacks.
* @default 1000
*/
intervalMs?: number;
/** Optional callback function to receive progress updates during the sleep */
progressCb?: ProgressCallback | null;
}
/**
* Options for {@link asyncmap} and {@link asyncfilter}
*/
export type MapFilterOptions = boolean | {
concurrency: number;
};
/**
* Object form of {@link sleep}'s argument: duration plus optional cancellation rejection override.
* Structural typing allows class instances; {@link sleep} accepts any non-array object with a finite `ms`.
*/
export interface SleepOptions {
/** Duration in milliseconds */
ms: number;
/**
* When {@link sleep}'s `cancel` runs: a non-empty string becomes {@link PromiseCancellationError}
* with that message; an `Error` rejects with that same instance; `null` resolves the promise
* instead of rejecting; omitted, `undefined`, or `''` use the default {@link PromiseCancellationError}.
*/
cancelError?: string | Error | null;
}
/**
* Argument to {@link sleep}: either milliseconds or an options object (see {@link SleepOptions}).
*/
export type SleepArg = number | SleepOptions;
/**
* A promise with a {@linkcode cancel} method (e.g. from {@link sleep}).
*
* @typeParam T - Resolved value type; {@link sleep} uses `void`.
*/
export type CancellablePromise<T = void> = Promise<T> & {
cancel: () => void;
};
/**
* Options for {@link waitForCondition}
*/
export interface WaitForConditionOptions {
/** Maximum time to wait in milliseconds.
* @default 5000
*/
waitMs?: number;
/** Interval in milliseconds between condition checks.
* @default 500
*/
intervalMs?: number;
/** Optional logger object with a debug method for logging wait progress */
logger?: {
debug: (...args: any[]) => void;
};
/** Custom error message (string) or Error object to throw if condition is not met.
* If not provided, a default error is thrown
*/
error?: string | Error;
}
//# sourceMappingURL=types.d.ts.map
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../lib/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG;IAAC,WAAW,EAAE,MAAM,CAAA;CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,YAAY,CAAC;AAE7C;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,CAAC,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG;IACtD,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,MAAM,CAAC,EAAE;QACP,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;KACjC,CAAC;IACF;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACxB"}
export {};
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../lib/types.ts"],"names":[],"mappings":""}
{
"type": "module"
}
+27
-8

@@ -9,3 +9,3 @@ {

],
"version": "6.3.5",
"version": "6.4.0",
"author": "jlipps@gmail.com",

@@ -24,3 +24,19 @@ "license": "Apache-2.0",

},
"main": "./build/lib/asyncbox.js",
"type": "module",
"main": "./build/cjs/lib/asyncbox.js",
"module": "./build/esm/lib/asyncbox.js",
"types": "./build/cjs/lib/asyncbox.d.ts",
"exports": {
".": {
"import": {
"types": "./build/esm/lib/asyncbox.d.ts",
"default": "./build/esm/lib/asyncbox.js"
},
"require": {
"types": "./build/cjs/lib/asyncbox.d.ts",
"default": "./build/cjs/lib/asyncbox.js"
}
},
"./package.json": "./package.json"
},
"bin": {},

@@ -32,11 +48,15 @@ "directories": {

"lib/**/*",
"build/lib/**/*"
"build/cjs/lib/**/*",
"build/cjs/package.json",
"build/esm/lib/**/*",
"build/esm/package.json"
],
"scripts": {
"build": "tsc -b",
"clean": "npm run build -- --clean",
"build": "tsc -b tsconfig.esm.json tsconfig.cjs.json",
"postbuild": "node scripts/postbuild.mjs",
"clean": "node -e \"require('fs').rmSync('build', {recursive: true, force: true})\"",
"rebuild": "npm run clean; npm run build",
"dev": "npm run build -- --watch",
"prepare": "npm run rebuild",
"test": "node --test --enable-source-maps --test-force-exit --test-timeout=60000 \"./build/test/**/*.spec.js\"",
"test": "node --test --enable-source-maps --test-force-exit --test-timeout=60000 \"./build/esm/test/**/*.spec.js\" \"./test/*.spec.cjs\"",
"lint": "eslint .",

@@ -65,4 +85,3 @@ "format": "prettier -w ./lib ./test",

"typescript": "^6.0.3"
},
"types": "./build/lib/asyncbox.d.ts"
}
}

@@ -10,2 +10,4 @@ asyncbox

Published as both ESM and CommonJS, so `import {sleep} from 'asyncbox'` and `const {sleep} = require('asyncbox')` both work.
Then, behold!

@@ -12,0 +14,0 @@

import type { CancellablePromise, LongSleepOptions, MapFilterOptions, SleepOptions, WaitForConditionOptions } from './types.js';
/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
export declare class TimeoutError extends Error {
constructor(message?: string);
}
/** Thrown when a promise is cancelled via `cancel`. */
export declare class PromiseCancellationError extends Error {
constructor(message?: string);
}
/**
* An async/await version of `setTimeout`. The returned promise has a `cancel()` method that clears
* the timer and usually rejects with {@link PromiseCancellationError} unless you use the object form with
* `cancelError: null` to resolve on cancel.
*
* @param ms - Milliseconds to wait
* @returns A thenable you can `await`; call `.cancel()` to abort early.
*/
export declare function sleep(ms: number): CancellablePromise<void>;
/**
* Object form: `ms` plus optional `cancelError` (non-empty string or `Error`, `null` to resolve on
* cancel, or omitted / `undefined` / `''` for default {@link PromiseCancellationError}). Any non-array
* object with a finite `ms` is accepted at runtime (including class instances), matching structural typing.
*
* @param options - Duration and optional cancellation behavior
* @returns A thenable you can `await`; call `.cancel()` to abort early.
*/
export declare function sleep(options: SleepOptions): CancellablePromise<void>;
/**
* Resolves with `promise` or rejects if it does not settle before `timeoutMs`.
*
* If the deadline passes first: with no third argument (or a falsy non-error value), rejects
* with {@link TimeoutError} whose message includes `timeoutMs`; with a non-empty string,
* rejects with {@link TimeoutError} using that message; with an `Error` instance, rejects
* with that same instance.
*
* @param promise - Promise to race against the timeout.
* @param timeoutMs - Maximum time in milliseconds before rejecting if `promise` has not settled.
* @param messageOrError - Optional override for the timeout rejection: custom {@link TimeoutError}
* message when the string is non-empty, or an existing `Error` to reject with verbatim.
* Omitted, `undefined`, or other falsy non-error values use the default timeout message (includes `timeoutMs`).
*/
export declare function withTimeout<T>(promise: Promise<T>, timeoutMs: number, messageOrError?: string | Error): Promise<T>;
/**
* Sometimes `Promise.delay` or `setTimeout` are inaccurate for large wait
* times. To safely wait for these long times (e.g. in the 5+ minute range), you
* can use `longSleep`.
*
* You can also pass a `progressCb` option which is a callback function that
* receives an object with the properties `elapsedMs`, `timeLeft`, and
* `progress`. This will be called on every wait interval so you can do your
* wait logging or whatever.
* @param ms - The number of milliseconds to wait
* @param options - Options for controlling the long sleep behavior
*/
export declare function longSleep(ms: number, { thresholdMs, intervalMs, progressCb }?: LongSleepOptions): Promise<void>;
/**
* An async/await way of running a method until it doesn't throw an error
* @param times - The maximum number of times to retry the function
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export declare function retry<T = any>(times: number, fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T | null>;
/**
* You can also use `retryInterval` to add a sleep in between retries. This can
* be useful if you want to throttle how fast we retry.
* @param times - The maximum number of times to retry the function
* @param sleepMs - The number of milliseconds to wait between retries
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
export declare function retryInterval<T = any>(times: number, sleepMs: number, fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T | null>;
/**
* Similar to `Array.prototype.map`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to map over
* @param mapper - The function to apply to each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export declare function asyncmap<T, R>(coll: T[], mapper: (value: T) => R | Promise<R>, options?: MapFilterOptions): Promise<R[]>;
/**
* Similar to `Array.prototype.filter`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to filter
* @param filter - The function to test each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
export declare function asyncfilter<T>(coll: T[], filter: (value: T) => boolean | Promise<boolean>, options?: MapFilterOptions): Promise<T[]>;
/**
* Takes a condition (a function returning a boolean or boolean promise), and
* waits until the condition is true.
*
* Throws a `/Condition unmet/` error if the condition has not been satisfied
* within the allocated time, unless an error is provided in the options, as the
* `error` property, which is either thrown itself, or used as the message.
*
* The condition result is returned if it is not falsy. If the condition throws an
* error then this exception will be immediately passed through.
*
* The default options are: `{ waitMs: 5000, intervalMs: 500 }`
* @param condFn - The condition function to evaluate
* @param options - Options for controlling the wait behavior
*/
export declare function waitForCondition<T>(condFn: () => Promise<T> | T, options?: WaitForConditionOptions): Promise<T>;
export type { CancellablePromise, Progress, ProgressCallback, LongSleepOptions, SleepArg, SleepOptions, WaitForConditionOptions, } from './types.js';
//# sourceMappingURL=asyncbox.d.ts.map
{"version":3,"file":"asyncbox.d.ts","sourceRoot":"","sources":["../../lib/asyncbox.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,gBAAgB,EAEhB,YAAY,EACZ,uBAAuB,EACxB,MAAM,YAAY,CAAC;AAIpB,yEAAyE;AACzE,qBAAa,YAAa,SAAQ,KAAK;gBACzB,OAAO,CAAC,EAAE,MAAM;CAI7B;AAED,uDAAuD;AACvD,qBAAa,wBAAyB,SAAQ,KAAK;gBACrC,OAAO,GAAE,MAA4B;CAIlD;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAC5D;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,OAAO,EAAE,YAAY,GAAG,kBAAkB,CAAC,IAAI,CAAC,CAAC;AAsCvE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAAC,CAAC,EACjC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EACnB,SAAS,EAAE,MAAM,EACjB,cAAc,CAAC,EAAE,MAAM,GAAG,KAAK,GAC9B,OAAO,CAAC,CAAC,CAAC,CAsBZ;AAED;;;;;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,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,EAC5B,OAAO,GAAE,uBAA4B,GACpC,OAAO,CAAC,CAAC,CAAC,CA8BZ;AAGD,YAAY,EACV,kBAAkB,EAClB,QAAQ,EACR,gBAAgB,EAChB,gBAAgB,EAChB,QAAQ,EACR,YAAY,EACZ,uBAAuB,GACxB,MAAM,YAAY,CAAC"}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseCancellationError = exports.TimeoutError = void 0;
exports.sleep = sleep;
exports.withTimeout = withTimeout;
exports.longSleep = longSleep;
exports.retry = retry;
exports.retryInterval = retryInterval;
exports.asyncmap = asyncmap;
exports.asyncfilter = asyncfilter;
exports.waitForCondition = waitForCondition;
const p_limit_1 = require("p-limit");
const LONG_SLEEP_THRESHOLD = 5000; // anything over 5000ms will turn into a spin
/** Error thrown by {@link withTimeout} when the deadline is exceeded. */
class TimeoutError extends Error {
constructor(message) {
super(message ?? 'Operation timed out');
this.name = 'TimeoutError';
}
}
exports.TimeoutError = TimeoutError;
/** Thrown when a promise is cancelled via `cancel`. */
class PromiseCancellationError extends Error {
constructor(message = 'Promise cancelled') {
super(message);
this.name = 'PromiseCancellationError';
}
}
exports.PromiseCancellationError = PromiseCancellationError;
function sleep(arg) {
const { ms, cancelError } = parseSleepArg(arg);
let timeoutId;
let resolveFn;
let rejectFn;
const promise = new Promise((resolve, reject) => {
resolveFn = resolve;
rejectFn = reject;
timeoutId = setTimeout(resolve, ms);
});
promise.cancel = () => {
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = undefined;
}
if (cancelError === null) {
resolveFn?.(undefined);
}
else {
let err;
if (typeof cancelError === 'string' && cancelError) {
err = new PromiseCancellationError(cancelError);
}
else if (cancelError instanceof Error) {
err = cancelError;
}
else {
err = new PromiseCancellationError();
}
rejectFn?.(err);
}
resolveFn = undefined;
rejectFn = undefined;
};
return promise;
}
/**
* Resolves with `promise` or rejects if it does not settle before `timeoutMs`.
*
* If the deadline passes first: with no third argument (or a falsy non-error value), rejects
* with {@link TimeoutError} whose message includes `timeoutMs`; with a non-empty string,
* rejects with {@link TimeoutError} using that message; with an `Error` instance, rejects
* with that same instance.
*
* @param promise - Promise to race against the timeout.
* @param timeoutMs - Maximum time in milliseconds before rejecting if `promise` has not settled.
* @param messageOrError - Optional override for the timeout rejection: custom {@link TimeoutError}
* message when the string is non-empty, or an existing `Error` to reject with verbatim.
* Omitted, `undefined`, or other falsy non-error values use the default timeout message (includes `timeoutMs`).
*/
async function withTimeout(promise, timeoutMs, messageOrError) {
let timer = null;
try {
return await Promise.race([
promise,
new Promise((_resolve, reject) => {
timer = setTimeout(() => {
if (typeof messageOrError === 'string' && messageOrError) {
reject(new TimeoutError(messageOrError));
}
else if (!messageOrError) {
reject(new TimeoutError(`Operation timed out after ${timeoutMs}ms`));
}
else {
reject(messageOrError);
}
}, timeoutMs);
}),
]);
}
finally {
if (timer) {
clearTimeout(timer);
}
}
}
/**
* Sometimes `Promise.delay` or `setTimeout` are inaccurate for large wait
* times. To safely wait for these long times (e.g. in the 5+ minute range), you
* can use `longSleep`.
*
* You can also pass a `progressCb` option which is a callback function that
* receives an object with the properties `elapsedMs`, `timeLeft`, and
* `progress`. This will be called on every wait interval so you can do your
* wait logging or whatever.
* @param ms - The number of milliseconds to wait
* @param options - Options for controlling the long sleep behavior
*/
async function longSleep(ms, { thresholdMs = LONG_SLEEP_THRESHOLD, intervalMs = 1000, progressCb = null } = {}) {
if (ms < thresholdMs) {
return await sleep(ms);
}
const endAt = Date.now() + ms;
let timeLeft;
let elapsedMs = 0;
do {
const pre = Date.now();
await sleep(intervalMs);
const post = Date.now();
timeLeft = endAt - post;
elapsedMs = elapsedMs + (post - pre);
if (typeof progressCb === 'function') {
progressCb({ elapsedMs, timeLeft, progress: elapsedMs / ms });
}
} while (timeLeft > 0);
}
/**
* An async/await way of running a method until it doesn't throw an error
* @param times - The maximum number of times to retry the function
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
async function retry(times, fn, ...args) {
let tries = 0;
let done = false;
let res = null;
while (!done && tries < times) {
tries++;
try {
res = await fn(...args);
done = true;
}
catch (err) {
if (tries >= times) {
throw err;
}
}
}
return res;
}
/**
* You can also use `retryInterval` to add a sleep in between retries. This can
* be useful if you want to throttle how fast we retry.
* @param times - The maximum number of times to retry the function
* @param sleepMs - The number of milliseconds to wait between retries
* @param fn - The async function to retry
* @param args - Arguments to pass to the function
*/
async function retryInterval(times, sleepMs, fn, ...args) {
let count = 0;
const wrapped = async () => {
count++;
let res;
try {
res = await fn(...args);
}
catch (e) {
// do not pause when finished the last retry
if (count !== times) {
await sleep(sleepMs);
}
throw e;
}
return res;
};
return await retry(times, wrapped);
}
/**
* Similar to `Array.prototype.map`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to map over
* @param mapper - The function to apply to each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
async function asyncmap(coll, mapper, options = true) {
if (options === null) {
throw new Error('Options cannot be null');
}
// limitFunction requires the mapper to always return a promise
const mapperAsync = async (value) => mapper(value);
if (options === false) {
return coll.reduce(async (acc, item) => [...(await acc), await mapperAsync(item)], Promise.resolve([]));
}
const adjustedMapper = options === true ? mapperAsync : (0, p_limit_1.limitFunction)(mapperAsync, { concurrency: options.concurrency });
return Promise.all(coll.map(adjustedMapper));
}
/**
* Similar to `Array.prototype.filter`; runs in parallel, serial, or with custom concurrency pool
* @param coll - The collection to filter
* @param filter - The function to test each element
* @param options - Options for controlling parallelism (default: true - fully parallel)
*/
async function asyncfilter(coll, filter, options = true) {
if (options === null) {
throw new Error('Options cannot be null');
}
// limitFunction requires the filter to always return a promise
const filterAsync = async (value) => filter(value);
if (options === false) {
return coll.reduce(async (accP, item) => {
const acc = await accP;
if (await filterAsync(item)) {
acc.push(item);
}
return acc;
}, Promise.resolve([]));
}
const adjustedFilter = options === true ? filterAsync : (0, p_limit_1.limitFunction)(filterAsync, { concurrency: options.concurrency });
const bools = await Promise.all(coll.map(adjustedFilter));
return coll.reduce((acc, item, i) => {
if (bools[i]) {
acc.push(item);
}
return acc;
}, []);
}
/**
* Takes a condition (a function returning a boolean or boolean promise), and
* waits until the condition is true.
*
* Throws a `/Condition unmet/` error if the condition has not been satisfied
* within the allocated time, unless an error is provided in the options, as the
* `error` property, which is either thrown itself, or used as the message.
*
* The condition result is returned if it is not falsy. If the condition throws an
* error then this exception will be immediately passed through.
*
* The default options are: `{ waitMs: 5000, intervalMs: 500 }`
* @param condFn - The condition function to evaluate
* @param options - Options for controlling the wait behavior
*/
async function waitForCondition(condFn, options = {}) {
const opts = {
...options,
waitMs: typeof options.waitMs === 'number' ? options.waitMs : 5000,
intervalMs: typeof options.intervalMs === 'number' ? options.intervalMs : 500,
};
const debug = opts.logger ? opts.logger.debug.bind(opts.logger) : () => undefined;
const error = opts.error;
const begunAt = Date.now();
const endAt = begunAt + opts.waitMs;
const spin = async function spin() {
const result = await condFn();
if (result) {
return result;
}
const now = Date.now();
const waited = now - begunAt;
const remainingTime = endAt - now;
if (now < endAt) {
debug(`Waited for ${waited} ms so far`);
await sleep(Math.min(opts.intervalMs, remainingTime));
return await spin();
}
// if there is an error option, it is either a string message or an error itself
if (error) {
throw typeof error === 'string' ? new Error(error) : error;
}
throw new Error(`Condition unmet after ${waited} ms. Timing out.`);
};
return await spin();
}
/** Non-array object values (including class instances); excludes `null` and arrays. */
function isSleepArgObject(value) {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function parseSleepArg(arg) {
if (typeof arg === 'number') {
if (!Number.isFinite(arg)) {
throw new TypeError('sleep: expected a finite number or an object with ms');
}
return { ms: arg };
}
if (isSleepArgObject(arg)) {
const ms = arg.ms;
if (typeof ms !== 'number' || !Number.isFinite(ms)) {
throw new TypeError('sleep: options.ms must be a finite number');
}
return { ms, cancelError: arg.cancelError };
}
throw new TypeError('sleep: expected a finite number or an object with ms');
}
//# sourceMappingURL=asyncbox.js.map
{"version":3,"file":"asyncbox.js","sourceRoot":"","sources":["../../lib/async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CAAC;IACD,IAAI,gBAAgB,CAAC,GAAG,CAAC,EAAE,CAAC;QAC1B,MAAM,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC;QAClB,IAAI,OAAO,EAAE,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC;YACnD,MAAM,IAAI,SAAS,CAAC,2CAA2C,CAAC,CAAC;QACnE,CAAC;QACD,OAAO,EAAC,EAAE,EAAE,WAAW,EAAE,GAAG,CAAC,WAAgD,EAAC,CAAC;IACjF,CAAC;IACD,MAAM,IAAI,SAAS,CAAC,sDAAsD,CAAC,CAAC;AAC9E,CAAC"}
/**
* Parameter provided to a progress callback
*/
export interface Progress {
/** Elapsed time in milliseconds since the operation started */
elapsedMs: number;
/** Remaining time in milliseconds until the operation completes */
timeLeft: number;
/** Progress as a number between 0 and 1 (0 = not started, 1 = complete) */
progress: number;
}
/**
* Progress callback for {@link longSleep}
*/
export type ProgressCallback = (progress: Progress) => void;
/**
* Options for {@link longSleep}
*/
export interface LongSleepOptions {
/** Minimum duration in milliseconds before using long sleep behavior.
* @default 5000
*/
thresholdMs?: number;
/** Interval in milliseconds between progress callbacks.
* @default 1000
*/
intervalMs?: number;
/** Optional callback function to receive progress updates during the sleep */
progressCb?: ProgressCallback | null;
}
/**
* Options for {@link asyncmap} and {@link asyncfilter}
*/
export type MapFilterOptions = boolean | {
concurrency: number;
};
/**
* Object form of {@link sleep}'s argument: duration plus optional cancellation rejection override.
* Structural typing allows class instances; {@link sleep} accepts any non-array object with a finite `ms`.
*/
export interface SleepOptions {
/** Duration in milliseconds */
ms: number;
/**
* When {@link sleep}'s `cancel` runs: a non-empty string becomes {@link PromiseCancellationError}
* with that message; an `Error` rejects with that same instance; `null` resolves the promise
* instead of rejecting; omitted, `undefined`, or `''` use the default {@link PromiseCancellationError}.
*/
cancelError?: string | Error | null;
}
/**
* Argument to {@link sleep}: either milliseconds or an options object (see {@link SleepOptions}).
*/
export type SleepArg = number | SleepOptions;
/**
* A promise with a {@linkcode cancel} method (e.g. from {@link sleep}).
*
* @typeParam T - Resolved value type; {@link sleep} uses `void`.
*/
export type CancellablePromise<T = void> = Promise<T> & {
cancel: () => void;
};
/**
* Options for {@link waitForCondition}
*/
export interface WaitForConditionOptions {
/** Maximum time to wait in milliseconds.
* @default 5000
*/
waitMs?: number;
/** Interval in milliseconds between condition checks.
* @default 500
*/
intervalMs?: number;
/** Optional logger object with a debug method for logging wait progress */
logger?: {
debug: (...args: any[]) => void;
};
/** Custom error message (string) or Error object to throw if condition is not met.
* If not provided, a default error is thrown
*/
error?: string | Error;
}
//# sourceMappingURL=types.d.ts.map
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../lib/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,+DAA+D;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;IACjB,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8EAA8E;IAC9E,UAAU,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,OAAO,GAAG;IAAC,WAAW,EAAE,MAAM,CAAA;CAAC,CAAC;AAE/D;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,+BAA+B;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,YAAY,CAAC;AAE7C;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,CAAC,CAAC,GAAG,IAAI,IAAI,OAAO,CAAC,CAAC,CAAC,GAAG;IACtD,MAAM,EAAE,MAAM,IAAI,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,uBAAuB;IACtC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,MAAM,CAAC,EAAE;QACP,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAC;KACjC,CAAC;IACF;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACxB"}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../lib/types.ts"],"names":[],"mappings":""}