{"version":3,"file":"index.cjs","names":["#source$","#observer","#subject$","Subject","#command","_perform","#canClear","#events","#resumeActions","#lastPaused","#hasBeenPaused","#boot","#perform"],"sources":["../src/index.ts"],"sourcesContent":["import type { Observable, Observer } from 'rxjs';\nimport { Subject } from 'rxjs/internal/Subject';\nimport type { Command, Delayed, State, SubArgs } from './types';\nimport { perform as _perform } from './helpers';\n\n/**\n * Internal class that backs the {@linkcode Pausable} public type.\n *\n * The constructor is private — use {@linkcode createPausable} to obtain an\n * instance.\n *\n * @template T - The value type emitted by the source observable.\n */\nclass Pausable<T = any> {\n  readonly #source$: Observable<T>;\n  readonly #observer: SubArgs<T> | undefined;\n  readonly #subject$: Subject<T>;\n  #lastPaused = Date.now();\n  #hasBeenPaused = false;\n  #events: Delayed<T>[] = [];\n  #command: Command = 'stop';\n\n  constructor(source$: Observable<T>, observer: SubArgs<T> | undefined) {\n    this.#source$ = source$;\n    this.#observer = observer;\n    this.#subject$ = new Subject<T>();\n  }\n\n  #canClear = () => this.#command === 'pause' || this.#command === 'stop';\n\n  #perform(timer: ReturnType<typeof setTimeout>, action: () => void) {\n    return _perform(timer, this.#canClear, () => {\n      action();\n      this.#events.shift();\n    });\n  }\n\n  get #resumeActions() {\n    return {\n      next: (value: T) => this.#subject$.next(value),\n      complete: this.stop,\n\n      error: (value: unknown) => {\n        this.#subject$.error(value);\n        this.stop();\n      },\n    };\n  }\n\n  #boot() {\n    this.#command = 'start';\n    this.#events = [];\n    this.#lastPaused = Date.now();\n    this.#hasBeenPaused = false;\n\n    const arrayObserver: Observer<T> = {\n      next: value => {\n        this.#events.push({ delay: Date.now(), value, isError: false });\n      },\n      error: value => {\n        this.#events.push({ delay: Date.now(), value, isError: true });\n      },\n      complete: () => {\n        this.#events.push({\n          delay: Date.now(),\n          value: undefined as T,\n          isError: false,\n          isComplete: true,\n        });\n      },\n    };\n\n    const startObserver: Observer<T> = {\n      next: value => {\n        if (this.#canClear()) return;\n        this.#subject$.next(value);\n        this.#events.shift();\n      },\n      error: value => {\n        if (this.#canClear()) return;\n        this.#subject$.error(value);\n        this.stop();\n      },\n      complete: () => {\n        // Only forward completion immediately if we have never been paused.\n        // If we have been paused, buffered events may still need replay.\n        if (!this.#hasBeenPaused) {\n          this.stop();\n        }\n      },\n    };\n\n    this.#source$.subscribe(arrayObserver);\n    this.#subject$.subscribe(this.#observer);\n    this.#source$.subscribe(startObserver);\n  }\n\n  /**\n   * Starts consuming the bound source observable and forwarding its events\n   * to the observer.\n   *\n   * Has no effect if the instance is not currently in the `'stopped'` state.\n   */\n  start = () => {\n    if (this.#command !== 'stop') return;\n    this.#boot();\n  };\n\n  /**\n   * Stops the stream. Cancels any pending resume timers by flipping\n   * `#command` to `'stop'` (which makes `#canClear` return `true`).\n   * Has no effect if the instance is already stopped.\n   */\n  stop = () => {\n    if (this.#command === 'stop') return;\n    this.#subject$.complete();\n    this.#events.length = 0;\n    this.#command = 'stop';\n  };\n\n  /**\n   * Suspends event dispatching while continuing to buffer incoming events.\n   *\n   * Records the current timestamp as `#lastPaused` (only on the first pause\n   * of the current run) so that `resume()` can compute correct replay delays.\n   * Has no effect if the instance is already paused or stopped.\n   */\n  pause = () => {\n    if (this.#canClear()) return;\n    this.#command = 'pause';\n\n    if (!this.#hasBeenPaused) {\n      this.#lastPaused = Date.now();\n      this.#hasBeenPaused = true;\n    }\n  };\n\n  /**\n   * Replays all buffered events and then resumes live forwarding.\n   *\n   * Each buffered event is scheduled via `setTimeout` using its original\n   * timestamp relative to `#lastPaused`, preserving the source's timing.\n   * The timers are guarded by `#canClear`: if the instance is paused or\n   * stopped again before a timer fires, that timer is cancelled.\n   *\n   * Has no effect if the instance is not currently paused.\n   */\n  resume = () => {\n    if (this.#command !== 'pause') return;\n    this.#command = 'resume';\n    const actions = this.#resumeActions;\n\n    for (const { delay, value, isError, isComplete } of this.#events) {\n      const timeout = delay - this.#lastPaused;\n\n      const timer = setTimeout(() => {\n        return this.#perform(timer, () => {\n          if (isError) return actions.error(value);\n          if (isComplete) return actions.complete();\n          return actions.next(value);\n        });\n      }, timeout);\n    }\n  };\n\n  /**\n   * Subscribes an additional observer to the internal subject.\n   *\n   * Unlike the observer passed to {@linkcode createPausable}, this subscriber\n   * is registered dynamically and receives the same forwarded events subject\n   * to the same pause/resume/stop lifecycle controls.\n   *\n   * @param observer - The subscriber to add. Accepts either a plain `next`\n   *   callback or a partial {@linkcode Observer}.\n   * @returns An RxJS `Subscription` that can be used to unsubscribe.\n   */\n  subscribe = (observer: SubArgs<T>) => this.#subject$.subscribe(observer);\n\n  /**\n   * Dispatches a no-argument lifecycle command by name.\n   *\n   * Equivalent to calling the corresponding method directly. Useful when\n   * the command is determined dynamically.\n   *\n   * @param action - The {@linkcode Command} to execute.\n   */\n  command = (action: Command) => {\n    return this[action]();\n  };\n\n  /**\n   * The current observable state of the instance, derived from `#command`.\n   *\n   * - `'stopped'` when `#command` is `'stop'`.\n   * - `'running'` when `#command` is `'start'` or `'resume'`.\n   * - `'paused'`  when `#command` is `'pause'`.\n   */\n  get state(): State {\n    return this.#command === 'stop'\n      ? 'stopped'\n      : this.#command === 'start' || this.#command === 'resume'\n        ? 'running'\n        : 'paused';\n  }\n}\n\nexport type { Pausable };\n\nexport type CreatePausable_F = <T = any>(\n  source$: Observable<T>,\n  observer?: SubArgs<T>,\n) => Pausable<T>;\n\n/**\n * Creates a {@linkcode Pausable} wrapper around a source RxJS observable.\n *\n * The returned object lets you `start`, `stop`, `pause`, and `resume`\n * the flow of events from `source$` to `observer`. Events that\n * arrive while the instance is paused are timestamped and buffered; when\n * `resume` is called they are replayed to the observer with their original\n * relative timing preserved.\n *\n * @template T - The value type emitted by the source observable.\n *\n * @param source$ - The RxJS observable whose emissions should be controlled.\n * @param observer - Optional subscriber that receives forwarded events.\n *   Accepts either a plain `next` callback or a partial {@linkcode Observer}.\n *\n * @returns A {@linkcode Pausable} instance exposing lifecycle controls and a\n *   read-only `state` property.\n *\n * @example\n * ```ts\n * import { interval } from 'rxjs';\n * import { createPausable } from '@bemedev/rx-pausable';\n *\n * const pausable = createPausable(interval(1000), value => console.log(value));\n * pausable.start();\n *\n * setTimeout(() => pausable.pause(),  3500);\n * setTimeout(() => pausable.resume(), 6000);\n * setTimeout(() => pausable.stop(),   9000);\n * ```\n */\nexport const createPausable: CreatePausable_F = (source$, observer) => {\n  return new Pausable(source$, observer);\n};\n\nexport * from './types';\n"],"mappings":";;;;;;;;;;;;;AAaA,IAAM,WAAN,MAAwB;CACtB;CACA;CACA;CACA,cAAc,KAAK,KAAK;CACxB,iBAAiB;CACjB,UAAwB,EAAE;CAC1B,WAAoB;CAEpB,YAAY,SAAwB,UAAkC;AACpE,QAAA,UAAgB;AAChB,QAAA,WAAiB;AACjB,QAAA,WAAiB,IAAIG,eAAAA,SAAY;;CAGnC,kBAAkB,MAAA,YAAkB,WAAW,MAAA,YAAkB;CAEjE,SAAS,OAAsC,QAAoB;AACjE,SAAOE,gBAAAA,QAAS,OAAO,MAAA,gBAAsB;AAC3C,WAAQ;AACR,SAAA,OAAa,OAAO;IACpB;;CAGJ,KAAA,gBAAqB;AACnB,SAAO;GACL,OAAO,UAAa,MAAA,SAAe,KAAK,MAAM;GAC9C,UAAU,KAAK;GAEf,QAAQ,UAAmB;AACzB,UAAA,SAAe,MAAM,MAAM;AAC3B,SAAK,MAAM;;GAEd;;CAGH,QAAQ;AACN,QAAA,UAAgB;AAChB,QAAA,SAAe,EAAE;AACjB,QAAA,aAAmB,KAAK,KAAK;AAC7B,QAAA,gBAAsB;EAEtB,MAAM,gBAA6B;GACjC,OAAM,UAAS;AACb,UAAA,OAAa,KAAK;KAAE,OAAO,KAAK,KAAK;KAAE;KAAO,SAAS;KAAO,CAAC;;GAEjE,QAAO,UAAS;AACd,UAAA,OAAa,KAAK;KAAE,OAAO,KAAK,KAAK;KAAE;KAAO,SAAS;KAAM,CAAC;;GAEhE,gBAAgB;AACd,UAAA,OAAa,KAAK;KAChB,OAAO,KAAK,KAAK;KACjB,OAAO,KAAA;KACP,SAAS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