"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.timeout = exports.TimeoutError = void 0;
const async_js_1 = require("../scheduler/async.js");
const isDate_js_1 = require("../util/isDate.js");
const Observable_js_1 = require("../Observable.js");
const executeSchedule_js_1 = require("../util/executeSchedule.js");
class TimeoutError extends Error {
    info;
    constructor(info = null) {
        super('Timeout has occurred');
        this.info = info;
        this.name = 'TimeoutError';
    }
}
exports.TimeoutError = TimeoutError;
function timeout(config, schedulerArg) {
    const { first, each, with: _with = timeoutErrorFactory, scheduler = schedulerArg ?? async_js_1.asyncScheduler, meta = null, } = ((0, isDate_js_1.isValidDate)(config) ? { first: config } : typeof config === 'number' ? { each: config } : config);
    if (first == null && each == null) {
        throw new TypeError('No timeout provided.');
    }
    return (source) => new Observable_js_1.Observable((destination) => {
        let originalSourceSubscription;
        let timerSubscription;
        let lastValue = null;
        let seen = 0;
        const startTimer = (delay) => {
            timerSubscription = (0, executeSchedule_js_1.executeSchedule)(destination, scheduler, () => {
                try {
                    originalSourceSubscription.unsubscribe();
                    (0, Observable_js_1.from)(_with({
                        meta,
                        lastValue,
                        seen,
                    })).subscribe(destination);
                }
                catch (err) {
                    destination.error(err);
                }
            }, delay);
        };
        originalSourceSubscription = source.subscribe((0, Observable_js_1.operate)({
            destination,
            next: (value) => {
                timerSubscription?.unsubscribe();
                seen++;
                destination.next((lastValue = value));
                each > 0 && startTimer(each);
            },
            finalize: () => {
                timerSubscription?.unsubscribe();
                lastValue = null;
            },
        }));
        !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler.now()) : each);
    });
}
exports.timeout = timeout;
function timeoutErrorFactory(info) {
    throw new TimeoutError(info);
}//# sourceMappingURL=http://go/sourcemap/sourcemaps/bf249e6efb5b097f23d7e21d7283429f0760b740/node_modules/rxjs/dist/cjs/internal/operators/timeout.js.map