import * as Errors from '../Errors.js';
/** @internal */
export function withTimeout(fn, options) {
    const { errorInstance = new TimeoutError(), timeout, signal } = options;
    return new Promise((resolve, reject) => {
        ;
        (async () => {
            let timeoutId;
            try {
                const controller = new AbortController();
                if (timeout > 0)
                    timeoutId = setTimeout(() => {
                        if (signal) {
                            controller.abort();
                        }
                        else {
                            reject(errorInstance);
                        }
                    }, timeout);
                resolve(await fn({ signal: controller.signal }));
            }
            catch (err) {
                if (err?.name === 'AbortError')
                    reject(errorInstance);
                reject(err);
            }
            finally {
                clearTimeout(timeoutId);
            }
        })();
    });
}
/** @internal */
/**
 * Thrown when an operation times out.
 * @internal
 */
export class TimeoutError extends Errors.BaseError {
    constructor() {
        super('Operation timed out.');
        Object.defineProperty(this, "name", {
            enumerable: true,
            configurable: true,
            writable: true,
            value: 'Promise.TimeoutError'
        });
    }
}
//# sourceMappingURL=promise.js.map