apitally
Version:
Simple API monitoring & analytics for REST APIs built with Express, Fastify, NestJS, AdonisJS, Hono, H3, Elysia, and Koa.
1 lines • 1.26 MB
Source Map (JSON)
{"version":3,"sources":["../../node_modules/rxjs/src/internal/util/isFunction.ts","../../node_modules/rxjs/src/internal/util/createErrorClass.ts","../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","../../node_modules/rxjs/src/internal/util/arrRemove.ts","../../node_modules/rxjs/src/internal/Subscription.ts","../../node_modules/rxjs/src/internal/config.ts","../../node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts","../../node_modules/rxjs/src/internal/util/reportUnhandledError.ts","../../node_modules/rxjs/src/internal/util/noop.ts","../../node_modules/rxjs/src/internal/NotificationFactories.ts","../../node_modules/rxjs/src/internal/util/errorContext.ts","../../node_modules/rxjs/src/internal/Subscriber.ts","../../node_modules/rxjs/src/internal/symbol/observable.ts","../../node_modules/rxjs/src/internal/util/identity.ts","../../node_modules/rxjs/src/internal/util/pipe.ts","../../node_modules/rxjs/src/internal/Observable.ts","../../node_modules/rxjs/src/internal/util/lift.ts","../../node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts","../../node_modules/rxjs/src/internal/operators/refCount.ts","../../node_modules/rxjs/src/internal/observable/ConnectableObservable.ts","../../node_modules/rxjs/src/internal/scheduler/performanceTimestampProvider.ts","../../node_modules/rxjs/src/internal/scheduler/animationFrameProvider.ts","../../node_modules/rxjs/src/internal/observable/dom/animationFrames.ts","../../node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts","../../node_modules/rxjs/src/internal/Subject.ts","../../node_modules/rxjs/src/internal/BehaviorSubject.ts","../../node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts","../../node_modules/rxjs/src/internal/ReplaySubject.ts","../../node_modules/rxjs/src/internal/AsyncSubject.ts","../../node_modules/rxjs/src/internal/scheduler/Action.ts","../../node_modules/rxjs/src/internal/scheduler/intervalProvider.ts","../../node_modules/rxjs/src/internal/scheduler/AsyncAction.ts","../../node_modules/rxjs/src/internal/util/Immediate.ts","../../node_modules/rxjs/src/internal/scheduler/immediateProvider.ts","../../node_modules/rxjs/src/internal/scheduler/AsapAction.ts","../../node_modules/rxjs/src/internal/Scheduler.ts","../../node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts","../../node_modules/rxjs/src/internal/scheduler/AsapScheduler.ts","../../node_modules/rxjs/src/internal/scheduler/asap.ts","../../node_modules/rxjs/src/internal/scheduler/async.ts","../../node_modules/rxjs/src/internal/scheduler/QueueAction.ts","../../node_modules/rxjs/src/internal/scheduler/QueueScheduler.ts","../../node_modules/rxjs/src/internal/scheduler/queue.ts","../../node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts","../../node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts","../../node_modules/rxjs/src/internal/scheduler/animationFrame.ts","../../node_modules/rxjs/src/internal/scheduler/VirtualTimeScheduler.ts","../../node_modules/rxjs/src/internal/observable/empty.ts","../../node_modules/rxjs/src/internal/util/isScheduler.ts","../../node_modules/rxjs/src/internal/util/args.ts","../../node_modules/rxjs/src/internal/util/isArrayLike.ts","../../node_modules/rxjs/src/internal/util/isPromise.ts","../../node_modules/rxjs/src/internal/util/isInteropObservable.ts","../../node_modules/rxjs/src/internal/util/isAsyncIterable.ts","../../node_modules/rxjs/src/internal/util/throwUnobservableError.ts","../../node_modules/rxjs/src/internal/symbol/iterator.ts","../../node_modules/rxjs/src/internal/util/isIterable.ts","../../node_modules/rxjs/src/internal/util/isReadableStreamLike.ts","../../node_modules/rxjs/src/internal/observable/innerFrom.ts","../../node_modules/rxjs/src/internal/util/executeSchedule.ts","../../node_modules/rxjs/src/internal/operators/observeOn.ts","../../node_modules/rxjs/src/internal/operators/subscribeOn.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts","../../node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts","../../node_modules/rxjs/src/internal/scheduled/scheduled.ts","../../node_modules/rxjs/src/internal/observable/from.ts","../../node_modules/rxjs/src/internal/observable/of.ts","../../node_modules/rxjs/src/internal/observable/throwError.ts","../../node_modules/rxjs/src/internal/Notification.ts","../../node_modules/rxjs/src/internal/util/isObservable.ts","../../node_modules/rxjs/src/internal/util/EmptyError.ts","../../node_modules/rxjs/src/internal/lastValueFrom.ts","../../node_modules/rxjs/src/internal/firstValueFrom.ts","../../node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts","../../node_modules/rxjs/src/internal/util/NotFoundError.ts","../../node_modules/rxjs/src/internal/util/SequenceError.ts","../../node_modules/rxjs/src/internal/util/isDate.ts","../../node_modules/rxjs/src/internal/operators/timeout.ts","../../node_modules/rxjs/src/internal/operators/map.ts","../../node_modules/rxjs/src/internal/util/mapOneOrManyArgs.ts","../../node_modules/rxjs/src/internal/observable/bindCallbackInternals.ts","../../node_modules/rxjs/src/internal/observable/bindCallback.ts","../../node_modules/rxjs/src/internal/observable/bindNodeCallback.ts","../../node_modules/rxjs/src/internal/util/argsArgArrayOrObject.ts","../../node_modules/rxjs/src/internal/util/createObject.ts","../../node_modules/rxjs/src/internal/observable/combineLatest.ts","../../node_modules/rxjs/src/internal/operators/mergeInternals.ts","../../node_modules/rxjs/src/internal/operators/mergeMap.ts","../../node_modules/rxjs/src/internal/operators/mergeAll.ts","../../node_modules/rxjs/src/internal/operators/concatAll.ts","../../node_modules/rxjs/src/internal/observable/concat.ts","../../node_modules/rxjs/src/internal/observable/defer.ts","../../node_modules/rxjs/src/internal/observable/connectable.ts","../../node_modules/rxjs/src/internal/observable/forkJoin.ts","../../node_modules/rxjs/src/internal/observable/fromEvent.ts","../../node_modules/rxjs/src/internal/observable/fromEventPattern.ts","../../node_modules/rxjs/src/internal/observable/generate.ts","../../node_modules/rxjs/src/internal/observable/iif.ts","../../node_modules/rxjs/src/internal/observable/timer.ts","../../node_modules/rxjs/src/internal/observable/interval.ts","../../node_modules/rxjs/src/internal/observable/merge.ts","../../node_modules/rxjs/src/internal/observable/never.ts","../../node_modules/rxjs/src/internal/util/argsOrArgArray.ts","../../node_modules/rxjs/src/internal/observable/onErrorResumeNext.ts","../../node_modules/rxjs/src/internal/observable/pairs.ts","../../node_modules/rxjs/src/internal/util/not.ts","../../node_modules/rxjs/src/internal/operators/filter.ts","../../node_modules/rxjs/src/internal/observable/partition.ts","../../node_modules/rxjs/src/internal/observable/race.ts","../../node_modules/rxjs/src/internal/observable/range.ts","../../node_modules/rxjs/src/internal/observable/using.ts","../../node_modules/rxjs/src/internal/observable/zip.ts","../../node_modules/rxjs/dist/cjs/internal/types.js","../../node_modules/rxjs/src/internal/operators/audit.ts","../../node_modules/rxjs/src/internal/operators/auditTime.ts","../../node_modules/rxjs/src/internal/operators/buffer.ts","../../node_modules/rxjs/src/internal/operators/bufferCount.ts","../../node_modules/rxjs/src/internal/operators/bufferTime.ts","../../node_modules/rxjs/src/internal/operators/bufferToggle.ts","../../node_modules/rxjs/src/internal/operators/bufferWhen.ts","../../node_modules/rxjs/src/internal/operators/catchError.ts","../../node_modules/rxjs/src/internal/operators/scanInternals.ts","../../node_modules/rxjs/src/internal/operators/reduce.ts","../../node_modules/rxjs/src/internal/operators/toArray.ts","../../node_modules/rxjs/src/internal/operators/joinAllInternals.ts","../../node_modules/rxjs/src/internal/operators/combineLatestAll.ts","../../node_modules/rxjs/src/internal/operators/combineAll.ts","../../node_modules/rxjs/src/internal/operators/combineLatest.ts","../../node_modules/rxjs/src/internal/operators/combineLatestWith.ts","../../node_modules/rxjs/src/internal/operators/concatMap.ts","../../node_modules/rxjs/src/internal/operators/concatMapTo.ts","../../node_modules/rxjs/src/internal/operators/concat.ts","../../node_modules/rxjs/src/internal/operators/concatWith.ts","../../node_modules/rxjs/src/internal/observable/fromSubscribable.ts","../../node_modules/rxjs/src/internal/operators/connect.ts","../../node_modules/rxjs/src/internal/operators/count.ts","../../node_modules/rxjs/src/internal/operators/debounce.ts","../../node_modules/rxjs/src/internal/operators/debounceTime.ts","../../node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts","../../node_modules/rxjs/src/internal/operators/take.ts","../../node_modules/rxjs/src/internal/operators/ignoreElements.ts","../../node_modules/rxjs/src/internal/operators/mapTo.ts","../../node_modules/rxjs/src/internal/operators/delayWhen.ts","../../node_modules/rxjs/src/internal/operators/delay.ts","../../node_modules/rxjs/src/internal/operators/dematerialize.ts","../../node_modules/rxjs/src/internal/operators/distinct.ts","../../node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts","../../node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts","../../node_modules/rxjs/src/internal/operators/throwIfEmpty.ts","../../node_modules/rxjs/src/internal/operators/elementAt.ts","../../node_modules/rxjs/src/internal/operators/endWith.ts","../../node_modules/rxjs/src/internal/operators/every.ts","../../node_modules/rxjs/src/internal/operators/exhaustMap.ts","../../node_modules/rxjs/src/internal/operators/exhaustAll.ts","../../node_modules/rxjs/src/internal/operators/exhaust.ts","../../node_modules/rxjs/src/internal/operators/expand.ts","../../node_modules/rxjs/src/internal/operators/finalize.ts","../../node_modules/rxjs/src/internal/operators/find.ts","../../node_modules/rxjs/src/internal/operators/findIndex.ts","../../node_modules/rxjs/src/internal/operators/first.ts","../../node_modules/rxjs/src/internal/operators/groupBy.ts","../../node_modules/rxjs/src/internal/operators/isEmpty.ts","../../node_modules/rxjs/src/internal/operators/takeLast.ts","../../node_modules/rxjs/src/internal/operators/last.ts","../../node_modules/rxjs/src/internal/operators/materialize.ts","../../node_modules/rxjs/src/internal/operators/max.ts","../../node_modules/rxjs/src/internal/operators/flatMap.ts","../../node_modules/rxjs/src/internal/operators/mergeMapTo.ts","../../node_modules/rxjs/src/internal/operators/mergeScan.ts","../../node_modules/rxjs/src/internal/operators/merge.ts","../../node_modules/rxjs/src/internal/operators/mergeWith.ts","../../node_modules/rxjs/src/internal/operators/min.ts","../../node_modules/rxjs/src/internal/operators/multicast.ts","../../node_modules/rxjs/src/internal/operators/onErrorResumeNextWith.ts","../../node_modules/rxjs/src/internal/operators/pairwise.ts","../../node_modules/rxjs/src/internal/operators/pluck.ts","../../node_modules/rxjs/src/internal/operators/publish.ts","../../node_modules/rxjs/src/internal/operators/publishBehavior.ts","../../node_modules/rxjs/src/internal/operators/publishLast.ts","../../node_modules/rxjs/src/internal/operators/publishReplay.ts","../../node_modules/rxjs/src/internal/operators/raceWith.ts","../../node_modules/rxjs/src/internal/operators/repeat.ts","../../node_modules/rxjs/src/internal/operators/repeatWhen.ts","../../node_modules/rxjs/src/internal/operators/retry.ts","../../node_modules/rxjs/src/internal/operators/retryWhen.ts","../../node_modules/rxjs/src/internal/operators/sample.ts","../../node_modules/rxjs/src/internal/operators/sampleTime.ts","../../node_modules/rxjs/src/internal/operators/scan.ts","../../node_modules/rxjs/src/internal/operators/sequenceEqual.ts","../../node_modules/rxjs/src/internal/operators/share.ts","../../node_modules/rxjs/src/internal/operators/shareReplay.ts","../../node_modules/rxjs/src/internal/operators/single.ts","../../node_modules/rxjs/src/internal/operators/skip.ts","../../node_modules/rxjs/src/internal/operators/skipLast.ts","../../node_modules/rxjs/src/internal/operators/skipUntil.ts","../../node_modules/rxjs/src/internal/operators/skipWhile.ts","../../node_modules/rxjs/src/internal/operators/startWith.ts","../../node_modules/rxjs/src/internal/operators/switchMap.ts","../../node_modules/rxjs/src/internal/operators/switchAll.ts","../../node_modules/rxjs/src/internal/operators/switchMapTo.ts","../../node_modules/rxjs/src/internal/operators/switchScan.ts","../../node_modules/rxjs/src/internal/operators/takeUntil.ts","../../node_modules/rxjs/src/internal/operators/takeWhile.ts","../../node_modules/rxjs/src/internal/operators/tap.ts","../../node_modules/rxjs/src/internal/operators/throttle.ts","../../node_modules/rxjs/src/internal/operators/throttleTime.ts","../../node_modules/rxjs/src/internal/operators/timeInterval.ts","../../node_modules/rxjs/src/internal/operators/timeoutWith.ts","../../node_modules/rxjs/src/internal/operators/timestamp.ts","../../node_modules/rxjs/src/internal/operators/window.ts","../../node_modules/rxjs/src/internal/operators/windowCount.ts","../../node_modules/rxjs/src/internal/operators/windowTime.ts","../../node_modules/rxjs/src/internal/operators/windowToggle.ts","../../node_modules/rxjs/src/internal/operators/windowWhen.ts","../../node_modules/rxjs/src/internal/operators/withLatestFrom.ts","../../node_modules/rxjs/src/internal/operators/zipAll.ts","../../node_modules/rxjs/src/internal/operators/zip.ts","../../node_modules/rxjs/src/internal/operators/zipWith.ts","../../node_modules/rxjs/src/index.ts","../../src/common/consumerRegistry.ts","../../src/common/logging.ts","../../src/common/paramValidation.ts","../../src/common/requestCounter.ts","../../src/common/sentry.ts","../../src/common/serverErrorCounter.ts","../../src/common/tempGzipFile.ts","../../src/common/requestLogger.ts","../../src/common/validationErrorCounter.ts","../../src/common/client.ts","../../src/common/headers.ts","../../src/common/packageVersions.ts","../../src/loggers/console.ts","../../src/loggers/utils.ts","../../src/loggers/nestjs.ts","../../node_modules/pino-std-serializers/lib/err-helpers.js","../../node_modules/pino-std-serializers/lib/err-proto.js","../../node_modules/pino-std-serializers/lib/err.js","../../node_modules/pino-std-serializers/lib/err-with-cause.js","../../node_modules/pino-std-serializers/lib/req.js","../../node_modules/pino-std-serializers/lib/res.js","../../node_modules/pino-std-serializers/index.js","../../node_modules/pino/lib/caller.js","../../node_modules/fast-redact/lib/validator.js","../../node_modules/fast-redact/lib/rx.js","../../node_modules/fast-redact/lib/parse.js","../../node_modules/fast-redact/lib/redactor.js","../../node_modules/fast-redact/lib/modifiers.js","../../node_modules/fast-redact/lib/restorer.js","../../node_modules/fast-redact/lib/state.js","../../node_modules/fast-redact/index.js","../../node_modules/pino/lib/symbols.js","../../node_modules/pino/lib/redaction.js","../../node_modules/pino/lib/time.js","../../node_modules/quick-format-unescaped/index.js","../../node_modules/atomic-sleep/index.js","../../node_modules/sonic-boom/index.js","../../node_modules/on-exit-leak-free/index.js","../../node_modules/thread-stream/package.json","../../node_modules/thread-stream/lib/wait.js","../../node_modules/thread-stream/lib/indexes.js","../../node_modules/thread-stream/index.js","../../node_modules/pino/lib/transport.js","../../node_modules/pino/lib/tools.js","../../node_modules/pino/lib/constants.js","../../node_modules/pino/lib/levels.js","../../node_modules/pino/lib/meta.js","../../node_modules/pino/lib/proto.js","../../node_modules/safe-stable-stringify/index.js","../../node_modules/pino/lib/multistream.js","../../node_modules/pino/pino.js","../../src/loggers/pino.ts","../../src/loggers/winston.ts","../../src/loggers/index.ts","../../src/express/utils.js","../../src/express/middleware.ts","../../src/express/index.ts","../../src/fastify/plugin.ts","../../src/fastify/index.ts","../../src/nestjs/index.ts"],"sourcesContent":["/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n","/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass<T>(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n","import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\n}\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n","/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove<T>(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n","import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n */\nexport class Subscription implements SubscriptionLike {\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude<TeardownLogic, void>[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude<TeardownLogic, void>): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n","import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification<any>, subscriber: Subscriber<any>) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: PromiseConstructorLike;\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n","import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n","/* tslint:disable:no-empty */\nexport function noop() { }\n","import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification<T>(value: T) {\n return createNotification('N', value, undefined) as NextNotification<T>;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n","import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n","import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create<T>(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber<T> {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber<any> | Observer<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber<any> | Observer<any>) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param value The `next` value.\n */\n next(value: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\n this._next(value!);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param err The `error` exception.\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind<Fn extends (...args: any[]) => any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver<T> implements Observer<T> {\n constructor(private partialObserver: Partial<Observer<T>>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber<T> extends Subscriber<T> {\n constructor(\n observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial<Observer<T>>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as ((value: T) => void) | undefined,\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent.\n * @param subscriber The stopped subscriber.\n */\nfunction handleStoppedNotification(notification: ObservableNotification<any>, subscriber: Subscriber<any>) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly<Observer<any>> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n","/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n","/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `<T>(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity<T>(x: T): T {\n return x;\n}\n","import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>\n): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>\n): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>\n): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>\n): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>\n): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>,\n fn9: UnaryFunction<H, I>\n): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>,\n fn9: UnaryFunction<H, I>,\n ...fns: UnaryFunction<any, any>[]\n): UnaryFunction<T, unknown>;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \n */\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n if (fns.length === 0) {\n return identity as UnaryFunction<any, any>;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n };\n}\n","import { Operator } from './Operator';\nimport { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n */\nexport class Observable<T> implements Subscribable<T> {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable<any> | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator<any, T> | undefined;\n\n /**\n * @param subscribe The function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new Observable by calling the Observable constructor\n * @param subscribe the subscriber function to be passed to the Observable constructor\n * @return A new observable.\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @param operator the operator defining the operation to take on the observable\n * @return A new observable with the Operator applied.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\n */\n lift<R>(operator?: Operator<T, R>): Observable<R> {\n const observable = new Observable<R>();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})\n *\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // 'Adding: 1'\n * // 'Adding: 2'\n * // 'Adding: 3'\n * // 'Sum equals: 6'\n * ```\n *\n * Cancel a subscription\n *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * });\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 'unsubscribed!' after 2.5s\n * ```\n *\n * @param observerOrNext Either an {@link Observer} with some or all callback methods,\n * or the `next` handler that is called for each value emitted from the subscribed Observable.\n * @param error A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param complete A handler for a terminal event resulting from successful completion.\n * @return A subscription reference to the registered handlers.\n */\n subscribe(\n observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next A handler for each value emitted by the observable.\n * @return A promise that either resolves on observable completion or\n * rejects with the handled error.\n */\n forEach(next: (value: T) => void): Promise<void>;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise<void>;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n const subscriber = new SafeSubscriber<T>({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise<void>;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @return This instance of the observable.\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable<T>;\n pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n pipe<A, B, C, D>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>\n ): Observable<D>;\n pipe<A, B, C, D, E>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>\n ): Observable<E>;\n pipe<A, B, C, D, E, F>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>\n ): Observable<F>;\n pipe<A, B, C, D, E, F, G>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>\n ): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>\n ): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>,\n op9: OperatorFunction<H, I>\n ): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>,\n op9: OperatorFunction<H, I>,\n ...operations: OperatorFunction<any, any>[]\n ): Observable<unknown>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x));\n * ```\n *\n * @return The Observable result of all the operators having been called\n * in the order they were passed in.\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise<T | undefined>;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise<T | undefined>;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise<T | undefined>;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise<T | undefined>;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver<T>(value: any): value is Observer<T> {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber<T>(value: any): value is Subscriber<T> {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType<typeof Observable>['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate<T, R>(\n init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => (() => void) | void\n): OperatorFunction<T, R> {\n return (source: Observable<T>) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber<R>, liftedSource: Observable<T>) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber<T>(\n destination: Subscriber<any>,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber<T> {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber<T> extends Subscriber<T> {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber<any>,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber<T>, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber<T>, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber<T>) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n","import { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Make a {@link ConnectableObservable} behave like a ordinary observable and automates the way\n * you can connect to it.\n *\n * Internally it counts the subscriptions to the observable and subscribes (only once) to the source if\n * the number of subscriptions is larger than 0. If the number of subscriptions is smaller than 1, it\n * unsubscribes from the source. This way you can make sure that everything before the *published*\n * refCount has only a single subscription independently of the number of subscribers to the target\n * observable.\n *\n * Note that using the {@link share} operator is exactly the same as using the `multicast(() => new Subject())` operator\n * (making the observable hot) and the *refCount* operator in a sequence.\n *\n * \n *\n * ## Example\n *\n * In the following example there are two intervals turned into connectable observables\n * by using the *publish* operator. The first one uses the *refCount* operator, the\n * second one does not use it. You will notice that a connectable observable does nothing\n * until you call its connect function.\n *\n * ```ts\n * import { interval, tap, publish, refCount } from 'rxjs';\n *\n * // Turn the interval observable into a ConnectableObservable (hot)\n * const refCountInterval = interval(400).pipe(\n * tap(num => console.log(`refCount ${ num }`)),\n * publish(),\n * refCount()\n * );\n *\n * const publishedInterval = interval(400).pipe(\n * tap(num => console.log(`publish ${ num }`)),\n * publish()\n * );\n *\n * refCountInterval.subscribe();\n * refCountInterval.subscribe();\n * // 'refCount 0' -----> 'refCount 1' -----> etc\n * // All subscriptions will receive the same value and the tap (and\n * // every other operator) before the `publish` operator will be executed\n * // only once per event independently of the number of subscriptions.\n *\n * publishedInterval.subscribe();\n * // Nothing happens until you call .connect() on the observable.\n * ```\n *\n * @return A function that returns an Observable that automates the connection\n * to ConnectableObservable.\n * @see {@link ConnectableObservable}\n * @see {@link share}\n * @see {@link publish}\n * @deprecated Replaced with the {@link share} operator. How `share` is used\n * will depend on the connectable observable you created just prior to the\n * `refCount` operator.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function refCount<T>(): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let connection: Subscription | null = null;\n\n (source as any)._refCount++;\n\n const refCounter = createOperatorSubscriber(subscriber, undefined, undefined, undefined, () => {\n if (!source || (source as any)._refCount <= 0 || 0 < --(source as any)._refCount) {\n connection = null;\n return;\n }\n\n ///\n // Compare the local RefCountSubscriber's connection Subscription to the\n // connection Subscription on the shared ConnectableObservable. In cases\n // where the ConnectableObservable source synchronously emits values, and\n // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n // execution continues to here before the RefCountOperator has a chance to\n // supply the RefCountSubscriber with the shared connection Subscription.\n // For example:\n // ```\n // range(0, 10).pipe(\n // publish(),\n // refCount(),\n // take(5),\n // )\n // .subscribe();\n // ```\n // In order to account for this case, RefCountSubscriber should only dispose\n // the ConnectableObservable's shared connection Subscription if the\n // connection Subscription exists, *and* either:\n // a. RefCountSubscriber doesn't have a reference to the shared connection\n // Subscription yet, or,\n // b. RefCountSubscriber's connection Subscription reference is identical\n // to the shared connection Subscription\n ///\n\n const sharedConnection = (source as any)._connection;\n const conn = connection;\n connection = null;\n\n if (sharedConnection && (!conn || sharedConnection === conn)) {\n sharedConnection.unsubscribe();\n }\n\n subscriber.unsubscribe();\n });\n\n source.subscribe(refCounter);\n\n if (!refCounter.closed) {\n connection = (source as ConnectableObservable<T>).connect();\n }\n });\n}\n","import { Subject } from '../Subject';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { hasLift } from '../util/lift';\n\n/**\n * @class ConnectableObservable<T>\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * If you are using the `refCount` method of `ConnectableObservable`, use the {@link share} operator\n * instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport class ConnectableObservable<T> extends Observable<T> {\n protected _subject: Subject<T> | null = null;\n protected _refCount: number = 0;\n protected _connection: Subscription | null = null;\n\n /**\n * @param source The source observable\n * @param subjectFactory The factory that creates the subject used internally.\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * `new ConnectableObservable(source, factory)` is equivalent to\n * `connectable(source, { connector: factory })`.\n * When the `refCount()` method is needed, the {@link share} operator should be used instead:\n * `new ConnectableObservable(source, factory).refCount()` is equivalent to\n * `source.pipe(share({ connector: factory }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n constructor(public source: Observable<T>, protected subjectFactory: () => Subject<T>) {\n super();\n // If we have lift, monkey patch that here. This is done so custom observable\n // types will compose through multicast. Otherwise the resulting observable would\n // simply be an instance of `ConnectableObservable`.\n if (hasLift(source)) {\n this.lift = source.lift;\n }\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>) {\n return this.getSubject().subscribe(subscriber);\n }\n\n protected getSubject(): Subject<T> {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject!;\n }\n\n protected _teardown() {\n this._refCount = 0;\n const { _connection } = this;\n this._subject = this._connection = null;\n _connection?.unsubscribe();\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use {@link connectable} instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n connect(): Subscription {\n let connection = this._connection;\n if (!connection) {\n connection = this._connection = new Subscription();\n const subject = this.getSubject();\n connection.add(\n this.source.subscribe(\n createOperatorSubscriber(\n subject as any,\n undefined,\n () => {\n this._teardown();\n subject.complete();\n },\n (err) => {\n this._teardown();\n subject.error(err);\n },\n () => this._teardown()\n )\n )\n );\n\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use the {@link share} operator instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n refCount(): Observable<T> {\n return higherOrderRefCount()(this) as Observable<T>;\n }\n}\n","import { TimestampProvider } from '../types';\n\ninterface PerformanceTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const performanceTimestampProvider: PerformanceTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (performanceTimestampProvider.delegate || performance).now();\n },\n delegate: undefined,\n};\n","import { Subscription } from '../Subscription';\n\ninterface AnimationFrameProvider {\n schedule(callback: FrameRequestCallback): Subscription;\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n delegate:\n | {\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n }\n | undefined;\n}\n\nexport const animationFrameProvider: AnimationFrameProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n schedule(callback) {\n let request = requestAnimationFrame;\n let cancel: typeof cancelAnimationFrame | undefined = cancelAnimationFrame;\n const { delegate } = animationFrameProvider;\n if (delegate) {\n request = delegate.requestAnimationFrame;\n cancel = delegate.cancelAnimationFrame;\n }\n const handle = request((timestamp) => {\n // Clear the cancel function. The request has been fulfilled, so\n // attempting to cancel the request upon unsubscription would be\n // pointless.\n cancel = undefined;\n callback(timestamp);\n });\n return new Subscription(() => cancel?.(handle));\n },\n requestAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.requestAnimationFrame || requestAnimationFrame)(...args);\n },\n cancelAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.cancelAnimationFrame || cancelAnimationFrame)(...args);\n },\n delegate: undefined,\n};\n","import { Observable } from '../../Observable';\nimport { TimestampProvider } from '../../types';\nimport { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider';\nimport { animationFrameProvider } from '../../scheduler/animationFrameProvider';\n\n/**\n * An observable of animation frames\n *\n * Emits the amount of time elapsed since subscription and the timestamp on each animation frame.\n * Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own.\n *\n * Every subscription will start a separate animation loop. Since animation frames are always scheduled\n * by the browser to occur directly before a repaint, scheduling more than one animation frame synchronously\n * should not be much different or have more overhead than looping over an array of events during\n * a single animation frame. However, if for some reason the developer would like to ensure the\n * execution of animation-related handlers are all executed during the same task by the engine,\n * the `share` operator can be used.\n *\n * This is useful for setting up animations with RxJS.\n *\n * ## Examples\n *\n * Tweening a div to move it on the screen\n *\n * ```ts\n * import { animationFrames, map, takeWhile, endWith } from 'rxjs';\n *\n * function tween(start: number, end: number, duration: number) {\n * const diff = end - start;\n * return animationFrames().pipe(\n * // Figure out what percentage of time has passed\n * map(({ elapsed }) => elapsed / duration),\n * // Take the vector while less than 100%\n * takeWhile(v => v < 1),\n * // Finish with 100%\n * endWith(1),\n * // Calculate the distance traveled between start and end\n * map(v => v * diff + start)\n * );\n * }\n *\n * // Setup a div for us to move around\n * const div = document.createElement('div');\n * document.body.appendChild(div);\n * div.style.position = 'absolute';\n * div.style.width = '40px';\n * div.style.height = '40px';\n * div.style.backgroundColor = 'lime';\n * div.style.transform = 'translate3d(10px, 0, 0)';\n *\n * tween(10, 200, 4000).subscribe(x => {\n * div.style.transform = `translate3d(${ x }px, 0, 0)`;\n * });\n * ```\n *\n * Providing a custom timestamp provider\n *\n * ```ts\n * import { animationFrames, TimestampProvider } from 'rxjs';\n *\n * // A custom timestamp provider\n * let now = 0;\n * const customTSProvider: TimestampProvider = {\n * now() { return now++; }\n * };\n *\n * const source$ = animationFrames(customTSProvider);\n *\n * // Log increasing numbers 0...1...2... on every animation frame.\n * source$.subscribe(({ elapsed }) => console.log(elapsed));\n * ```\n *\n * @param timestampProvider An object with a `now` method that provides a numeric timestamp\n */\nexport function animationFrames(timestampProvider?: TimestampProvider) {\n return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;\n}\n\n/**\n * Does the work of creating the observable for `animationFrames`.\n * @param timestampProvider The timestamp provider to use to create the observable\n */\nfunction animationFramesFactory(timestampProvider?: TimestampProvider) {\n return new Observable<{ timestamp: number; elapsed: number }>((subscriber) => {\n // If no timestamp provider is specified, use performance.now() - as it\n // will return timestamps 'compatible' with those passed to the run\n // callback and won't be affected by NTP adjustments, etc.\n const provider = timestampProvider || performanceTimestampProvider;\n\n // Capture the start time upon subscription, as the run callback can remain\n // queued for a considerable period of time and the elapsed time should\n // represent the time elapsed since subscription - not the time since the\n // first rendered animation frame.\n const start = provider.now();\n\n let id = 0;\n const run = () => {\n if (!subscriber.closed) {\n id = animationFrameProvider.requestAnimationFrame((timestamp: DOMHighResTimeStamp | number) => {\n id = 0;\n // Use the provider's timestamp to calculate the elapsed time. Note that\n // this means - if the caller hasn't passed a provider - that\n // performance.now() will be used instead of the timestamp that was\n // passed to the run callback. The reason for this is that the timestamp\n // passed to the callback can be earlier than the start time, as it\n // represents the time at which the browser decided it would render any\n // queued frames - and that time can be earlier the captured start time.\n const now = provider.now();\n subscriber.next({\n timestamp: timestampProvider ? now : timestamp,\n elapsed: now - start,\n });\n run();\n });\n }\n };\n\n run();\n\n return () => {\n if (id) {\n animationFrameProvider.cancelAnimationFrame(id);\n }\n };\n });\n}\n\n/**\n * In the common case, where the timestamp provided by the rAF API is used,\n * we use this shared observable to reduce overhead.\n */\nconst DEFAULT_ANIMATION_FRAMES = animationFramesFactory();\n","import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\n}\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n","import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n */\nexport class Subject<T> extends Observable<T> implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer<T>[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer<T>[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {\n return new AnonymousSubject<T>(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber<any>) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber<any>) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return Observable that this Subject casts to.\n */\n asObservable(): Observable<T> {\n const observable: any = new Observable<T>();\n observable.source = this;\n return observable;\n }\n}\n\nexport class AnonymousSubject<T> extends Subject<T> {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer<T>,\n source?: Observable<T>\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n */\nexport class BehaviorSubject<T> extends Subject<T> {\n constructor(private _value: T) {\n super();\n }\n\n get value(): T {\n return this.getValue();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n const subscription = super._subscribe(subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n }\n\n getValue(): T {\n const { hasError, thrownError, _value } = this;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n }\n\n next(value: T): void {\n super.next((this._value = value));\n }\n}\n","import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n","import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject<T> extends Subject<T> {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param _bufferSize The size of the buffer to replay on subscription\n * @param _windowTime The amount of time the buffered items will stay buffered\n * @param _timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\n\n/**\n * A variant of Subject that only emits a value when it completes. It will emit\n * its latest value to all its observers on completion.\n */\nexport class AsyncSubject<T> extends Subject<T> {\n private _value: T | null = null;\n private _hasValue = false;\n private _isComplete = false;\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber<T>) {\n const { hasError, _hasValue, _value, thrownError, isStopped, _isComplete } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped || _isComplete) {\n _hasValue && subscriber.next(_value!);\n subscriber.complete();\n }\n }\n\n next(value: T): void {\n if (!this.isStopped) {\n this._value = value;\n this._hasValue = true;\n }\n }\n\n complete(): void {\n const { _hasValue, _value, _isComplete } = this;\n if (!_isComplete) {\n this._isComplete = true;\n _hasValue && super.next(_value!);\n super.complete();\n }\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action<T> extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n */\nexport class Action<T> extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction<T>, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param state Some contextual data that the `work` function uses when called by the\n * Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is implicit\n * and defined by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n","import type { TimerHandle } from './timerHandle';\ntype SetIntervalFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearIntervalFunction = (handle: TimerHandle) => void;\n\ninterface IntervalProvider {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n delegate:\n | {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n }\n | undefined;\n}\n\nexport const intervalProvider: IntervalProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setInterval(handler: () => void, timeout?: number, ...args) {\n const { delegate } = intervalProvider;\n if (delegate?.setInterval) {\n return delegate.setInterval(handler, timeout, ...args);\n }\n return setInterval(handler, timeout, ...args);\n },\n clearInterval(handle) {\n const { delegate } = intervalProvider;\n return (delegate?.clearInterval || clearInterval)(handle as any);\n },\n delegate: undefined,\n};\n","import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { intervalProvider } from './intervalProvider';\nimport { arrRemove } from '../util/arrRemove';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncAction<T> extends Action<T> {\n public id: TimerHandle | undefined;\n public state?: T;\n // @ts-ignore: Property has no initializer and is not definitely assigned\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id ?? this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, _id?: TimerHandle, delay: number = 0): TimerHandle {\n return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(_scheduler: AsyncScheduler, id?: TimerHandle, delay: number | null = 0): TimerHandle | undefined {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay != null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n if (id != null) {\n intervalProvider.clearInterval(id);\n }\n\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n */\n public execute(state: T, delay: number): any {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, _delay: number): any {\n let errored: boolean = false;\n let errorValue: any;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n // HACK: Since code elsewhere is relying on the \"truthiness\" of the\n // return here, we can't have it return \"\" or 0 or false.\n // TODO: Clean this up when we refactor schedulers mid-version-8 or so.\n errorValue = e ? e : new Error('Scheduled action threw falsy error');\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n unsubscribe() {\n if (!this.closed) {\n const { id, scheduler } = this;\n const { actions } = scheduler;\n\n this.work = this.state = this.scheduler = null!;\n this.pending = false;\n\n arrRemove(actions, this);\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null!;\n super.unsubscribe();\n }\n }\n}\n","let nextHandle = 1;\n// The promise needs to be created lazily otherwise it won't be patched by Zones\nlet resolved: Promise<any>;\nconst activeHandles: { [key: number]: any } = {};\n\n/**\n * Finds the handle in the list of active handles, and removes it.\n * Returns `true` if found, `false` otherwise. Used both to clear\n * Immediate scheduled tasks, and to identify if a task should be scheduled.\n */\nfunction findAndClearHandle(handle: number): boolean {\n if (handle in activeHandles) {\n delete activeHandles[handle];\n return true;\n }\n return false;\n}\n\n/**\n * Helper functions to schedule and unschedule microtasks.\n */\nexport const Immediate = {\n setImmediate(cb: () => void): number {\n const handle = nextHandle++;\n activeHandles[handle] = true;\n if (!resolved) {\n resolved = Promise.resolve();\n }\n resolved.then(() => findAndClearHandle(handle) && cb());\n return handle;\n },\n\n clearImmediate(handle: number): void {\n findAndClearHandle(handle);\n },\n};\n\n/**\n * Used for internal testing purposes only. Do not export from library.\n */\nexport const TestTools = {\n pending() {\n return Object.keys(activeHandles).length;\n }\n};\n","import { Immediate } from '../util/Immediate';\nimport type { TimerHandle } from './timerHandle';\nconst { setImmediate, clearImmediate } = Immediate;\n\ntype SetImmediateFunction = (handler: () => void, ...args: any[]) => TimerHandle;\ntype ClearImmediateFunction = (handle: TimerHandle) => void;\n\ninterface ImmediateProvider {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n delegate:\n | {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n }\n | undefined;\n}\n\nexport const immediateProvider: ImmediateProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setImmediate(...args) {\n const { delegate } = immediateProvider;\n return (delegate?.setImmediate || setImmediate)(...args);\n },\n clearImmediate(handle) {\n const { delegate } = immediateProvider;\n return (delegate?.clearImmediate || clearImmediate)(handle as any);\n },\n delegate: undefined,\n};\n","import { AsyncAction } from './AsyncAction';\nimport { AsapScheduler } from './AsapScheduler';\nimport { SchedulerAction } from '../types';\nimport { immediateProvider } from './immediateProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsapAction<T> extends AsyncAction<T> {\n constructor(protected scheduler: AsapScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If a microtask has already been scheduled, don't schedule another\n // one. If a microtask hasn't been scheduled yet, schedule one now. Return\n // the current scheduled microtask id.\n return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));\n }\n\n protected recycleAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested microtask and set the scheduled flag to undefined\n // so the next AsapAction will request its own.\n const { actions } = scheduler;\n if (id != null && actions[actions.length - 1]?.id !== id) {\n immediateProvider.clearImmediate(id);\n if (scheduler._scheduled === id) {\n scheduler._scheduled = undefined;\n }\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n","import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}. Will be made internal in v8.\n */\nexport class Scheduler implements SchedulerLike {\n public static now: () => number = dateTimestampProvider.now;\n\n constructor(private schedulerActionCtor: typeof Action, now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param work A function representing a task, or some unit of work to be\n * executed by the Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is\n * implicit and defined by the Scheduler itself.\n * @param state Some contextual data that the `work` function uses when called\n * by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.schedulerActionCtor<T>(this, work).schedule(state, delay);\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncScheduler extends Scheduler {\n public actions: Array<AsyncAction<any>> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @internal\n */\n public _active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @internal\n */\n public _scheduled: TimerHandle | undefined;\n\n constructor(SchedulerAction: typeof Action, now: () => number = Scheduler.now) {\n super(SchedulerAction, now);\n }\n\n public flush(action: AsyncAction<any>): void {\n const { actions } = this;\n\n if (this._active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this._active = true;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions.shift()!)); // exhaust the scheduler queue\n\n this._active = false;\n\n if (error) {\n while ((action = actions.shift()!)) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AsapScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction<any>): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n const flushId = this._scheduled;\n this._scheduled = undefined;\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsapAction } from './AsapAction';\nimport { AsapScheduler } from './AsapScheduler';\n\n/**\n *\n * Asap Scheduler\n *\n * <span class=\"informal\">Perform task as fast as it can be performed asynchronously</span>\n *\n * `asap` scheduler behaves the same as {@link asyncScheduler} scheduler when you use it to delay task\n * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing\n * code to end and then it will try to execute given task as fast as possible.\n *\n * `asap` scheduler will do its best to minimize time between end of currently executing code\n * and start of scheduled task. This makes it best candidate for performing so called \"deferring\".\n * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves\n * some (although minimal) unwanted delay.\n *\n * Note that using `asap` scheduler does not necessarily mean that your task will be first to process\n * after currently executing code. In particular, if some task was also scheduled with `asap` before,\n * that task will execute first. That being said, if you need to schedule task asynchronously, but\n * as soon as possible, `asap` scheduler is your best bet.\n *\n * ## Example\n * Compare async and asap scheduler<\n * ```ts\n * import { asapScheduler, asyncScheduler } from 'rxjs';\n *\n * asyncScheduler.schedule(() => console.log('async')); // scheduling 'async' first...\n * asapScheduler.schedule(() => console.log('asap'));\n *\n * // Logs:\n * // \"asap\"\n * // \"async\"\n * // ... but 'asap' goes first!\n * ```\n */\n\nexport const asapScheduler = new AsapScheduler(AsapAction);\n\n/**\n * @deprecated Renamed to {@link asapScheduler}. Will be removed in v8.\n */\nexport const asap = asapScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * <span class=\"informal\">Schedule task as if you used setTimeout(task, duration)</span>\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\n\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated Renamed to {@link asyncScheduler}. Will be removed in v8.\n */\nexport const async = asyncScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class QueueAction<T> extends AsyncAction<T> {\n constructor(protected scheduler: QueueScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n\n public execute(state: T, delay: number): any {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n\n protected requestAsyncId(scheduler: QueueScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n\n if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n\n // Otherwise flush the scheduler starting with this action.\n scheduler.flush(this);\n\n // HACK: In the past, this was returning `void`. However, `void` isn't a valid\n // `TimerHandle`, and generally the return value here isn't really used. So the\n // compromise is to return `0` which is both \"falsy\" and a valid `TimerHandle`,\n // as opposed to refactoring every other instanceo of `requestAsyncId`.\n return 0;\n }\n}\n","import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n","import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * <span class=\"informal\">Put every next task on a queue, instead of executing it immediately</span>\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n * queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n * console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n * if (state !== 0) {\n * console.log('before', state);\n * this.schedule(state - 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * console.log('after', state);\n * }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n */\n\nexport const queueScheduler = new QueueScheduler(QueueAction);\n\n/**\n * @deprecated Renamed to {@link queueScheduler}. Will be removed in v8.\n */\nexport const queue = queueScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\nimport { animationFrameProvider } from './animationFrameProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AnimationFrameAction<T> extends AsyncAction<T> {\n constructor(protected scheduler: AnimationFrameScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If an animation frame has already been requested, don't request another\n // one. If an animation frame hasn't been requested yet, request one. Return\n // the current animation frame request id.\n return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(() => scheduler.flush(undefined)));\n }\n\n protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested animation frame and set the scheduled flag to\n // undefined so the next AnimationFrameAction will request its own.\n const { actions } = scheduler;\n if (id != null && id === scheduler._scheduled && actions[actions.length - 1]?.id !== id) {\n animationFrameProvider.cancelAnimationFrame(id as number);\n scheduler._scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction<any>): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n let flushId;\n if (action) {\n flushId = action.id;\n } else {\n flushId = this._scheduled;\n this._scheduled = undefined;\n }\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * <span class=\"informal\">Perform task when `window.requestAnimationFrame` would fire</span>\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html: <div style=\"background: #0ff;\"></div>\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n * div.style.height = height + \"px\";\n *\n * this.schedule(height + 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n */\n\nexport const animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction);\n\n/**\n * @deprecated Renamed to {@link animationFrameScheduler}. Will be removed in v8.\n */\nexport const animationFrame = animationFrameScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class VirtualTimeScheduler extends AsyncScheduler {\n /** @deprecated Not used in VirtualTimeScheduler directly. Will be removed in v8. */\n static frameTimeFactor = 10;\n\n /**\n * The current frame for the state of the virtual scheduler instance. The difference\n * between two \"frames\" is synonymous with the passage of \"virtual time units\". So if\n * you record `scheduler.frame` to be `1`, then later, observe `scheduler.frame` to be at `11`,\n * that means `10` virtual time units have passed.\n */\n public frame: number = 0;\n\n /**\n * Used internally to examine the current virtual action index being processed.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n public index: number = -1;\n\n /**\n * This creates an instance of a `VirtualTimeScheduler`. Experts only. The signature of\n * this constructor is likely to change in the long run.\n *\n * @param schedulerActionCtor The type of Action to initialize when initializing actions during scheduling.\n * @param maxFrames The maximum number of frames to process before stopping. Used to prevent endless flush cycles.\n */\n constructor(schedulerActionCtor: typeof AsyncAction = VirtualAction as any, public maxFrames: number = Infinity) {\n super(schedulerActionCtor, () => this.frame);\n }\n\n /**\n * Prompt the Scheduler to execute all of its queued actions, therefore\n * clearing its queue.\n */\n public flush(): void {\n const { actions, maxFrames } = this;\n let error: any;\n let action: AsyncAction<any> | undefined;\n\n while ((action = actions[0]) && action.delay <= maxFrames) {\n actions.shift();\n this.frame = action.delay;\n\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n }\n\n if (error) {\n while ((action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n\nexport class VirtualAction<T> extends AsyncAction<T> {\n protected active: boolean = true;\n\n constructor(\n protected scheduler: VirtualTimeScheduler,\n protected work: (this: SchedulerAction<T>, state?: T) => void,\n protected index: number = (scheduler.index += 1)\n ) {\n super(scheduler, work);\n this.index = scheduler.index = index;\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (Number.isFinite(delay)) {\n if (!this.id) {\n return super.schedule(state, delay);\n }\n this.active = false;\n // If an action is rescheduled, we save allocations by mutating its state,\n // pushing it to the end of the scheduler queue, and recycling the action.\n // But since the VirtualTimeScheduler is used for testing, VirtualActions\n // must be immutable so they can be inspected later.\n const action = new VirtualAction(this.scheduler, this.work);\n this.add(action);\n return action.schedule(state, delay);\n } else {\n // If someone schedules something with Infinity, it'll never happen. So we\n // don't even schedule it.\n return Subscription.EMPTY;\n }\n }\n\n protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle {\n this.delay = scheduler.frame + delay;\n const { actions } = scheduler;\n actions.push(this);\n (actions as Array<VirtualAction<T>>).sort(VirtualAction.sortActions);\n return 1;\n }\n\n protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle | undefined {\n return undefined;\n }\n\n protected _execute(state: T, delay: number): any {\n if (this.active === true) {\n return super._execute(state, delay);\n }\n }\n\n private static sortActions<T>(a: VirtualAction<T>, b: VirtualAction<T>) {\n if (a.delay === b.delay) {\n if (a.index === b.index) {\n return 0;\n } else if (a.index > b.index) {\n return 1;\n } else {\n return -1;\n }\n } else if (a.delay > b.delay) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * <span class=\"informal\">Just emits 'complete', and nothing else.</span>\n *\n * \n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable<never>((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable<never>((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n","import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n","import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last<T>(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n","export const isArrayLike = (<T>(x: any): x is ArrayLike<T> => x && typeof x.length === 'number' && typeof x !== 'function');","import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return isFunction(value?.then);\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n return isFunction(input[Symbol_observable]);\n}\n","import { isFunction } from './isFunction';\n\nexport function isAsyncIterable<T>(obj: any): obj is AsyncIterable<T> {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n","/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\n}\n","export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return isFunction(input?.[Symbol_iterator]);\n}\n","import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator<T>(readableStream: ReadableStreamLike<T>): AsyncGenerator<T> {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike<T>(obj: any): obj is ReadableStreamLike<T> {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an <iframe>.\n return isFunction(obj?.getReader);\n}\n","import { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { ObservableInput, ObservedValueOf, ReadableStreamLike } from '../types';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { Subscriber } from '../Subscriber';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\nexport function innerFrom<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\nexport function innerFrom<T>(input: ObservableInput<T>): Observable<T> {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n\n throw createInvalidObservableTypeError(input);\n}\n\n/**\n * Creates an RxJS Observable from an object that implements `Symbol.observable`.\n * @param obj An object that properly implements `Symbol.observable`.\n */\nexport function fromInteropObservable<T>(obj: any) {\n return new Observable((subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\n\n/**\n * Synchronously emits the values of an array like and completes.\n * This is exported because there are creation functions and operators that need to\n * make direct use of the same logic, and there's no reason to make them run through\n * `from` conditionals because we *know* they're dealing with an array.\n * @param array The array to emit values from\n */\nexport function fromArrayLike<T>(array: ArrayLike<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n // Loop over the array and emit each value. Note two things here:\n // 1. We're making sure that the subscriber is not closed on each loop.\n // This is so we don't continue looping over a very large array after\n // something like a `take`, `takeWhile`, or other synchronous unsubscription\n // has already unsubscribed.\n // 2. In this form, reentrant code can alter that array we're looping over.\n // This is a known issue, but considered an edge case. The alternative would\n // be to copy the array before executing the loop, but this has\n // performance implications.\n for (let i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\n\nexport function fromPromise<T>(promise: PromiseLike<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n promise\n .then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, reportUnhandledError);\n });\n}\n\nexport function fromIterable<T>(iterable: Iterable<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n for (const value of iterable) {\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n });\n}\n\nexport function fromAsyncIterable<T>(asyncIterable: AsyncIterable<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n process(asyncIterable, subscriber).catch((err) => subscriber.error(err));\n });\n}\n\nexport function fromReadableStreamLike<T>(readableStream: ReadableStreamLike<T>) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\n\nasync function process<T>(asyncIterable: AsyncIterable<T>, subscriber: Subscriber<T>) {\n for await (const value of asyncIterable) {\n subscriber.next(value);\n // A side-effect may have closed our subscriber,\n // check before the next iteration.\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n}\n","import { Subscription } from '../Subscription';\nimport { SchedulerAction, SchedulerLike } from '../types';\n\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay: number,\n repeat: true\n): void;\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay?: number,\n repeat?: false\n): Subscription;\n\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay = 0,\n repeat = false\n): Subscription | void {\n const scheduleSubscription = scheduler.schedule(function (this: SchedulerAction<any>) {\n work();\n if (repeat) {\n parentSubscription.add(this.schedule(null, delay));\n } else {\n this.unsubscribe();\n }\n }, delay);\n\n parentSubscription.add(scheduleSubscription);\n\n if (!repeat) {\n // Because user-land scheduler implementations are unlikely to properly reuse\n // Actions for repeat scheduling, we can't trust that the returned subscription\n // will control repeat subscription scenarios. So we're trying to avoid using them\n // incorrectly within this library.\n return scheduleSubscription;\n }\n}\n","/** @prettier */\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Re-emits all notifications from source Observable with specified scheduler.\n *\n * <span class=\"informal\">Ensure a specific scheduler is used, from outside of an Observable.</span>\n *\n * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule\n * notifications emitted by the source Observable. It might be useful, if you do not have control over\n * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.\n *\n * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,\n * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal\n * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits\n * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.\n * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split\n * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source\n * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a\n * little bit more, to ensure that they are emitted at expected moments.\n *\n * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications\n * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`\n * will delay all notifications - including error notifications - while `delay` will pass through error\n * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator\n * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used\n * for notification emissions in general.\n *\n * ## Example\n *\n * Ensure values in subscribe are called just before browser repaint\n *\n * ```ts\n * import { interval, observeOn, animationFrameScheduler } from 'rxjs';\n *\n * const someDiv = document.createElement('div');\n * someDiv.style.cssText = 'width: 200px;background: #09c';\n * document.body.appendChild(someDiv);\n * const intervals = interval(10); // Intervals are scheduled\n * // with async scheduler by default...\n * intervals.pipe(\n * observeOn(animationFrameScheduler) // ...but we will observe on animationFrame\n * ) // scheduler to ensure smooth animation.\n * .subscribe(val => {\n * someDiv.style.height = val + 'px';\n * });\n * ```\n *\n * @see {@link delay}\n *\n * @param scheduler Scheduler that will be used to reschedule notifications from source Observable.\n * @param delay Number of milliseconds that states with what delay every notification should be rescheduled.\n * @return A function that returns an Observable that emits the same\n * notifications as the source Observable, but with provided scheduler.\n */\nexport function observeOn<T>(scheduler: SchedulerLike, delay = 0): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => executeSchedule(subscriber, scheduler, () => subscriber.next(value), delay),\n () => executeSchedule(subscriber, scheduler, () => subscriber.complete(), delay),\n (err) => executeSchedule(subscriber, scheduler, () => subscriber.error(err), delay)\n )\n );\n });\n}\n","import { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\n\n/**\n * Asynchronously subscribes Observers to this Observable on the specified {@link SchedulerLike}.\n *\n * With `subscribeOn` you can decide what type of scheduler a specific Observable will be using when it is subscribed to.\n *\n * Schedulers control the speed and order of emissions to observers from an Observable stream.\n *\n * \n *\n * ## Example\n *\n * Given the following code:\n *\n * ```ts\n * import { of, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3);\n * const b = of(4, 5, 6);\n *\n * merge(a, b).subscribe(console.log);\n *\n * // Outputs\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * // 6\n * ```\n *\n * Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to.\n *\n * If we instead use the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emitted by Observable `a`:\n *\n * ```ts\n * import { of, subscribeOn, asyncScheduler, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3).pipe(subscribeOn(asyncScheduler));\n * const b = of(4, 5, 6);\n *\n * merge(a, b).subscribe(console.log);\n *\n * // Outputs\n * // 4\n * // 5\n * // 6\n * // 1\n * // 2\n * // 3\n * ```\n *\n * The reason for this is that Observable `b` emits its values directly and synchronously like before\n * but the emissions from `a` are scheduled on the event loop because we are now using the {@link asyncScheduler} for that specific Observable.\n *\n * @param scheduler The {@link SchedulerLike} to perform subscription actions on.\n * @param delay A delay to pass to the scheduler to delay subscriptions\n * @return A function that returns an Observable modified so that its\n * subscriptions happen on the specified {@link SchedulerLike}.\n */\nexport function subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n subscriber.add(scheduler.schedule(() => source.subscribe(subscriber), delay));\n });\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { InteropObservable, SchedulerLike } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { SchedulerLike } from '../types';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>((subscriber) => {\n // The current array index.\n let i = 0;\n // Start iterating over the array like on a schedule.\n return scheduler.schedule(function () {\n if (i === input.length) {\n // If we have hit the end of the array like in the\n // previous job, we can complete.\n subscriber.complete();\n } else {\n // Otherwise let's next the value at the current index,\n // then increment our index.\n subscriber.next(input[i++]);\n // If the last emission didn't cause us to close the subscriber\n // (via take or some side effect), reschedule the job and we'll\n // make another pass.\n if (!subscriber.closed) {\n this.schedule();\n }\n }\n });\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from '../util/isFunction';\nimport { executeSchedule } from '../util/executeSchedule';\n\n/**\n * Used in {@link scheduled} to create an observable from an Iterable.\n * @param input The iterable to create an observable from\n * @param scheduler The scheduler to use\n */\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n return new Observable<T>((subscriber) => {\n let iterator: Iterator<T, T>;\n\n // Schedule the initial creation of the iterator from\n // the iterable. This is so the code in the iterable is\n // not called until the scheduled job fires.\n executeSchedule(subscriber, scheduler, () => {\n // Create the iterator.\n iterator = (input as any)[Symbol_iterator]();\n\n executeSchedule(\n subscriber,\n scheduler,\n () => {\n let value: T;\n let done: boolean | undefined;\n try {\n // Pull the value out of the iterator\n ({ value, done } = iterator.next());\n } catch (err) {\n // We got an error while pulling from the iterator\n subscriber.error(err);\n return;\n }\n\n if (done) {\n // If it is \"done\" we just complete. This mimics the\n // behavior of JavaScript's `for..of` consumption of\n // iterables, which will not emit the value from an iterator\n // result of `{ done: true: value: 'here' }`.\n subscriber.complete();\n } else {\n // The iterable is not done, emit the value.\n subscriber.next(value);\n }\n },\n 0,\n true\n );\n });\n\n // During finalization, if we see this iterator has a `return` method,\n // then we know it is a Generator, and not just an Iterator. So we call\n // the `return()` function. This will ensure that any `finally { }` blocks\n // inside of the generator we can hit will be hit properly.\n return () => isFunction(iterator?.return) && iterator.return();\n });\n}\n","import { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function scheduleAsyncIterable<T>(input: AsyncIterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>((subscriber) => {\n executeSchedule(subscriber, scheduler, () => {\n const iterator = input[Symbol.asyncIterator]();\n executeSchedule(\n subscriber,\n scheduler,\n () => {\n iterator.next().then((result) => {\n if (result.done) {\n // This will remove the subscriptions from\n // the parent subscription.\n subscriber.complete();\n } else {\n subscriber.next(result.value);\n }\n });\n },\n 0,\n true\n );\n });\n });\n}\n","import { SchedulerLike, ReadableStreamLike } from '../types';\nimport { Observable } from '../Observable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\n\nexport function scheduleReadableStreamLike<T>(input: ReadableStreamLike<T>, scheduler: SchedulerLike): Observable<T> {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isReadableStreamLike } from '../util/isReadableStreamLike';\nimport { scheduleReadableStreamLike } from './scheduleReadableStreamLike';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see {@link from}\n * @see {@link of}\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n }\n if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n if (isAsyncIterable(input)) {\n return scheduleAsyncIterable(input, scheduler);\n }\n if (isIterable(input)) {\n return scheduleIterable(input, scheduler);\n }\n if (isReadableStreamLike(input)) {\n return scheduleReadableStreamLike(input, scheduler);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike | undefined): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * \n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from, take } from 'rxjs';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * With `asyncScheduler`\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // 'start'\n * // 'end'\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param input A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param scheduler An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return An Observable converted from {@link ObservableInput}.\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n","import { SchedulerLike, ValueFromArray } from '../types';\nimport { Observable } from '../Observable';\nimport { popScheduler } from '../util/args';\nimport { from } from './from';\n\n// Devs are more likely to pass null or undefined than they are a scheduler\n// without accompanying values. To make things easier for (naughty) devs who\n// use the `strictNullChecks: false` TypeScript compiler option, these\n// overloads with explicit null and undefined values are included.\n\nexport function of(value: null): Observable<null>;\nexport function of(value: undefined): Observable<undefined>;\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function of(scheduler: SchedulerLike): Observable<never>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function of<A extends readonly unknown[]>(...valuesAndScheduler: [...A, SchedulerLike]): Observable<ValueFromArray<A>>;\n\nexport function of(): Observable<never>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function of<T>(): Observable<T>;\nexport function of<T>(value: T): Observable<T>;\nexport function of<A extends readonly unknown[]>(...values: A): Observable<ValueFromArray<A>>;\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * <span class=\"informal\">Each argument becomes a `next` notification.</span>\n *\n * \n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe({\n * next: value => console.log('next:', value),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // Outputs\n * // next: 10\n * // next: 20\n * // next: 30\n * // the end\n * ```\n *\n * Emit the array `[1, 2, 3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1, 2, 3])\n * .subscribe({\n * next: value => console.log('next:', value),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // Outputs\n * // next: [1, 2, 3]\n * // the end\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param args A comma separated list of arguments you want to be emitted.\n * @return An Observable that synchronously emits the arguments described\n * above and then immediately completes.\n */\nexport function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {\n const scheduler = popScheduler(args);\n return from(args as T[], scheduler);\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { SchedulerLike } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * Creates an observable that will create an error instance and push it to the consumer as an error\n * immediately upon subscription.\n *\n * <span class=\"informal\">Just errors and does nothing else</span>\n *\n * \n *\n * This creation function is useful for creating an observable that will create an error and error every\n * time it is subscribed to. Generally, inside of most operators when you might want to return an errored\n * observable, this is unnecessary. In most cases, such as in the inner return of {@link concatMap},\n * {@link mergeMap}, {@link defer}, and many others, you can simply throw the error, and RxJS will pick\n * that up and notify the consumer of the error.\n *\n * ## Example\n *\n * Create a simple observable that will create a new error with a timestamp and log it\n * and the message every time you subscribe to it\n *\n * ```ts\n * import { throwError } from 'rxjs';\n *\n * let errorCount = 0;\n *\n * const errorWithTimestamp$ = throwError(() => {\n * const error: any = new Error(`This is error number ${ ++errorCount }`);\n * error.timestamp = Date.now();\n * return error;\n * });\n *\n * errorWithTimestamp$.subscribe({\n * error: err => console.log(err.timestamp, err.message)\n * });\n *\n * errorWithTimestamp$.subscribe({\n * error: err => console.log(err.timestamp, err.message)\n * });\n *\n * // Logs the timestamp and a new error message for each subscription\n * ```\n *\n * ### Unnecessary usage\n *\n * Using `throwError` inside of an operator or creation function\n * with a callback, is usually not necessary\n *\n * ```ts\n * import { of, concatMap, timer, throwError } from 'rxjs';\n *\n * const delays$ = of(1000, 2000, Infinity, 3000);\n *\n * delays$.pipe(\n * concatMap(ms => {\n * if (ms < 10000) {\n * return timer(ms);\n * } else {\n * // This is probably overkill.\n * return throwError(() => new Error(`Invalid time ${ ms }`));\n * }\n * })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * You can just throw the error instead\n *\n * ```ts\n * import { of, concatMap, timer } from 'rxjs';\n *\n * const delays$ = of(1000, 2000, Infinity, 3000);\n *\n * delays$.pipe(\n * concatMap(ms => {\n * if (ms < 10000) {\n * return timer(ms);\n * } else {\n * // Cleaner and easier to read for most folks.\n * throw new Error(`Invalid time ${ ms }`);\n * }\n * })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * @param errorFactory A factory function that will create the error instance that is pushed.\n */\nexport function throwError(errorFactory: () => any): Observable<never>;\n\n/**\n * Returns an observable that will error with the specified error immediately upon subscription.\n *\n * @param error The error instance to emit\n * @deprecated Support for passing an error value will be removed in v8. Instead, pass a factory function to `throwError(() => new Error('test'))`. This is\n * because it will create the error at the moment it should be created and capture a more appropriate stack trace. If\n * for some reason you need to create the error ahead of time, you can still do that: `const err = new Error('test'); throwError(() => err);`.\n */\nexport function throwError(error: any): Observable<never>;\n\n/**\n * Notifies the consumer of an error using a given scheduler by scheduling it at delay `0` upon subscription.\n *\n * @param errorOrErrorFactory An error instance or error factory\n * @param scheduler A scheduler to use to schedule the error notification\n * @deprecated The `scheduler` parameter will be removed in v8.\n * Use `throwError` in combination with {@link observeOn}: `throwError(() => new Error('test')).pipe(observeOn(scheduler));`.\n * Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function throwError(errorOrErrorFactory: any, scheduler: SchedulerLike): Observable<never>;\n\nexport function throwError(errorOrErrorFactory: any, scheduler?: SchedulerLike): Observable<never> {\n const errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory;\n const init = (subscriber: Subscriber<never>) => subscriber.error(errorFactory());\n return new Observable(scheduler ? (subscriber) => scheduler.schedule(init as any, 0, subscriber) : init);\n}\n","import { PartialObserver, ObservableNotification, CompleteNotification, NextNotification, ErrorNotification } from './types';\nimport { Observable } from './Observable';\nimport { EMPTY } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nimport { isFunction } from './util/isFunction';\n\n// TODO: When this enum is removed, replace it with a type alias. See #4556.\n/**\n * @deprecated Use a string literal instead. `NotificationKind` will be replaced with a type alias in v8.\n * It will not be replaced with a const enum as those are not compatible with isolated modules.\n */\nexport enum NotificationKind {\n NEXT = 'N',\n ERROR = 'E',\n COMPLETE = 'C',\n}\n\n/**\n * Represents a push-based event or value that an {@link Observable} can emit.\n * This class is particularly useful for operators that manage notifications,\n * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and\n * others. Besides wrapping the actual delivered value, it also annotates it\n * with metadata of, for instance, what type of push message it is (`next`,\n * `error`, or `complete`).\n *\n * @see {@link materialize}\n * @see {@link dematerialize}\n * @see {@link observeOn}\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\nexport class Notification<T> {\n /**\n * A value signifying that the notification will \"next\" if observed. In truth,\n * This is really synonymous with just checking `kind === \"N\"`.\n * @deprecated Will be removed in v8. Instead, just check to see if the value of `kind` is `\"N\"`.\n */\n readonly hasValue: boolean;\n\n /**\n * Creates a \"Next\" notification object.\n * @param kind Always `'N'`\n * @param value The value to notify with if observed.\n * @deprecated Internal implementation detail. Use {@link Notification#createNext createNext} instead.\n */\n constructor(kind: 'N', value?: T);\n /**\n * Creates an \"Error\" notification object.\n * @param kind Always `'E'`\n * @param value Always `undefined`\n * @param error The error to notify with if observed.\n * @deprecated Internal implementation detail. Use {@link Notification#createError createError} instead.\n */\n constructor(kind: 'E', value: undefined, error: any);\n /**\n * Creates a \"completion\" notification object.\n * @param kind Always `'C'`\n * @deprecated Internal implementation detail. Use {@link Notification#createComplete createComplete} instead.\n */\n constructor(kind: 'C');\n constructor(public readonly kind: 'N' | 'E' | 'C', public readonly value?: T, public readonly error?: any) {\n this.hasValue = kind === 'N';\n }\n\n /**\n * Executes the appropriate handler on a passed `observer` given the `kind` of notification.\n * If the handler is missing it will do nothing. Even if the notification is an error, if\n * there is no error handler on the observer, an error will not be thrown, it will noop.\n * @param observer The observer to notify.\n */\n observe(observer: PartialObserver<T>): void {\n return observeNotification(this as ObservableNotification<T>, observer);\n }\n\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @param complete A complete handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n do(next: (value: T) => void, error: (err: any) => void, complete: () => void): void;\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n do(next: (value: T) => void, error: (err: any) => void): void;\n /**\n * Executes the next handler if the Notification is of `kind` `\"N\"`. Otherwise\n * this will not error, and it will be a noop.\n * @param next The next handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n do(next: (value: T) => void): void;\n do(nextHandler: (value: T) => void, errorHandler?: (err: any) => void, completeHandler?: () => void): void {\n const { kind, value, error } = this;\n return kind === 'N' ? nextHandler?.(value!) : kind === 'E' ? errorHandler?.(error) : completeHandler?.();\n }\n\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @param complete A complete handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(next: (value: T) => void, error: (err: any) => void, complete: () => void): void;\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(next: (value: T) => void, error: (err: any) => void): void;\n /**\n * Executes the next handler if the Notification is of `kind` `\"N\"`. Otherwise\n * this will not error, and it will be a noop.\n * @param next The next handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(next: (value: T) => void): void;\n\n /**\n * Executes the appropriate handler on a passed `observer` given the `kind` of notification.\n * If the handler is missing it will do nothing. Even if the notification is an error, if\n * there is no error handler on the observer, an error will not be thrown, it will noop.\n * @param observer The observer to notify.\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(observer: PartialObserver<T>): void;\n accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {\n return isFunction((nextOrObserver as any)?.next)\n ? this.observe(nextOrObserver as PartialObserver<T>)\n : this.do(nextOrObserver as (value: T) => void, error as any, complete as any);\n }\n\n /**\n * Returns a simple Observable that just delivers the notification represented\n * by this Notification instance.\n *\n * @deprecated Will be removed in v8. To convert a `Notification` to an {@link Observable},\n * use {@link of} and {@link dematerialize}: `of(notification).pipe(dematerialize())`.\n */\n toObservable(): Observable<T> {\n const { kind, value, error } = this;\n // Select the observable to return by `kind`\n const result =\n kind === 'N'\n ? // Next kind. Return an observable of that value.\n of(value!)\n : //\n kind === 'E'\n ? // Error kind. Return an observable that emits the error.\n throwError(() => error)\n : //\n kind === 'C'\n ? // Completion kind. Kind is \"C\", return an observable that just completes.\n EMPTY\n : // Unknown kind, return falsy, so we error below.\n 0;\n if (!result) {\n // TODO: consider removing this check. The only way to cause this would be to\n // use the Notification constructor directly in a way that is not type-safe.\n // and direct use of the Notification constructor is deprecated.\n throw new TypeError(`Unexpected notification kind ${kind}`);\n }\n return result;\n }\n\n private static completeNotification = new Notification('C') as Notification<never> & CompleteNotification;\n /**\n * A shortcut to create a Notification instance of the type `next` from a\n * given value.\n * @param value The `next` value.\n * @return The \"next\" Notification representing the argument.\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\n static createNext<T>(value: T) {\n return new Notification('N', value) as Notification<T> & NextNotification<T>;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `error` from a\n * given error.\n * @param err The `error` error.\n * @return The \"error\" Notification representing the argument.\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\n static createError(err?: any) {\n return new Notification('E', undefined, err) as Notification<never> & ErrorNotification;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `complete`.\n * @return The valueless \"complete\" Notification.\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\n static createComplete(): Notification<never> & CompleteNotification {\n return Notification.completeNotification;\n }\n}\n\n/**\n * Executes the appropriate handler on a passed `observer` given the `kind` of notification.\n * If the handler is missing it will do nothing. Even if the notification is an error, if\n * there is no error handler on the observer, an error will not be thrown, it will noop.\n * @param notification The notification object to observe.\n * @param observer The observer to notify.\n */\nexport function observeNotification<T>(notification: ObservableNotification<T>, observer: PartialObserver<T>) {\n const { kind, value, error } = notification as any;\n if (typeof kind !== 'string') {\n throw new TypeError('Invalid notification, missing \"kind\"');\n }\n kind === 'N' ? observer.next?.(value!) : kind === 'E' ? observer.error?.(error) : observer.complete?.();\n}\n","/** prettier */\nimport { Observable } from '../Observable';\nimport { isFunction } from './isFunction';\n\n/**\n * Tests to see if the object is an RxJS {@link Observable}\n * @param obj the object to test\n */\nexport function isObservable(obj: any): obj is Observable<unknown> {\n // The !! is to ensure that this publicly exposed function returns\n // `false` if something like `null` or `0` is passed.\n return !!obj && (obj instanceof Observable || (isFunction(obj.lift) && isFunction(obj.subscribe)));\n}\n","import { createErrorClass } from './createErrorClass';\n\nexport interface EmptyError extends Error {}\n\nexport interface EmptyErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): EmptyError;\n}\n\n/**\n * An error thrown when an Observable or a sequence was queried but has no\n * elements.\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link single}\n * @see {@link firstValueFrom}\n * @see {@link lastValueFrom}\n */\nexport const EmptyError: EmptyErrorCtor = createErrorClass(\n (_super) =>\n function EmptyErrorImpl(this: any) {\n _super(this);\n this.name = 'EmptyError';\n this.message = 'no elements in sequence';\n }\n);\n","import { Observable } from './Observable';\nimport { EmptyError } from './util/EmptyError';\n\nexport interface LastValueFromConfig<T> {\n defaultValue: T;\n}\n\nexport function lastValueFrom<T, D>(source: Observable<T>, config: LastValueFromConfig<D>): Promise<T | D>;\nexport function lastValueFrom<T>(source: Observable<T>): Promise<T>;\n\n/**\n * Converts an observable to a promise by subscribing to the observable,\n * waiting for it to complete, and resolving the returned promise with the\n * last value from the observed stream.\n *\n * If the observable stream completes before any values were emitted, the\n * returned promise will reject with {@link EmptyError} or will resolve\n * with the default value if a default was specified.\n *\n * If the observable stream emits an error, the returned promise will reject\n * with that error.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * ## Example\n *\n * Wait for the last value from a stream and emit it from a promise in\n * an async function\n *\n * ```ts\n * import { interval, take, lastValueFrom } from 'rxjs';\n *\n * async function execute() {\n * const source$ = interval(2000).pipe(take(10));\n * const finalNumber = await lastValueFrom(source$);\n * console.log(`The final number is ${ finalNumber }`);\n * }\n *\n * execute();\n *\n * // Expected output:\n * // 'The final number is 9'\n * ```\n *\n * @see {@link firstValueFrom}\n *\n * @param source the observable to convert to a promise\n * @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value\n */\nexport function lastValueFrom<T, D>(source: Observable<T>, config?: LastValueFromConfig<D>): Promise<T | D> {\n const hasConfig = typeof config === 'object';\n return new Promise<T | D>((resolve, reject) => {\n let _hasValue = false;\n let _value: T;\n source.subscribe({\n next: (value) => {\n _value = value;\n _hasValue = true;\n },\n error: reject,\n complete: () => {\n if (_hasValue) {\n resolve(_value);\n } else if (hasConfig) {\n resolve(config!.defaultValue);\n } else {\n reject(new EmptyError());\n }\n },\n });\n });\n}\n","import { Observable } from './Observable';\nimport { EmptyError } from './util/EmptyError';\nimport { SafeSubscriber } from './Subscriber';\n\nexport interface FirstValueFromConfig<T> {\n defaultValue: T;\n}\n\nexport function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;\nexport function firstValueFrom<T>(source: Observable<T>): Promise<T>;\n\n/**\n * Converts an observable to a promise by subscribing to the observable,\n * and returning a promise that will resolve as soon as the first value\n * arrives from the observable. The subscription will then be closed.\n *\n * If the observable stream completes before any values were emitted, the\n * returned promise will reject with {@link EmptyError} or will resolve\n * with the default value if a default was specified.\n *\n * If the observable stream emits an error, the returned promise will reject\n * with that error.\n *\n * **WARNING**: Only use this with observables you *know* will emit at least one value,\n * *OR* complete. If the source observable does not emit one value or complete, you will\n * end up with a promise that is hung up, and potentially all of the state of an\n * async function hanging out in memory. To avoid this situation, look into adding\n * something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}\n * amongst others.\n *\n * ## Example\n *\n * Wait for the first value from a stream and emit it from a promise in\n * an async function\n *\n * ```ts\n * import { interval, firstValueFrom } from 'rxjs';\n *\n * async function execute() {\n * const source$ = interval(2000);\n * const firstNumber = await firstValueFrom(source$);\n * console.log(`The first number is ${ firstNumber }`);\n * }\n *\n * execute();\n *\n * // Expected output:\n * // 'The first number is 0'\n * ```\n *\n * @see {@link lastValueFrom}\n *\n * @param source the observable to convert to a promise\n * @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value\n */\nexport function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {\n const hasConfig = typeof config === 'object';\n return new Promise<T | D>((resolve, reject) => {\n const subscriber = new SafeSubscriber<T>({\n next: (value) => {\n resolve(value);\n subscriber.unsubscribe();\n },\n error: reject,\n complete: () => {\n if (hasConfig) {\n resolve(config!.defaultValue);\n } else {\n reject(new EmptyError());\n }\n },\n });\n source.subscribe(subscriber);\n });\n}\n","import { createErrorClass } from './createErrorClass';\n\nexport interface ArgumentOutOfRangeError extends Error {}\n\nexport interface ArgumentOutOfRangeErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ArgumentOutOfRangeError;\n}\n\n/**\n * An error thrown when an element was queried at a certain index of an\n * Observable, but no such index or position exists in that sequence.\n *\n * @see {@link elementAt}\n * @see {@link take}\n * @see {@link takeLast}\n */\nexport const ArgumentOutOfRangeError: ArgumentOutOfRangeErrorCtor = createErrorClass(\n (_super) =>\n function ArgumentOutOfRangeErrorImpl(this: any) {\n _super(this);\n this.name = 'ArgumentOutOfRangeError';\n this.message = 'argument out of range';\n }\n);\n","import { createErrorClass } from './createErrorClass';\n\nexport interface NotFoundError extends Error {}\n\nexport interface NotFoundErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (message: string): NotFoundError;\n}\n\n/**\n * An error thrown when a value or values are missing from an\n * observable sequence.\n *\n * @see {@link operators/single}\n */\nexport const NotFoundError: NotFoundErrorCtor = createErrorClass(\n (_super) =>\n function NotFoundErrorImpl(this: any, message: string) {\n _super(this);\n this.name = 'NotFoundError';\n this.message = message;\n }\n);\n","import { createErrorClass } from './createErrorClass';\n\nexport interface SequenceError extends Error {}\n\nexport interface SequenceErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (message: string): SequenceError;\n}\n\n/**\n * An error thrown when something is wrong with the sequence of\n * values arriving on the observable.\n *\n * @see {@link operators/single}\n */\nexport const SequenceError: SequenceErrorCtor = createErrorClass(\n (_super) =>\n function SequenceErrorImpl(this: any, message: string) {\n _super(this);\n this.name = 'SequenceError';\n this.message = message;\n }\n);\n","/**\n * Checks to see if a value is not only a `Date` object,\n * but a *valid* `Date` object that can be converted to a\n * number. For example, `new Date('blah')` is indeed an\n * `instanceof Date`, however it cannot be converted to a\n * number.\n */\nexport function isValidDate(value: any): value is Date {\n return value instanceof Date && !isNaN(value as any);\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { isValidDate } from '../util/isDate';\nimport { Subscription } from '../Subscription';\nimport { operate } from '../util/lift';\nimport { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createErrorClass } from '../util/createErrorClass';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport interface TimeoutConfig<T, O extends ObservableInput<unknown> = ObservableInput<T>, M = unknown> {\n /**\n * The time allowed between values from the source before timeout is triggered.\n */\n each?: number;\n\n /**\n * The relative time as a `number` in milliseconds, or a specific time as a `Date` object,\n * by which the first value must arrive from the source before timeout is triggered.\n */\n first?: number | Date;\n\n /**\n * The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler}\n */\n scheduler?: SchedulerLike;\n\n /**\n * A factory used to create observable to switch to when timeout occurs. Provides\n * a {@link TimeoutInfo} about the source observable's emissions and what delay or\n * exact time triggered the timeout.\n */\n with?: (info: TimeoutInfo<T, M>) => O;\n\n /**\n * Optional additional metadata you can provide to code that handles\n * the timeout, will be provided through the {@link TimeoutError}.\n * This can be used to help identify the source of a timeout or pass along\n * other information related to the timeout.\n */\n meta?: M;\n}\n\nexport interface TimeoutInfo<T, M = unknown> {\n /** Optional metadata that was provided to the timeout configuration. */\n readonly meta: M;\n /** The number of messages seen before the timeout */\n readonly seen: number;\n /** The last message seen */\n readonly lastValue: T | null;\n}\n\n/**\n * An error emitted when a timeout occurs.\n */\nexport interface TimeoutError<T = unknown, M = unknown> extends Error {\n /**\n * The information provided to the error by the timeout\n * operation that created the error. Will be `null` if\n * used directly in non-RxJS code with an empty constructor.\n * (Note that using this constructor directly is not recommended,\n * you should create your own errors)\n */\n info: TimeoutInfo<T, M> | null;\n}\n\nexport interface TimeoutErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new <T = unknown, M = unknown>(info?: TimeoutInfo<T, M>): TimeoutError<T, M>;\n}\n\n/**\n * An error thrown by the {@link timeout} operator.\n *\n * Provided so users can use as a type and do quality comparisons.\n * We recommend you do not subclass this or create instances of this class directly.\n * If you have need of a error representing a timeout, you should\n * create your own error class and use that.\n *\n * @see {@link timeout}\n */\nexport const TimeoutError: TimeoutErrorCtor = createErrorClass(\n (_super) =>\n function TimeoutErrorImpl(this: any, info: TimeoutInfo<any> | null = null) {\n _super(this);\n this.message = 'Timeout has occurred';\n this.name = 'TimeoutError';\n this.info = info;\n }\n);\n\n/**\n * If `with` is provided, this will return an observable that will switch to a different observable if the source\n * does not push values within the specified time parameters.\n *\n * <span class=\"informal\">The most flexible option for creating a timeout behavior.</span>\n *\n * The first thing to know about the configuration is if you do not provide a `with` property to the configuration,\n * when timeout conditions are met, this operator will emit a {@link TimeoutError}. Otherwise, it will use the factory\n * function provided by `with`, and switch your subscription to the result of that. Timeout conditions are provided by\n * the settings in `first` and `each`.\n *\n * The `first` property can be either a `Date` for a specific time, a `number` for a time period relative to the\n * point of subscription, or it can be skipped. This property is to check timeout conditions for the arrival of\n * the first value from the source _only_. The timings of all subsequent values from the source will be checked\n * against the time period provided by `each`, if it was provided.\n *\n * The `each` property can be either a `number` or skipped. If a value for `each` is provided, it represents the amount of\n * time the resulting observable will wait between the arrival of values from the source before timing out. Note that if\n * `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first\n * value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first.\n *\n * ## Examples\n *\n * Emit a custom error if there is too much time between values\n *\n * ```ts\n * import { interval, timeout, throwError } from 'rxjs';\n *\n * class CustomTimeoutError extends Error {\n * constructor() {\n * super('It was too slow');\n * this.name = 'CustomTimeoutError';\n * }\n * }\n *\n * const slow$ = interval(900);\n *\n * slow$.pipe(\n * timeout({\n * each: 1000,\n * with: () => throwError(() => new CustomTimeoutError())\n * })\n * )\n * .subscribe({\n * error: console.error\n * });\n * ```\n *\n * Switch to a faster observable if your source is slow.\n *\n * ```ts\n * import { interval, timeout } from 'rxjs';\n *\n * const slow$ = interval(900);\n * const fast$ = interval(500);\n *\n * slow$.pipe(\n * timeout({\n * each: 1000,\n * with: () => fast$,\n * })\n * )\n * .subscribe(console.log);\n * ```\n * @param config The configuration for the timeout.\n */\nexport function timeout<T, O extends ObservableInput<unknown>, M = unknown>(\n config: TimeoutConfig<T, O, M> & { with: (info: TimeoutInfo<T, M>) => O }\n): OperatorFunction<T, T | ObservedValueOf<O>>;\n\n/**\n * Returns an observable that will error or switch to a different observable if the source does not push values\n * within the specified time parameters.\n *\n * <span class=\"informal\">The most flexible option for creating a timeout behavior.</span>\n *\n * The first thing to know about the configuration is if you do not provide a `with` property to the configuration,\n * when timeout conditions are met, this operator will emit a {@link TimeoutError}. Otherwise, it will use the factory\n * function provided by `with`, and switch your subscription to the result of that. Timeout conditions are provided by\n * the settings in `first` and `each`.\n *\n * The `first` property can be either a `Date` for a specific time, a `number` for a time period relative to the\n * point of subscription, or it can be skipped. This property is to check timeout conditions for the arrival of\n * the first value from the source _only_. The timings of all subsequent values from the source will be checked\n * against the time period provided by `each`, if it was provided.\n *\n * The `each` property can be either a `number` or skipped. If a value for `each` is provided, it represents the amount of\n * time the resulting observable will wait between the arrival of values from the source before timing out. Note that if\n * `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first\n * value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first.\n *\n * ### Handling TimeoutErrors\n *\n * If no `with` property was provided, subscriptions to the resulting observable may emit an error of {@link TimeoutError}.\n * The timeout error provides useful information you can examine when you're handling the error. The most common way to handle\n * the error would be with {@link catchError}, although you could use {@link tap} or just the error handler in your `subscribe` call\n * directly, if your error handling is only a side effect (such as notifying the user, or logging).\n *\n * In this case, you would check the error for `instanceof TimeoutError` to validate that the error was indeed from `timeout`, and\n * not from some other source. If it's not from `timeout`, you should probably rethrow it if you're in a `catchError`.\n *\n * ## Examples\n *\n * Emit a {@link TimeoutError} if the first value, and _only_ the first value, does not arrive within 5 seconds\n *\n * ```ts\n * import { interval, timeout } from 'rxjs';\n *\n * // A random interval that lasts between 0 and 10 seconds per tick\n * const source$ = interval(Math.round(Math.random() * 10_000));\n *\n * source$.pipe(\n * timeout({ first: 5_000 })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * Emit a {@link TimeoutError} if the source waits longer than 5 seconds between any two values or the first value\n * and subscription.\n *\n * ```ts\n * import { timer, timeout, expand } from 'rxjs';\n *\n * const getRandomTime = () => Math.round(Math.random() * 10_000);\n *\n * // An observable that waits a random amount of time between each delivered value\n * const source$ = timer(getRandomTime())\n * .pipe(expand(() => timer(getRandomTime())));\n *\n * source$\n * .pipe(timeout({ each: 5_000 }))\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * Emit a {@link TimeoutError} if the source does not emit before 7 seconds, _or_ if the source waits longer than\n * 5 seconds between any two values after the first.\n *\n * ```ts\n * import { timer, timeout, expand } from 'rxjs';\n *\n * const getRandomTime = () => Math.round(Math.random() * 10_000);\n *\n * // An observable that waits a random amount of time between each delivered value\n * const source$ = timer(getRandomTime())\n * .pipe(expand(() => timer(getRandomTime())));\n *\n * source$\n * .pipe(timeout({ first: 7_000, each: 5_000 }))\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n */\nexport function timeout<T, M = unknown>(config: Omit<TimeoutConfig<T, any, M>, 'with'>): OperatorFunction<T, T>;\n\n/**\n * Returns an observable that will error if the source does not push its first value before the specified time passed as a `Date`.\n * This is functionally the same as `timeout({ first: someDate })`.\n *\n * <span class=\"informal\">Errors if the first value doesn't show up before the given date and time</span>\n *\n * \n *\n * @param first The date to at which the resulting observable will timeout if the source observable\n * does not emit at least one value.\n * @param scheduler The scheduler to use. Defaults to {@link asyncScheduler}.\n */\nexport function timeout<T>(first: Date, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an observable that will error if the source does not push a value within the specified time in milliseconds.\n * This is functionally the same as `timeout({ each: milliseconds })`.\n *\n * <span class=\"informal\">Errors if it waits too long between any value</span>\n *\n * \n *\n * @param each The time allowed between each pushed value from the source before the resulting observable\n * will timeout.\n * @param scheduler The scheduler to use. Defaults to {@link asyncScheduler}.\n */\nexport function timeout<T>(each: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n\n/**\n *\n * Errors if Observable does not emit a value in given time span.\n *\n * <span class=\"informal\">Timeouts on Observable that doesn't emit values fast enough.</span>\n *\n * \n *\n * @see {@link timeoutWith}\n *\n * @return A function that returns an Observable that mirrors behaviour of the\n * source Observable, unless timeout happens when it throws an error.\n */\nexport function timeout<T, O extends ObservableInput<any>, M>(\n config: number | Date | TimeoutConfig<T, O, M>,\n schedulerArg?: SchedulerLike\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n // Intentionally terse code.\n // If the first argument is a valid `Date`, then we use it as the `first` config.\n // Otherwise, if the first argument is a `number`, then we use it as the `each` config.\n // Otherwise, it can be assumed the first argument is the configuration object itself, and\n // we destructure that into what we're going to use, setting important defaults as we do.\n // NOTE: The default for `scheduler` will be the `scheduler` argument if it exists, or\n // it will default to the `asyncScheduler`.\n const {\n first,\n each,\n with: _with = timeoutErrorFactory,\n scheduler = schedulerArg ?? asyncScheduler,\n meta = null!,\n } = (isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config) as TimeoutConfig<T, O, M>;\n\n if (first == null && each == null) {\n // Ensure timeout was provided at runtime.\n throw new TypeError('No timeout provided.');\n }\n\n return operate((source, subscriber) => {\n // This subscription encapsulates our subscription to the\n // source for this operator. We're capturing it separately,\n // because if there is a `with` observable to fail over to,\n // we want to unsubscribe from our original subscription, and\n // hand of the subscription to that one.\n let originalSourceSubscription: Subscription;\n // The subscription for our timeout timer. This changes\n // every time we get a new value.\n let timerSubscription: Subscription;\n // A bit of state we pass to our with and error factories to\n // tell what the last value we saw was.\n let lastValue: T | null = null;\n // A bit of state we pass to the with and error factories to\n // tell how many values we have seen so far.\n let seen = 0;\n const startTimer = (delay: number) => {\n timerSubscription = executeSchedule(\n subscriber,\n scheduler,\n () => {\n try {\n originalSourceSubscription.unsubscribe();\n innerFrom(\n _with!({\n meta,\n lastValue,\n seen,\n })\n ).subscribe(subscriber);\n } catch (err) {\n subscriber.error(err);\n }\n },\n delay\n );\n };\n\n originalSourceSubscription = source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // clear the timer so we can emit and start another one.\n timerSubscription?.unsubscribe();\n seen++;\n // Emit\n subscriber.next((lastValue = value));\n // null | undefined are both < 0. Thanks, JavaScript.\n each! > 0 && startTimer(each!);\n },\n undefined,\n undefined,\n () => {\n if (!timerSubscription?.closed) {\n timerSubscription?.unsubscribe();\n }\n // Be sure not to hold the last value in memory after unsubscription\n // it could be quite large.\n lastValue = null;\n }\n )\n );\n\n // Intentionally terse code.\n // If we've `seen` a value, that means the \"first\" clause was met already, if it existed.\n // it also means that a timer was already started for \"each\" (in the next handler above).\n // If `first` was provided, and it's a number, then use it.\n // If `first` was provided and it's not a number, it's a Date, and we get the difference between it and \"now\".\n // If `first` was not provided at all, then our first timer will be the value from `each`.\n !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler!.now()) : each!);\n });\n}\n\n/**\n * The default function to use to emit an error when timeout occurs and a `with` function\n * is not specified.\n * @param info The information about the timeout to pass along to the error\n */\nfunction timeoutErrorFactory(info: TimeoutInfo<any>): Observable<never> {\n throw new TimeoutError(info);\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function map<T, R>(project: (value: T, index: number) => R): OperatorFunction<T, R>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * \n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n *\n * Map every click to the `clientX` position of that click\n *\n * ```ts\n * import { fromEvent, map } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n *\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param project The function to apply to each `value` emitted by the source\n * Observable. The `index` parameter is the number `i` for the i-th emission\n * that has happened since the subscription, starting from the number `0`.\n * @param thisArg An optional argument to define what `this` is in the\n * `project` function.\n * @return A function that returns an Observable that emits the values from the\n * source Observable transformed by the given `project` function.\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return operate((source, subscriber) => {\n // The index of the value from the source. Used with projection.\n let index = 0;\n // Subscribe to the source, all errors and completions are sent along\n // to the consumer.\n source.subscribe(\n createOperatorSubscriber(subscriber, (value: T) => {\n // Call the projection function with the appropriate this context,\n // and send the resulting value to the consumer.\n subscriber.next(project.call(thisArg, value, index++));\n })\n );\n });\n}\n","import { OperatorFunction } from \"../types\";\nimport { map } from \"../operators/map\";\n\nconst { isArray } = Array;\n\nfunction callOrApply<T, R>(fn: ((...values: T[]) => R), args: T|T[]): R {\n return isArray(args) ? fn(...args) : fn(args);\n}\n\n/**\n * Used in several -- mostly deprecated -- situations where we need to \n * apply a list of arguments or a single argument to a result selector.\n */\nexport function mapOneOrManyArgs<T, R>(fn: ((...values: T[]) => R)): OperatorFunction<T|T[], R> {\n return map(args => callOrApply(fn, args))\n}","import { SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { Observable } from '../Observable';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { observeOn } from '../operators/observeOn';\nimport { AsyncSubject } from '../AsyncSubject';\n\nexport function bindCallbackInternals(\n isNodeStyle: boolean,\n callbackFunc: any,\n resultSelector?: any,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<unknown> {\n if (resultSelector) {\n if (isScheduler(resultSelector)) {\n scheduler = resultSelector;\n } else {\n // The user provided a result selector.\n return function (this: any, ...args: any[]) {\n return (bindCallbackInternals(isNodeStyle, callbackFunc, scheduler) as any)\n .apply(this, args)\n .pipe(mapOneOrManyArgs(resultSelector as any));\n };\n }\n }\n\n // If a scheduler was passed, use our `subscribeOn` and `observeOn` operators\n // to compose that behavior for the user.\n if (scheduler) {\n return function (this: any, ...args: any[]) {\n return (bindCallbackInternals(isNodeStyle, callbackFunc) as any)\n .apply(this, args)\n .pipe(subscribeOn(scheduler!), observeOn(scheduler!));\n };\n }\n\n return function (this: any, ...args: any[]): Observable<any> {\n // We're using AsyncSubject, because it emits when it completes,\n // and it will play the value to all late-arriving subscribers.\n const subject = new AsyncSubject<any>();\n\n // If this is true, then we haven't called our function yet.\n let uninitialized = true;\n return new Observable((subscriber) => {\n // Add our subscriber to the subject.\n const subs = subject.subscribe(subscriber);\n\n if (uninitialized) {\n uninitialized = false;\n // We're going to execute the bound function\n // This bit is to signal that we are hitting the callback asynchronously.\n // Because we don't have any anti-\"Zalgo\" guarantees with whatever\n // function we are handed, we use this bit to figure out whether or not\n // we are getting hit in a callback synchronously during our call.\n let isAsync = false;\n\n // This is used to signal that the callback completed synchronously.\n let isComplete = false;\n\n // Call our function that has a callback. If at any time during this\n // call, an error is thrown, it will be caught by the Observable\n // subscription process and sent to the consumer.\n callbackFunc.apply(\n // Pass the appropriate `this` context.\n this,\n [\n // Pass the arguments.\n ...args,\n // And our callback handler.\n (...results: any[]) => {\n if (isNodeStyle) {\n // If this is a node callback, shift the first value off of the\n // results and check it, as it is the error argument. By shifting,\n // we leave only the argument(s) we want to pass to the consumer.\n const err = results.shift();\n if (err != null) {\n subject.error(err);\n // If we've errored, we can stop processing this function\n // as there's nothing else to do. Just return to escape.\n return;\n }\n }\n // If we have one argument, notify the consumer\n // of it as a single value, otherwise, if there's more than one, pass\n // them as an array. Note that if there are no arguments, `undefined`\n // will be emitted.\n subject.next(1 < results.length ? results : results[0]);\n // Flip this flag, so we know we can complete it in the synchronous\n // case below.\n isComplete = true;\n // If we're not asynchronous, we need to defer the `complete` call\n // until after the call to the function is over. This is because an\n // error could be thrown in the function after it calls our callback,\n // and if that is the case, if we complete here, we are unable to notify\n // the consumer than an error occurred.\n if (isAsync) {\n subject.complete();\n }\n },\n ]\n );\n // If we flipped `isComplete` during the call, we resolved synchronously,\n // notify complete, because we skipped it in the callback to wait\n // to make sure there were no errors during the call.\n if (isComplete) {\n subject.complete();\n }\n\n // We're no longer synchronous. If the callback is called at this point\n // we can notify complete on the spot.\n isAsync = true;\n }\n\n // Return the subscription from adding our subscriber to the subject.\n return subs;\n });\n };\n}\n","/* @prettier */\nimport { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { bindCallbackInternals } from './bindCallbackInternals';\n\nexport function bindCallback(\n callbackFunc: (...args: any[]) => void,\n resultSelector: (...args: any[]) => any,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<any>;\n\n// args is the arguments array and we push the callback on the rest tuple since the rest parameter must be last (only item) in a parameter list\nexport function bindCallback<A extends readonly unknown[], R extends readonly unknown[]>(\n callbackFunc: (...args: [...A, (...res: R) => void]) => void,\n schedulerLike?: SchedulerLike\n): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;\n\n/**\n * Converts a callback API to a function that returns an Observable.\n *\n * <span class=\"informal\">Give it a function `f` of type `f(x, callback)` and\n * it will return a function `g` that when called as `g(x)` will output an\n * Observable.</span>\n *\n * `bindCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters. The\n * last parameter must be a callback function that `func` calls when it is\n * done.\n *\n * The output of `bindCallback` is a function that takes the same parameters\n * as `func`, except the last one (the callback). When the output function\n * is called with arguments it will return an Observable. If function `func`\n * calls its callback with one argument, the Observable will emit that value.\n * If on the other hand the callback is called with multiple values the resulting\n * Observable will emit an array with said values as arguments.\n *\n * It is **very important** to remember that input function `func` is not called\n * when the output function is, but rather when the Observable returned by the output\n * function is subscribed. This means if `func` makes an AJAX request, that request\n * will be made every time someone subscribes to the resulting Observable, but not before.\n *\n * The last optional parameter - `scheduler` - can be used to control when the call\n * to `func` happens after someone subscribes to Observable, as well as when results\n * passed to callback will be emitted. By default, the subscription to an Observable calls `func`\n * synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`,\n * just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler\n * and call `subscribe` on the output Observable, all function calls that are currently executing\n * will end before `func` is invoked.\n *\n * By default, results passed to the callback are emitted immediately after `func` invokes the callback.\n * In particular, if the callback is called synchronously, then the subscription of the resulting Observable\n * will call the `next` function synchronously as well. If you want to defer that call,\n * you may use {@link asyncScheduler} just as before. This means that by using `Scheduler.async` you can\n * ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.\n *\n * Note that the Observable created by the output function will always emit a single value\n * and then complete immediately. If `func` calls the callback multiple times, values from subsequent\n * calls will not appear in the stream. If you need to listen for multiple calls,\n * you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.\n *\n * If `func` depends on some context (`this` property) and is not already bound, the context of `func`\n * will be the context that the output function has at call time. In particular, if `func`\n * is called as a method of some object and if `func` is not already bound, in order to preserve the context\n * it is recommended that the context of the output function is set to that object as well.\n *\n * If the input function calls its callback in the \"node style\" (i.e. first argument to callback is\n * optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}\n * provides convenient error handling and probably is a better choice.\n * `bindCallback` will treat such functions the same as any other and error parameters\n * (whether passed or not) will always be interpreted as regular callback argument.\n *\n * ## Examples\n *\n * Convert jQuery's getJSON to an Observable API\n *\n * ```ts\n * import { bindCallback } from 'rxjs';\n * import * as jQuery from 'jquery';\n *\n * // Suppose we have jQuery.getJSON('/my/url', callback)\n * const getJSONAsObservable = bindCallback(jQuery.getJSON);\n * const result = getJSONAsObservable('/my/url');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * Receive an array of arguments passed to a callback\n *\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const someFunction = (n, s, cb) => {\n * cb(n, s, { someProperty: 'someValue' });\n * };\n *\n * const boundSomeFunction = bindCallback(someFunction);\n * boundSomeFunction(5, 'some string').subscribe((values) => {\n * console.log(values); // [5, 'some string', {someProperty: 'someValue'}]\n * });\n * ```\n *\n * Compare behaviour with and without `asyncScheduler`\n *\n * ```ts\n * import { bindCallback, asyncScheduler } from 'rxjs';\n *\n * function iCallMyCallbackSynchronously(cb) {\n * cb();\n * }\n *\n * const boundSyncFn = bindCallback(iCallMyCallbackSynchronously);\n * const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, asyncScheduler);\n *\n * boundSyncFn().subscribe(() => console.log('I was sync!'));\n * boundAsyncFn().subscribe(() => console.log('I was async!'));\n * console.log('This happened...');\n *\n * // Logs:\n * // I was sync!\n * // This happened...\n * // I was async!\n * ```\n *\n * Use `bindCallback` on an object method\n *\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const boundMethod = bindCallback(someObject.methodWithCallback);\n * boundMethod\n * .call(someObject) // make sure methodWithCallback has access to someObject\n * .subscribe(subscriber);\n * ```\n *\n * @see {@link bindNodeCallback}\n * @see {@link from}\n *\n * @param callbackFunc A function with a callback as the last parameter.\n * @param resultSelector A mapping function used to transform callback events.\n * @param scheduler The scheduler on which to schedule the callbacks.\n * @return A function which returns the Observable that delivers the same\n * values the callback would deliver.\n */\nexport function bindCallback(\n callbackFunc: (...args: [...any[], (...res: any) => void]) => void,\n resultSelector?: ((...args: any[]) => any) | SchedulerLike,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<unknown> {\n return bindCallbackInternals(false, callbackFunc, resultSelector, scheduler);\n}\n","/* @prettier */\nimport { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { bindCallbackInternals } from './bindCallbackInternals';\n\nexport function bindNodeCallback(\n callbackFunc: (...args: any[]) => void,\n resultSelector: (...args: any[]) => any,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<any>;\n\n// args is the arguments array and we push the callback on the rest tuple since the rest parameter must be last (only item) in a parameter list\nexport function bindNodeCallback<A extends readonly unknown[], R extends readonly unknown[]>(\n callbackFunc: (...args: [...A, (err: any, ...res: R) => void]) => void,\n schedulerLike?: SchedulerLike\n): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;\n\n/**\n * Converts a Node.js-style callback API to a function that returns an\n * Observable.\n *\n * <span class=\"informal\">It's just like {@link bindCallback}, but the\n * callback is expected to be of type `callback(error, result)`.</span>\n *\n * `bindNodeCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters, but the\n * last parameter must be a callback function that `func` calls when it is\n * done. The callback function is expected to follow Node.js conventions,\n * where the first argument to the callback is an error object, signaling\n * whether call was successful. If that object is passed to callback, it means\n * something went wrong.\n *\n * The output of `bindNodeCallback` is a function that takes the same\n * parameters as `func`, except the last one (the callback). When the output\n * function is called with arguments, it will return an Observable.\n * If `func` calls its callback with error parameter present, Observable will\n * error with that value as well. If error parameter is not passed, Observable will emit\n * second parameter. If there are more parameters (third and so on),\n * Observable will emit an array with all arguments, except first error argument.\n *\n * Note that `func` will not be called at the same time output function is,\n * but rather whenever resulting Observable is subscribed. By default call to\n * `func` will happen synchronously after subscription, but that can be changed\n * with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}\n * can also control when values from callback will be emitted by Observable.\n * To find out more, check out documentation for {@link bindCallback}, where\n * {@link SchedulerLike} works exactly the same.\n *\n * As in {@link bindCallback}, context (`this` property) of input function will be set to context\n * of returned function, when it is called.\n *\n * After Observable emits value, it will complete immediately. This means\n * even if `func` calls callback again, values from second and consecutive\n * calls will never appear on the stream. If you need to handle functions\n * that call callbacks multiple times, check out {@link fromEvent} or\n * {@link fromEventPattern} instead.\n *\n * Note that `bindNodeCallback` can be used in non-Node.js environments as well.\n * \"Node.js-style\" callbacks are just a convention, so if you write for\n * browsers or any other environment and API you use implements that callback style,\n * `bindNodeCallback` can be safely used on that API functions as well.\n *\n * Remember that Error object passed to callback does not have to be an instance\n * of JavaScript built-in `Error` object. In fact, it does not even have to an object.\n * Error parameter of callback function is interpreted as \"present\", when value\n * of that parameter is truthy. It could be, for example, non-zero number, non-empty\n * string or boolean `true`. In all of these cases resulting Observable would error\n * with that value. This means usually regular style callbacks will fail very often when\n * `bindNodeCallback` is used. If your Observable errors much more often then you\n * would expect, check if callback really is called in Node.js-style and, if not,\n * switch to {@link bindCallback} instead.\n *\n * Note that even if error parameter is technically present in callback, but its value\n * is falsy, it still won't appear in array emitted by Observable.\n *\n * ## Examples\n *\n * Read a file from the filesystem and get the data as an Observable\n *\n * ```ts\n * import * as fs from 'fs';\n * const readFileAsObservable = bindNodeCallback(fs.readFile);\n * const result = readFileAsObservable('./roadNames.txt', 'utf8');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * Use on function calling callback with multiple arguments\n *\n * ```ts\n * someFunction((err, a, b) => {\n * console.log(err); // null\n * console.log(a); // 5\n * console.log(b); // \"some string\"\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(value => {\n * console.log(value); // [5, \"some string\"]\n * });\n * ```\n *\n * Use on function calling callback in regular style\n *\n * ```ts\n * someFunction(a => {\n * console.log(a); // 5\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(\n * value => {} // never gets called\n * err => console.log(err) // 5\n * );\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link from}\n *\n * @param callbackFunc Function with a Node.js-style callback as the last parameter.\n * @param resultSelector A mapping function used to transform callback events.\n * @param scheduler The scheduler on which to schedule the callbacks.\n * @return A function which returns the Observable that delivers the same values the\n * Node.js callback would deliver.\n */\nexport function bindNodeCallback(\n callbackFunc: (...args: [...any[], (err: any, ...res: any) => void]) => void,\n resultSelector?: ((...args: any[]) => any) | SchedulerLike,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<any> {\n return bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);\n}\n","const { isArray } = Array;\nconst { getPrototypeOf, prototype: objectProto, keys: getKeys } = Object;\n\n/**\n * Used in functions where either a list of arguments, a single array of arguments, or a\n * dictionary of arguments can be returned. Returns an object with an `args` property with\n * the arguments in an array, if it is a dictionary, it will also return the `keys` in another\n * property.\n */\nexport function argsArgArrayOrObject<T, O extends Record<string, T>>(args: T[] | [O] | [T[]]): { args: T[]; keys: string[] | null } {\n if (args.length === 1) {\n const first = args[0];\n if (isArray(first)) {\n return { args: first, keys: null };\n }\n if (isPOJO(first)) {\n const keys = getKeys(first);\n return {\n args: keys.map((key) => first[key]),\n keys,\n };\n }\n }\n\n return { args: args as T[], keys: null };\n}\n\nfunction isPOJO(obj: any): obj is object {\n return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;\n}\n","export function createObject(keys: string[], values: any[]) {\n return keys.reduce((result, key, i) => ((result[key] = values[i]), result), {} as any);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf, ObservableInputTuple } from '../types';\nimport { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';\nimport { Subscriber } from '../Subscriber';\nimport { from } from './from';\nimport { identity } from '../util/identity';\nimport { Subscription } from '../Subscription';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { popResultSelector, popScheduler } from '../util/args';\nimport { createObject } from '../util/createObject';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { AnyCatcher } from '../AnyCatcher';\nimport { executeSchedule } from '../util/executeSchedule';\n\n// combineLatest(any)\n// We put this first because we need to catch cases where the user has supplied\n// _exactly `any`_ as the argument. Since `any` literally matches _anything_,\n// we don't want it to randomly hit one of the other type signatures below,\n// as we have no idea at build-time what type we should be returning when given an any.\n\n/**\n * You have passed `any` here, we can't figure out if it is\n * an array or an object, so you're getting `unknown`. Use better types.\n * @param arg Something typed as `any`\n */\nexport function combineLatest<T extends AnyCatcher>(arg: T): Observable<unknown>;\n\n// combineLatest([a, b, c])\nexport function combineLatest(sources: []): Observable<never>;\nexport function combineLatest<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[], R>(\n sources: readonly [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R,\n scheduler: SchedulerLike\n): Observable<R>;\nexport function combineLatest<A extends readonly unknown[], R>(\n sources: readonly [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R\n): Observable<R>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[]>(\n sources: readonly [...ObservableInputTuple<A>],\n scheduler: SchedulerLike\n): Observable<A>;\n\n// combineLatest(a, b, c)\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function combineLatest<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[], R>(\n ...sourcesAndResultSelectorAndScheduler: [...ObservableInputTuple<A>, (...values: A) => R, SchedulerLike]\n): Observable<R>;\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function combineLatest<A extends readonly unknown[], R>(\n ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]\n): Observable<R>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]\n): Observable<A>;\n\n// combineLatest({a, b, c})\nexport function combineLatest(sourcesObject: { [K in any]: never }): Observable<never>;\nexport function combineLatest<T extends Record<string, ObservableInput<any>>>(\n sourcesObject: T\n): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;\n\n/**\n * Combines multiple Observables to create an Observable whose values are\n * calculated from the latest values of each of its input Observables.\n *\n * <span class=\"informal\">Whenever any input Observable emits a value, it\n * computes a formula using the latest values from all the inputs, then emits\n * the output of that formula.</span>\n *\n * \n *\n * `combineLatest` combines the values from all the Observables passed in the\n * observables array. This is done by subscribing to each Observable in order and,\n * whenever any Observable emits, collecting an array of the most recent\n * values from each Observable. So if you pass `n` Observables to this operator,\n * the returned Observable will always emit an array of `n` values, in an order\n * corresponding to the order of the passed Observables (the value from the first Observable\n * will be at index 0 of the array and so on).\n *\n * Static version of `combineLatest` accepts an array of Observables. Note that an array of\n * Observables is a good choice, if you don't know beforehand how many Observables\n * you will combine. Passing an empty array will result in an Observable that\n * completes immediately.\n *\n * To ensure the output array always has the same length, `combineLatest` will\n * actually wait for all input Observables to emit at least once,\n * before it starts emitting results. This means if some Observable emits\n * values before other Observables started emitting, all these values but the last\n * will be lost. On the other hand, if some Observable does not emit a value but\n * completes, resulting Observable will complete at the same moment without\n * emitting anything, since it will now be impossible to include a value from the\n * completed Observable in the resulting array. Also, if some input Observable does\n * not emit any value and never completes, `combineLatest` will also never emit\n * and never complete, since, again, it will wait for all streams to emit some\n * value.\n *\n * If at least one Observable was passed to `combineLatest` and all passed Observables\n * emitted something, the resulting Observable will complete when all combined\n * streams complete. So even if some Observable completes, the result of\n * `combineLatest` will still emit values when other Observables do. In case\n * of a completed Observable, its value from now on will always be the last\n * emitted value. On the other hand, if any Observable errors, `combineLatest`\n * will error immediately as well, and all other Observables will be unsubscribed.\n *\n * ## Examples\n *\n * Combine two timer Observables\n *\n * ```ts\n * import { timer, combineLatest } from 'rxjs';\n *\n * const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now\n * const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now\n * const combinedTimers = combineLatest([firstTimer, secondTimer]);\n * combinedTimers.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0] after 0.5s\n * // [1, 0] after 1s\n * // [1, 1] after 1.5s\n * // [2, 1] after 2s\n * ```\n *\n * Combine a dictionary of Observables\n *\n * ```ts\n * import { of, delay, startWith, combineLatest } from 'rxjs';\n *\n * const observables = {\n * a: of(1).pipe(delay(1000), startWith(0)),\n * b: of(5).pipe(delay(5000), startWith(0)),\n * c: of(10).pipe(delay(10000), startWith(0))\n * };\n * const combined = combineLatest(observables);\n * combined.subscribe(value => console.log(value));\n * // Logs\n * // { a: 0, b: 0, c: 0 } immediately\n * // { a: 1, b: 0, c: 0 } after 1s\n * // { a: 1, b: 5, c: 0 } after 5s\n * // { a: 1, b: 5, c: 10 } after 10s\n * ```\n *\n * Combine an array of Observables\n *\n * ```ts\n * import { of, delay, startWith, combineLatest } from 'rxjs';\n *\n * const observables = [1, 5, 10].map(\n * n => of(n).pipe(\n * delay(n * 1000), // emit 0 and then emit n after n seconds\n * startWith(0)\n * )\n * );\n * const combined = combineLatest(observables);\n * combined.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0, 0] immediately\n * // [1, 0, 0] after 1s\n * // [1, 5, 0] after 5s\n * // [1, 5, 10] after 10s\n * ```\n *\n * Use map operator to dynamically calculate the Body-Mass Index\n *\n * ```ts\n * import { of, combineLatest, map } from 'rxjs';\n *\n * const weight = of(70, 72, 76, 79, 75);\n * const height = of(1.76, 1.77, 1.78);\n * const bmi = combineLatest([weight, height]).pipe(\n * map(([w, h]) => w / (h * h)),\n * );\n * bmi.subscribe(x => console.log('BMI is ' + x));\n *\n * // With output to console:\n * // BMI is 24.212293388429753\n * // BMI is 23.93948099205209\n * // BMI is 23.671253629592222\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link merge}\n * @see {@link withLatestFrom}\n *\n * @param args Any number of `ObservableInput`s provided either as an array or as an object\n * to combine with each other. If the last parameter is the function, it will be used to project the\n * values from the combined latest values into a new value on the output Observable.\n * @return An Observable of projected values from the most recent values from each `ObservableInput`,\n * or an array of the most recent values from each `ObservableInput`.\n */\nexport function combineLatest<O extends ObservableInput<any>, R>(...args: any[]): Observable<R> | Observable<ObservedValueOf<O>[]> {\n const scheduler = popScheduler(args);\n const resultSelector = popResultSelector(args);\n\n const { args: observables, keys } = argsArgArrayOrObject(args);\n\n if (observables.length === 0) {\n // If no observables are passed, or someone has passed an empty array\n // of observables, or even an empty object POJO, we need to just\n // complete (EMPTY), but we have to honor the scheduler provided if any.\n return from([], scheduler as any);\n }\n\n const result = new Observable<ObservedValueOf<O>[]>(\n combineLatestInit(\n observables as ObservableInput<ObservedValueOf<O>>[],\n scheduler,\n keys\n ? // A handler for scrubbing the array of args into a dictionary.\n (values) => createObject(keys, values)\n : // A passthrough to just return the array\n identity\n )\n );\n\n return resultSelector ? (result.pipe(mapOneOrManyArgs(resultSelector)) as Observable<R>) : result;\n}\n\nexport function combineLatestInit(\n observables: ObservableInput<any>[],\n scheduler?: SchedulerLike,\n valueTransform: (values: any[]) => any = identity\n) {\n return (subscriber: Subscriber<any>) => {\n // The outer subscription. We're capturing this in a function\n // because we may have to schedule it.\n maybeSchedule(\n scheduler,\n () => {\n const { length } = observables;\n // A store for the values each observable has emitted so far. We match observable to value on index.\n const values = new Array(length);\n // The number of currently active subscriptions, as they complete, we decrement this number to see if\n // we are all done combining values, so we can complete the result.\n let active = length;\n // The number of inner sources that still haven't emitted the first value\n // We need to track this because all sources need to emit one value in order\n // to start emitting values.\n let remainingFirstValues = length;\n // The loop to kick off subscription. We're keying everything on index `i` to relate the observables passed\n // in to the slot in the output array or the key in the array of keys in the output dictionary.\n for (let i = 0; i < length; i++) {\n maybeSchedule(\n scheduler,\n () => {\n const source = from(observables[i], scheduler as any);\n let hasFirstValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // When we get a value, record it in our set of values.\n values[i] = value;\n if (!hasFirstValue) {\n // If this is our first value, record that.\n hasFirstValue = true;\n remainingFirstValues--;\n }\n if (!remainingFirstValues) {\n // We're not waiting for any more\n // first values, so we can emit!\n subscriber.next(valueTransform(values.slice()));\n }\n },\n () => {\n if (!--active) {\n // We only complete the result if we have no more active\n // inner observables.\n subscriber.complete();\n }\n }\n )\n );\n },\n subscriber\n );\n }\n },\n subscriber\n );\n };\n}\n\n/**\n * A small utility to handle the couple of locations where we want to schedule if a scheduler was provided,\n * but we don't if there was no scheduler.\n */\nfunction maybeSchedule(scheduler: SchedulerLike | undefined, execute: () => void, subscription: Subscription) {\n if (scheduler) {\n executeSchedule(subscription, scheduler, execute);\n } else {\n execute();\n }\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subscriber } from '../Subscriber';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * A process embodying the general \"merge\" strategy. This is used in\n * `mergeMap` and `mergeScan` because the logic is otherwise nearly identical.\n * @param source The original source observable\n * @param subscriber The consumer subscriber\n * @param project The projection function to get our inner sources\n * @param concurrent The number of concurrent inner subscriptions\n * @param onBeforeNext Additional logic to apply before nexting to our consumer\n * @param expand If `true` this will perform an \"expand\" strategy, which differs only\n * in that it recurses, and the inner subscription must be schedule-able.\n * @param innerSubScheduler A scheduler to use to schedule inner subscriptions,\n * this is to support the expand strategy, mostly, and should be deprecated\n */\nexport function mergeInternals<T, R>(\n source: Observable<T>,\n subscriber: Subscriber<R>,\n project: (value: T, index: number) => ObservableInput<R>,\n concurrent: number,\n onBeforeNext?: (innerValue: R) => void,\n expand?: boolean,\n innerSubScheduler?: SchedulerLike,\n additionalFinalizer?: () => void\n) {\n // Buffered values, in the event of going over our concurrency limit\n const buffer: T[] = [];\n // The number of active inner subscriptions.\n let active = 0;\n // An index to pass to our accumulator function\n let index = 0;\n // Whether or not the outer source has completed.\n let isComplete = false;\n\n /**\n * Checks to see if we can complete our result or not.\n */\n const checkComplete = () => {\n // If the outer has completed, and nothing is left in the buffer,\n // and we don't have any active inner subscriptions, then we can\n // Emit the state and complete.\n if (isComplete && !buffer.length && !active) {\n subscriber.complete();\n }\n };\n\n // If we're under our concurrency limit, just start the inner subscription, otherwise buffer and wait.\n const outerNext = (value: T) => (active < concurrent ? doInnerSub(value) : buffer.push(value));\n\n const doInnerSub = (value: T) => {\n // If we're expanding, we need to emit the outer values and the inner values\n // as the inners will \"become outers\" in a way as they are recursively fed\n // back to the projection mechanism.\n expand && subscriber.next(value as any);\n\n // Increment the number of active subscriptions so we can track it\n // against our concurrency limit later.\n active++;\n\n // A flag used to show that the inner observable completed.\n // This is checked during finalization to see if we should\n // move to the next item in the buffer, if there is on.\n let innerComplete = false;\n\n // Start our inner subscription.\n innerFrom(project(value, index++)).subscribe(\n createOperatorSubscriber(\n subscriber,\n (innerValue) => {\n // `mergeScan` has additional handling here. For example\n // taking the inner value and updating state.\n onBeforeNext?.(innerValue);\n\n if (expand) {\n // If we're expanding, then just recurse back to our outer\n // handler. It will emit the value first thing.\n outerNext(innerValue as any);\n } else {\n // Otherwise, emit the inner value.\n subscriber.next(innerValue);\n }\n },\n () => {\n // Flag that we have completed, so we know to check the buffer\n // during finalization.\n innerComplete = true;\n },\n // Errors are passed to the destination.\n undefined,\n () => {\n // During finalization, if the inner completed (it wasn't errored or\n // cancelled), then we want to try the next item in the buffer if\n // there is one.\n if (innerComplete) {\n // We have to wrap this in a try/catch because it happens during\n // finalization, possibly asynchronously, and we want to pass\n // any errors that happen (like in a projection function) to\n // the outer Subscriber.\n try {\n // INNER SOURCE COMPLETE\n // Decrement the active count to ensure that the next time\n // we try to call `doInnerSub`, the number is accurate.\n active--;\n // If we have more values in the buffer, try to process those\n // Note that this call will increment `active` ahead of the\n // next conditional, if there were any more inner subscriptions\n // to start.\n while (buffer.length && active < concurrent) {\n const bufferedValue = buffer.shift()!;\n // Particularly for `expand`, we need to check to see if a scheduler was provided\n // for when we want to start our inner subscription. Otherwise, we just start\n // are next inner subscription.\n if (innerSubScheduler) {\n executeSchedule(subscriber, innerSubScheduler, () => doInnerSub(bufferedValue));\n } else {\n doInnerSub(bufferedValue);\n }\n }\n // Check to see if we can complete, and complete if so.\n checkComplete();\n } catch (err) {\n subscriber.error(err);\n }\n }\n }\n )\n );\n };\n\n // Subscribe to our source observable.\n source.subscribe(\n createOperatorSubscriber(subscriber, outerNext, () => {\n // Outer completed, make a note of it, and check to see if we can complete everything.\n isComplete = true;\n checkComplete();\n })\n );\n\n // Additional finalization (for when the destination is torn down).\n // Other finalization is added implicitly via subscription above.\n return () => {\n additionalFinalizer?.();\n };\n}\n","import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n concurrent?: number\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function mergeMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined,\n concurrent?: number\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n concurrent?: number\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n *\n * Map and flatten each letter to an Observable ticking every 1 second\n *\n * ```ts\n * import { of, mergeMap, interval, map } from 'rxjs';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x + i)))\n * );\n *\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a, b, c every second with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @param concurrent Maximum number of `ObservableInput`s being subscribed to concurrently.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and merging\n * the results of the Observables obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Infinity\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n if (isFunction(resultSelector)) {\n // DEPRECATED PATH\n return mergeMap((a, i) => map((b: any, ii: number) => resultSelector(a, b, i, ii))(innerFrom(project(a, i))), concurrent);\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n\n return operate((source, subscriber) => mergeInternals(source, subscriber, project, concurrent));\n}\n","import { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * \n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n *\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n *\n * ```ts\n * import { fromEvent, map, interval, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map(() => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n *\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n *\n * ```ts\n * import { fromEvent, map, interval, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(10)))\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n *\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link exhaustAll}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param concurrent Maximum number of inner Observables being subscribed to\n * concurrently.\n * @return A function that returns an Observable that emits values coming from\n * all the inner Observables emitted by the source Observable.\n */\nexport function mergeAll<O extends ObservableInput<any>>(concurrent: number = Infinity): OperatorFunction<O, ObservedValueOf<O>> {\n return mergeMap(identity, concurrent);\n}\n","import { mergeAll } from './mergeAll';\nimport { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable by\n * concatenating the inner Observables in order.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by putting one\n * inner Observable after the other.</span>\n *\n * \n *\n * Joins every Observable emitted by the source (a higher-order Observable), in\n * a serial fashion. It subscribes to each inner Observable only after the\n * previous inner Observable has completed, and merges all of their values into\n * the returned observable.\n *\n * __Warning:__ If the source Observable emits Observables quickly and\n * endlessly, and the inner Observables it emits generally complete slower than\n * the source emits, you can run into memory issues as the incoming Observables\n * collect in an unbounded buffer.\n *\n * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, map, interval, take, concatAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(4)))\n * );\n * const firstOrder = higherOrder.pipe(concatAll());\n * firstOrder.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concat}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link exhaustAll}\n * @see {@link mergeAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @return A function that returns an Observable emitting values from all the\n * inner Observables concatenated.\n */\nexport function concatAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {\n return mergeAll(1);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInputTuple, SchedulerLike } from '../types';\nimport { concatAll } from '../operators/concatAll';\nimport { popScheduler } from '../util/args';\nimport { from } from './from';\n\nexport function concat<T extends readonly unknown[]>(...inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;\nexport function concat<T extends readonly unknown[]>(\n ...inputsAndScheduler: [...ObservableInputTuple<T>, SchedulerLike]\n): Observable<T[number]>;\n\n/**\n * Creates an output Observable which sequentially emits all values from the first given\n * Observable and then moves on to the next.\n *\n * <span class=\"informal\">Concatenates multiple Observables together by\n * sequentially emitting their values, one Observable after the other.</span>\n *\n * \n *\n * `concat` joins multiple Observables together, by subscribing to them one at a time and\n * merging their results into the output Observable. You can pass either an array of\n * Observables, or put them directly as arguments. Passing an empty array will result\n * in Observable that completes immediately.\n *\n * `concat` will subscribe to first input Observable and emit all its values, without\n * changing or affecting them in any way. When that Observable completes, it will\n * subscribe to then next Observable passed and, again, emit its values. This will be\n * repeated, until the operator runs out of Observables. When last input Observable completes,\n * `concat` will complete as well. At any given moment only one Observable passed to operator\n * emits values. If you would like to emit values from passed Observables concurrently, check out\n * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,\n * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.\n *\n * Note that if some input Observable never completes, `concat` will also never complete\n * and Observables following the one that did not complete will never be subscribed. On the other\n * hand, if some Observable simply completes immediately after it is subscribed, it will be\n * invisible for `concat`, which will just move on to the next Observable.\n *\n * If any Observable in chain errors, instead of passing control to the next Observable,\n * `concat` will error immediately as well. Observables that would be subscribed after\n * the one that emitted error, never will.\n *\n * If you pass to `concat` the same Observable many times, its stream of values\n * will be \"replayed\" on every subscription, which means you can repeat given Observable\n * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,\n * you can always use {@link repeat}.\n *\n * ## Examples\n *\n * Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10\n *\n * ```ts\n * import { interval, take, range, concat } from 'rxjs';\n *\n * const timer = interval(1000).pipe(take(4));\n * const sequence = range(1, 10);\n * const result = concat(timer, sequence);\n * result.subscribe(x => console.log(x));\n *\n * // results in:\n * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10\n * ```\n *\n * Concatenate 3 Observables\n *\n * ```ts\n * import { interval, take, concat } from 'rxjs';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const result = concat(timer1, timer2, timer3);\n * result.subscribe(x => console.log(x));\n *\n * // results in the following:\n * // (Prints to console sequentially)\n * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9\n * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5\n * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9\n * ```\n *\n * Concatenate the same Observable to repeat it\n *\n * ```ts\n * import { interval, take, concat } from 'rxjs';\n *\n * const timer = interval(1000).pipe(take(2));\n *\n * concat(timer, timer) // concatenating the same Observable!\n * .subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('...and it is done!')\n * });\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 0 after 3s\n * // 1 after 4s\n * // '...and it is done!' also after 4s\n * ```\n *\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link startWith}\n * @see {@link endWith}\n *\n * @param args `ObservableInput`s to concatenate.\n */\nexport function concat(...args: any[]): Observable<unknown> {\n return concatAll()(from(args, popScheduler(args)));\n}\n","import { Observable } from '../Observable';\nimport { ObservedValueOf, ObservableInput } from '../types';\nimport { innerFrom } from './innerFrom';\n\n/**\n * Creates an Observable that, on subscribe, calls an Observable factory to\n * make an Observable for each new Observer.\n *\n * <span class=\"informal\">Creates the Observable lazily, that is, only when it\n * is subscribed.\n * </span>\n *\n * \n *\n * `defer` allows you to create an Observable only when the Observer\n * subscribes. It waits until an Observer subscribes to it, calls the given\n * factory function to get an Observable -- where a factory function typically\n * generates a new Observable -- and subscribes the Observer to this Observable.\n * In case the factory function returns a falsy value, then EMPTY is used as\n * Observable instead. Last but not least, an exception during the factory\n * function call is transferred to the Observer by calling `error`.\n *\n * ## Example\n *\n * Subscribe to either an Observable of clicks or an Observable of interval, at random\n *\n * ```ts\n * import { defer, fromEvent, interval } from 'rxjs';\n *\n * const clicksOrInterval = defer(() => {\n * return Math.random() > 0.5\n * ? fromEvent(document, 'click')\n * : interval(1000);\n * });\n * clicksOrInterval.subscribe(x => console.log(x));\n *\n * // Results in the following behavior:\n * // If the result of Math.random() is greater than 0.5 it will listen\n * // for clicks anywhere on the \"document\"; when document is clicked it\n * // will log a MouseEvent object to the console. If the result is less\n * // than 0.5 it will emit ascending numbers, one every second(1000ms).\n * ```\n *\n * @see {@link Observable}\n *\n * @param observableFactory The Observable factory function to invoke for each\n * Observer that subscribes to the output Observable. May also return any\n * `ObservableInput`, which will be converted on the fly to an Observable.\n * @return An Observable whose Observers' subscriptions trigger an invocation of the\n * given Observable factory function.\n */\nexport function defer<R extends ObservableInput<any>>(observableFactory: () => R): Observable<ObservedValueOf<R>> {\n return new Observable<ObservedValueOf<R>>((subscriber) => {\n innerFrom(observableFactory()).subscribe(subscriber);\n });\n}\n","import { Connectable, ObservableInput, SubjectLike } from '../types';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { defer } from './defer';\n\nexport interface ConnectableConfig<T> {\n /**\n * A factory function used to create the Subject through which the source\n * is multicast. By default this creates a {@link Subject}.\n */\n connector: () => SubjectLike<T>;\n /**\n * If true, the resulting observable will reset internal state upon disconnection\n * and return to a \"cold\" state. This allows the resulting observable to be\n * reconnected.\n * If false, upon disconnection, the connecting subject will remain the\n * connecting subject, meaning the resulting observable will not go \"cold\" again,\n * and subsequent repeats or resubscriptions will resubscribe to that same subject.\n */\n resetOnDisconnect?: boolean;\n}\n\n/**\n * The default configuration for `connectable`.\n */\nconst DEFAULT_CONFIG: ConnectableConfig<unknown> = {\n connector: () => new Subject<unknown>(),\n resetOnDisconnect: true,\n};\n\n/**\n * Creates an observable that multicasts once `connect()` is called on it.\n *\n * @param source The observable source to make connectable.\n * @param config The configuration object for `connectable`.\n * @returns A \"connectable\" observable, that has a `connect()` method, that you must call to\n * connect the source to all consumers through the subject provided as the connector.\n */\nexport function connectable<T>(source: ObservableInput<T>, config: ConnectableConfig<T> = DEFAULT_CONFIG): Connectable<T> {\n // The subscription representing the connection.\n let connection: Subscription | null = null;\n const { connector, resetOnDisconnect = true } = config;\n let subject = connector();\n\n const result: any = new Observable<T>((subscriber) => {\n return subject.subscribe(subscriber);\n });\n\n // Define the `connect` function. This is what users must call\n // in order to \"connect\" the source to the subject that is\n // multicasting it.\n result.connect = () => {\n if (!connection || connection.closed) {\n connection = defer(() => source).subscribe(subject);\n if (resetOnDisconnect) {\n connection.add(() => (subject = connector()));\n }\n }\n return connection;\n };\n\n return result;\n}\n","import { Observable } from '../Observable';\nimport { ObservedValueOf, ObservableInputTuple, ObservableInput } from '../types';\nimport { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';\nimport { innerFrom } from './innerFrom';\nimport { popResultSelector } from '../util/args';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { createObject } from '../util/createObject';\nimport { AnyCatcher } from '../AnyCatcher';\n\n// forkJoin(any)\n// We put this first because we need to catch cases where the user has supplied\n// _exactly `any`_ as the argument. Since `any` literally matches _anything_,\n// we don't want it to randomly hit one of the other type signatures below,\n// as we have no idea at build-time what type we should be returning when given an any.\n\n/**\n * You have passed `any` here, we can't figure out if it is\n * an array or an object, so you're getting `unknown`. Use better types.\n * @param arg Something typed as `any`\n */\nexport function forkJoin<T extends AnyCatcher>(arg: T): Observable<unknown>;\n\n// forkJoin(null | undefined)\nexport function forkJoin(scheduler: null | undefined): Observable<never>;\n\n// forkJoin([a, b, c])\nexport function forkJoin(sources: readonly []): Observable<never>;\nexport function forkJoin<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;\nexport function forkJoin<A extends readonly unknown[], R>(\n sources: readonly [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R\n): Observable<R>;\n\n// forkJoin(a, b, c)\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function forkJoin<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function forkJoin<A extends readonly unknown[], R>(\n ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]\n): Observable<R>;\n\n// forkJoin({a, b, c})\nexport function forkJoin(sourcesObject: { [K in any]: never }): Observable<never>;\nexport function forkJoin<T extends Record<string, ObservableInput<any>>>(\n sourcesObject: T\n): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;\n\n/**\n * Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns\n * an {@link Observable} that emits either an array of values in the exact same order as the passed array,\n * or a dictionary of values in the same shape as the passed dictionary.\n *\n * <span class=\"informal\">Wait for Observables to complete and then combine last values they emitted;\n * complete immediately if an empty array is passed.</span>\n *\n * \n *\n * `forkJoin` is an operator that takes any number of input observables which can be passed either as an array\n * or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed),\n * then the resulting stream will complete immediately.\n *\n * `forkJoin` will wait for all passed observables to emit and complete and then it will emit an array or an object with last\n * values from corresponding observables.\n *\n * If you pass an array of `n` observables to the operator, then the resulting\n * array will have `n` values, where the first value is the last one emitted by the first observable,\n * second value is the last one emitted by the second observable and so on.\n *\n * If you pass a dictionary of observables to the operator, then the resulting\n * objects will have the same keys as the dictionary passed, with their last values they have emitted\n * located at the corresponding key.\n *\n * That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined\n * values not only at the end of the lifecycle of passed observables, but also throughout it, try out {@link combineLatest}\n * or {@link zip} instead.\n *\n * In order for the resulting array to have the same length as the number of input observables, whenever any of\n * the given observables completes without emitting any value, `forkJoin` will complete at that moment as well\n * and it will not emit anything either, even if it already has some last values from other observables.\n * Conversely, if there is an observable that never completes, `forkJoin` will never complete either,\n * unless at any point some other observable completes without emitting a value, which brings us back to\n * the previous case. Overall, in order for `forkJoin` to emit a value, all given observables\n * have to emit something at least once and complete.\n *\n * If any given observable errors at some point, `forkJoin` will error as well and immediately unsubscribe\n * from the other observables.\n *\n * Optionally `forkJoin` accepts a `resultSelector` function, that will be called with values which normally\n * would land in the emitted array. Whatever is returned by the `resultSelector`, will appear in the output\n * observable instead. This means that the default `resultSelector` can be thought of as a function that takes\n * all its arguments and puts them into an array. Note that the `resultSelector` will be called only\n * when `forkJoin` is supposed to emit a result.\n *\n * ## Examples\n *\n * Use `forkJoin` with a dictionary of observable inputs\n *\n * ```ts\n * import { forkJoin, of, timer } from 'rxjs';\n *\n * const observable = forkJoin({\n * foo: of(1, 2, 3, 4),\n * bar: Promise.resolve(8),\n * baz: timer(4000)\n * });\n * observable.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // { foo: 4, bar: 8, baz: 0 } after 4 seconds\n * // 'This is how it ends!' immediately after\n * ```\n *\n * Use `forkJoin` with an array of observable inputs\n *\n * ```ts\n * import { forkJoin, of, timer } from 'rxjs';\n *\n * const observable = forkJoin([\n * of(1, 2, 3, 4),\n * Promise.resolve(8),\n * timer(4000)\n * ]);\n * observable.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // [4, 8, 0] after 4 seconds\n * // 'This is how it ends!' immediately after\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n *\n * @param args Any number of `ObservableInput`s provided either as an array, as an object\n * or as arguments passed directly to the operator.\n * @return Observable emitting either an array of last values emitted by passed Observables\n * or value from project function.\n */\nexport function forkJoin(...args: any[]): Observable<any> {\n const resultSelector = popResultSelector(args);\n const { args: sources, keys } = argsArgArrayOrObject(args);\n const result = new Observable((subscriber) => {\n const { length } = sources;\n if (!length) {\n subscriber.complete();\n return;\n }\n const values = new Array(length);\n let remainingCompletions = length;\n let remainingEmissions = length;\n for (let sourceIndex = 0; sourceIndex < length; sourceIndex++) {\n let hasValue = false;\n innerFrom(sources[sourceIndex]).subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n if (!hasValue) {\n hasValue = true;\n remainingEmissions--;\n }\n values[sourceIndex] = value;\n },\n () => remainingCompletions--,\n undefined,\n () => {\n if (!remainingCompletions || !hasValue) {\n if (!remainingEmissions) {\n subscriber.next(keys ? createObject(keys, values) : values);\n }\n subscriber.complete();\n }\n }\n )\n );\n }\n });\n return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { Observable } from '../Observable';\nimport { mergeMap } from '../operators/mergeMap';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isFunction } from '../util/isFunction';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\n\n// These constants are used to create handler registry functions using array mapping below.\nconst nodeEventEmitterMethods = ['addListener', 'removeListener'] as const;\nconst eventTargetMethods = ['addEventListener', 'removeEventListener'] as const;\nconst jqueryMethods = ['on', 'off'] as const;\n\nexport interface NodeStyleEventEmitter {\n addListener(eventName: string | symbol, handler: NodeEventHandler): this;\n removeListener(eventName: string | symbol, handler: NodeEventHandler): this;\n}\n\nexport type NodeEventHandler = (...args: any[]) => void;\n\n// For APIs that implement `addListener` and `removeListener` methods that may\n// not use the same arguments or return EventEmitter values\n// such as React Native\nexport interface NodeCompatibleEventEmitter {\n addListener(eventName: string, handler: NodeEventHandler): void | {};\n removeListener(eventName: string, handler: NodeEventHandler): void | {};\n}\n\n// Use handler types like those in @types/jquery. See:\n// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/847731ba1d7fa6db6b911c0e43aa0afe596e7723/types/jquery/misc.d.ts#L6395\nexport interface JQueryStyleEventEmitter<TContext, T> {\n on(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;\n off(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;\n}\n\nexport interface EventListenerObject<E> {\n handleEvent(evt: E): void;\n}\n\nexport interface HasEventTargetAddRemove<E> {\n addEventListener(\n type: string,\n listener: ((evt: E) => void) | EventListenerObject<E> | null,\n options?: boolean | AddEventListenerOptions\n ): void;\n removeEventListener(\n type: string,\n listener: ((evt: E) => void) | EventListenerObject<E> | null,\n options?: EventListenerOptions | boolean\n ): void;\n}\n\nexport interface EventListenerOptions {\n capture?: boolean;\n passive?: boolean;\n once?: boolean;\n}\n\nexport interface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\nexport function fromEvent<T>(target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>, eventName: string): Observable<T>;\nexport function fromEvent<T, R>(\n target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,\n eventName: string,\n resultSelector: (event: T) => R\n): Observable<R>;\nexport function fromEvent<T>(\n target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,\n eventName: string,\n options: EventListenerOptions\n): Observable<T>;\nexport function fromEvent<T, R>(\n target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,\n eventName: string,\n options: EventListenerOptions,\n resultSelector: (event: T) => R\n): Observable<R>;\n\nexport function fromEvent(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<unknown>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function fromEvent<T>(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<T>;\nexport function fromEvent<R>(\n target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>,\n eventName: string,\n resultSelector: (...args: any[]) => R\n): Observable<R>;\n\nexport function fromEvent(\n target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,\n eventName: string\n): Observable<unknown>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function fromEvent<T>(target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>, eventName: string): Observable<T>;\nexport function fromEvent<R>(\n target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,\n eventName: string,\n resultSelector: (...args: any[]) => R\n): Observable<R>;\n\nexport function fromEvent<T>(\n target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,\n eventName: string\n): Observable<T>;\nexport function fromEvent<T, R>(\n target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,\n eventName: string,\n resultSelector: (value: T, ...args: any[]) => R\n): Observable<R>;\n\n/**\n * Creates an Observable that emits events of a specific type coming from the\n * given event target.\n *\n * <span class=\"informal\">Creates an Observable from DOM events, or Node.js\n * EventEmitter events or others.</span>\n *\n * \n *\n * `fromEvent` accepts as a first argument event target, which is an object with methods\n * for registering event handler functions. As a second argument it takes string that indicates\n * type of event we want to listen for. `fromEvent` supports selected types of event targets,\n * which are described in detail below. If your event target does not match any of the ones listed,\n * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.\n * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event\n * handler functions have different names, but they all accept a string describing event type\n * and function itself, which will be called whenever said event happens.\n *\n * Every time resulting Observable is subscribed, event handler function will be registered\n * to event target on given event type. When that event fires, value\n * passed as a first argument to registered function will be emitted by output Observable.\n * When Observable is unsubscribed, function will be unregistered from event target.\n *\n * Note that if event target calls registered function with more than one argument, second\n * and following arguments will not appear in resulting stream. In order to get access to them,\n * you can pass to `fromEvent` optional project function, which will be called with all arguments\n * passed to event handler. Output Observable will then emit value returned by project function,\n * instead of the usual value.\n *\n * Remember that event targets listed below are checked via duck typing. It means that\n * no matter what kind of object you have and no matter what environment you work in,\n * you can safely use `fromEvent` on that object if it exposes described methods (provided\n * of course they behave as was described above). So for example if Node.js library exposes\n * event target which has the same method names as DOM EventTarget, `fromEvent` is still\n * a good choice.\n *\n * If the API you use is more callback then event handler oriented (subscribed\n * callback function fires only once and thus there is no need to manually\n * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}\n * instead.\n *\n * `fromEvent` supports following types of event targets:\n *\n * **DOM EventTarget**\n *\n * This is an object with `addEventListener` and `removeEventListener` methods.\n *\n * In the browser, `addEventListener` accepts - apart from event type string and event\n * handler function arguments - optional third parameter, which is either an object or boolean,\n * both used for additional configuration how and when passed function will be called. When\n * `fromEvent` is used with event target of that type, you can provide this values\n * as third parameter as well.\n *\n * **Node.js EventEmitter**\n *\n * An object with `addListener` and `removeListener` methods.\n *\n * **JQuery-style event target**\n *\n * An object with `on` and `off` methods\n *\n * **DOM NodeList**\n *\n * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.\n *\n * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes\n * it contains and install event handler function in every of them. When returned Observable\n * is unsubscribed, function will be removed from all Nodes.\n *\n * **DOM HtmlCollection**\n *\n * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is\n * installed and removed in each of elements.\n *\n *\n * ## Examples\n *\n * Emit clicks happening on the DOM document\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * clicks.subscribe(x => console.log(x));\n *\n * // Results in:\n * // MouseEvent object logged to console every time a click\n * // occurs on the document.\n * ```\n *\n * Use `addEventListener` with capture option\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * // note optional configuration parameter which will be passed to addEventListener\n * const clicksInDocument = fromEvent(document, 'click', { capture: true });\n * const clicksInDiv = fromEvent(div, 'click');\n *\n * clicksInDocument.subscribe(() => console.log('document'));\n * clicksInDiv.subscribe(() => console.log('div'));\n *\n * // By default events bubble UP in DOM tree, so normally\n * // when we would click on div in document\n * // \"div\" would be logged first and then \"document\".\n * // Since we specified optional `capture` option, document\n * // will catch event when it goes DOWN DOM tree, so console\n * // will log \"document\" and then \"div\".\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n * @see {@link fromEventPattern}\n *\n * @param target The DOM EventTarget, Node.js EventEmitter, JQuery-like event target,\n * NodeList or HTMLCollection to attach the event handler to.\n * @param eventName The event name of interest, being emitted by the `target`.\n * @param options Options to pass through to the underlying `addListener`,\n * `addEventListener` or `on` functions.\n * @param resultSelector A mapping function used to transform events. It takes the\n * arguments from the event handler and should return a single value.\n * @return An Observable emitting events registered through `target`'s\n * listener handlers.\n */\nexport function fromEvent<T>(\n target: any,\n eventName: string,\n options?: EventListenerOptions | ((...args: any[]) => T),\n resultSelector?: (...args: any[]) => T\n): Observable<T> {\n if (isFunction(options)) {\n resultSelector = options;\n options = undefined;\n }\n if (resultSelector) {\n return fromEvent<T>(target, eventName, options as EventListenerOptions).pipe(mapOneOrManyArgs(resultSelector));\n }\n\n // Figure out our add and remove methods. In order to do this,\n // we are going to analyze the target in a preferred order, if\n // the target matches a given signature, we take the two \"add\" and \"remove\"\n // method names and apply them to a map to create opposite versions of the\n // same function. This is because they all operate in duplicate pairs,\n // `addListener(name, handler)`, `removeListener(name, handler)`, for example.\n // The call only differs by method name, as to whether or not you're adding or removing.\n const [add, remove] =\n // If it is an EventTarget, we need to use a slightly different method than the other two patterns.\n isEventTarget(target)\n ? eventTargetMethods.map((methodName) => (handler: any) => target[methodName](eventName, handler, options as EventListenerOptions))\n : // In all other cases, the call pattern is identical with the exception of the method names.\n isNodeStyleEventEmitter(target)\n ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))\n : isJQueryStyleEventEmitter(target)\n ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))\n : [];\n\n // If add is falsy, it's because we didn't match a pattern above.\n // Check to see if it is an ArrayLike, because if it is, we want to\n // try to apply fromEvent to all of it's items. We do this check last,\n // because there are may be some types that are both ArrayLike *and* implement\n // event registry points, and we'd rather delegate to that when possible.\n if (!add) {\n if (isArrayLike(target)) {\n return mergeMap((subTarget: any) => fromEvent(subTarget, eventName, options as EventListenerOptions))(\n innerFrom(target)\n ) as Observable<T>;\n }\n }\n\n // If add is falsy and we made it here, it's because we didn't\n // match any valid target objects above.\n if (!add) {\n throw new TypeError('Invalid event target');\n }\n\n return new Observable<T>((subscriber) => {\n // The handler we are going to register. Forwards the event object, by itself, or\n // an array of arguments to the event handler, if there is more than one argument,\n // to the consumer.\n const handler = (...args: any[]) => subscriber.next(1 < args.length ? args : args[0]);\n // Do the work of adding the handler to the target.\n add(handler);\n // When we finalize, we want to remove the handler and free up memory.\n return () => remove!(handler);\n });\n}\n\n/**\n * Used to create `add` and `remove` functions to register and unregister event handlers\n * from a target in the most common handler pattern, where there are only two arguments.\n * (e.g. `on(name, fn)`, `off(name, fn)`, `addListener(name, fn)`, or `removeListener(name, fn)`)\n * @param target The target we're calling methods on\n * @param eventName The event name for the event we're creating register or unregister functions for\n */\nfunction toCommonHandlerRegistry(target: any, eventName: string) {\n return (methodName: string) => (handler: any) => target[methodName](eventName, handler);\n}\n\n/**\n * Checks to see if the target implements the required node-style EventEmitter methods\n * for adding and removing event handlers.\n * @param target the object to check\n */\nfunction isNodeStyleEventEmitter(target: any): target is NodeStyleEventEmitter {\n return isFunction(target.addListener) && isFunction(target.removeListener);\n}\n\n/**\n * Checks to see if the target implements the required jQuery-style EventEmitter methods\n * for adding and removing event handlers.\n * @param target the object to check\n */\nfunction isJQueryStyleEventEmitter(target: any): target is JQueryStyleEventEmitter<any, any> {\n return isFunction(target.on) && isFunction(target.off);\n}\n\n/**\n * Checks to see if the target implements the required EventTarget methods\n * for adding and removing event handlers.\n * @param target the object to check\n */\nfunction isEventTarget(target: any): target is HasEventTargetAddRemove<any> {\n return isFunction(target.addEventListener) && isFunction(target.removeEventListener);\n}\n","import { Observable } from '../Observable';\nimport { isFunction } from '../util/isFunction';\nimport { NodeEventHandler } from './fromEvent';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\n\n/* tslint:disable:max-line-length */\nexport function fromEventPattern<T>(\n addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void\n): Observable<T>;\nexport function fromEventPattern<T>(\n addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void,\n resultSelector?: (...args: any[]) => T\n): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Creates an Observable from an arbitrary API for registering event handlers.\n *\n * <span class=\"informal\">When that method for adding event handler was something {@link fromEvent}\n * was not prepared for.</span>\n *\n * \n *\n * `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions\n * for events. It is similar to {@link fromEvent}, but far\n * more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by\n * `fromEventPattern` (although in slightly more verbose way).\n *\n * This operator accepts as a first argument an `addHandler` function, which will be injected with\n * handler parameter. That handler is actually an event handler function that you now can pass\n * to API expecting it. `addHandler` will be called whenever Observable\n * returned by the operator is subscribed, so registering handler in API will not\n * necessarily happen when `fromEventPattern` is called.\n *\n * After registration, every time an event that we listen to happens,\n * Observable returned by `fromEventPattern` will emit value that event handler\n * function was called with. Note that if event handler was called with more\n * than one argument, second and following arguments will not appear in the Observable.\n *\n * If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`\n * another function - `removeHandler` - as a second parameter. It will be injected\n * with the same handler function as before, which now you can use to unregister\n * it from the API. `removeHandler` will be called when consumer of resulting Observable\n * unsubscribes from it.\n *\n * In some APIs unregistering is actually handled differently. Method registering an event handler\n * returns some kind of token, which is later used to identify which function should\n * be unregistered or it itself has method that unregisters event handler.\n * If that is the case with your API, make sure token returned\n * by registering method is returned by `addHandler`. Then it will be passed\n * as a second argument to `removeHandler`, where you will be able to use it.\n *\n * If you need access to all event handler parameters (not only the first one),\n * or you need to transform them in any way, you can call `fromEventPattern` with optional\n * third parameter - project function which will accept all arguments passed to\n * event handler when it is called. Whatever is returned from project function will appear on\n * resulting stream instead of usual event handlers first argument. This means\n * that default project can be thought of as function that takes its first parameter\n * and ignores the rest.\n *\n * ## Examples\n *\n * Emits clicks happening on the DOM document\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * function addClickHandler(handler) {\n * document.addEventListener('click', handler);\n * }\n *\n * function removeClickHandler(handler) {\n * document.removeEventListener('click', handler);\n * }\n *\n * const clicks = fromEventPattern(\n * addClickHandler,\n * removeClickHandler\n * );\n * clicks.subscribe(x => console.log(x));\n *\n * // Whenever you click anywhere in the browser, DOM MouseEvent\n * // object will be logged.\n * ```\n *\n * Use with API that returns cancellation token\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * const token = someAPI.registerEventHandler(function() {});\n * someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts\n * // not handler itself, but special token.\n *\n * const someAPIObservable = fromEventPattern(\n * function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...\n * function(handler, token) { someAPI.unregisterEventHandler(token); } // ...to then use it here.\n * );\n * ```\n *\n * Use with project function\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * someAPI.registerEventHandler((eventType, eventMessage) => {\n * console.log(eventType, eventMessage); // Logs 'EVENT_TYPE' 'EVENT_MESSAGE' to console.\n * });\n *\n * const someAPIObservable = fromEventPattern(\n * handler => someAPI.registerEventHandler(handler),\n * handler => someAPI.unregisterEventHandler(handler)\n * (eventType, eventMessage) => eventType + ' --- ' + eventMessage // without that function only 'EVENT_TYPE'\n * ); // would be emitted by the Observable\n *\n * someAPIObservable.subscribe(value => console.log(value));\n *\n * // Logs:\n * // 'EVENT_TYPE --- EVENT_MESSAGE'\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n *\n * @param addHandler A function that takes a `handler` function as argument and attaches it\n * somehow to the actual source of events.\n * @param removeHandler A function that takes a `handler` function as an argument and removes\n * it from the event source. If `addHandler` returns some kind of token, `removeHandler` function\n * will have it as a second parameter.\n * @param resultSelector A function to transform results. It takes the arguments from the event\n * handler and should return a single value.\n * @return Observable which, when an event happens, emits first parameter passed to registered\n * event handler. Alternatively it emits whatever project function returns at that moment.\n */\nexport function fromEventPattern<T>(\n addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void,\n resultSelector?: (...args: any[]) => T\n): Observable<T | T[]> {\n if (resultSelector) {\n return fromEventPattern<T>(addHandler, removeHandler).pipe(mapOneOrManyArgs(resultSelector));\n }\n\n return new Observable<T | T[]>((subscriber) => {\n const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);\n const retValue = addHandler(handler);\n return isFunction(removeHandler) ? () => removeHandler(handler, retValue) : undefined;\n });\n}\n","import { Observable } from '../Observable';\nimport { identity } from '../util/identity';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { defer } from './defer';\nimport { scheduleIterable } from '../scheduled/scheduleIterable';\n\ntype ConditionFunc<S> = (state: S) => boolean;\ntype IterateFunc<S> = (state: S) => S;\ntype ResultFunc<S, T> = (state: S) => T;\n\nexport interface GenerateBaseOptions<S> {\n /**\n * Initial state.\n */\n initialState: S;\n /**\n * Condition function that accepts state and returns boolean.\n * When it returns false, the generator stops.\n * If not specified, a generator never stops.\n */\n condition?: ConditionFunc<S>;\n /**\n * Iterate function that accepts state and returns new state.\n */\n iterate: IterateFunc<S>;\n /**\n * SchedulerLike to use for generation process.\n * By default, a generator starts immediately.\n */\n scheduler?: SchedulerLike;\n}\n\nexport interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {\n /**\n * Result selection function that accepts state and returns a value to emit.\n */\n resultSelector: ResultFunc<S, T>;\n}\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n *\n * \n *\n * ## Examples\n *\n * Produces sequence of numbers\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate(0, x => x < 3, x => x + 1, x => x);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * ```\n *\n * Use `asapScheduler`\n *\n * ```ts\n * import { generate, asapScheduler } from 'rxjs';\n *\n * const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asapScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 2\n * // 3\n * // 5\n * ```\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param initialState Initial state.\n * @param condition Condition to terminate generation (upon returning false).\n * @param iterate Iteration step function.\n * @param resultSelector Selector function for results produced in the sequence.\n * @param scheduler A {@link SchedulerLike} on which to run the generator loop.\n * If not provided, defaults to emit immediately.\n * @returns The generated sequence.\n * @deprecated Instead of passing separate arguments, use the options argument.\n * Signatures taking separate arguments will be removed in v8.\n */\nexport function generate<T, S>(\n initialState: S,\n condition: ConditionFunc<S>,\n iterate: IterateFunc<S>,\n resultSelector: ResultFunc<S, T>,\n scheduler?: SchedulerLike\n): Observable<T>;\n\n/**\n * Generates an Observable by running a state-driven loop\n * that emits an element on each iteration.\n *\n * <span class=\"informal\">Use it instead of nexting values in a for loop.</span>\n *\n * \n *\n * `generate` allows you to create a stream of values generated with a loop very similar to\n * a traditional for loop. The first argument of `generate` is a beginning value. The second argument\n * is a function that accepts this value and tests if some condition still holds. If it does,\n * then the loop continues, if not, it stops. The third value is a function which takes the\n * previously defined value and modifies it in some way on each iteration. Note how these three parameters\n * are direct equivalents of three expressions in a traditional for loop: the first expression\n * initializes some state (for example, a numeric index), the second tests if the loop can perform the next\n * iteration (for example, if the index is lower than 10) and the third states how the defined value\n * will be modified on every step (for example, the index will be incremented by one).\n *\n * Return value of a `generate` operator is an Observable that on each loop iteration\n * emits a value. First of all, the condition function is ran. If it returns true, then the Observable\n * emits the currently stored value (initial value at the first iteration) and finally updates\n * that value with iterate function. If at some point the condition returns false, then the Observable\n * completes at that moment.\n *\n * Optionally you can pass a fourth parameter to `generate` - a result selector function which allows you\n * to immediately map the value that would normally be emitted by an Observable.\n *\n * If you find three anonymous functions in `generate` call hard to read, you can provide\n * a single object to the operator instead where the object has the properties: `initialState`,\n * `condition`, `iterate` and `resultSelector`, which should have respective values that you\n * would normally pass to `generate`. `resultSelector` is still optional, but that form\n * of calling `generate` allows you to omit `condition` as well. If you omit it, that means\n * condition always holds, or in other words the resulting Observable will never complete.\n *\n * Both forms of `generate` can optionally accept a scheduler. In case of a multi-parameter call,\n * scheduler simply comes as a last argument (no matter if there is a `resultSelector`\n * function or not). In case of a single-parameter call, you can provide it as a\n * `scheduler` property on the object passed to the operator. In both cases, a scheduler decides when\n * the next iteration of the loop will happen and therefore when the next value will be emitted\n * by the Observable. For example, to ensure that each value is pushed to the Observer\n * on a separate task in the event loop, you could use the `async` scheduler. Note that\n * by default (when no scheduler is passed) values are simply emitted synchronously.\n *\n *\n * ## Examples\n *\n * Use with condition and iterate functions\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate(0, x => x < 3, x => x + 1);\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 'Complete!'\n * ```\n *\n * Use with condition, iterate and resultSelector functions\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate(0, x => x < 3, x => x + 1, x => x * 1000);\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 'Complete!'\n * ```\n *\n * Use with options object\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * condition(value) { return value < 3; },\n * iterate(value) { return value + 1; },\n * resultSelector(value) { return value * 1000; }\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 'Complete!'\n * ```\n *\n * Use options object without condition function\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * iterate(value) { return value + 1; },\n * resultSelector(value) { return value * 1000; }\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!') // This will never run\n * });\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 3000\n * // ...and never stops.\n * ```\n *\n * @see {@link from}\n *\n * @param initialState Initial state.\n * @param condition Condition to terminate generation (upon returning false).\n * @param iterate Iteration step function.\n * @param scheduler A {@link Scheduler} on which to run the generator loop. If not\n * provided, defaults to emitting immediately.\n * @return The generated sequence.\n * @deprecated Instead of passing separate arguments, use the options argument.\n * Signatures taking separate arguments will be removed in v8.\n */\nexport function generate<S>(\n initialState: S,\n condition: ConditionFunc<S>,\n iterate: IterateFunc<S>,\n scheduler?: SchedulerLike\n): Observable<S>;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition and scheduler.\n *\n * \n *\n * ## Examples\n *\n * Use options object with condition function\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * condition: x => x < 3,\n * iterate: x => x + 1\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 'Complete!'\n * ```\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param options Object that must contain initialState, iterate and might contain condition and scheduler.\n * @returns The generated sequence.\n */\nexport function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition, result selector and scheduler.\n *\n * \n *\n * ## Examples\n *\n * Use options object with condition and iterate function\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * condition: x => x < 3,\n * iterate: x => x + 1,\n * resultSelector: x => x\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 'Complete!'\n * ```\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.\n * @returns The generated sequence.\n */\nexport function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;\n\nexport function generate<T, S>(\n initialStateOrOptions: S | GenerateOptions<T, S>,\n condition?: ConditionFunc<S>,\n iterate?: IterateFunc<S>,\n resultSelectorOrScheduler?: ResultFunc<S, T> | SchedulerLike,\n scheduler?: SchedulerLike\n): Observable<T> {\n let resultSelector: ResultFunc<S, T>;\n let initialState: S;\n\n // TODO: Remove this as we move away from deprecated signatures\n // and move towards a configuration object argument.\n if (arguments.length === 1) {\n // If we only have one argument, we can assume it is a configuration object.\n // Note that folks not using TypeScript may trip over this.\n ({\n initialState,\n condition,\n iterate,\n resultSelector = identity as ResultFunc<S, T>,\n scheduler,\n } = initialStateOrOptions as GenerateOptions<T, S>);\n } else {\n // Deprecated arguments path. Figure out what the user\n // passed and set it here.\n initialState = initialStateOrOptions as S;\n if (!resultSelectorOrScheduler || isScheduler(resultSelectorOrScheduler)) {\n resultSelector = identity as ResultFunc<S, T>;\n scheduler = resultSelectorOrScheduler as SchedulerLike;\n } else {\n resultSelector = resultSelectorOrScheduler as ResultFunc<S, T>;\n }\n }\n\n // The actual generator used to \"generate\" values.\n function* gen() {\n for (let state = initialState; !condition || condition(state); state = iterate!(state)) {\n yield resultSelector(state);\n }\n }\n\n // We use `defer` because we want to defer the creation of the iterator from the iterable.\n return defer(\n (scheduler\n ? // If a scheduler was provided, use `scheduleIterable` to ensure that iteration/generation\n // happens on the scheduler.\n () => scheduleIterable(gen(), scheduler!)\n : // Otherwise, if there's no scheduler, we can just use the generator function directly in\n // `defer` and executing it will return the generator (which is iterable).\n gen) as () => ObservableInput<T>\n );\n}\n","import { Observable } from '../Observable';\nimport { defer } from './defer';\nimport { ObservableInput } from '../types';\n\n/**\n * Checks a boolean at subscription time, and chooses between one of two observable sources\n *\n * `iif` expects a function that returns a boolean (the `condition` function), and two sources,\n * the `trueResult` and the `falseResult`, and returns an Observable.\n *\n * At the moment of subscription, the `condition` function is called. If the result is `true`, the\n * subscription will be to the source passed as the `trueResult`, otherwise, the subscription will be\n * to the source passed as the `falseResult`.\n *\n * If you need to check more than two options to choose between more than one observable, have a look at the {@link defer} creation method.\n *\n * ## Examples\n *\n * Change at runtime which Observable will be subscribed\n *\n * ```ts\n * import { iif, of } from 'rxjs';\n *\n * let subscribeToFirst;\n * const firstOrSecond = iif(\n * () => subscribeToFirst,\n * of('first'),\n * of('second')\n * );\n *\n * subscribeToFirst = true;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // 'first'\n *\n * subscribeToFirst = false;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // 'second'\n * ```\n *\n * Control access to an Observable\n *\n * ```ts\n * import { iif, of, EMPTY } from 'rxjs';\n *\n * let accessGranted;\n * const observableIfYouHaveAccess = iif(\n * () => accessGranted,\n * of('It seems you have an access...'),\n * EMPTY\n * );\n *\n * accessGranted = true;\n * observableIfYouHaveAccess.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('The end')\n * });\n *\n * // Logs:\n * // 'It seems you have an access...'\n * // 'The end'\n *\n * accessGranted = false;\n * observableIfYouHaveAccess.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('The end')\n * });\n *\n * // Logs:\n * // 'The end'\n * ```\n *\n * @see {@link defer}\n *\n * @param condition Condition which Observable should be chosen.\n * @param trueResult An Observable that will be subscribed if condition is true.\n * @param falseResult An Observable that will be subscribed if condition is false.\n * @return An observable that proxies to `trueResult` or `falseResult`, depending on the result of the `condition` function.\n */\nexport function iif<T, F>(condition: () => boolean, trueResult: ObservableInput<T>, falseResult: ObservableInput<F>): Observable<T | F> {\n return defer(() => (condition() ? trueResult : falseResult));\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { async as asyncScheduler } from '../scheduler/async';\nimport { isScheduler } from '../util/isScheduler';\nimport { isValidDate } from '../util/isDate';\n\n/**\n * Creates an observable that will wait for a specified time period, or exact date, before\n * emitting the number 0.\n *\n * <span class=\"informal\">Used to emit a notification after a delay.</span>\n *\n * This observable is useful for creating delays in code, or racing against other values\n * for ad-hoc timeouts.\n *\n * The `delay` is specified by default in milliseconds, however providing a custom scheduler could\n * create a different behavior.\n *\n * ## Examples\n *\n * Wait 3 seconds and start another observable\n *\n * You might want to use `timer` to delay subscription to an\n * observable by a set amount of time. Here we use a timer with\n * {@link concatMapTo} or {@link concatMap} in order to wait\n * a few seconds and start a subscription to a source.\n *\n * ```ts\n * import { of, timer, concatMap } from 'rxjs';\n *\n * // This could be any observable\n * const source = of(1, 2, 3);\n *\n * timer(3000)\n * .pipe(concatMap(() => source))\n * .subscribe(console.log);\n * ```\n *\n * Take all values until the start of the next minute\n *\n * Using a `Date` as the trigger for the first emission, you can\n * do things like wait until midnight to fire an event, or in this case,\n * wait until a new minute starts (chosen so the example wouldn't take\n * too long to run) in order to stop watching a stream. Leveraging\n * {@link takeUntil}.\n *\n * ```ts\n * import { interval, takeUntil, timer } from 'rxjs';\n *\n * // Build a Date object that marks the\n * // next minute.\n * const currentDate = new Date();\n * const startOfNextMinute = new Date(\n * currentDate.getFullYear(),\n * currentDate.getMonth(),\n * currentDate.getDate(),\n * currentDate.getHours(),\n * currentDate.getMinutes() + 1\n * );\n *\n * // This could be any observable stream\n * const source = interval(1000);\n *\n * const result = source.pipe(\n * takeUntil(timer(startOfNextMinute))\n * );\n *\n * result.subscribe(console.log);\n * ```\n *\n * ### Known Limitations\n *\n * - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.\n *\n * - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and\n * a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission\n * should occur will be incorrect. In this case, it would be best to do your own calculations\n * ahead of time, and pass a `number` in as the `dueTime`.\n *\n * @param due If a `number`, the amount of time in milliseconds to wait before emitting.\n * If a `Date`, the exact time at which to emit.\n * @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.\n */\nexport function timer(due: number | Date, scheduler?: SchedulerLike): Observable<0>;\n\n/**\n * Creates an observable that starts an interval after a specified delay, emitting incrementing numbers -- starting at `0` --\n * on each interval after words.\n *\n * The `delay` and `intervalDuration` are specified by default in milliseconds, however providing a custom scheduler could\n * create a different behavior.\n *\n * ## Example\n *\n * ### Start an interval that starts right away\n *\n * Since {@link interval} waits for the passed delay before starting,\n * sometimes that's not ideal. You may want to start an interval immediately.\n * `timer` works well for this. Here we have both side-by-side so you can\n * see them in comparison.\n *\n * Note that this observable will never complete.\n *\n * ```ts\n * import { timer, interval } from 'rxjs';\n *\n * timer(0, 1000).subscribe(n => console.log('timer', n));\n * interval(1000).subscribe(n => console.log('interval', n));\n * ```\n *\n * ### Known Limitations\n *\n * - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.\n *\n * - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and\n * a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission\n * should occur will be incorrect. In this case, it would be best to do your own calculations\n * ahead of time, and pass a `number` in as the `startDue`.\n * @param startDue If a `number`, is the time to wait before starting the interval.\n * If a `Date`, is the exact time at which to start the interval.\n * @param intervalDuration The delay between each value emitted in the interval. Passing a\n * negative number here will result in immediate completion after the first value is emitted, as though\n * no `intervalDuration` was passed at all.\n * @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.\n */\nexport function timer(startDue: number | Date, intervalDuration: number, scheduler?: SchedulerLike): Observable<number>;\n\n/**\n * @deprecated The signature allowing `undefined` to be passed for `intervalDuration` will be removed in v8. Use the `timer(dueTime, scheduler?)` signature instead.\n */\nexport function timer(dueTime: number | Date, unused: undefined, scheduler?: SchedulerLike): Observable<0>;\n\nexport function timer(\n dueTime: number | Date = 0,\n intervalOrScheduler?: number | SchedulerLike,\n scheduler: SchedulerLike = asyncScheduler\n): Observable<number> {\n // Since negative intervalDuration is treated as though no\n // interval was specified at all, we start with a negative number.\n let intervalDuration = -1;\n\n if (intervalOrScheduler != null) {\n // If we have a second argument, and it's a scheduler,\n // override the scheduler we had defaulted. Otherwise,\n // it must be an interval.\n if (isScheduler(intervalOrScheduler)) {\n scheduler = intervalOrScheduler;\n } else {\n // Note that this *could* be negative, in which case\n // it's like not passing an intervalDuration at all.\n intervalDuration = intervalOrScheduler;\n }\n }\n\n return new Observable((subscriber) => {\n // If a valid date is passed, calculate how long to wait before\n // executing the first value... otherwise, if it's a number just schedule\n // that many milliseconds (or scheduler-specified unit size) in the future.\n let due = isValidDate(dueTime) ? +dueTime - scheduler!.now() : dueTime;\n\n if (due < 0) {\n // Ensure we don't schedule in the future.\n due = 0;\n }\n\n // The incrementing value we emit.\n let n = 0;\n\n // Start the timer.\n return scheduler.schedule(function () {\n if (!subscriber.closed) {\n // Emit the next value and increment.\n subscriber.next(n++);\n\n if (0 <= intervalDuration) {\n // If we have a interval after the initial timer,\n // reschedule with the period.\n this.schedule(undefined, intervalDuration);\n } else {\n // We didn't have an interval. So just complete.\n subscriber.complete();\n }\n }\n }, due);\n });\n}\n","import { Observable } from '../Observable';\nimport { asyncScheduler } from '../scheduler/async';\nimport { SchedulerLike } from '../types';\nimport { timer } from './timer';\n\n/**\n * Creates an Observable that emits sequential numbers every specified\n * interval of time, on a specified {@link SchedulerLike}.\n *\n * <span class=\"informal\">Emits incremental numbers periodically in time.</span>\n *\n * \n *\n * `interval` returns an Observable that emits an infinite sequence of\n * ascending integers, with a constant interval of time of your choosing\n * between those emissions. The first emission is not sent immediately, but\n * only after the first period has passed. By default, this operator uses the\n * `async` {@link SchedulerLike} to provide a notion of time, but you may pass any\n * {@link SchedulerLike} to it.\n *\n * ## Example\n *\n * Emits ascending numbers, one every second (1000ms) up to the number 3\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const numbers = interval(1000);\n *\n * const takeFourNumbers = numbers.pipe(take(4));\n *\n * takeFourNumbers.subscribe(x => console.log('Next: ', x));\n *\n * // Logs:\n * // Next: 0\n * // Next: 1\n * // Next: 2\n * // Next: 3\n * ```\n *\n * @see {@link timer}\n * @see {@link delay}\n *\n * @param period The interval size in milliseconds (by default) or the time unit determined\n * by the scheduler's clock.\n * @param scheduler The {@link SchedulerLike} to use for scheduling the emission of values,\n * and providing a notion of \"time\".\n * @return An Observable that emits a sequential number each time interval.\n */\nexport function interval(period = 0, scheduler: SchedulerLike = asyncScheduler): Observable<number> {\n if (period < 0) {\n // We cannot schedule an interval in the past.\n period = 0;\n }\n\n return timer(period, period, scheduler);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, ObservableInputTuple, SchedulerLike } from '../types';\nimport { mergeAll } from '../operators/mergeAll';\nimport { innerFrom } from './innerFrom';\nimport { EMPTY } from './empty';\nimport { popNumber, popScheduler } from '../util/args';\nimport { from } from './from';\n\nexport function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;\nexport function merge<A extends readonly unknown[]>(...sourcesAndConcurrency: [...ObservableInputTuple<A>, number?]): Observable<A[number]>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `mergeAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function merge<A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike?]\n): Observable<A[number]>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `mergeAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function merge<A extends readonly unknown[]>(\n ...sourcesAndConcurrencyAndScheduler: [...ObservableInputTuple<A>, number?, SchedulerLike?]\n): Observable<A[number]>;\n\n/**\n * Creates an output Observable which concurrently emits all values from every\n * given input Observable.\n *\n * <span class=\"informal\">Flattens multiple Observables together by blending\n * their values into one Observable.</span>\n *\n * \n *\n * `merge` subscribes to each given input Observable (as arguments), and simply\n * forwards (without doing any transformation) all the values from all the input\n * Observables to the output Observable. The output Observable only completes\n * once all input Observables have completed. Any error delivered by an input\n * Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n *\n * Merge together two Observables: 1s interval and clicks\n *\n * ```ts\n * import { merge, fromEvent, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const clicksOrTimer = merge(clicks, timer);\n * clicksOrTimer.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // timer will emit ascending values, one every second(1000ms) to console\n * // clicks logs MouseEvents to console every time the \"document\" is clicked\n * // Since the two streams are merged you see these happening\n * // as they occur.\n * ```\n *\n * Merge together 3 Observables, but run only 2 concurrently\n *\n * ```ts\n * import { interval, take, merge } from 'rxjs';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const concurrent = 2; // the argument\n * const merged = merge(timer1, timer2, timer3, concurrent);\n * merged.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - First timer1 and timer2 will run concurrently\n * // - timer1 will emit a value every 1000ms for 10 iterations\n * // - timer2 will emit a value every 2000ms for 6 iterations\n * // - after timer1 hits its max iteration, timer2 will\n * // continue, and timer3 will start to run concurrently with timer2\n * // - when timer2 hits its max iteration it terminates, and\n * // timer3 will continue to emit a value every 500ms until it is complete\n * ```\n *\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n *\n * @param args `ObservableInput`s to merge together. If the last parameter\n * is of type number, `merge` will use it to limit number of concurrently\n * subscribed `ObservableInput`s. If the last parameter is {@link SchedulerLike},\n * it will be used for scheduling the emission of values.\n * @return An Observable that emits items that are the result of every input Observable.\n */\nexport function merge(...args: (ObservableInput<unknown> | number | SchedulerLike)[]): Observable<unknown> {\n const scheduler = popScheduler(args);\n const concurrent = popNumber(args, Infinity);\n const sources = args as ObservableInput<unknown>[];\n return !sources.length\n ? // No source provided\n EMPTY\n : sources.length === 1\n ? // One source? Just return it.\n innerFrom(sources[0])\n : // Merge all sources\n mergeAll(concurrent)(from(sources, scheduler));\n}\n","import { Observable } from '../Observable';\nimport { noop } from '../util/noop';\n\n/**\n * An Observable that emits no items to the Observer and never completes.\n *\n * \n *\n * A simple Observable that emits neither values nor errors nor the completion\n * notification. It can be used for testing purposes or for composing with other\n * Observables. Please note that by never emitting a complete notification, this\n * Observable keeps the subscription from being disposed automatically.\n * Subscriptions need to be manually disposed.\n *\n * ## Example\n *\n * Emit the number 7, then never emit anything else (not even complete)\n *\n * ```ts\n * import { NEVER, startWith } from 'rxjs';\n *\n * const info = () => console.log('Will not be called');\n *\n * const result = NEVER.pipe(startWith(7));\n * result.subscribe({\n * next: x => console.log(x),\n * error: info,\n * complete: info\n * });\n * ```\n *\n * @see {@link Observable}\n * @see {@link EMPTY}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const NEVER = new Observable<never>(noop);\n\n/**\n * @deprecated Replaced with the {@link NEVER} constant. Will be removed in v8.\n */\nexport function never() {\n return NEVER;\n}\n","const { isArray } = Array;\n\n/**\n * Used in operators and functions that accept either a list of arguments, or an array of arguments\n * as a single argument.\n */\nexport function argsOrArgArray<T>(args: (T | T[])[]): T[] {\n return args.length === 1 && isArray(args[0]) ? args[0] : (args as T[]);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInputTuple } from '../types';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { OperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { innerFrom } from './innerFrom';\n\nexport function onErrorResumeNext<A extends readonly unknown[]>(sources: [...ObservableInputTuple<A>]): Observable<A[number]>;\nexport function onErrorResumeNext<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;\n\n/**\n * When any of the provided Observable emits a complete or an error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * <span class=\"informal\">Execute series of Observables no matter what, even if it means swallowing errors.</span>\n *\n * \n *\n * `onErrorResumeNext` will subscribe to each observable source it is provided, in order.\n * If the source it's subscribed to emits an error or completes, it will move to the next source\n * without error.\n *\n * If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link EMPTY}.\n *\n * `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its\n * sources emits an error.\n *\n * Note that there is no way to handle any errors thrown by sources via the result of\n * `onErrorResumeNext`. If you want to handle errors thrown in any given source, you can\n * always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`.\n *\n * ## Example\n *\n * Subscribe to the next Observable after map fails\n *\n * ```ts\n * import { onErrorResumeNext, of, map } from 'rxjs';\n *\n * onErrorResumeNext(\n * of(1, 2, 3, 0).pipe(\n * map(x => {\n * if (x === 0) {\n * throw Error();\n * }\n * return 10 / x;\n * })\n * ),\n * of(1, 2, 3)\n * )\n * .subscribe({\n * next: value => console.log(value),\n * error: err => console.log(err), // Will never be called.\n * complete: () => console.log('done')\n * });\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // 'done'\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param sources `ObservableInput`s passed either directly or as an array.\n * @return An Observable that concatenates all sources, one after the other,\n * ignoring all errors, such that any error causes it to move on to the next source.\n */\nexport function onErrorResumeNext<A extends readonly unknown[]>(\n ...sources: [[...ObservableInputTuple<A>]] | [...ObservableInputTuple<A>]\n): Observable<A[number]> {\n const nextSources: ObservableInputTuple<A> = argsOrArgArray(sources) as any;\n\n return new Observable((subscriber) => {\n let sourceIndex = 0;\n const subscribeNext = () => {\n if (sourceIndex < nextSources.length) {\n let nextSource: Observable<A[number]>;\n try {\n nextSource = innerFrom(nextSources[sourceIndex++]);\n } catch (err) {\n subscribeNext();\n return;\n }\n const innerSubscriber = new OperatorSubscriber(subscriber, undefined, noop, noop);\n nextSource.subscribe(innerSubscriber);\n innerSubscriber.add(subscribeNext);\n } else {\n subscriber.complete();\n }\n };\n subscribeNext();\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { from } from './from';\n\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs<T>(arr: readonly T[], scheduler?: SchedulerLike): Observable<[string, T]>;\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs<O extends Record<string, unknown>>(obj: O, scheduler?: SchedulerLike): Observable<[keyof O, O[keyof O]]>;\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs<T>(iterable: Iterable<T>, scheduler?: SchedulerLike): Observable<[string, T]>;\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs(\n n: number | bigint | boolean | ((...args: any[]) => any) | symbol,\n scheduler?: SchedulerLike\n): Observable<[never, never]>;\n\n/**\n * Convert an object into an Observable of `[key, value]` pairs.\n *\n * <span class=\"informal\">Turn entries of an object into a stream.</span>\n *\n * \n *\n * `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each\n * emitted array has exactly two elements - the first is a key from the object\n * and the second is a value corresponding to that key. Keys are extracted from\n * an object via `Object.keys` function, which means that they will be only\n * enumerable keys that are present on an object directly - not ones inherited\n * via prototype chain.\n *\n * By default, these arrays are emitted synchronously. To change that you can\n * pass a {@link SchedulerLike} as a second argument to `pairs`.\n *\n * ## Example\n *\n * Converts an object to an Observable\n *\n * ```ts\n * import { pairs } from 'rxjs';\n *\n * const obj = {\n * foo: 42,\n * bar: 56,\n * baz: 78\n * };\n *\n * pairs(obj).subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // ['foo', 42]\n * // ['bar', 56]\n * // ['baz', 78]\n * // 'Complete!'\n * ```\n *\n * ### Object.entries required\n *\n * In IE, you will need to polyfill `Object.entries` in order to use this.\n * [MDN has a polyfill here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)\n *\n * @param obj The object to inspect and turn into an Observable sequence.\n * @param scheduler An optional IScheduler to schedule when resulting\n * Observable will emit values.\n * @returns An observable sequence of [key, value] pairs from the object.\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs(obj: any, scheduler?: SchedulerLike) {\n return from(Object.entries(obj), scheduler as any);\n}\n","export function not<T>(pred: (value: T, index: number) => boolean, thisArg: any): (value: T, index: number) => boolean {\n return (value: T, index: number) => !pred.call(thisArg, value, index); \n}","import { OperatorFunction, MonoTypeOperatorFunction, TruthyTypesOf } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function filter<T, S extends T, A>(predicate: (this: A, value: T, index: number) => value is S, thisArg: A): OperatorFunction<T, S>;\nexport function filter<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;\nexport function filter<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function filter<T, A>(predicate: (this: A, value: T, index: number) => boolean, thisArg: A): MonoTypeOperatorFunction<T>;\nexport function filter<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Filter items emitted by the source Observable by only emitting those that\n * satisfy a specified predicate.\n *\n * <span class=\"informal\">Like\n * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\n * it only emits a value from the source if it passes a criterion function.</span>\n *\n * \n *\n * Similar to the well-known `Array.prototype.filter` method, this operator\n * takes values from the source Observable, passes them through a `predicate`\n * function and only emits those values that yielded `true`.\n *\n * ## Example\n *\n * Emit only click events whose target was a DIV element\n *\n * ```ts\n * import { fromEvent, filter } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksOnDivs = clicks.pipe(filter(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * clicksOnDivs.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n * @see {@link ignoreElements}\n * @see {@link partition}\n * @see {@link skip}\n *\n * @param predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted, if `false` the value is not passed to the output\n * Observable. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number\n * `0`.\n * @param thisArg An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return A function that returns an Observable that emits items from the\n * source Observable that satisfy the specified `predicate`.\n */\nexport function filter<T>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n // An index passed to our predicate function on each call.\n let index = 0;\n\n // Subscribe to the source, all errors and completions are\n // forwarded to the consumer.\n source.subscribe(\n // Call the predicate with the appropriate `this` context,\n // if the predicate returns `true`, then send the value\n // to the consumer.\n createOperatorSubscriber(subscriber, (value) => predicate.call(thisArg, value, index++) && subscriber.next(value))\n );\n });\n}\n","import { not } from '../util/not';\nimport { filter } from '../operators/filter';\nimport { ObservableInput } from '../types';\nimport { Observable } from '../Observable';\nimport { innerFrom } from './innerFrom';\n\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function partition<T, U extends T, A>(\n source: ObservableInput<T>,\n predicate: (this: A, value: T, index: number) => value is U,\n thisArg: A\n): [Observable<U>, Observable<Exclude<T, U>>];\nexport function partition<T, U extends T>(\n source: ObservableInput<T>,\n predicate: (value: T, index: number) => value is U\n): [Observable<U>, Observable<Exclude<T, U>>];\n\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function partition<T, A>(\n source: ObservableInput<T>,\n predicate: (this: A, value: T, index: number) => boolean,\n thisArg: A\n): [Observable<T>, Observable<T>];\nexport function partition<T>(source: ObservableInput<T>, predicate: (value: T, index: number) => boolean): [Observable<T>, Observable<T>];\n\n/**\n * Splits the source Observable into two, one with values that satisfy a\n * predicate, and another with values that don't satisfy the predicate.\n *\n * <span class=\"informal\">It's like {@link filter}, but returns two Observables:\n * one like the output of {@link filter}, and the other with values that did not\n * pass the condition.</span>\n *\n * \n *\n * `partition` outputs an array with two Observables that partition the values\n * from the source Observable through the given `predicate` function. The first\n * Observable in that array emits source values for which the predicate argument\n * returns true. The second Observable emits source values for which the\n * predicate returns false. The first behaves like {@link filter} and the second\n * behaves like {@link filter} with the predicate negated.\n *\n * ## Example\n *\n * Partition a set of numbers into odds and evens observables\n *\n * ```ts\n * import { of, partition } from 'rxjs';\n *\n * const observableValues = of(1, 2, 3, 4, 5, 6);\n * const [evens$, odds$] = partition(observableValues, value => value % 2 === 0);\n *\n * odds$.subscribe(x => console.log('odds', x));\n * evens$.subscribe(x => console.log('evens', x));\n *\n * // Logs:\n * // odds 1\n * // odds 3\n * // odds 5\n * // evens 2\n * // evens 4\n * // evens 6\n * ```\n *\n * @see {@link filter}\n *\n * @param source The source `ObservableInput` that will be split into a tuple of\n * two Observable elements.\n * @param predicate A function that evaluates each value emitted by the source\n * Observable. If it returns `true`, the value is emitted on the first Observable\n * in the returned array, if `false` the value is emitted on the second Observable\n * in the array. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number `0`.\n * @param thisArg An optional argument to determine the value of `this` in the\n * `predicate` function.\n * @return An array with two Observables: one with values that passed the\n * predicate, and another with values that did not pass the predicate.\n */\nexport function partition<T>(\n source: ObservableInput<T>,\n predicate: (this: any, value: T, index: number) => boolean,\n thisArg?: any\n): [Observable<T>, Observable<T>] {\n return [filter(predicate, thisArg)(innerFrom(source)), filter(not(predicate, thisArg))(innerFrom(source))] as [\n Observable<T>,\n Observable<T>\n ];\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from './innerFrom';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, ObservableInputTuple } from '../types';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { Subscriber } from '../Subscriber';\n\nexport function race<T extends readonly unknown[]>(inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;\nexport function race<T extends readonly unknown[]>(...inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;\n\n/**\n * Returns an observable that mirrors the first source observable to emit an item.\n *\n * \n *\n * `race` returns an observable, that when subscribed to, subscribes to all source observables immediately.\n * As soon as one of the source observables emits a value, the result unsubscribes from the other sources.\n * The resulting observable will forward all notifications, including error and completion, from the \"winning\"\n * source observable.\n *\n * If one of the used source observable throws an errors before a first notification\n * the race operator will also throw an error, no matter if another source observable\n * could potentially win the race.\n *\n * `race` can be useful for selecting the response from the fastest network connection for\n * HTTP or WebSockets. `race` can also be useful for switching observable context based on user\n * input.\n *\n * ## Example\n *\n * Subscribes to the observable that was the first to start emitting.\n *\n * ```ts\n * import { interval, map, race } from 'rxjs';\n *\n * const obs1 = interval(7000).pipe(map(() => 'slow one'));\n * const obs2 = interval(3000).pipe(map(() => 'fast one'));\n * const obs3 = interval(5000).pipe(map(() => 'medium one'));\n *\n * race(obs1, obs2, obs3)\n * .subscribe(winner => console.log(winner));\n *\n * // Outputs\n * // a series of 'fast one'\n * ```\n *\n * @param sources Used to race for which `ObservableInput` emits first.\n * @return An Observable that mirrors the output of the first Observable to emit an item.\n */\nexport function race<T>(...sources: (ObservableInput<T> | ObservableInput<T>[])[]): Observable<any> {\n sources = argsOrArgArray(sources);\n // If only one source was passed, just return it. Otherwise return the race.\n return sources.length === 1 ? innerFrom(sources[0] as ObservableInput<T>) : new Observable<T>(raceInit(sources as ObservableInput<T>[]));\n}\n\n/**\n * An observable initializer function for both the static version and the\n * operator version of race.\n * @param sources The sources to race\n */\nexport function raceInit<T>(sources: ObservableInput<T>[]) {\n return (subscriber: Subscriber<T>) => {\n let subscriptions: Subscription[] = [];\n\n // Subscribe to all of the sources. Note that we are checking `subscriptions` here\n // Is is an array of all actively \"racing\" subscriptions, and it is `null` after the\n // race has been won. So, if we have racer that synchronously \"wins\", this loop will\n // stop before it subscribes to any more.\n for (let i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {\n subscriptions.push(\n innerFrom(sources[i] as ObservableInput<T>).subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n if (subscriptions) {\n // We're still racing, but we won! So unsubscribe\n // all other subscriptions that we have, except this one.\n for (let s = 0; s < subscriptions.length; s++) {\n s !== i && subscriptions[s].unsubscribe();\n }\n subscriptions = null!;\n }\n subscriber.next(value);\n })\n )\n );\n }\n };\n}\n","import { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { EMPTY } from './empty';\n\nexport function range(start: number, count?: number): Observable<number>;\n\n/**\n * @deprecated The `scheduler` parameter will be removed in v8. Use `range(start, count).pipe(observeOn(scheduler))` instead. Details: Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function range(start: number, count: number | undefined, scheduler: SchedulerLike): Observable<number>;\n\n/**\n * Creates an Observable that emits a sequence of numbers within a specified\n * range.\n *\n * <span class=\"informal\">Emits a sequence of numbers in a range.</span>\n *\n * \n *\n * `range` operator emits a range of sequential integers, in order, where you\n * select the `start` of the range and its `length`. By default, uses no\n * {@link SchedulerLike} and just delivers the notifications synchronously, but may use\n * an optional {@link SchedulerLike} to regulate those deliveries.\n *\n * ## Example\n *\n * Produce a range of numbers\n *\n * ```ts\n * import { range } from 'rxjs';\n *\n * const numbers = range(1, 3);\n *\n * numbers.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 1\n * // 2\n * // 3\n * // 'Complete!'\n * ```\n *\n * @see {@link timer}\n * @see {@link interval}\n *\n * @param start The value of the first integer in the sequence.\n * @param count The number of sequential integers to generate.\n * @param scheduler A {@link SchedulerLike} to use for scheduling the emissions\n * of the notifications.\n * @return An Observable of numbers that emits a finite range of sequential integers.\n */\nexport function range(start: number, count?: number, scheduler?: SchedulerLike): Observable<number> {\n if (count == null) {\n // If one argument was passed, it's the count, not the start.\n count = start;\n start = 0;\n }\n\n if (count <= 0) {\n // No count? We're going nowhere. Return EMPTY.\n return EMPTY;\n }\n\n // Where the range should stop.\n const end = count + start;\n\n return new Observable(\n scheduler\n ? // The deprecated scheduled path.\n (subscriber) => {\n let n = start;\n return scheduler.schedule(function () {\n if (n < end) {\n subscriber.next(n++);\n this.schedule();\n } else {\n subscriber.complete();\n }\n });\n }\n : // Standard synchronous range.\n (subscriber) => {\n let n = start;\n while (n < end && !subscriber.closed) {\n subscriber.next(n++);\n }\n subscriber.complete();\n }\n );\n}\n","import { Observable } from '../Observable';\nimport { Unsubscribable, ObservableInput, ObservedValueOf } from '../types';\nimport { innerFrom } from './innerFrom';\nimport { EMPTY } from './empty';\n\n/**\n * Creates an Observable that uses a resource which will be disposed at the same time as the Observable.\n *\n * <span class=\"informal\">Use it when you catch yourself cleaning up after an Observable.</span>\n *\n * `using` is a factory operator, which accepts two functions. First function returns a disposable resource.\n * It can be an arbitrary object that implements `unsubscribe` method. Second function will be injected with\n * that object and should return an Observable. That Observable can use resource object during its execution.\n * Both functions passed to `using` will be called every time someone subscribes - neither an Observable nor\n * resource object will be shared in any way between subscriptions.\n *\n * When Observable returned by `using` is subscribed, Observable returned from the second function will be subscribed\n * as well. All its notifications (nexted values, completion and error events) will be emitted unchanged by the output\n * Observable. If however someone unsubscribes from the Observable or source Observable completes or errors by itself,\n * the `unsubscribe` method on resource object will be called. This can be used to do any necessary clean up, which\n * otherwise would have to be handled by hand. Note that complete or error notifications are not emitted when someone\n * cancels subscription to an Observable via `unsubscribe`, so `using` can be used as a hook, allowing you to make\n * sure that all resources which need to exist during an Observable execution will be disposed at appropriate time.\n *\n * @see {@link defer}\n *\n * @param resourceFactory A function which creates any resource object that implements `unsubscribe` method.\n * @param observableFactory A function which creates an Observable, that can use injected resource object.\n * @return An Observable that behaves the same as Observable returned by `observableFactory`, but\n * which - when completed, errored or unsubscribed - will also call `unsubscribe` on created resource object.\n */\nexport function using<T extends ObservableInput<any>>(\n resourceFactory: () => Unsubscribable | void,\n observableFactory: (resource: Unsubscribable | void) => T | void\n): Observable<ObservedValueOf<T>> {\n return new Observable<ObservedValueOf<T>>((subscriber) => {\n const resource = resourceFactory();\n const result = observableFactory(resource);\n const source = result ? innerFrom(result) : EMPTY;\n source.subscribe(subscriber);\n return () => {\n // NOTE: Optional chaining did not work here.\n // Related TS Issue: https://github.com/microsoft/TypeScript/issues/40818\n if (resource) {\n resource.unsubscribe();\n }\n };\n });\n}\n","import { Observable } from '../Observable';\nimport { ObservableInputTuple } from '../types';\nimport { innerFrom } from './innerFrom';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { EMPTY } from './empty';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { popResultSelector } from '../util/args';\n\nexport function zip<A extends readonly unknown[]>(sources: [...ObservableInputTuple<A>]): Observable<A>;\nexport function zip<A extends readonly unknown[], R>(\n sources: [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R\n): Observable<R>;\nexport function zip<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;\nexport function zip<A extends readonly unknown[], R>(\n ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]\n): Observable<R>;\n\n/**\n * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each\n * of its input Observables.\n *\n * If the last parameter is a function, this function is used to compute the created value from the input values.\n * Otherwise, an array of the input values is returned.\n *\n * ## Example\n *\n * Combine age and name from different sources\n *\n * ```ts\n * import { of, zip, map } from 'rxjs';\n *\n * const age$ = of(27, 25, 29);\n * const name$ = of('Foo', 'Bar', 'Beer');\n * const isDev$ = of(true, true, false);\n *\n * zip(age$, name$, isDev$).pipe(\n * map(([age, name, isDev]) => ({ age, name, isDev }))\n * )\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // { age: 27, name: 'Foo', isDev: true }\n * // { age: 25, name: 'Bar', isDev: true }\n * // { age: 29, name: 'Beer', isDev: false }\n * ```\n *\n * @param args Any number of `ObservableInput`s provided either as an array or as an object\n * to combine with each other.\n * @return An Observable of array values of the values emitted at the same index from each\n * individual `ObservableInput`.\n */\nexport function zip(...args: unknown[]): Observable<unknown> {\n const resultSelector = popResultSelector(args);\n\n const sources = argsOrArgArray(args) as Observable<unknown>[];\n\n return sources.length\n ? new Observable<unknown[]>((subscriber) => {\n // A collection of buffers of values from each source.\n // Keyed by the same index with which the sources were passed in.\n let buffers: unknown[][] = sources.map(() => []);\n\n // An array of flags of whether or not the sources have completed.\n // This is used to check to see if we should complete the result.\n // Keyed by the same index with which the sources were passed in.\n let completed = sources.map(() => false);\n\n // When everything is done, release the arrays above.\n subscriber.add(() => {\n buffers = completed = null!;\n });\n\n // Loop over our sources and subscribe to each one. The index `i` is\n // especially important here, because we use it in closures below to\n // access the related buffers and completion properties\n for (let sourceIndex = 0; !subscriber.closed && sourceIndex < sources.length; sourceIndex++) {\n innerFrom(sources[sourceIndex]).subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n buffers[sourceIndex].push(value);\n // if every buffer has at least one value in it, then we\n // can shift out the oldest value from each buffer and emit\n // them as an array.\n if (buffers.every((buffer) => buffer.length)) {\n const result: any = buffers.map((buffer) => buffer.shift()!);\n // Emit the array. If theres' a result selector, use that.\n subscriber.next(resultSelector ? resultSelector(...result) : result);\n // If any one of the sources is both complete and has an empty buffer\n // then we complete the result. This is because we cannot possibly have\n // any more values to zip together.\n if (buffers.some((buffer, i) => !buffer.length && completed[i])) {\n subscriber.complete();\n }\n }\n },\n () => {\n // This source completed. Mark it as complete so we can check it later\n // if we have to.\n completed[sourceIndex] = true;\n // But, if this complete source has nothing in its buffer, then we\n // can complete the result, because we can't possibly have any more\n // values from this to zip together with the other values.\n !buffers[sourceIndex].length && subscriber.complete();\n }\n )\n );\n }\n\n // When everything is done, release the arrays above.\n return () => {\n buffers = completed = null!;\n };\n })\n : EMPTY;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n}); //# sourceMappingURL=types.js.map\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuanMiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9pbnRlcm5hbC90eXBlcy50cyJdLCJzb3VyY2VSb290IjoiIiwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiJ9","import { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\n\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Ignores source values for a duration determined by another Observable, then\n * emits the most recent value from the source Observable, then repeats this\n * process.\n *\n * <span class=\"informal\">It's like {@link auditTime}, but the silencing\n * duration is determined by a second Observable.</span>\n *\n * \n *\n * `audit` is similar to `throttle`, but emits the last value from the silenced\n * time window, instead of the first value. `audit` emits the most recent value\n * from the source Observable on the output Observable as soon as its internal\n * timer becomes disabled, and ignores source values while the timer is enabled.\n * Initially, the timer is disabled. As soon as the first source value arrives,\n * the timer is enabled by calling the `durationSelector` function with the\n * source value, which returns the \"duration\" Observable. When the duration\n * Observable emits a value, the timer is disabled, then the most\n * recent source value is emitted on the output Observable, and this process\n * repeats for the next source value.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, audit, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(audit(ev => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttle}\n *\n * @param durationSelector A function\n * that receives a value from the source Observable, for computing the silencing\n * duration, returned as an Observable or a Promise.\n * @return A function that returns an Observable that performs rate-limiting of\n * emissions from the source Observable.\n */\nexport function audit<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let lastValue: T | null = null;\n let durationSubscriber: Subscriber<any> | null = null;\n let isComplete = false;\n\n const endDuration = () => {\n durationSubscriber?.unsubscribe();\n durationSubscriber = null;\n if (hasValue) {\n hasValue = false;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n isComplete && subscriber.complete();\n };\n\n const cleanupDuration = () => {\n durationSubscriber = null;\n isComplete && subscriber.complete();\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n lastValue = value;\n if (!durationSubscriber) {\n innerFrom(durationSelector(value)).subscribe(\n (durationSubscriber = createOperatorSubscriber(subscriber, endDuration, cleanupDuration))\n );\n }\n },\n () => {\n isComplete = true;\n (!hasValue || !durationSubscriber || durationSubscriber.closed) && subscriber.complete();\n }\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { audit } from './audit';\nimport { timer } from '../observable/timer';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/**\n * Ignores source values for `duration` milliseconds, then emits the most recent\n * value from the source Observable, then repeats this process.\n *\n * <span class=\"informal\">When it sees a source value, it ignores that plus\n * the next ones for `duration` milliseconds, and then it emits the most recent\n * value from the source.</span>\n *\n * \n *\n * `auditTime` is similar to `throttleTime`, but emits the last value from the\n * silenced time window, instead of the first value. `auditTime` emits the most\n * recent value from the source Observable on the output Observable as soon as\n * its internal timer becomes disabled, and ignores source values while the\n * timer is enabled. Initially, the timer is disabled. As soon as the first\n * source value arrives, the timer is enabled. After `duration` milliseconds (or\n * the time unit determined internally by the optional `scheduler`) has passed,\n * the timer is disabled, then the most recent source value is emitted on the\n * output Observable, and this process repeats for the next source value.\n * Optionally takes a {@link SchedulerLike} for managing timers.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, auditTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(auditTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param duration Time to wait before emitting the most recent source value,\n * measured in milliseconds or the time unit determined internally by the\n * optional `scheduler`.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers\n * that handle the rate-limiting behavior.\n * @return A function that returns an Observable that performs rate-limiting of\n * emissions from the source Observable.\n */\nexport function auditTime<T>(duration: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n return audit(() => timer(duration, scheduler));\n}\n","import { OperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Buffers the source Observable values until `closingNotifier` emits.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * that array only when another Observable emits.</span>\n *\n * \n *\n * Buffers the incoming Observable values until the given `closingNotifier`\n * `ObservableInput` (that internally gets converted to an Observable)\n * emits a value, at which point it emits the buffer on the output\n * Observable and starts a new buffer internally, awaiting the next time\n * `closingNotifier` emits.\n *\n * ## Example\n *\n * On every click, emit array of most recent interval events\n *\n * ```ts\n * import { fromEvent, interval, buffer } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const intervalEvents = interval(1000);\n * const buffered = intervalEvents.pipe(buffer(clicks));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link window}\n *\n * @param closingNotifier An `ObservableInput` that signals the\n * buffer to be emitted on the output Observable.\n * @return A function that returns an Observable of buffers, which are arrays\n * of values.\n */\nexport function buffer<T>(closingNotifier: ObservableInput<any>): OperatorFunction<T, T[]> {\n return operate((source, subscriber) => {\n // The current buffered values.\n let currentBuffer: T[] = [];\n\n // Subscribe to our source.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => currentBuffer.push(value),\n () => {\n subscriber.next(currentBuffer);\n subscriber.complete();\n }\n )\n );\n\n // Subscribe to the closing notifier.\n innerFrom(closingNotifier).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n // Start a new buffer and emit the previous one.\n const b = currentBuffer;\n currentBuffer = [];\n subscriber.next(b);\n },\n noop\n )\n );\n\n return () => {\n // Ensure buffered values are released on finalization.\n currentBuffer = null!;\n };\n });\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { arrRemove } from '../util/arrRemove';\n\n/**\n * Buffers the source Observable values until the size hits the maximum\n * `bufferSize` given.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * that array only when its size reaches `bufferSize`.</span>\n *\n * \n *\n * Buffers a number of values from the source Observable by `bufferSize` then\n * emits the buffer and clears it, and starts a new buffer each\n * `startBufferEvery` values. If `startBufferEvery` is not provided or is\n * `null`, then new buffers are started immediately at the start of the source\n * and when each buffer closes and is emitted.\n *\n * ## Examples\n *\n * Emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent, bufferCount } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * On every click, emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent, bufferCount } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2, 1));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link pairwise}\n * @see {@link windowCount}\n *\n * @param bufferSize The maximum size of the buffer emitted.\n * @param startBufferEvery Interval at which to start a new buffer.\n * For example if `startBufferEvery` is `2`, then a new buffer will be started\n * on every other value from the source. A new buffer is started at the\n * beginning of the source by default.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferCount<T>(bufferSize: number, startBufferEvery: number | null = null): OperatorFunction<T, T[]> {\n // If no `startBufferEvery` value was supplied, then we're\n // opening and closing on the bufferSize itself.\n startBufferEvery = startBufferEvery ?? bufferSize;\n\n return operate((source, subscriber) => {\n let buffers: T[][] = [];\n let count = 0;\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n let toEmit: T[][] | null = null;\n\n // Check to see if we need to start a buffer.\n // This will start one at the first value, and then\n // a new one every N after that.\n if (count++ % startBufferEvery! === 0) {\n buffers.push([]);\n }\n\n // Push our value into our active buffers.\n for (const buffer of buffers) {\n buffer.push(value);\n // Check to see if we're over the bufferSize\n // if we are, record it so we can emit it later.\n // If we emitted it now and removed it, it would\n // mutate the `buffers` array while we're looping\n // over it.\n if (bufferSize <= buffer.length) {\n toEmit = toEmit ?? [];\n toEmit.push(buffer);\n }\n }\n\n if (toEmit) {\n // We have found some buffers that are over the\n // `bufferSize`. Emit them, and remove them from our\n // buffers list.\n for (const buffer of toEmit) {\n arrRemove(buffers, buffer);\n subscriber.next(buffer);\n }\n }\n },\n () => {\n // When the source completes, emit all of our\n // active buffers.\n for (const buffer of buffers) {\n subscriber.next(buffer);\n }\n subscriber.complete();\n },\n // Pass all errors through to consumer.\n undefined,\n () => {\n // Clean up our memory when we finalize\n buffers = null!;\n }\n )\n );\n });\n}\n","import { Subscription } from '../Subscription';\nimport { OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { arrRemove } from '../util/arrRemove';\nimport { asyncScheduler } from '../scheduler/async';\nimport { popScheduler } from '../util/args';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function bufferTime<T>(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;\nexport function bufferTime<T>(\n bufferTimeSpan: number,\n bufferCreationInterval: number | null | undefined,\n scheduler?: SchedulerLike\n): OperatorFunction<T, T[]>;\nexport function bufferTime<T>(\n bufferTimeSpan: number,\n bufferCreationInterval: number | null | undefined,\n maxBufferSize: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, T[]>;\n\n/**\n * Buffers the source Observable values for a specific time period.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * those arrays periodically in time.</span>\n *\n * \n *\n * Buffers values from the source for a specific time duration `bufferTimeSpan`.\n * Unless the optional argument `bufferCreationInterval` is given, it emits and\n * resets the buffer every `bufferTimeSpan` milliseconds. If\n * `bufferCreationInterval` is given, this operator opens the buffer every\n * `bufferCreationInterval` milliseconds and closes (emits and resets) the\n * buffer every `bufferTimeSpan` milliseconds. When the optional argument\n * `maxBufferSize` is specified, the buffer will be closed either after\n * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.\n *\n * ## Examples\n *\n * Every second, emit an array of the recent click events\n *\n * ```ts\n * import { fromEvent, bufferTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(1000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds, emit the click events from the next 2 seconds\n *\n * ```ts\n * import { fromEvent, bufferTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(2000, 5000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link windowTime}\n *\n * @param bufferTimeSpan The amount of time to fill each buffer array.\n * @param otherArgs Other configuration arguments such as:\n * - `bufferCreationInterval` - the interval at which to start new buffers;\n * - `maxBufferSize` - the maximum buffer size;\n * - `scheduler` - the scheduler on which to schedule the intervals that determine buffer boundaries.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferTime<T>(bufferTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, T[]> {\n const scheduler = popScheduler(otherArgs) ?? asyncScheduler;\n const bufferCreationInterval = (otherArgs[0] as number) ?? null;\n const maxBufferSize = (otherArgs[1] as number) || Infinity;\n\n return operate((source, subscriber) => {\n // The active buffers, their related subscriptions, and removal functions.\n let bufferRecords: { buffer: T[]; subs: Subscription }[] | null = [];\n // If true, it means that every time we emit a buffer, we want to start a new buffer\n // this is only really used for when *just* the buffer time span is passed.\n let restartOnEmit = false;\n\n /**\n * Does the work of emitting the buffer from the record, ensuring that the\n * record is removed before the emission so reentrant code (from some custom scheduling, perhaps)\n * does not alter the buffer. Also checks to see if a new buffer needs to be started\n * after the emit.\n */\n const emit = (record: { buffer: T[]; subs: Subscription }) => {\n const { buffer, subs } = record;\n subs.unsubscribe();\n arrRemove(bufferRecords, record);\n subscriber.next(buffer);\n restartOnEmit && startBuffer();\n };\n\n /**\n * Called every time we start a new buffer. This does\n * the work of scheduling a job at the requested bufferTimeSpan\n * that will emit the buffer (if it's not unsubscribed before then).\n */\n const startBuffer = () => {\n if (bufferRecords) {\n const subs = new Subscription();\n subscriber.add(subs);\n const buffer: T[] = [];\n const record = {\n buffer,\n subs,\n };\n bufferRecords.push(record);\n executeSchedule(subs, scheduler, () => emit(record), bufferTimeSpan);\n }\n };\n\n if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {\n // The user passed both a bufferTimeSpan (required), and a creation interval\n // That means we need to start new buffers on the interval, and those buffers need\n // to wait the required time span before emitting.\n executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);\n } else {\n restartOnEmit = true;\n }\n\n startBuffer();\n\n const bufferTimeSubscriber = createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Copy the records, so if we need to remove one we\n // don't mutate the array. It's hard, but not impossible to\n // set up a buffer time that could mutate the array and\n // cause issues here.\n const recordsCopy = bufferRecords!.slice();\n for (const record of recordsCopy) {\n // Loop over all buffers and\n const { buffer } = record;\n buffer.push(value);\n // If the buffer is over the max size, we need to emit it.\n maxBufferSize <= buffer.length && emit(record);\n }\n },\n () => {\n // The source completed, emit all of the active\n // buffers we have before we complete.\n while (bufferRecords?.length) {\n subscriber.next(bufferRecords.shift()!.buffer);\n }\n bufferTimeSubscriber?.unsubscribe();\n subscriber.complete();\n subscriber.unsubscribe();\n },\n // Pass all errors through to consumer.\n undefined,\n // Clean up\n () => (bufferRecords = null)\n );\n\n source.subscribe(bufferTimeSubscriber);\n });\n}\n","import { Subscription } from '../Subscription';\nimport { OperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { arrRemove } from '../util/arrRemove';\n\n/**\n * Buffers the source Observable values starting from an emission from\n * `openings` and ending when the output of `closingSelector` emits.\n *\n * <span class=\"informal\">Collects values from the past as an array. Starts\n * collecting only when `opening` emits, and calls the `closingSelector`\n * function to get an Observable that tells when to close the buffer.</span>\n *\n * \n *\n * Buffers values from the source by opening the buffer via signals from an\n * Observable provided to `openings`, and closing and sending the buffers when\n * a Subscribable or Promise returned by the `closingSelector` function emits.\n *\n * ## Example\n *\n * Every other second, emit the click events from the next 500ms\n *\n * ```ts\n * import { fromEvent, interval, bufferToggle, EMPTY } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const buffered = clicks.pipe(bufferToggle(openings, i =>\n * i % 2 ? interval(500) : EMPTY\n * ));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferWhen}\n * @see {@link windowToggle}\n *\n * @param openings A Subscribable or Promise of notifications to start new\n * buffers.\n * @param closingSelector A function that takes\n * the value emitted by the `openings` observable and returns a Subscribable or Promise,\n * which, when it emits, signals that the associated buffer should be emitted\n * and cleared.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferToggle<T, O>(\n openings: ObservableInput<O>,\n closingSelector: (value: O) => ObservableInput<any>\n): OperatorFunction<T, T[]> {\n return operate((source, subscriber) => {\n const buffers: T[][] = [];\n\n // Subscribe to the openings notifier first\n innerFrom(openings).subscribe(\n createOperatorSubscriber(\n subscriber,\n (openValue) => {\n const buffer: T[] = [];\n buffers.push(buffer);\n // We use this composite subscription, so that\n // when the closing notifier emits, we can tear it down.\n const closingSubscription = new Subscription();\n\n const emitBuffer = () => {\n arrRemove(buffers, buffer);\n subscriber.next(buffer);\n closingSubscription.unsubscribe();\n };\n\n // The line below will add the subscription to the parent subscriber *and* the closing subscription.\n closingSubscription.add(innerFrom(closingSelector(openValue)).subscribe(createOperatorSubscriber(subscriber, emitBuffer, noop)));\n },\n noop\n )\n );\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Value from our source. Add it to all pending buffers.\n for (const buffer of buffers) {\n buffer.push(value);\n }\n },\n () => {\n // Source complete. Emit all pending buffers.\n while (buffers.length > 0) {\n subscriber.next(buffers.shift()!);\n }\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Buffers the source Observable values, using a factory function of closing\n * Observables to determine when to close, emit, and reset the buffer.\n *\n * <span class=\"informal\">Collects values from the past as an array. When it\n * starts collecting values, it calls a function that returns an Observable that\n * tells when to close the buffer and restart collecting.</span>\n *\n * \n *\n * Opens a buffer immediately, then closes the buffer when the observable\n * returned by calling `closingSelector` function emits a value. When it closes\n * the buffer, it immediately opens a new buffer and repeats the process.\n *\n * ## Example\n *\n * Emit an array of the last clicks every [1-5] random seconds\n *\n * ```ts\n * import { fromEvent, bufferWhen, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(\n * bufferWhen(() => interval(1000 + Math.random() * 4000))\n * );\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link windowWhen}\n *\n * @param closingSelector A function that takes no arguments and returns an\n * Observable that signals buffer closure.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferWhen<T>(closingSelector: () => ObservableInput<any>): OperatorFunction<T, T[]> {\n return operate((source, subscriber) => {\n // The buffer we keep and emit.\n let buffer: T[] | null = null;\n // A reference to the subscriber used to subscribe to\n // the closing notifier. We need to hold this so we can\n // end the subscription after the first notification.\n let closingSubscriber: Subscriber<T> | null = null;\n\n // Ends the previous closing notifier subscription, so it\n // terminates after the first emission, then emits\n // the current buffer if there is one, starts a new buffer, and starts a\n // new closing notifier.\n const openBuffer = () => {\n // Make sure to finalize the closing subscription, we only cared\n // about one notification.\n closingSubscriber?.unsubscribe();\n // emit the buffer if we have one, and start a new buffer.\n const b = buffer;\n buffer = [];\n b && subscriber.next(b);\n\n // Get a new closing notifier and subscribe to it.\n innerFrom(closingSelector()).subscribe((closingSubscriber = createOperatorSubscriber(subscriber, openBuffer, noop)));\n };\n\n // Start the first buffer.\n openBuffer();\n\n // Subscribe to our source.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n // Add every new value to the current buffer.\n (value) => buffer?.push(value),\n // When we complete, emit the buffer if we have one,\n // then complete the result.\n () => {\n buffer && subscriber.next(buffer);\n subscriber.complete();\n },\n // Pass all errors through to consumer.\n undefined,\n // Release memory on finalization\n () => (buffer = closingSubscriber = null!)\n )\n );\n });\n}\n","import { Observable } from '../Observable';\n\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { Subscription } from '../Subscription';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { operate } from '../util/lift';\n\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>>;\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * <span class=\"informal\">\n * It only listens to the error channel and ignores notifications.\n * Handles errors from the source observable, and maps them to a new observable.\n * The error may also be rethrown, or a new error can be thrown to emit an error from the result.\n * </span>\n *\n * \n *\n * This operator handles errors, but forwards along all other events to the resulting observable.\n * If the source observable terminates with an error, it will map that error to a new observable,\n * subscribe to it, and forward all of its events to the resulting observable.\n *\n * ## Examples\n *\n * Continue with a different Observable when there's an error\n *\n * ```ts\n * import { of, map, catchError } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => of('I', 'II', 'III', 'IV', 'V'))\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retry the caught source Observable again in case of error, similar to `retry()` operator\n *\n * ```ts\n * import { of, map, catchError, take } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError((err, caught) => caught),\n * take(30)\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throw a new error when the source Observable throws an error\n *\n * ```ts\n * import { of, map, catchError } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => {\n * throw 'error in source. Details: ' + err;\n * })\n * )\n * .subscribe({\n * next: x => console.log(x),\n * error: err => console.log(err)\n * });\n * // 1, 2, 3, error in source. Details: four!\n * ```\n *\n * @see {@link onErrorResumeNext}\n * @see {@link repeat}\n * @see {@link repeatWhen}\n * @see {@link retry }\n * @see {@link retryWhen}\n *\n * @param selector A function that takes as arguments `err`, which is the error, and `caught`, which\n * is the source observable, in case you'd like to \"retry\" that observable by returning it again.\n * Whatever observable is returned by the `selector` will be used to continue the observable chain.\n * @return A function that returns an Observable that originates from either\n * the source or the Observable returned by the `selector` function.\n */\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null = null;\n let syncUnsub = false;\n let handledResult: Observable<ObservedValueOf<O>>;\n\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, undefined, (err) => {\n handledResult = innerFrom(selector(err, catchError(selector)(source)));\n if (innerSub) {\n innerSub.unsubscribe();\n innerSub = null;\n handledResult.subscribe(subscriber);\n } else {\n // We don't have an innerSub yet, that means the error was synchronous\n // because the subscribe call hasn't returned yet.\n syncUnsub = true;\n }\n })\n );\n\n if (syncUnsub) {\n // We have a synchronous error, we need to make sure to\n // finalize right away. This ensures that callbacks in the `finalize` operator are called\n // at the right time, and that finalization occurs at the expected\n // time between the source error and the subscription to the\n // next observable.\n innerSub.unsubscribe();\n innerSub = null;\n handledResult!.subscribe(subscriber);\n }\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * A basic scan operation. This is used for `scan` and `reduce`.\n * @param accumulator The accumulator to use\n * @param seed The seed value for the state to accumulate\n * @param hasSeed Whether or not a seed was provided\n * @param emitOnNext Whether or not to emit the state on next\n * @param emitBeforeComplete Whether or not to emit the before completion\n */\n\nexport function scanInternals<V, A, S>(\n accumulator: (acc: V | A | S, value: V, index: number) => A,\n seed: S,\n hasSeed: boolean,\n emitOnNext: boolean,\n emitBeforeComplete?: undefined | true\n) {\n return (source: Observable<V>, subscriber: Subscriber<any>) => {\n // Whether or not we have state yet. This will only be\n // false before the first value arrives if we didn't get\n // a seed value.\n let hasState = hasSeed;\n // The state that we're tracking, starting with the seed,\n // if there is one, and then updated by the return value\n // from the accumulator on each emission.\n let state: any = seed;\n // An index to pass to the accumulator function.\n let index = 0;\n\n // Subscribe to our source. All errors and completions are passed through.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Always increment the index.\n const i = index++;\n // Set the state\n state = hasState\n ? // We already have state, so we can get the new state from the accumulator\n accumulator(state, value, i)\n : // We didn't have state yet, a seed value was not provided, so\n\n // we set the state to the first value, and mark that we have state now\n ((hasState = true), value);\n\n // Maybe send it to the consumer.\n emitOnNext && subscriber.next(state);\n },\n // If an onComplete was given, call it, otherwise\n // just pass through the complete notification to the consumer.\n emitBeforeComplete &&\n (() => {\n hasState && subscriber.next(state);\n subscriber.complete();\n })\n )\n );\n };\n}\n","import { scanInternals } from './scanInternals';\nimport { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\nexport function reduce<V, A = V>(accumulator: (acc: A | V, value: V, index: number) => A): OperatorFunction<V, V | A>;\nexport function reduce<V, A>(accumulator: (acc: A, value: V, index: number) => A, seed: A): OperatorFunction<V, A>;\nexport function reduce<V, A, S = A>(accumulator: (acc: A | S, value: V, index: number) => A, seed: S): OperatorFunction<V, A>;\n\n/**\n * Applies an accumulator function over the source Observable, and returns the\n * accumulated result when the source completes, given an optional seed value.\n *\n * <span class=\"informal\">Combines together all values emitted on the source,\n * using an accumulator function that knows how to join a new source value into\n * the accumulation from the past.</span>\n *\n * \n *\n * Like\n * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),\n * `reduce` applies an `accumulator` function against an accumulation and each\n * value of the source Observable (from the past) to reduce it to a single\n * value, emitted on the output Observable. Note that `reduce` will only emit\n * one value, only when the source Observable completes. It is equivalent to\n * applying operator {@link scan} followed by operator {@link last}.\n *\n * Returns an Observable that applies a specified `accumulator` function to each\n * item emitted by the source Observable. If a `seed` value is specified, then\n * that value will be used as the initial value for the accumulator. If no seed\n * value is specified, the first item of the source is used as the seed.\n *\n * ## Example\n *\n * Count the number of click events that happened in 5 seconds\n *\n * ```ts\n * import { fromEvent, takeUntil, interval, map, reduce } from 'rxjs';\n *\n * const clicksInFiveSeconds = fromEvent(document, 'click')\n * .pipe(takeUntil(interval(5000)));\n *\n * const ones = clicksInFiveSeconds.pipe(map(() => 1));\n * const seed = 0;\n * const count = ones.pipe(reduce((acc, one) => acc + one, seed));\n *\n * count.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link count}\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link scan}\n *\n * @param accumulator The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @return A function that returns an Observable that emits a single value that\n * is the result of accumulating the values emitted by the source Observable.\n */\nexport function reduce<V, A>(accumulator: (acc: V | A, value: V, index: number) => A, seed?: any): OperatorFunction<V, V | A> {\n return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));\n}\n","import { reduce } from './reduce';\nimport { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\nconst arrReducer = (arr: any[], value: any) => (arr.push(value), arr);\n\n/**\n * Collects all source emissions and emits them as an array when the source completes.\n *\n * <span class=\"informal\">Get all values inside an array when the source completes</span>\n *\n * \n *\n * `toArray` will wait until the source Observable completes before emitting\n * the array containing all emissions. When the source Observable errors no\n * array will be emitted.\n *\n * ## Example\n *\n * ```ts\n * import { interval, take, toArray } from 'rxjs';\n *\n * const source = interval(1000);\n * const example = source.pipe(\n * take(10),\n * toArray()\n * );\n *\n * example.subscribe(value => console.log(value));\n *\n * // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @return A function that returns an Observable that emits an array of items\n * emitted by the source Observable when source completes.\n */\nexport function toArray<T>(): OperatorFunction<T, T[]> {\n // Because arrays are mutable, and we're mutating the array in this\n // reducer process, we have to encapsulate the creation of the initial\n // array within this `operate` function.\n return operate((source, subscriber) => {\n reduce(arrReducer, [] as T[])(source).subscribe(subscriber);\n });\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { identity } from '../util/identity';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { pipe } from '../util/pipe';\nimport { mergeMap } from './mergeMap';\nimport { toArray } from './toArray';\n\n/**\n * Collects all of the inner sources from source observable. Then, once the\n * source completes, joins the values using the given static.\n *\n * This is used for {@link combineLatestAll} and {@link zipAll} which both have the\n * same behavior of collecting all inner observables, then operating on them.\n *\n * @param joinFn The type of static join to apply to the sources collected\n * @param project The projection function to apply to the values, if any\n */\nexport function joinAllInternals<T, R>(joinFn: (sources: ObservableInput<T>[]) => Observable<T>, project?: (...args: any[]) => R) {\n return pipe(\n // Collect all inner sources into an array, and emit them when the\n // source completes.\n toArray() as OperatorFunction<ObservableInput<T>, ObservableInput<T>[]>,\n // Run the join function on the collected array of inner sources.\n mergeMap((sources) => joinFn(sources)),\n // If a projection function was supplied, apply it to each result.\n project ? mapOneOrManyArgs(project) : (identity as any)\n );\n}\n","import { combineLatest } from '../observable/combineLatest';\nimport { OperatorFunction, ObservableInput } from '../types';\nimport { joinAllInternals } from './joinAllInternals';\n\nexport function combineLatestAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;\nexport function combineLatestAll<T>(): OperatorFunction<any, T[]>;\nexport function combineLatestAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;\nexport function combineLatestAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;\n\n/**\n * Flattens an Observable-of-Observables by applying {@link combineLatest} when the Observable-of-Observables completes.\n *\n * `combineLatestAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes,\n * it subscribes to all collected Observables and combines their values using the {@link combineLatest} strategy, such that:\n *\n * * Every time an inner Observable emits, the output Observable emits\n * * When the returned observable emits, it emits all of the latest values by:\n * * If a `project` function is provided, it is called with each recent value from each inner Observable in whatever order they\n * arrived, and the result of the `project` function is what is emitted by the output Observable.\n * * If there is no `project` function, an array of all the most recent values is emitted by the output Observable.\n *\n * ## Example\n *\n * Map two click events to a finite interval Observable, then apply `combineLatestAll`\n *\n * ```ts\n * import { fromEvent, map, interval, take, combineLatestAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(Math.random() * 2000).pipe(take(3))),\n * take(2)\n * );\n * const result = higherOrder.pipe(combineLatestAll());\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link combineLatestWith}\n * @see {@link mergeAll}\n *\n * @param project optional function to map the most recent values from each inner Observable into a new result.\n * Takes each of the most recent values from each collected inner Observable as arguments, in order.\n * @return A function that returns an Observable that flattens Observables\n * emitted by the source Observable.\n */\nexport function combineLatestAll<R>(project?: (...values: Array<any>) => R) {\n return joinAllInternals(combineLatest, project);\n}\n","import { combineLatestAll } from './combineLatestAll';\n\n/**\n * @deprecated Renamed to {@link combineLatestAll}. Will be removed in v8.\n */\nexport const combineAll = combineLatestAll;\n","import { combineLatestInit } from '../observable/combineLatest';\nimport { ObservableInput, ObservableInputTuple, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { pipe } from '../util/pipe';\nimport { popResultSelector } from '../util/args';\n\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(\n sources: [...ObservableInputTuple<A>],\n project: (...values: [T, ...A]) => R\n): OperatorFunction<T, R>;\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(sources: [...ObservableInputTuple<A>]): OperatorFunction<T, [T, ...A]>;\n\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(\n ...sourcesAndProject: [...ObservableInputTuple<A>, (...values: [T, ...A]) => R]\n): OperatorFunction<T, R>;\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, [T, ...A]>;\n\n/**\n * @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8.\n */\nexport function combineLatest<T, R>(...args: (ObservableInput<any> | ((...values: any[]) => R))[]): OperatorFunction<T, unknown> {\n const resultSelector = popResultSelector(args);\n return resultSelector\n ? pipe(combineLatest(...(args as Array<ObservableInput<any>>)), mapOneOrManyArgs(resultSelector))\n : operate((source, subscriber) => {\n combineLatestInit([source, ...argsOrArgArray(args)])(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction, Cons } from '../types';\nimport { combineLatest } from './combineLatest';\n\n/**\n * Create an observable that combines the latest values from all passed observables and the source\n * into arrays and emits them.\n *\n * Returns an observable, that when subscribed to, will subscribe to the source observable and all\n * sources provided as arguments. Once all sources emit at least one value, all of the latest values\n * will be emitted as an array. After that, every time any source emits a value, all of the latest values\n * will be emitted as an array.\n *\n * This is a useful operator for eagerly calculating values based off of changed inputs.\n *\n * ## Example\n *\n * Simple concatenation of values from two inputs\n *\n * ```ts\n * import { fromEvent, combineLatestWith, map } from 'rxjs';\n *\n * // Setup: Add two inputs to the page\n * const input1 = document.createElement('input');\n * document.body.appendChild(input1);\n * const input2 = document.createElement('input');\n * document.body.appendChild(input2);\n *\n * // Get streams of changes\n * const input1Changes$ = fromEvent(input1, 'change');\n * const input2Changes$ = fromEvent(input2, 'change');\n *\n * // Combine the changes by adding them together\n * input1Changes$.pipe(\n * combineLatestWith(input2Changes$),\n * map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value)\n * )\n * .subscribe(x => console.log(x));\n * ```\n *\n * @param otherSources the other sources to subscribe to.\n * @return A function that returns an Observable that emits the latest\n * emissions from both source and provided Observables.\n */\nexport function combineLatestWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, Cons<T, A>> {\n return combineLatest(...otherSources);\n}\n","import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\nexport function concatMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, in a serialized fashion waiting for each one to complete before\n * merging the next.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link concatAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each new inner Observable is\n * concatenated with the previous inner Observable.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, concatMap, interval, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMap(ev => interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMapTo}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and taking\n * values from each projected inner Observable sequentially.\n */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);\n}\n","import { concatMap } from './concatMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/** @deprecated Will be removed in v9. Use {@link concatMap} instead: `concatMap(() => result)` */\nexport function concatMapTo<O extends ObservableInput<unknown>>(observable: O): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMapTo<O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: undefined\n): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMapTo<T, R, O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in a serialized fashion on the output Observable.\n *\n * <span class=\"informal\">It's like {@link concatMap}, but maps each value\n * always to the same inner Observable.</span>\n *\n * \n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. Each new `innerObservable`\n * instance emitted on the output Observable is concatenated with the previous\n * `innerObservable` instance.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter\n * set to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, concatMapTo, interval, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMapTo(interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link mergeMapTo}\n * @see {@link switchMapTo}\n *\n * @param innerObservable An `ObservableInput` to replace each value from the\n * source Observable.\n * @return A function that returns an Observable of values merged together by\n * joining the passed Observable with itself, one after the other, for each\n * value emitted from the source.\n * @deprecated Will be removed in v9. Use {@link concatMap} instead: `concatMap(() => result)`\n */\nexport function concatMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return isFunction(resultSelector) ? concatMap(() => innerObservable, resultSelector) : concatMap(() => innerObservable);\n}\n","import { ObservableInputTuple, OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { concatAll } from './concatAll';\nimport { popScheduler } from '../util/args';\nimport { from } from '../observable/from';\n\n/** @deprecated Replaced with {@link concatWith}. Will be removed in v8. */\nexport function concat<T, A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link concatWith}. Will be removed in v8. */\nexport function concat<T, A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]\n): OperatorFunction<T, T | A[number]>;\n\n/**\n * @deprecated Replaced with {@link concatWith}. Will be removed in v8.\n */\nexport function concat<T, R>(...args: any[]): OperatorFunction<T, R> {\n const scheduler = popScheduler(args);\n return operate((source, subscriber) => {\n concatAll()(from([source, ...args], scheduler)).subscribe(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction } from '../types';\nimport { concat } from './concat';\n\n/**\n * Emits all of the values from the source observable, then, once it completes, subscribes\n * to each observable source provided, one at a time, emitting all of their values, and not subscribing\n * to the next one until it completes.\n *\n * `concat(a$, b$, c$)` is the same as `a$.pipe(concatWith(b$, c$))`.\n *\n * ## Example\n *\n * Listen for one mouse click, then listen for all mouse moves.\n *\n * ```ts\n * import { fromEvent, map, take, concatWith } from 'rxjs';\n *\n * const clicks$ = fromEvent(document, 'click');\n * const moves$ = fromEvent(document, 'mousemove');\n *\n * clicks$.pipe(\n * map(() => 'click'),\n * take(1),\n * concatWith(\n * moves$.pipe(\n * map(() => 'move')\n * )\n * )\n * )\n * .subscribe(x => console.log(x));\n *\n * // 'click'\n * // 'move'\n * // 'move'\n * // 'move'\n * // ...\n * ```\n *\n * @param otherSources Other observable sources to subscribe to, in sequence, after the original source is complete.\n * @return A function that returns an Observable that concatenates\n * subscriptions to the source and provided Observables subscribing to the next\n * only once the current subscription completes.\n */\nexport function concatWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n return concat(...otherSources);\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscribable } from '../types';\n\n/**\n * Used to convert a subscribable to an observable.\n *\n * Currently, this is only used within internals.\n *\n * TODO: Discuss ObservableInput supporting \"Subscribable\".\n * https://github.com/ReactiveX/rxjs/issues/5909\n *\n * @param subscribable A subscribable\n */\nexport function fromSubscribable<T>(subscribable: Subscribable<T>) {\n return new Observable((subscriber: Subscriber<T>) => subscribable.subscribe(subscriber));\n}\n","import { OperatorFunction, ObservableInput, ObservedValueOf, SubjectLike } from '../types';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { fromSubscribable } from '../observable/fromSubscribable';\n\n/**\n * An object used to configure {@link connect} operator.\n */\nexport interface ConnectConfig<T> {\n /**\n * A factory function used to create the Subject through which the source\n * is multicast. By default, this creates a {@link Subject}.\n */\n connector: () => SubjectLike<T>;\n}\n\n/**\n * The default configuration for `connect`.\n */\nconst DEFAULT_CONFIG: ConnectConfig<unknown> = {\n connector: () => new Subject<unknown>(),\n};\n\n/**\n * Creates an observable by multicasting the source within a function that\n * allows the developer to define the usage of the multicast prior to connection.\n *\n * This is particularly useful if the observable source you wish to multicast could\n * be synchronous or asynchronous. This sets it apart from {@link share}, which, in the\n * case of totally synchronous sources will fail to share a single subscription with\n * multiple consumers, as by the time the subscription to the result of {@link share}\n * has returned, if the source is synchronous its internal reference count will jump from\n * 0 to 1 back to 0 and reset.\n *\n * To use `connect`, you provide a `selector` function that will give you\n * a multicast observable that is not yet connected. You then use that multicast observable\n * to create a resulting observable that, when subscribed, will set up your multicast. This is\n * generally, but not always, accomplished with {@link merge}.\n *\n * Note that using a {@link takeUntil} inside of `connect`'s `selector` _might_ mean you were looking\n * to use the {@link takeWhile} operator instead.\n *\n * When you subscribe to the result of `connect`, the `selector` function will be called. After\n * the `selector` function returns, the observable it returns will be subscribed to, _then_ the\n * multicast will be connected to the source.\n *\n * ## Example\n *\n * Sharing a totally synchronous observable\n *\n * ```ts\n * import { of, tap, connect, merge, map, filter } from 'rxjs';\n *\n * const source$ = of(1, 2, 3, 4, 5).pipe(\n * tap({\n * subscribe: () => console.log('subscription started'),\n * next: n => console.log(`source emitted ${ n }`)\n * })\n * );\n *\n * source$.pipe(\n * // Notice in here we're merging 3 subscriptions to `shared$`.\n * connect(shared$ => merge(\n * shared$.pipe(map(n => `all ${ n }`)),\n * shared$.pipe(filter(n => n % 2 === 0), map(n => `even ${ n }`)),\n * shared$.pipe(filter(n => n % 2 === 1), map(n => `odd ${ n }`))\n * ))\n * )\n * .subscribe(console.log);\n *\n * // Expected output: (notice only one subscription)\n * 'subscription started'\n * 'source emitted 1'\n * 'all 1'\n * 'odd 1'\n * 'source emitted 2'\n * 'all 2'\n * 'even 2'\n * 'source emitted 3'\n * 'all 3'\n * 'odd 3'\n * 'source emitted 4'\n * 'all 4'\n * 'even 4'\n * 'source emitted 5'\n * 'all 5'\n * 'odd 5'\n * ```\n *\n * @param selector A function used to set up the multicast. Gives you a multicast observable\n * that is not yet connected. With that, you're expected to create and return\n * and Observable, that when subscribed to, will utilize the multicast observable.\n * After this function is executed -- and its return value subscribed to -- the\n * operator will subscribe to the source, and the connection will be made.\n * @param config The configuration object for `connect`.\n */\nexport function connect<T, O extends ObservableInput<unknown>>(\n selector: (shared: Observable<T>) => O,\n config: ConnectConfig<T> = DEFAULT_CONFIG\n): OperatorFunction<T, ObservedValueOf<O>> {\n const { connector } = config;\n return operate((source, subscriber) => {\n const subject = connector();\n innerFrom(selector(fromSubscribable(subject))).subscribe(subscriber);\n subscriber.add(source.subscribe(subject));\n });\n}\n","import { OperatorFunction } from '../types';\nimport { reduce } from './reduce';\n\n/**\n * Counts the number of emissions on the source and emits that number when the\n * source completes.\n *\n * <span class=\"informal\">Tells how many values were emitted, when the source\n * completes.</span>\n *\n * \n *\n * `count` transforms an Observable that emits values into an Observable that\n * emits a single value that represents the number of values emitted by the\n * source Observable. If the source Observable terminates with an error, `count`\n * will pass this error notification along without emitting a value first. If\n * the source Observable does not terminate at all, `count` will neither emit\n * a value nor terminate. This operator takes an optional `predicate` function\n * as argument, in which case the output emission will represent the number of\n * source values that matched `true` with the `predicate`.\n *\n * ## Examples\n *\n * Counts how many seconds have passed before the first click happened\n *\n * ```ts\n * import { interval, fromEvent, takeUntil, count } from 'rxjs';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const secondsBeforeClick = seconds.pipe(takeUntil(clicks));\n * const result = secondsBeforeClick.pipe(count());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Counts how many odd numbers are there between 1 and 7\n *\n * ```ts\n * import { range, count } from 'rxjs';\n *\n * const numbers = range(1, 7);\n * const result = numbers.pipe(count(i => i % 2 === 1));\n * result.subscribe(x => console.log(x));\n * // Results in:\n * // 4\n * ```\n *\n * @see {@link max}\n * @see {@link min}\n * @see {@link reduce}\n *\n * @param predicate A function that is used to analyze the value and the index and\n * determine whether or not to increment the count. Return `true` to increment the count,\n * and return `false` to keep the count the same.\n * If the predicate is not provided, every value will be counted.\n * @return A function that returns an Observable that emits one number that\n * represents the count of emissions.\n */\nexport function count<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, number> {\n return reduce((total, value, i) => (!predicate || predicate(value, i) ? total + 1 : total), 0);\n}\n","import { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Emits a notification from the source Observable only after a particular time span\n * determined by another Observable has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link debounceTime}, but the time span of\n * emission silence is determined by a second Observable.</span>\n *\n * \n *\n * `debounce` delays notifications emitted by the source Observable, but drops previous\n * pending delayed emissions if a new notification arrives on the source Observable.\n * This operator keeps track of the most recent notification from the source\n * Observable, and spawns a duration Observable by calling the\n * `durationSelector` function. The notification is emitted only when the duration\n * Observable emits a next notification, and if no other notification was emitted on\n * the source Observable since the duration Observable was spawned. If a new\n * notification appears before the duration Observable emits, the previous notification will\n * not be emitted and a new duration is scheduled from `durationSelector` is scheduled.\n * If the completing event happens during the scheduled duration the last cached notification\n * is emitted before the completion event is forwarded to the output observable.\n * If the error event happens during the scheduled duration or after it only the error event is\n * forwarded to the output observable. The cache notification is not emitted in this case.\n *\n * Like {@link debounceTime}, this is a rate-limiting operator, and also a\n * delay-like operator since output emissions do not necessarily occur at the\n * same time as they did on the source Observable.\n *\n * ## Example\n *\n * Emit the most recent click after a burst of clicks\n *\n * ```ts\n * import { fromEvent, scan, debounce, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * scan(i => ++i, 1),\n * debounce(i => interval(200 * i))\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link throttle}\n * @see {@link throttleTime}\n *\n * @param durationSelector A function\n * that receives a value from the source Observable, for computing the timeout\n * duration for each source value, returned as an Observable or a Promise.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by the specified duration Observable returned by\n * `durationSelector`, and may drop some values if they occur too frequently.\n */\nexport function debounce<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let lastValue: T | null = null;\n // The subscriber/subscription for the current debounce, if there is one.\n let durationSubscriber: Subscriber<any> | null = null;\n\n const emit = () => {\n // Unsubscribe any current debounce subscription we have,\n // we only cared about the first notification from it, and we\n // want to clean that subscription up as soon as possible.\n durationSubscriber?.unsubscribe();\n durationSubscriber = null;\n if (hasValue) {\n // We have a value! Free up memory first, then emit the value.\n hasValue = false;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Cancel any pending debounce duration. We don't\n // need to null it out here yet tho, because we're just going\n // to create another one in a few lines.\n durationSubscriber?.unsubscribe();\n hasValue = true;\n lastValue = value;\n // Capture our duration subscriber, so we can unsubscribe it when we're notified\n // and we're going to emit the value.\n durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);\n // Subscribe to the duration.\n innerFrom(durationSelector(value)).subscribe(durationSubscriber);\n },\n () => {\n // Source completed.\n // Emit any pending debounced values then complete\n emit();\n subscriber.complete();\n },\n // Pass all errors through to consumer\n undefined,\n () => {\n // Finalization.\n lastValue = durationSubscriber = null;\n }\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits a notification from the source Observable only after a particular time span\n * has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link delay}, but passes only the most\n * recent notification from each burst of emissions.</span>\n *\n * \n *\n * `debounceTime` delays notifications emitted by the source Observable, but drops\n * previous pending delayed emissions if a new notification arrives on the source\n * Observable. This operator keeps track of the most recent notification from the\n * source Observable, and emits that only when `dueTime` has passed\n * without any other notification appearing on the source Observable. If a new value\n * appears before `dueTime` silence occurs, the previous notification will be dropped\n * and will not be emitted and a new `dueTime` is scheduled.\n * If the completing event happens during `dueTime` the last cached notification\n * is emitted before the completion event is forwarded to the output observable.\n * If the error event happens during `dueTime` or after it only the error event is\n * forwarded to the output observable. The cache notification is not emitted in this case.\n *\n * This is a rate-limiting operator, because it is impossible for more than one\n * notification to be emitted in any time window of duration `dueTime`, but it is also\n * a delay-like operator since output emissions do not occur at the same time as\n * they did on the source Observable. Optionally takes a {@link SchedulerLike} for\n * managing timers.\n *\n * ## Example\n *\n * Emit the most recent click after a burst of clicks\n *\n * ```ts\n * import { fromEvent, debounceTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounceTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link throttle}\n * @see {@link throttleTime}\n *\n * @param dueTime The timeout duration in milliseconds (or the time unit determined\n * internally by the optional `scheduler`) for the window of time required to wait\n * for emission silence before emitting the most recent source value.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers that\n * handle the timeout for each value.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by the specified `dueTime`, and may drop some values\n * if they occur too frequently.\n */\nexport function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let activeTask: Subscription | null = null;\n let lastValue: T | null = null;\n let lastTime: number | null = null;\n\n const emit = () => {\n if (activeTask) {\n // We have a value! Free up memory first, then emit the value.\n activeTask.unsubscribe();\n activeTask = null;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n };\n function emitWhenIdle(this: SchedulerAction<unknown>) {\n // This is called `dueTime` after the first value\n // but we might have received new values during this window!\n\n const targetTime = lastTime! + dueTime;\n const now = scheduler.now();\n if (now < targetTime) {\n // On that case, re-schedule to the new target\n activeTask = this.schedule(undefined, targetTime - now);\n subscriber.add(activeTask);\n return;\n }\n\n emit();\n }\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n lastValue = value;\n lastTime = scheduler.now();\n\n // Only set up a task if it's not already up\n if (!activeTask) {\n activeTask = scheduler.schedule(emitWhenIdle, dueTime);\n subscriber.add(activeTask);\n }\n },\n () => {\n // Source completed.\n // Emit any pending debounced values then complete\n emit();\n subscriber.complete();\n },\n // Pass all errors through to consumer.\n undefined,\n () => {\n // Finalization.\n lastValue = activeTask = null;\n }\n )\n );\n });\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits a given value if the source Observable completes without emitting any\n * `next` value, otherwise mirrors the source Observable.\n *\n * <span class=\"informal\">If the source Observable turns out to be empty, then\n * this operator will emit a default value.</span>\n *\n * \n *\n * `defaultIfEmpty` emits the values emitted by the source Observable or a\n * specified default value if the source Observable is empty (completes without\n * having emitted any `next` value).\n *\n * ## Example\n *\n * If no clicks happen in 5 seconds, then emit 'no clicks'\n *\n * ```ts\n * import { fromEvent, takeUntil, interval, defaultIfEmpty } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));\n * const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link empty}\n * @see {@link last}\n *\n * @param defaultValue The default value used if the source\n * Observable is empty.\n * @return A function that returns an Observable that emits either the\n * specified `defaultValue` if the source Observable emits no items, or the\n * values emitted by the source Observable.\n */\nexport function defaultIfEmpty<T, R>(defaultValue: R): OperatorFunction<T, T | R> {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n subscriber.next(value);\n },\n () => {\n if (!hasValue) {\n subscriber.next(defaultValue!);\n }\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { EMPTY } from '../observable/empty';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits only the first `count` values emitted by the source Observable.\n *\n * <span class=\"informal\">Takes the first `count` values from the source, then\n * completes.</span>\n *\n * \n *\n * `take` returns an Observable that emits only the first `count` values emitted\n * by the source Observable. If the source emits fewer than `count` values then\n * all of its values are emitted. After that, it completes, regardless if the\n * source completes.\n *\n * ## Example\n *\n * Take the first 5 seconds of an infinite 1-second interval Observable\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const intervalCount = interval(1000);\n * const takeFive = intervalCount.pipe(take(5));\n * takeFive.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param count The maximum number of `next` values to emit.\n * @return A function that returns an Observable that emits only the first\n * `count` values emitted by the source Observable, or all of the values from\n * the source if the source emits fewer than `count` values.\n */\nexport function take<T>(count: number): MonoTypeOperatorFunction<T> {\n return count <= 0\n ? // If we are taking no values, that's empty.\n () => EMPTY\n : operate((source, subscriber) => {\n let seen = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n // Increment the number of values we have seen,\n // then check it against the allowed count to see\n // if we are still letting values through.\n if (++seen <= count) {\n subscriber.next(value);\n // If we have met or passed our allowed count,\n // we need to complete. We have to do <= here,\n // because re-entrant code will increment `seen` twice.\n if (count <= seen) {\n subscriber.complete();\n }\n }\n })\n );\n });\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\n\n/**\n * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.\n *\n * \n *\n * The `ignoreElements` operator suppresses all items emitted by the source Observable,\n * but allows its termination notification (either `error` or `complete`) to pass through unchanged.\n *\n * If you do not care about the items being emitted by an Observable, but you do want to be notified\n * when it completes or when it terminates with an error, you can apply the `ignoreElements` operator\n * to the Observable, which will ensure that it will never call its observers’ `next` handlers.\n *\n * ## Example\n *\n * Ignore all `next` emissions from the source\n *\n * ```ts\n * import { of, ignoreElements } from 'rxjs';\n *\n * of('you', 'talking', 'to', 'me')\n * .pipe(ignoreElements())\n * .subscribe({\n * next: word => console.log(word),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // result:\n * // 'the end'\n * ```\n *\n * @return A function that returns an empty Observable that only calls\n * `complete` or `error`, based on which one is called by the source\n * Observable.\n */\nexport function ignoreElements(): OperatorFunction<unknown, never> {\n return operate((source, subscriber) => {\n source.subscribe(createOperatorSubscriber(subscriber, noop));\n });\n}\n","import { OperatorFunction } from '../types';\nimport { map } from './map';\n\n/** @deprecated To be removed in v9. Use {@link map} instead: `map(() => value)`. */\nexport function mapTo<R>(value: R): OperatorFunction<unknown, R>;\n/**\n * @deprecated Do not specify explicit type parameters. Signatures with type parameters\n * that cannot be inferred will be removed in v8. `mapTo` itself will be removed in v9,\n * use {@link map} instead: `map(() => value)`.\n * */\nexport function mapTo<T, R>(value: R): OperatorFunction<T, R>;\n\n/**\n * Emits the given constant value on the output Observable every time the source\n * Observable emits a value.\n *\n * <span class=\"informal\">Like {@link map}, but it maps every source value to\n * the same output value every time.</span>\n *\n * \n *\n * Takes a constant `value` as argument, and emits that whenever the source\n * Observable emits a value. In other words, ignores the actual source value,\n * and simply uses the emission moment to know when to emit the given `value`.\n *\n * ## Example\n *\n * Map every click to the string `'Hi'`\n *\n * ```ts\n * import { fromEvent, mapTo } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const greetings = clicks.pipe(mapTo('Hi'));\n *\n * greetings.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param value The value to map each source value to.\n * @return A function that returns an Observable that emits the given `value`\n * every time the source Observable emits.\n * @deprecated To be removed in v9. Use {@link map} instead: `map(() => value)`.\n */\nexport function mapTo<R>(value: R): OperatorFunction<unknown, R> {\n return map(() => value);\n}\n","import { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { concat } from '../observable/concat';\nimport { take } from './take';\nimport { ignoreElements } from './ignoreElements';\nimport { mapTo } from './mapTo';\nimport { mergeMap } from './mergeMap';\nimport { innerFrom } from '../observable/innerFrom';\n\n/** @deprecated The `subscriptionDelay` parameter will be removed in v8. */\nexport function delayWhen<T>(\n delayDurationSelector: (value: T, index: number) => ObservableInput<any>,\n subscriptionDelay: Observable<any>\n): MonoTypeOperatorFunction<T>;\nexport function delayWhen<T>(delayDurationSelector: (value: T, index: number) => ObservableInput<any>): MonoTypeOperatorFunction<T>;\n\n/**\n * Delays the emission of items from the source Observable by a given time span\n * determined by the emissions of another Observable.\n *\n * <span class=\"informal\">It's like {@link delay}, but the time span of the\n * delay duration is determined by a second Observable.</span>\n *\n * \n *\n * `delayWhen` operator shifts each emitted value from the source Observable by\n * a time span determined by another Observable. When the source emits a value,\n * the `delayDurationSelector` function is called with the value emitted from\n * the source Observable as the first argument to the `delayDurationSelector`.\n * The `delayDurationSelector` function should return an {@link ObservableInput},\n * that is internally converted to an Observable that is called the \"duration\"\n * Observable.\n *\n * The source value is emitted on the output Observable only when the \"duration\"\n * Observable emits ({@link guide/glossary-and-semantics#next next}s) any value.\n * Upon that, the \"duration\" Observable gets unsubscribed.\n *\n * Before RxJS V7, the {@link guide/glossary-and-semantics#complete completion}\n * of the \"duration\" Observable would have been triggering the emission of the\n * source value to the output Observable, but with RxJS V7, this is not the case\n * anymore.\n *\n * Only next notifications (from the \"duration\" Observable) trigger values from\n * the source Observable to be passed to the output Observable. If the \"duration\"\n * Observable only emits the complete notification (without next), the value\n * emitted by the source Observable will never get to the output Observable - it\n * will be swallowed. If the \"duration\" Observable errors, the error will be\n * propagated to the output Observable.\n *\n * Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which\n * is an Observable. When `subscriptionDelay` emits its first value or\n * completes, the source Observable is subscribed to and starts behaving like\n * described in the previous paragraph. If `subscriptionDelay` is not provided,\n * `delayWhen` will subscribe to the source Observable as soon as the output\n * Observable is subscribed.\n *\n * ## Example\n *\n * Delay each click by a random amount of time, between 0 and 5 seconds\n *\n * ```ts\n * import { fromEvent, delayWhen, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(\n * delayWhen(() => interval(Math.random() * 5000))\n * );\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link delay}\n * @see {@link throttle}\n * @see {@link throttleTime}\n * @see {@link debounce}\n * @see {@link debounceTime}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link audit}\n * @see {@link auditTime}\n *\n * @param delayDurationSelector A function that returns an `ObservableInput` for\n * each `value` emitted by the source Observable, which is then used to delay the\n * emission of that `value` on the output Observable until the `ObservableInput`\n * returned from this function emits a next value. When called, beside `value`,\n * this function receives a zero-based `index` of the emission order.\n * @param subscriptionDelay An Observable that triggers the subscription to the\n * source Observable once it emits any value.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by an amount of time specified by the Observable\n * returned by `delayDurationSelector`.\n */\nexport function delayWhen<T>(\n delayDurationSelector: (value: T, index: number) => ObservableInput<any>,\n subscriptionDelay?: Observable<any>\n): MonoTypeOperatorFunction<T> {\n if (subscriptionDelay) {\n // DEPRECATED PATH\n return (source: Observable<T>) =>\n concat(subscriptionDelay.pipe(take(1), ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));\n }\n\n return mergeMap((value, index) => innerFrom(delayDurationSelector(value, index)).pipe(take(1), mapTo(value)));\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { delayWhen } from './delayWhen';\nimport { timer } from '../observable/timer';\n\n/**\n * Delays the emission of items from the source Observable by a given timeout or\n * until a given Date.\n *\n * <span class=\"informal\">Time shifts each item by some specified amount of\n * milliseconds.</span>\n *\n * \n *\n * If the delay argument is a Number, this operator time shifts the source\n * Observable by that amount of time expressed in milliseconds. The relative\n * time intervals between the values are preserved.\n *\n * If the delay argument is a Date, this operator time shifts the start of the\n * Observable execution until the given date occurs.\n *\n * ## Examples\n *\n * Delay each click by one second\n *\n * ```ts\n * import { fromEvent, delay } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * Delay all clicks until a future date happens\n *\n * ```ts\n * import { fromEvent, delay } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const date = new Date('March 15, 2050 12:00:00'); // in the future\n * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link delayWhen}\n * @see {@link throttle}\n * @see {@link throttleTime}\n * @see {@link debounce}\n * @see {@link debounceTime}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link audit}\n * @see {@link auditTime}\n *\n * @param due The delay duration in milliseconds (a `number`) or a `Date` until\n * which the emission of the source items is delayed.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers\n * that handle the time-shift for each item.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by the specified timeout or Date.\n */\nexport function delay<T>(due: number | Date, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n const duration = timer(due, scheduler);\n return delayWhen(() => duration);\n}\n","import { observeNotification } from '../Notification';\nimport { OperatorFunction, ObservableNotification, ValueFromNotification } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Converts an Observable of {@link ObservableNotification} objects into the emissions\n * that they represent.\n *\n * <span class=\"informal\">Unwraps {@link ObservableNotification} objects as actual `next`,\n * `error` and `complete` emissions. The opposite of {@link materialize}.</span>\n *\n * \n *\n * `dematerialize` is assumed to operate an Observable that only emits\n * {@link ObservableNotification} objects as `next` emissions, and does not emit any\n * `error`. Such Observable is the output of a `materialize` operation. Those\n * notifications are then unwrapped using the metadata they contain, and emitted\n * as `next`, `error`, and `complete` on the output Observable.\n *\n * Use this operator in conjunction with {@link materialize}.\n *\n * ## Example\n *\n * Convert an Observable of Notifications to an actual Observable\n *\n * ```ts\n * import { NextNotification, ErrorNotification, of, dematerialize } from 'rxjs';\n *\n * const notifA: NextNotification<string> = { kind: 'N', value: 'A' };\n * const notifB: NextNotification<string> = { kind: 'N', value: 'B' };\n * const notifE: ErrorNotification = { kind: 'E', error: new TypeError('x.toUpperCase is not a function') };\n *\n * const materialized = of(notifA, notifB, notifE);\n *\n * const upperCase = materialized.pipe(dematerialize());\n * upperCase.subscribe({\n * next: x => console.log(x),\n * error: e => console.error(e)\n * });\n *\n * // Results in:\n * // A\n * // B\n * // TypeError: x.toUpperCase is not a function\n * ```\n *\n * @see {@link materialize}\n *\n * @return A function that returns an Observable that emits items and\n * notifications embedded in Notification objects emitted by the source\n * Observable.\n */\nexport function dematerialize<N extends ObservableNotification<any>>(): OperatorFunction<N, ValueFromNotification<N>> {\n return operate((source, subscriber) => {\n source.subscribe(createOperatorSubscriber(subscriber, (notification) => observeNotification(notification, subscriber)));\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.\n *\n * If a `keySelector` function is provided, then it will project each value from the source observable into a new value that it will\n * check for equality with previously projected values. If the `keySelector` function is not provided, it will use each value from the\n * source observable directly with an equality check against previous values.\n *\n * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.\n *\n * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the\n * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`\n * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so\n * that the internal `Set` can be \"flushed\", basically clearing it of values.\n *\n * ## Examples\n *\n * A simple example with numbers\n *\n * ```ts\n * import { of, distinct } from 'rxjs';\n *\n * of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)\n * .pipe(distinct())\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * An example using the `keySelector` function\n *\n * ```ts\n * import { of, distinct } from 'rxjs';\n *\n * of(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'}\n * )\n * .pipe(distinct(({ name }) => name))\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * ```\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param keySelector Optional `function` to select which value you want to check as distinct.\n * @param flushes Optional `ObservableInput` for flushing the internal HashSet of the operator.\n * @return A function that returns an Observable that emits items from the\n * source Observable with distinct values.\n */\nexport function distinct<T, K>(keySelector?: (value: T) => K, flushes?: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n const distinctKeys = new Set();\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const key = keySelector ? keySelector(value) : value;\n if (!distinctKeys.has(key)) {\n distinctKeys.add(key);\n subscriber.next(value);\n }\n })\n );\n\n flushes && innerFrom(flushes).subscribe(createOperatorSubscriber(subscriber, () => distinctKeys.clear(), noop));\n });\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { identity } from '../util/identity';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function distinctUntilChanged<T>(comparator?: (previous: T, current: T) => boolean): MonoTypeOperatorFunction<T>;\nexport function distinctUntilChanged<T, K>(\n comparator: (previous: K, current: K) => boolean,\n keySelector: (value: T) => K\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns a result {@link Observable} that emits all values pushed by the source observable if they\n * are distinct in comparison to the last value the result observable emitted.\n *\n * When provided without parameters or with the first parameter (`{@link distinctUntilChanged#comparator comparator}`),\n * it behaves like this:\n *\n * 1. It will always emit the first value from the source.\n * 2. For all subsequent values pushed by the source, they will be compared to the previously emitted values\n * using the provided `comparator` or an `===` equality check.\n * 3. If the value pushed by the source is determined to be unequal by this check, that value is emitted and\n * becomes the new \"previously emitted value\" internally.\n *\n * When the second parameter (`{@link distinctUntilChanged#keySelector keySelector}`) is provided, the behavior\n * changes:\n *\n * 1. It will always emit the first value from the source.\n * 2. The `keySelector` will be run against all values, including the first value.\n * 3. For all values after the first, the selected key will be compared against the key selected from\n * the previously emitted value using the `comparator`.\n * 4. If the keys are determined to be unequal by this check, the value (not the key), is emitted\n * and the selected key from that value is saved for future comparisons against other keys.\n *\n * ## Examples\n *\n * A very basic example with no `{@link distinctUntilChanged#comparator comparator}`. Note that `1` is emitted more than once,\n * because it's distinct in comparison to the _previously emitted_ value,\n * not in comparison to _all other emitted values_.\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * of(1, 1, 1, 2, 2, 2, 1, 1, 3, 3)\n * .pipe(distinctUntilChanged())\n * .subscribe(console.log);\n * // Logs: 1, 2, 1, 3\n * ```\n *\n * With a `{@link distinctUntilChanged#comparator comparator}`, you can do custom comparisons. Let's say\n * you only want to emit a value when all of its components have\n * changed:\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * const totallyDifferentBuilds$ = of(\n * { engineVersion: '1.1.0', transmissionVersion: '1.2.0' },\n * { engineVersion: '1.1.0', transmissionVersion: '1.4.0' },\n * { engineVersion: '1.3.0', transmissionVersion: '1.4.0' },\n * { engineVersion: '1.3.0', transmissionVersion: '1.5.0' },\n * { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }\n * ).pipe(\n * distinctUntilChanged((prev, curr) => {\n * return (\n * prev.engineVersion === curr.engineVersion ||\n * prev.transmissionVersion === curr.transmissionVersion\n * );\n * })\n * );\n *\n * totallyDifferentBuilds$.subscribe(console.log);\n *\n * // Logs:\n * // { engineVersion: '1.1.0', transmissionVersion: '1.2.0' }\n * // { engineVersion: '1.3.0', transmissionVersion: '1.4.0' }\n * // { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }\n * ```\n *\n * You can also provide a custom `{@link distinctUntilChanged#comparator comparator}` to check that emitted\n * changes are only in one direction. Let's say you only want to get\n * the next record temperature:\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * const temps$ = of(30, 31, 20, 34, 33, 29, 35, 20);\n *\n * const recordHighs$ = temps$.pipe(\n * distinctUntilChanged((prevHigh, temp) => {\n * // If the current temp is less than\n * // or the same as the previous record,\n * // the record hasn't changed.\n * return temp <= prevHigh;\n * })\n * );\n *\n * recordHighs$.subscribe(console.log);\n * // Logs: 30, 31, 34, 35\n * ```\n *\n * Selecting update events only when the `updatedBy` field shows\n * the account changed hands.\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * // A stream of updates to a given account\n * const accountUpdates$ = of(\n * { updatedBy: 'blesh', data: [] },\n * { updatedBy: 'blesh', data: [] },\n * { updatedBy: 'ncjamieson', data: [] },\n * { updatedBy: 'ncjamieson', data: [] },\n * { updatedBy: 'blesh', data: [] }\n * );\n *\n * // We only want the events where it changed hands\n * const changedHands$ = accountUpdates$.pipe(\n * distinctUntilChanged(undefined, update => update.updatedBy)\n * );\n *\n * changedHands$.subscribe(console.log);\n * // Logs:\n * // { updatedBy: 'blesh', data: Array[0] }\n * // { updatedBy: 'ncjamieson', data: Array[0] }\n * // { updatedBy: 'blesh', data: Array[0] }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param comparator A function used to compare the previous and current keys for\n * equality. Defaults to a `===` check.\n * @param keySelector Used to select a key value to be passed to the `comparator`.\n *\n * @return A function that returns an Observable that emits items from the\n * source Observable with distinct values.\n */\nexport function distinctUntilChanged<T, K>(\n comparator?: (previous: K, current: K) => boolean,\n keySelector: (value: T) => K = identity as (value: T) => K\n): MonoTypeOperatorFunction<T> {\n // We've been allowing `null` do be passed as the `compare`, so we can't do\n // a default value for the parameter, because that will only work\n // for `undefined`.\n comparator = comparator ?? defaultCompare;\n\n return operate((source, subscriber) => {\n // The previous key, used to compare against keys selected\n // from new arrivals to determine \"distinctiveness\".\n let previousKey: K;\n // Whether or not this is the first value we've gotten.\n let first = true;\n\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n // We always call the key selector.\n const currentKey = keySelector(value);\n\n // If it's the first value, we always emit it.\n // Otherwise, we compare this key to the previous key, and\n // if the comparer returns false, we emit.\n if (first || !comparator!(previousKey, currentKey)) {\n // Update our state *before* we emit the value\n // as emission can be the source of re-entrant code\n // in functional libraries like this. We only really\n // need to do this if it's the first value, or if the\n // key we're tracking in previous needs to change.\n first = false;\n previousKey = currentKey;\n\n // Emit the value!\n subscriber.next(value);\n }\n })\n );\n });\n}\n\nfunction defaultCompare(a: any, b: any) {\n return a === b;\n}\n","import { distinctUntilChanged } from './distinctUntilChanged';\nimport { MonoTypeOperatorFunction } from '../types';\n\nexport function distinctUntilKeyChanged<T>(key: keyof T): MonoTypeOperatorFunction<T>;\nexport function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that\n * are distinct by comparison from the previous item, using a property accessed by\n * using the key provided to check if the two items are distinct.\n *\n * If a comparator function is provided, then it will be called for each item to\n * test for whether that value should be emitted or not.\n *\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Examples\n *\n * An example comparing the name of persons\n *\n * ```ts\n * import { of, distinctUntilKeyChanged } from 'rxjs';\n *\n * of(\n * { age: 4, name: 'Foo' },\n * { age: 7, name: 'Bar' },\n * { age: 5, name: 'Foo' },\n * { age: 6, name: 'Foo' }\n * ).pipe(\n * distinctUntilKeyChanged('name')\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * An example comparing the first letters of the name\n *\n * ```ts\n * import { of, distinctUntilKeyChanged } from 'rxjs';\n *\n * of(\n * { age: 4, name: 'Foo1' },\n * { age: 7, name: 'Bar' },\n * { age: 5, name: 'Foo2' },\n * { age: 6, name: 'Foo3' }\n * ).pipe(\n * distinctUntilKeyChanged('name', (x, y) => x.substring(0, 3) === y.substring(0, 3))\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo1' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo2' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n *\n * @param key String key for object property lookup on each item.\n * @param compare Optional comparison function called to test if an item is distinct\n * from the previous item in the source.\n * @return A function that returns an Observable that emits items from the source\n * Observable with distinct values based on the key specified.\n */\nexport function distinctUntilKeyChanged<T, K extends keyof T>(\n key: K,\n compare?: (x: T[K], y: T[K]) => boolean\n): MonoTypeOperatorFunction<T> {\n return distinctUntilChanged((x: T, y: T) => (compare ? compare(x[key], y[key]) : x[key] === y[key]));\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * If the source observable completes without emitting a value, it will emit\n * an error. The error will be created at that time by the optional\n * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.\n *\n * \n *\n * ## Example\n *\n * Throw an error if the document wasn't clicked within 1 second\n *\n * ```ts\n * import { fromEvent, takeUntil, timer, throwIfEmpty } from 'rxjs';\n *\n * const click$ = fromEvent(document, 'click');\n *\n * click$.pipe(\n * takeUntil(timer(1000)),\n * throwIfEmpty(() => new Error('The document was not clicked within 1 second'))\n * )\n * .subscribe({\n * next() {\n * console.log('The document was clicked');\n * },\n * error(err) {\n * console.error(err.message);\n * }\n * });\n * ```\n *\n * @param errorFactory A factory function called to produce the\n * error to be thrown when the source observable completes without emitting a\n * value.\n * @return A function that returns an Observable that throws an error if the\n * source Observable completed without emitting.\n */\nexport function throwIfEmpty<T>(errorFactory: () => any = defaultErrorFactory): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n subscriber.next(value);\n },\n () => (hasValue ? subscriber.complete() : subscriber.error(errorFactory()))\n )\n );\n });\n}\n\nfunction defaultErrorFactory() {\n return new EmptyError();\n}\n","import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\nimport { filter } from './filter';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { take } from './take';\n\n/**\n * Emits the single value at the specified `index` in a sequence of emissions\n * from the source Observable.\n *\n * <span class=\"informal\">Emits only the i-th value, then completes.</span>\n *\n * \n *\n * `elementAt` returns an Observable that emits the item at the specified\n * `index` in the source Observable, or a default value if that `index` is out\n * of range and the `default` argument is provided. If the `default` argument is\n * not given and the `index` is out of range, the output Observable will emit an\n * `ArgumentOutOfRangeError` error.\n *\n * ## Example\n *\n * Emit only the third click event\n *\n * ```ts\n * import { fromEvent, elementAt } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(elementAt(2));\n * result.subscribe(x => console.log(x));\n *\n * // Results in:\n * // click 1 = nothing\n * // click 2 = nothing\n * // click 3 = MouseEvent object logged to console\n * ```\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link skip}\n * @see {@link single}\n * @see {@link take}\n *\n * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an\n * `ArgumentOutOfRangeError` to the Observer's `error` callback if `i < 0` or the\n * Observable has completed before emitting the i-th `next` notification.\n *\n * @param index Is the number `i` for the i-th source emission that has happened\n * since the subscription, starting from the number `0`.\n * @param defaultValue The default value returned for missing indices.\n * @return A function that returns an Observable that emits a single item, if\n * it is found. Otherwise, it will emit the default value if given. If not, it\n * emits an error.\n */\nexport function elementAt<T, D = T>(index: number, defaultValue?: D): OperatorFunction<T, T | D> {\n if (index < 0) {\n throw new ArgumentOutOfRangeError();\n }\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable<T>) =>\n source.pipe(\n filter((v, i) => i === index),\n take(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new ArgumentOutOfRangeError())\n );\n}\n","/** prettier */\nimport { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { of } from '../observable/of';\nimport { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction, ValueFromArray } from '../types';\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function endWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function endWith<T, A extends unknown[] = T[]>(\n ...valuesAndScheduler: [...A, SchedulerLike]\n): OperatorFunction<T, T | ValueFromArray<A>>;\n\nexport function endWith<T, A extends unknown[] = T[]>(...values: A): OperatorFunction<T, T | ValueFromArray<A>>;\n\n/**\n * Returns an observable that will emit all values from the source, then synchronously emit\n * the provided value(s) immediately after the source completes.\n *\n * NOTE: Passing a last argument of a Scheduler is _deprecated_, and may result in incorrect\n * types in TypeScript.\n *\n * This is useful for knowing when an observable ends. Particularly when paired with an\n * operator like {@link takeUntil}\n *\n * \n *\n * ## Example\n *\n * Emit values to know when an interval starts and stops. The interval will\n * stop when a user clicks anywhere on the document.\n *\n * ```ts\n * import { interval, map, fromEvent, startWith, takeUntil, endWith } from 'rxjs';\n *\n * const ticker$ = interval(5000).pipe(\n * map(() => 'tick')\n * );\n *\n * const documentClicks$ = fromEvent(document, 'click');\n *\n * ticker$.pipe(\n * startWith('interval started'),\n * takeUntil(documentClicks$),\n * endWith('interval ended by click')\n * )\n * .subscribe(x => console.log(x));\n *\n * // Result (assuming a user clicks after 15 seconds)\n * // 'interval started'\n * // 'tick'\n * // 'tick'\n * // 'tick'\n * // 'interval ended by click'\n * ```\n *\n * @see {@link startWith}\n * @see {@link concat}\n * @see {@link takeUntil}\n *\n * @param values Items you want the modified Observable to emit last.\n * @return A function that returns an Observable that emits all values from the\n * source, then synchronously emits the provided value(s) immediately after the\n * source completes.\n */\nexport function endWith<T>(...values: Array<T | SchedulerLike>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => concat(source, of(...values)) as Observable<T>;\n}\n","import { Observable } from '../Observable';\nimport { Falsy, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function every<T>(predicate: BooleanConstructor): OperatorFunction<T, Exclude<T, Falsy> extends never ? false : boolean>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function every<T>(\n predicate: BooleanConstructor,\n thisArg: any\n): OperatorFunction<T, Exclude<T, Falsy> extends never ? false : boolean>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function every<T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,\n thisArg: A\n): OperatorFunction<T, boolean>;\nexport function every<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, boolean>;\n\n/**\n * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.\n *\n * <span class=\"informal\">If all values pass predicate before the source completes, emits true before completion,\n * otherwise emit false, then complete.</span>\n *\n * \n *\n * ## Example\n *\n * A simple example emitting true if all elements are less than 5, false otherwise\n *\n * ```ts\n * import { of, every } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5, 6)\n * .pipe(every(x => x < 5))\n * .subscribe(x => console.log(x)); // -> false\n * ```\n *\n * @param predicate A function for determining if an item meets a specified condition.\n * @param thisArg Optional object to use for `this` in the callback.\n * @return A function that returns an Observable of booleans that determines if\n * all items of the source Observable meet the condition specified.\n */\nexport function every<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg?: any\n): OperatorFunction<T, boolean> {\n return operate((source, subscriber) => {\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n if (!predicate.call(thisArg, value, index++, source)) {\n subscriber.next(false);\n subscriber.complete();\n }\n },\n () => {\n subscriber.next(true);\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/* tslint:disable:max-line-length */\nexport function exhaustMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function exhaustMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function exhaustMap<T, I, R>(\n project: (value: T, index: number) => ObservableInput<I>,\n resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable only if the previous projected Observable has completed.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link exhaustAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. When it projects a source value to\n * an Observable, the output Observable begins emitting the items emitted by\n * that projected Observable. However, `exhaustMap` ignores every new projected\n * Observable if the previous projected Observable has not yet completed. Once\n * that one completes, it will accept and flatten the next projected Observable\n * and repeat this process.\n *\n * ## Example\n *\n * Run a finite timer for each click, only if there is no currently active timer\n *\n * ```ts\n * import { fromEvent, exhaustMap, interval, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * exhaustMap(() => interval(1000).pipe(take(5)))\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaust}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @return A function that returns an Observable containing projected\n * Observables of each item of the source, ignoring projected Observables that\n * start before their preceding Observable has completed.\n */\nexport function exhaustMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n if (resultSelector) {\n // DEPRECATED PATH\n return (source: Observable<T>) =>\n source.pipe(exhaustMap((a, i) => innerFrom(project(a, i)).pipe(map((b: any, ii: any) => resultSelector(a, b, i, ii)))));\n }\n return operate((source, subscriber) => {\n let index = 0;\n let innerSub: Subscriber<T> | null = null;\n let isComplete = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (outerValue) => {\n if (!innerSub) {\n innerSub = createOperatorSubscriber(subscriber, undefined, () => {\n innerSub = null;\n isComplete && subscriber.complete();\n });\n innerFrom(project(outerValue, index++)).subscribe(innerSub);\n }\n },\n () => {\n isComplete = true;\n !innerSub && subscriber.complete();\n }\n )\n );\n });\n}\n","import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { exhaustMap } from './exhaustMap';\nimport { identity } from '../util/identity';\n\n/**\n * Converts a higher-order Observable into a first-order Observable by dropping\n * inner Observables while the previous inner Observable has not yet completed.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by dropping the\n * next inner Observables while the current inner is still executing.</span>\n *\n * \n *\n * `exhaustAll` subscribes to an Observable that emits Observables, also known as a\n * higher-order Observable. Each time it observes one of these emitted inner\n * Observables, the output Observable begins emitting the items emitted by that\n * inner Observable. So far, it behaves like {@link mergeAll}. However,\n * `exhaustAll` ignores every new inner Observable if the previous Observable has\n * not yet completed. Once that one completes, it will accept and flatten the\n * next inner Observable and repeat this process.\n *\n * ## Example\n *\n * Run a finite timer for each click, only if there is no currently active timer\n *\n * ```ts\n * import { fromEvent, map, interval, take, exhaustAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(5)))\n * );\n * const result = higherOrder.pipe(exhaustAll());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeAll}\n * @see {@link exhaustMap}\n * @see {@link zipAll}\n *\n * @return A function that returns an Observable that takes a source of\n * Observables and propagates the first Observable exclusively until it\n * completes before subscribing to the next.\n */\nexport function exhaustAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {\n return exhaustMap(identity);\n}\n","import { exhaustAll } from './exhaustAll';\n\n/**\n * @deprecated Renamed to {@link exhaustAll}. Will be removed in v8.\n */\nexport const exhaust = exhaustAll;\n","import { OperatorFunction, ObservableInput, ObservedValueOf, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\n\n/* tslint:disable:max-line-length */\nexport function expand<T, O extends ObservableInput<unknown>>(\n project: (value: T, index: number) => O,\n concurrent?: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, ObservedValueOf<O>>;\n/**\n * @deprecated The `scheduler` parameter will be removed in v8. If you need to schedule the inner subscription,\n * use `subscribeOn` within the projection function: `expand((value) => fn(value).pipe(subscribeOn(scheduler)))`.\n * Details: Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function expand<T, O extends ObservableInput<unknown>>(\n project: (value: T, index: number) => O,\n concurrent: number | undefined,\n scheduler: SchedulerLike\n): OperatorFunction<T, ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Recursively projects each source value to an Observable which is merged in\n * the output Observable.\n *\n * <span class=\"informal\">It's similar to {@link mergeMap}, but applies the\n * projection function to every source value as well as every output value.\n * It's recursive.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger. *Expand* will re-emit on the output\n * Observable every source value. Then, each output value is given to the\n * `project` function which returns an inner Observable to be merged on the\n * output Observable. Those output values resulting from the projection are also\n * given to the `project` function to produce new output values. This is how\n * *expand* behaves recursively.\n *\n * ## Example\n *\n * Start emitting the powers of two on every click, at most 10 of them\n *\n * ```ts\n * import { fromEvent, map, expand, of, delay, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const powersOfTwo = clicks.pipe(\n * map(() => 1),\n * expand(x => of(2 * x).pipe(delay(1000))),\n * take(10)\n * );\n * powersOfTwo.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n *\n * @param project A function that, when applied to an item emitted by the source\n * or the output Observable, returns an Observable.\n * @param concurrent Maximum number of input Observables being subscribed to\n * concurrently.\n * @param scheduler The {@link SchedulerLike} to use for subscribing to\n * each projected inner Observable.\n * @return A function that returns an Observable that emits the source values\n * and also result of applying the projection function to each value emitted on\n * the output Observable and merging the results of the Observables obtained\n * from this transformation.\n */\nexport function expand<T, O extends ObservableInput<unknown>>(\n project: (value: T, index: number) => O,\n concurrent = Infinity,\n scheduler?: SchedulerLike\n): OperatorFunction<T, ObservedValueOf<O>> {\n concurrent = (concurrent || 0) < 1 ? Infinity : concurrent;\n return operate((source, subscriber) =>\n mergeInternals(\n // General merge params\n source,\n subscriber,\n project,\n concurrent,\n\n // onBeforeNext\n undefined,\n\n // Expand-specific\n true, // Use expand path\n scheduler // Inner subscription scheduler\n )\n );\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\n/**\n * Returns an Observable that mirrors the source Observable, but will call a specified function when\n * the source terminates on complete or error.\n * The specified function will also be called when the subscriber explicitly unsubscribes.\n *\n * ## Examples\n *\n * Execute callback function when the observable completes\n *\n * ```ts\n * import { interval, take, finalize } from 'rxjs';\n *\n * // emit value in sequence every 1 second\n * const source = interval(1000);\n * const example = source.pipe(\n * take(5), //take only the first 5 values\n * finalize(() => console.log('Sequence complete')) // Execute when the observable completes\n * );\n * const subscribe = example.subscribe(val => console.log(val));\n *\n * // results:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 'Sequence complete'\n * ```\n *\n * Execute callback function when the subscriber explicitly unsubscribes\n *\n * ```ts\n * import { interval, finalize, tap, noop, timer } from 'rxjs';\n *\n * const source = interval(100).pipe(\n * finalize(() => console.log('[finalize] Called')),\n * tap({\n * next: () => console.log('[next] Called'),\n * error: () => console.log('[error] Not called'),\n * complete: () => console.log('[tap complete] Not called')\n * })\n * );\n *\n * const sub = source.subscribe({\n * next: x => console.log(x),\n * error: noop,\n * complete: () => console.log('[complete] Not called')\n * });\n *\n * timer(150).subscribe(() => sub.unsubscribe());\n *\n * // results:\n * // '[next] Called'\n * // 0\n * // '[finalize] Called'\n * ```\n *\n * @param callback Function to be called when source terminates.\n * @return A function that returns an Observable that mirrors the source, but\n * will call the specified function on termination.\n */\nexport function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n // TODO: This try/finally was only added for `useDeprecatedSynchronousErrorHandling`.\n // REMOVE THIS WHEN THAT HOT GARBAGE IS REMOVED IN V8.\n try {\n source.subscribe(subscriber);\n } finally {\n subscriber.add(callback);\n }\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, TruthyTypesOf } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function find<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function find<T, S extends T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => value is S,\n thisArg: A\n): OperatorFunction<T, S | undefined>;\nexport function find<T, S extends T>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S\n): OperatorFunction<T, S | undefined>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function find<T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,\n thisArg: A\n): OperatorFunction<T, T | undefined>;\nexport function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, T | undefined>;\n/**\n * Emits only the first value emitted by the source Observable that meets some\n * condition.\n *\n * <span class=\"informal\">Finds the first value that passes some test and emits\n * that.</span>\n *\n * \n *\n * `find` searches for the first item in the source Observable that matches the\n * specified condition embodied by the `predicate`, and returns the first\n * occurrence in the source. Unlike {@link first}, the `predicate` is required\n * in `find`, and does not emit an error if a valid value is not found\n * (emits `undefined` instead).\n *\n * ## Example\n *\n * Find and emit the first click that happens on a DIV element\n *\n * ```ts\n * import { fromEvent, find } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(find(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link first}\n * @see {@link findIndex}\n * @see {@link take}\n *\n * @param predicate A function called with each item to test for condition matching.\n * @param thisArg An optional argument to determine the value of `this` in the\n * `predicate` function.\n * @return A function that returns an Observable that emits the first item that\n * matches the condition.\n */\nexport function find<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg?: any\n): OperatorFunction<T, T | undefined> {\n return operate(createFind(predicate, thisArg, 'value'));\n}\n\nexport function createFind<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg: any,\n emit: 'value' | 'index'\n) {\n const findIndex = emit === 'index';\n return (source: Observable<T>, subscriber: Subscriber<any>) => {\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n const i = index++;\n if (predicate.call(thisArg, value, i, source)) {\n subscriber.next(findIndex ? i : value);\n subscriber.complete();\n }\n },\n () => {\n subscriber.next(findIndex ? -1 : undefined);\n subscriber.complete();\n }\n )\n );\n };\n}\n","import { Observable } from '../Observable';\nimport { Falsy, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createFind } from './find';\n\nexport function findIndex<T>(predicate: BooleanConstructor): OperatorFunction<T, T extends Falsy ? -1 : number>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function findIndex<T>(predicate: BooleanConstructor, thisArg: any): OperatorFunction<T, T extends Falsy ? -1 : number>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function findIndex<T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,\n thisArg: A\n): OperatorFunction<T, number>;\nexport function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, number>;\n\n/**\n * Emits only the index of the first value emitted by the source Observable that\n * meets some condition.\n *\n * <span class=\"informal\">It's like {@link find}, but emits the index of the\n * found value, not the value itself.</span>\n *\n * \n *\n * `findIndex` searches for the first item in the source Observable that matches\n * the specified condition embodied by the `predicate`, and returns the\n * (zero-based) index of the first occurrence in the source. Unlike\n * {@link first}, the `predicate` is required in `findIndex`, and does not emit\n * an error if a valid value is not found.\n *\n * ## Example\n *\n * Emit the index of first click that happens on a DIV element\n *\n * ```ts\n * import { fromEvent, findIndex } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(findIndex(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link first}\n * @see {@link take}\n *\n * @param predicate A function called with each item to test for condition matching.\n * @param thisArg An optional argument to determine the value of `this` in the\n * `predicate` function.\n * @return A function that returns an Observable that emits the index of the\n * first item that matches the condition.\n */\nexport function findIndex<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg?: any\n): OperatorFunction<T, number> {\n return operate(createFind(predicate, thisArg, 'index'));\n}\n","import { Observable } from '../Observable';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction, TruthyTypesOf } from '../types';\nimport { filter } from './filter';\nimport { take } from './take';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { identity } from '../util/identity';\n\nexport function first<T, D = T>(predicate?: null, defaultValue?: D): OperatorFunction<T, T | D>;\nexport function first<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function first<T, D>(predicate: BooleanConstructor, defaultValue: D): OperatorFunction<T, TruthyTypesOf<T> | D>;\nexport function first<T, S extends T>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S,\n defaultValue?: S\n): OperatorFunction<T, S>;\nexport function first<T, S extends T, D>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S,\n defaultValue: D\n): OperatorFunction<T, S | D>;\nexport function first<T, D = T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n defaultValue?: D\n): OperatorFunction<T, T | D>;\n\n/**\n * Emits only the first value (or the first value that meets some condition)\n * emitted by the source Observable.\n *\n * <span class=\"informal\">Emits only the first value. Or emits only the first\n * value that passes some test.</span>\n *\n * \n *\n * If called with no arguments, `first` emits the first value of the source\n * Observable, then completes. If called with a `predicate` function, `first`\n * emits the first value of the source that matches the specified condition. Emits an error\n * notification if `defaultValue` was not provided and a matching element is not found.\n *\n * ## Examples\n *\n * Emit only the first click that happens on the DOM\n *\n * ```ts\n * import { fromEvent, first } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Emits the first click that happens on a DIV\n *\n * ```ts\n * import { fromEvent, first } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link take}\n * @see {@link last}\n *\n * @throws {EmptyError} Delivers an `EmptyError` to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * This is how `first()` is different from `take(1)` which completes instead.\n *\n * @param predicate An optional function called with each item to test for condition\n * matching.\n * @param defaultValue The default value emitted in case no valid value was found on\n * the source.\n * @return A function that returns an Observable that emits the first item that\n * matches the condition.\n */\nexport function first<T, D>(\n predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,\n defaultValue?: D\n): OperatorFunction<T, T | D> {\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable<T>) =>\n source.pipe(\n predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n take(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new EmptyError())\n );\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { ObservableInput, Observer, OperatorFunction, SubjectLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber, OperatorSubscriber } from './OperatorSubscriber';\n\nexport interface BasicGroupByOptions<K, T> {\n element?: undefined;\n duration?: (grouped: GroupedObservable<K, T>) => ObservableInput<any>;\n connector?: () => SubjectLike<T>;\n}\n\nexport interface GroupByOptionsWithElement<K, E, T> {\n element: (value: T) => E;\n duration?: (grouped: GroupedObservable<K, E>) => ObservableInput<any>;\n connector?: () => SubjectLike<E>;\n}\n\nexport function groupBy<T, K>(key: (value: T) => K, options: BasicGroupByOptions<K, T>): OperatorFunction<T, GroupedObservable<K, T>>;\n\nexport function groupBy<T, K, E>(\n key: (value: T) => K,\n options: GroupByOptionsWithElement<K, E, T>\n): OperatorFunction<T, GroupedObservable<K, E>>;\n\nexport function groupBy<T, K extends T>(\n key: (value: T) => value is K\n): OperatorFunction<T, GroupedObservable<true, K> | GroupedObservable<false, Exclude<T, K>>>;\n\nexport function groupBy<T, K>(key: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;\n\n/**\n * @deprecated use the options parameter instead.\n */\nexport function groupBy<T, K>(\n key: (value: T) => K,\n element: void,\n duration: (grouped: GroupedObservable<K, T>) => Observable<any>\n): OperatorFunction<T, GroupedObservable<K, T>>;\n\n/**\n * @deprecated use the options parameter instead.\n */\nexport function groupBy<T, K, R>(\n key: (value: T) => K,\n element?: (value: T) => R,\n duration?: (grouped: GroupedObservable<K, R>) => Observable<any>\n): OperatorFunction<T, GroupedObservable<K, R>>;\n\n/**\n * Groups the items emitted by an Observable according to a specified criterion,\n * and emits these grouped items as `GroupedObservables`, one\n * {@link GroupedObservable} per group.\n *\n * \n *\n * When the Observable emits an item, a key is computed for this item with the key function.\n *\n * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Otherwise, a new\n * {@link GroupedObservable} for this key is created and emits.\n *\n * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common\n * key is available as the `key` field of a {@link GroupedObservable} instance.\n *\n * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements\n * returned by the element function.\n *\n * ## Examples\n *\n * Group objects by `id` and return as array\n *\n * ```ts\n * import { of, groupBy, mergeMap, reduce } from 'rxjs';\n *\n * of(\n * { id: 1, name: 'JavaScript' },\n * { id: 2, name: 'Parcel' },\n * { id: 2, name: 'webpack' },\n * { id: 1, name: 'TypeScript' },\n * { id: 3, name: 'TSLint' }\n * ).pipe(\n * groupBy(p => p.id),\n * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [])))\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // [{ id: 1, name: 'JavaScript' }, { id: 1, name: 'TypeScript'}]\n * // [{ id: 2, name: 'Parcel' }, { id: 2, name: 'webpack'}]\n * // [{ id: 3, name: 'TSLint' }]\n * ```\n *\n * Pivot data on the `id` field\n *\n * ```ts\n * import { of, groupBy, mergeMap, reduce, map } from 'rxjs';\n *\n * of(\n * { id: 1, name: 'JavaScript' },\n * { id: 2, name: 'Parcel' },\n * { id: 2, name: 'webpack' },\n * { id: 1, name: 'TypeScript' },\n * { id: 3, name: 'TSLint' }\n * ).pipe(\n * groupBy(p => p.id, { element: p => p.name }),\n * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [`${ group$.key }`]))),\n * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }\n * // { id: 2, values: [ 'Parcel', 'webpack' ] }\n * // { id: 3, values: [ 'TSLint' ] }\n * ```\n *\n * @param key A function that extracts the key\n * for each item.\n * @param element A function that extracts the\n * return element for each item.\n * @param duration\n * A function that returns an Observable to determine how long each group should\n * exist.\n * @param connector Factory function to create an\n * intermediate Subject through which grouped elements are emitted.\n * @return A function that returns an Observable that emits GroupedObservables,\n * each of which corresponds to a unique key value and each of which emits\n * those items from the source Observable that share that key value.\n *\n * @deprecated Use the options parameter instead.\n */\nexport function groupBy<T, K, R>(\n key: (value: T) => K,\n element?: (value: T) => R,\n duration?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n connector?: () => Subject<R>\n): OperatorFunction<T, GroupedObservable<K, R>>;\n\n// Impl\nexport function groupBy<T, K, R>(\n keySelector: (value: T) => K,\n elementOrOptions?: ((value: any) => any) | void | BasicGroupByOptions<K, T> | GroupByOptionsWithElement<K, R, T>,\n duration?: (grouped: GroupedObservable<any, any>) => ObservableInput<any>,\n connector?: () => SubjectLike<any>\n): OperatorFunction<T, GroupedObservable<K, R>> {\n return operate((source, subscriber) => {\n let element: ((value: any) => any) | void;\n if (!elementOrOptions || typeof elementOrOptions === 'function') {\n element = elementOrOptions as ((value: any) => any);\n } else {\n ({ duration, element, connector } = elementOrOptions);\n }\n\n // A lookup for the groups that we have so far.\n const groups = new Map<K, SubjectLike<any>>();\n\n // Used for notifying all groups and the subscriber in the same way.\n const notify = (cb: (group: Observer<any>) => void) => {\n groups.forEach(cb);\n cb(subscriber);\n };\n\n // Used to handle errors from the source, AND errors that occur during the\n // next call from the source.\n const handleError = (err: any) => notify((consumer) => consumer.error(err));\n\n // The number of actively subscribed groups\n let activeGroups = 0;\n\n // Whether or not teardown was attempted on this subscription.\n let teardownAttempted = false;\n\n // Capturing a reference to this, because we need a handle to it\n // in `createGroupedObservable` below. This is what we use to\n // subscribe to our source observable. This sometimes needs to be unsubscribed\n // out-of-band with our `subscriber` which is the downstream subscriber, or destination,\n // in cases where a user unsubscribes from the main resulting subscription, but\n // still has groups from this subscription subscribed and would expect values from it\n // Consider: `source.pipe(groupBy(fn), take(2))`.\n const groupBySourceSubscriber = new OperatorSubscriber(\n subscriber,\n (value: T) => {\n // Because we have to notify all groups of any errors that occur in here,\n // we have to add our own try/catch to ensure that those errors are propagated.\n // OperatorSubscriber will only send the error to the main subscriber.\n try {\n const key = keySelector(value);\n\n let group = groups.get(key);\n if (!group) {\n // Create our group subject\n groups.set(key, (group = connector ? connector() : new Subject<any>()));\n\n // Emit the grouped observable. Note that we can't do a simple `asObservable()` here,\n // because the grouped observable has special semantics around reference counting\n // to ensure we don't sever our connection to the source prematurely.\n const grouped = createGroupedObservable(key, group);\n subscriber.next(grouped);\n\n if (duration) {\n const durationSubscriber = createOperatorSubscriber(\n // Providing the group here ensures that it is disposed of -- via `unsubscribe` --\n // when the duration subscription is torn down. That is important, because then\n // if someone holds a handle to the grouped observable and tries to subscribe to it\n // after the connection to the source has been severed, they will get an\n // `ObjectUnsubscribedError` and know they can't possibly get any notifications.\n group as any,\n () => {\n // Our duration notified! We can complete the group.\n // The group will be removed from the map in the finalization phase.\n group!.complete();\n durationSubscriber?.unsubscribe();\n },\n // Completions are also sent to the group, but just the group.\n undefined,\n // Errors on the duration subscriber are sent to the group\n // but only the group. They are not sent to the main subscription.\n undefined,\n // Finalization: Remove this group from our map.\n () => groups.delete(key)\n );\n\n // Start our duration notifier.\n groupBySourceSubscriber.add(innerFrom(duration(grouped)).subscribe(durationSubscriber));\n }\n }\n\n // Send the value to our group.\n group.next(element ? element(value) : value);\n } catch (err) {\n handleError(err);\n }\n },\n // Source completes.\n () => notify((consumer) => consumer.complete()),\n // Error from the source.\n handleError,\n // Free up memory.\n // When the source subscription is _finally_ torn down, release the subjects and keys\n // in our groups Map, they may be quite large and we don't want to keep them around if we\n // don't have to.\n () => groups.clear(),\n () => {\n teardownAttempted = true;\n // We only kill our subscription to the source if we have\n // no active groups. As stated above, consider this scenario:\n // source$.pipe(groupBy(fn), take(2)).\n return activeGroups === 0;\n }\n );\n\n // Subscribe to the source\n source.subscribe(groupBySourceSubscriber);\n\n /**\n * Creates the actual grouped observable returned.\n * @param key The key of the group\n * @param groupSubject The subject that fuels the group\n */\n function createGroupedObservable(key: K, groupSubject: SubjectLike<any>) {\n const result: any = new Observable<T>((groupSubscriber) => {\n activeGroups++;\n const innerSub = groupSubject.subscribe(groupSubscriber);\n return () => {\n innerSub.unsubscribe();\n // We can kill the subscription to our source if we now have no more\n // active groups subscribed, and a finalization was already attempted on\n // the source.\n --activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();\n };\n });\n result.key = key;\n return result;\n }\n });\n}\n\n/**\n * An observable of values that is the emitted by the result of a {@link groupBy} operator,\n * contains a `key` property for the grouping.\n */\nexport interface GroupedObservable<K, T> extends Observable<T> {\n /**\n * The key value for the grouped notifications.\n */\n readonly key: K;\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits `false` if the input Observable emits any values, or emits `true` if the\n * input Observable completes without emitting any values.\n *\n * <span class=\"informal\">Tells whether any values are emitted by an Observable.</span>\n *\n * \n *\n * `isEmpty` transforms an Observable that emits values into an Observable that\n * emits a single boolean value representing whether or not any values were\n * emitted by the source Observable. As soon as the source Observable emits a\n * value, `isEmpty` will emit a `false` and complete. If the source Observable\n * completes having not emitted anything, `isEmpty` will emit a `true` and\n * complete.\n *\n * A similar effect could be achieved with {@link count}, but `isEmpty` can emit\n * a `false` value sooner.\n *\n * ## Examples\n *\n * Emit `false` for a non-empty Observable\n *\n * ```ts\n * import { Subject, isEmpty } from 'rxjs';\n *\n * const source = new Subject<string>();\n * const result = source.pipe(isEmpty());\n *\n * source.subscribe(x => console.log(x));\n * result.subscribe(x => console.log(x));\n *\n * source.next('a');\n * source.next('b');\n * source.next('c');\n * source.complete();\n *\n * // Outputs\n * // 'a'\n * // false\n * // 'b'\n * // 'c'\n * ```\n *\n * Emit `true` for an empty Observable\n *\n * ```ts\n * import { EMPTY, isEmpty } from 'rxjs';\n *\n * const result = EMPTY.pipe(isEmpty());\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // true\n * ```\n *\n * @see {@link count}\n * @see {@link EMPTY}\n *\n * @return A function that returns an Observable that emits boolean value\n * indicating whether the source Observable was empty or not.\n */\nexport function isEmpty<T>(): OperatorFunction<T, boolean> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n subscriber.next(false);\n subscriber.complete();\n },\n () => {\n subscriber.next(true);\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { EMPTY } from '../observable/empty';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Waits for the source to complete, then emits the last N values from the source,\n * as specified by the `count` argument.\n *\n * \n *\n * `takeLast` results in an observable that will hold values up to `count` values in memory,\n * until the source completes. It then pushes all values in memory to the consumer, in the\n * order they were received from the source, then notifies the consumer that it is\n * complete.\n *\n * If for some reason the source completes before the `count` supplied to `takeLast` is reached,\n * all values received until that point are emitted, and then completion is notified.\n *\n * **Warning**: Using `takeLast` with an observable that never completes will result\n * in an observable that never emits a value.\n *\n * ## Example\n *\n * Take the last 3 values of an Observable with many values\n *\n * ```ts\n * import { range, takeLast } from 'rxjs';\n *\n * const many = range(1, 100);\n * const lastThree = many.pipe(takeLast(3));\n * lastThree.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param count The maximum number of values to emit from the end of\n * the sequence of values emitted by the source Observable.\n * @return A function that returns an Observable that emits at most the last\n * `count` values emitted by the source Observable.\n */\nexport function takeLast<T>(count: number): MonoTypeOperatorFunction<T> {\n return count <= 0\n ? () => EMPTY\n : operate((source, subscriber) => {\n // This buffer will hold the values we are going to emit\n // when the source completes. Since we only want to take the\n // last N values, we can't emit until we're sure we're not getting\n // any more values.\n let buffer: T[] = [];\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Add the most recent value onto the end of our buffer.\n buffer.push(value);\n // If our buffer is now larger than the number of values we\n // want to take, we remove the oldest value from the buffer.\n count < buffer.length && buffer.shift();\n },\n () => {\n // The source completed, we now know what are last values\n // are, emit them in the order they were received.\n for (const value of buffer) {\n subscriber.next(value);\n }\n subscriber.complete();\n },\n // Errors are passed through to the consumer\n undefined,\n () => {\n // During finalization release the values in our buffer.\n buffer = null!;\n }\n )\n );\n });\n}\n","import { Observable } from '../Observable';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction, TruthyTypesOf } from '../types';\nimport { filter } from './filter';\nimport { takeLast } from './takeLast';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { identity } from '../util/identity';\n\nexport function last<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function last<T, D>(predicate: BooleanConstructor, defaultValue: D): OperatorFunction<T, TruthyTypesOf<T> | D>;\nexport function last<T, D = T>(predicate?: null, defaultValue?: D): OperatorFunction<T, T | D>;\nexport function last<T, S extends T>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S,\n defaultValue?: S\n): OperatorFunction<T, S>;\nexport function last<T, D = T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n defaultValue?: D\n): OperatorFunction<T, T | D>;\n\n/**\n * Returns an Observable that emits only the last item emitted by the source Observable.\n * It optionally takes a predicate function as a parameter, in which case, rather than emitting\n * the last item from the source Observable, the resulting Observable will emit the last item\n * from the source Observable that satisfies the predicate.\n *\n * \n *\n * It will emit an error notification if the source completes without notification or one that matches\n * the predicate. It returns the last value or if a predicate is provided last value that matches the\n * predicate. It returns the given default value if no notification is emitted or matches the predicate.\n *\n * ## Examples\n *\n * Last alphabet from the sequence\n *\n * ```ts\n * import { from, last } from 'rxjs';\n *\n * const source = from(['x', 'y', 'z']);\n * const result = source.pipe(last());\n *\n * result.subscribe(value => console.log(`Last alphabet: ${ value }`));\n *\n * // Outputs\n * // Last alphabet: z\n * ```\n *\n * Default value when the value in the predicate is not matched\n *\n * ```ts\n * import { from, last } from 'rxjs';\n *\n * const source = from(['x', 'y', 'z']);\n * const result = source.pipe(last(char => char === 'a', 'not found'));\n *\n * result.subscribe(value => console.log(`'a' is ${ value }.`));\n *\n * // Outputs\n * // 'a' is not found.\n * ```\n *\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipLast}\n * @see {@link skipWhile}\n * @see {@link first}\n *\n * @throws {EmptyError} Delivers an `EmptyError` to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n *\n * @param predicate The condition any source emitted item has to satisfy.\n * @param defaultValue An optional default value to provide if last `predicate`\n * isn't met or no values were emitted.\n * @return A function that returns an Observable that emits only the last item\n * satisfying the given condition from the source, or an error notification\n * with an `EmptyError` object if no such items are emitted.\n */\nexport function last<T, D>(\n predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,\n defaultValue?: D\n): OperatorFunction<T, T | D> {\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable<T>) =>\n source.pipe(\n predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n takeLast(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new EmptyError())\n );\n}\n","import { Notification } from '../Notification';\nimport { OperatorFunction, ObservableNotification } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Represents all of the notifications from the source Observable as `next`\n * emissions marked with their original types within {@link Notification}\n * objects.\n *\n * <span class=\"informal\">Wraps `next`, `error` and `complete` emissions in\n * {@link Notification} objects, emitted as `next` on the output Observable.\n * </span>\n *\n * \n *\n * `materialize` returns an Observable that emits a `next` notification for each\n * `next`, `error`, or `complete` emission of the source Observable. When the\n * source Observable emits `complete`, the output Observable will emit `next` as\n * a Notification of type \"complete\", and then it will emit `complete` as well.\n * When the source Observable emits `error`, the output will emit `next` as a\n * Notification of type \"error\", and then `complete`.\n *\n * This operator is useful for producing metadata of the source Observable, to\n * be consumed as `next` emissions. Use it in conjunction with\n * {@link dematerialize}.\n *\n * ## Example\n *\n * Convert a faulty Observable to an Observable of Notifications\n *\n * ```ts\n * import { of, materialize, map } from 'rxjs';\n *\n * const letters = of('a', 'b', 13, 'd');\n * const upperCase = letters.pipe(map((x: any) => x.toUpperCase()));\n * const materialized = upperCase.pipe(materialize());\n *\n * materialized.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - Notification { kind: 'N', value: 'A', error: undefined, hasValue: true }\n * // - Notification { kind: 'N', value: 'B', error: undefined, hasValue: true }\n * // - Notification { kind: 'E', value: undefined, error: TypeError { message: x.toUpperCase is not a function }, hasValue: false }\n * ```\n *\n * @see {@link Notification}\n * @see {@link dematerialize}\n *\n * @return A function that returns an Observable that emits\n * {@link Notification} objects that wrap the original emissions from the\n * source Observable with metadata.\n */\nexport function materialize<T>(): OperatorFunction<T, Notification<T> & ObservableNotification<T>> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n subscriber.next(Notification.createNext(value));\n },\n () => {\n subscriber.next(Notification.createComplete());\n subscriber.complete();\n },\n (err) => {\n subscriber.next(Notification.createError(err));\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * The `max` operator operates on an Observable that emits numbers (or items that\n * can be compared with a provided function), and when source Observable completes\n * it emits a single item: the item with the largest value.\n *\n * \n *\n * ## Examples\n *\n * Get the maximal value of a series of numbers\n *\n * ```ts\n * import { of, max } from 'rxjs';\n *\n * of(5, 4, 7, 2, 8)\n * .pipe(max())\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // 8\n * ```\n *\n * Use a comparer function to get the maximal item\n *\n * ```ts\n * import { of, max } from 'rxjs';\n *\n * of(\n * { age: 7, name: 'Foo' },\n * { age: 5, name: 'Bar' },\n * { age: 9, name: 'Beer' }\n * ).pipe(\n * max((a, b) => a.age < b.age ? -1 : 1)\n * )\n * .subscribe(x => console.log(x.name));\n *\n * // Outputs\n * // 'Beer'\n * ```\n *\n * @see {@link min}\n *\n * @param comparer Optional comparer function that it will use instead of its\n * default to compare the value of two items.\n * @return A function that returns an Observable that emits item with the\n * largest value.\n */\nexport function max<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {\n return reduce(isFunction(comparer) ? (x, y) => (comparer(x, y) > 0 ? x : y) : (x, y) => (x > y ? x : y));\n}\n","import { mergeMap } from './mergeMap';\n\n/**\n * @deprecated Renamed to {@link mergeMap}. Will be removed in v8.\n */\nexport const flatMap = mergeMap;\n","import { OperatorFunction, ObservedValueOf, ObservableInput } from '../types';\nimport { mergeMap } from './mergeMap';\nimport { isFunction } from '../util/isFunction';\n\n/** @deprecated Will be removed in v9. Use {@link mergeMap} instead: `mergeMap(() => result)` */\nexport function mergeMapTo<O extends ObservableInput<unknown>>(\n innerObservable: O,\n concurrent?: number\n): OperatorFunction<unknown, ObservedValueOf<O>>;\n/**\n * @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead.\n * Details: https://rxjs.dev/deprecations/resultSelector\n */\nexport function mergeMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n concurrent?: number\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in the output Observable.\n *\n * <span class=\"informal\">It's like {@link mergeMap}, but maps each value always\n * to the same inner Observable.</span>\n *\n * \n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then merges those resulting Observables into one\n * single Observable, which is the output Observable.\n *\n * ## Example\n *\n * For each click event, start an interval Observable ticking every 1 second\n *\n * ```ts\n * import { fromEvent, mergeMapTo, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(mergeMapTo(interval(1000)));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n * @see {@link switchMapTo}\n *\n * @param innerObservable An `ObservableInput` to replace each value from the\n * source Observable.\n * @param concurrent Maximum number of input Observables being subscribed to\n * concurrently.\n * @return A function that returns an Observable that emits items from the\n * given `innerObservable`.\n * @deprecated Will be removed in v9. Use {@link mergeMap} instead: `mergeMap(() => result)`\n */\nexport function mergeMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Infinity\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n if (isFunction(resultSelector)) {\n return mergeMap(() => innerObservable, resultSelector, concurrent);\n }\n if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return mergeMap(() => innerObservable, concurrent);\n}\n","import { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\n\n/**\n * Applies an accumulator function over the source Observable where the\n * accumulator function itself returns an Observable, then each intermediate\n * Observable returned is merged into the output Observable.\n *\n * <span class=\"informal\">It's like {@link scan}, but the Observables returned\n * by the accumulator are merged into the outer Observable.</span>\n *\n * The first parameter of the `mergeScan` is an `accumulator` function which is\n * being called every time the source Observable emits a value. `mergeScan` will\n * subscribe to the value returned by the `accumulator` function and will emit\n * values to the subscriber emitted by inner Observable.\n *\n * The `accumulator` function is being called with three parameters passed to it:\n * `acc`, `value` and `index`. The `acc` parameter is used as the state parameter\n * whose value is initially set to the `seed` parameter (the second parameter\n * passed to the `mergeScan` operator).\n *\n * `mergeScan` internally keeps the value of the `acc` parameter: as long as the\n * source Observable emits without inner Observable emitting, the `acc` will be\n * set to `seed`. The next time the inner Observable emits a value, `mergeScan`\n * will internally remember it and it will be passed to the `accumulator`\n * function as `acc` parameter the next time source emits.\n *\n * The `value` parameter of the `accumulator` function is the value emitted by the\n * source Observable, while the `index` is a number which represent the order of the\n * current emission by the source Observable. It starts with 0.\n *\n * The last parameter to the `mergeScan` is the `concurrent` value which defaults\n * to Infinity. It represents the maximum number of inner Observable subscriptions\n * at a time.\n *\n * ## Example\n *\n * Count the number of click events\n *\n * ```ts\n * import { fromEvent, map, mergeScan, of } from 'rxjs';\n *\n * const click$ = fromEvent(document, 'click');\n * const one$ = click$.pipe(map(() => 1));\n * const seed = 0;\n * const count$ = one$.pipe(\n * mergeScan((acc, one) => of(acc + one), seed)\n * );\n *\n * count$.subscribe(x => console.log(x));\n *\n * // Results:\n * // 1\n * // 2\n * // 3\n * // 4\n * // ...and so on for each click\n * ```\n *\n * @see {@link scan}\n * @see {@link switchScan}\n *\n * @param accumulator The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @param concurrent Maximum number of input Observables being subscribed to\n * concurrently.\n * @return A function that returns an Observable of the accumulated values.\n */\nexport function mergeScan<T, R>(\n accumulator: (acc: R, value: T, index: number) => ObservableInput<R>,\n seed: R,\n concurrent = Infinity\n): OperatorFunction<T, R> {\n return operate((source, subscriber) => {\n // The accumulated state.\n let state = seed;\n\n return mergeInternals(\n source,\n subscriber,\n (value, index) => accumulator(state, value, index),\n concurrent,\n (value) => {\n state = value;\n },\n false,\n undefined,\n () => (state = null!)\n );\n });\n}\n","import { ObservableInput, ObservableInputTuple, OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { mergeAll } from './mergeAll';\nimport { popNumber, popScheduler } from '../util/args';\nimport { from } from '../observable/from';\n\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(\n ...sourcesAndConcurrency: [...ObservableInputTuple<A>, number]\n): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]\n): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(\n ...sourcesAndConcurrencyAndScheduler: [...ObservableInputTuple<A>, number, SchedulerLike]\n): OperatorFunction<T, T | A[number]>;\n\nexport function merge<T>(...args: unknown[]): OperatorFunction<T, unknown> {\n const scheduler = popScheduler(args);\n const concurrent = popNumber(args, Infinity);\n\n return operate((source, subscriber) => {\n mergeAll(concurrent)(from([source, ...(args as ObservableInput<T>[])], scheduler)).subscribe(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction } from '../types';\nimport { merge } from './merge';\n\n/**\n * Merge the values from all observables to a single observable result.\n *\n * Creates an observable, that when subscribed to, subscribes to the source\n * observable, and all other sources provided as arguments. All values from\n * every source are emitted from the resulting subscription.\n *\n * When all sources complete, the resulting observable will complete.\n *\n * When any source errors, the resulting observable will error.\n *\n * ## Example\n *\n * Joining all outputs from multiple user input event streams\n *\n * ```ts\n * import { fromEvent, map, mergeWith } from 'rxjs';\n *\n * const clicks$ = fromEvent(document, 'click').pipe(map(() => 'click'));\n * const mousemoves$ = fromEvent(document, 'mousemove').pipe(map(() => 'mousemove'));\n * const dblclicks$ = fromEvent(document, 'dblclick').pipe(map(() => 'dblclick'));\n *\n * mousemoves$\n * .pipe(mergeWith(clicks$, dblclicks$))\n * .subscribe(x => console.log(x));\n *\n * // result (assuming user interactions)\n * // 'mousemove'\n * // 'mousemove'\n * // 'mousemove'\n * // 'click'\n * // 'click'\n * // 'dblclick'\n * ```\n *\n * @see {@link merge}\n *\n * @param otherSources the sources to combine the current source with.\n * @return A function that returns an Observable that merges the values from\n * all given Observables.\n */\nexport function mergeWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n return merge(...otherSources);\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * The `min` operator operates on an Observable that emits numbers (or items that\n * can be compared with a provided function), and when source Observable completes\n * it emits a single item: the item with the smallest value.\n *\n * \n *\n * ## Examples\n *\n * Get the minimal value of a series of numbers\n *\n * ```ts\n * import { of, min } from 'rxjs';\n *\n * of(5, 4, 7, 2, 8)\n * .pipe(min())\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // 2\n * ```\n *\n * Use a comparer function to get the minimal item\n *\n * ```ts\n * import { of, min } from 'rxjs';\n *\n * of(\n * { age: 7, name: 'Foo' },\n * { age: 5, name: 'Bar' },\n * { age: 9, name: 'Beer' }\n * ).pipe(\n * min((a, b) => a.age < b.age ? -1 : 1)\n * )\n * .subscribe(x => console.log(x.name));\n *\n * // Outputs\n * // 'Bar'\n * ```\n *\n * @see {@link max}\n *\n * @param comparer Optional comparer function that it will use instead of its\n * default to compare the value of two items.\n * @return A function that returns an Observable that emits item with the\n * smallest value.\n */\nexport function min<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {\n return reduce(isFunction(comparer) ? (x, y) => (comparer(x, y) < 0 ? x : y) : (x, y) => (x < y ? x : y));\n}\n","import { Subject } from '../Subject';\nimport { Observable } from '../Observable';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { OperatorFunction, UnaryFunction, ObservedValueOf, ObservableInput } from '../types';\nimport { isFunction } from '../util/isFunction';\nimport { connect } from './connect';\n\n/**\n * An operator that creates a {@link ConnectableObservable}, that when connected,\n * with the `connect` method, will use the provided subject to multicast the values\n * from the source to all consumers.\n *\n * @param subject The subject to multicast through.\n * @return A function that returns a {@link ConnectableObservable}\n * @deprecated Will be removed in v8. To create a connectable observable, use {@link connectable}.\n * If you're using {@link refCount} after `multicast`, use the {@link share} operator instead.\n * `multicast(subject), refCount()` is equivalent to\n * `share({ connector: () => subject, resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T>(subject: Subject<T>): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\n\n/**\n * Because this is deprecated in favor of the {@link connect} operator, and was otherwise poorly documented,\n * rather than duplicate the effort of documenting the same behavior, please see documentation for the\n * {@link connect} operator.\n *\n * @param subject The subject used to multicast.\n * @param selector A setup function to setup the multicast\n * @return A function that returns an observable that mirrors the observable returned by the selector.\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `multicast(subject, selector)` is equivalent to\n * `connect(selector, { connector: () => subject })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T, O extends ObservableInput<any>>(\n subject: Subject<T>,\n selector: (shared: Observable<T>) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * An operator that creates a {@link ConnectableObservable}, that when connected,\n * with the `connect` method, will use the provided subject to multicast the values\n * from the source to all consumers.\n *\n * @param subjectFactory A factory that will be called to create the subject. Passing a function here\n * will cause the underlying subject to be \"reset\" on error, completion, or refCounted unsubscription of\n * the source.\n * @return A function that returns a {@link ConnectableObservable}\n * @deprecated Will be removed in v8. To create a connectable observable, use {@link connectable}.\n * If you're using {@link refCount} after `multicast`, use the {@link share} operator instead.\n * `multicast(() => new BehaviorSubject('test')), refCount()` is equivalent to\n * `share({ connector: () => new BehaviorSubject('test') })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T>(subjectFactory: () => Subject<T>): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\n\n/**\n * Because this is deprecated in favor of the {@link connect} operator, and was otherwise poorly documented,\n * rather than duplicate the effort of documenting the same behavior, please see documentation for the\n * {@link connect} operator.\n *\n * @param subjectFactory A factory that creates the subject used to multicast.\n * @param selector A function to setup the multicast and select the output.\n * @return A function that returns an observable that mirrors the observable returned by the selector.\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `multicast(subjectFactory, selector)` is equivalent to\n * `connect(selector, { connector: subjectFactory })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T, O extends ObservableInput<any>>(\n subjectFactory: () => Subject<T>,\n selector: (shared: Observable<T>) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * @deprecated Will be removed in v8. Use the {@link connectable} observable, the {@link connect} operator or the\n * {@link share} operator instead. See the overloads below for equivalent replacement examples of this operator's\n * behaviors.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T, R>(\n subjectOrSubjectFactory: Subject<T> | (() => Subject<T>),\n selector?: (source: Observable<T>) => Observable<R>\n): OperatorFunction<T, R> {\n const subjectFactory = isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : () => subjectOrSubjectFactory;\n\n if (isFunction(selector)) {\n // If a selector function is provided, then we're a \"normal\" operator that isn't\n // going to return a ConnectableObservable. We can use `connect` to do what we\n // need to do.\n return connect(selector, {\n connector: subjectFactory,\n });\n }\n\n return (source: Observable<T>) => new ConnectableObservable<any>(source, subjectFactory);\n}\n","import { ObservableInputTuple, OperatorFunction } from '../types';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { onErrorResumeNext as oERNCreate } from '../observable/onErrorResumeNext';\n\nexport function onErrorResumeNextWith<T, A extends readonly unknown[]>(\n sources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]>;\nexport function onErrorResumeNextWith<T, A extends readonly unknown[]>(\n ...sources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]>;\n\n/**\n * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * <span class=\"informal\">Execute series of Observables, subscribes to next one on error or complete.</span>\n *\n * \n *\n * `onErrorResumeNext` is an operator that accepts a series of Observables, provided either directly as\n * arguments or as an array. If no single Observable is provided, returned Observable will simply behave the same\n * as the source.\n *\n * `onErrorResumeNext` returns an Observable that starts by subscribing and re-emitting values from the source Observable.\n * When its stream of values ends - no matter if Observable completed or emitted an error - `onErrorResumeNext`\n * will subscribe to the first Observable that was passed as an argument to the method. It will start re-emitting\n * its values as well and - again - when that stream ends, `onErrorResumeNext` will proceed to subscribing yet another\n * Observable in provided series, no matter if previous Observable completed or ended with an error. This will\n * be happening until there is no more Observables left in the series, at which point returned Observable will\n * complete - even if the last subscribed stream ended with an error.\n *\n * `onErrorResumeNext` can be therefore thought of as version of {@link concat} operator, which is more permissive\n * when it comes to the errors emitted by its input Observables. While `concat` subscribes to the next Observable\n * in series only if previous one successfully completed, `onErrorResumeNext` subscribes even if it ended with\n * an error.\n *\n * Note that you do not get any access to errors emitted by the Observables. In particular do not\n * expect these errors to appear in error callback passed to {@link Observable#subscribe}. If you want to take\n * specific actions based on what error was emitted by an Observable, you should try out {@link catchError} instead.\n *\n *\n * ## Example\n *\n * Subscribe to the next Observable after map fails\n *\n * ```ts\n * import { of, onErrorResumeNext, map } from 'rxjs';\n *\n * of(1, 2, 3, 0)\n * .pipe(\n * map(x => {\n * if (x === 0) {\n * throw Error();\n * }\n *\n * return 10 / x;\n * }),\n * onErrorResumeNext(of(1, 2, 3))\n * )\n * .subscribe({\n * next: val => console.log(val),\n * error: err => console.log(err), // Will never be called.\n * complete: () => console.log('that\\'s it!')\n * });\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // 'that's it!'\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param sources `ObservableInput`s passed either directly or as an array.\n * @return A function that returns an Observable that emits values from source\n * Observable, but - if it errors - subscribes to the next passed Observable\n * and so on, until it completes or runs out of Observables.\n */\nexport function onErrorResumeNextWith<T, A extends readonly unknown[]>(\n ...sources: [[...ObservableInputTuple<A>]] | [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n // For some reason, TS 4.1 RC gets the inference wrong here and infers the\n // result to be `A[number][]` - completely dropping the ObservableInput part\n // of the type. This makes no sense whatsoever. As a workaround, the type is\n // asserted explicitly.\n const nextSources = argsOrArgArray(sources) as unknown as ObservableInputTuple<A>;\n\n return (source) => oERNCreate(source, ...nextSources);\n}\n\n/**\n * @deprecated Renamed. Use {@link onErrorResumeNextWith} instead. Will be removed in v8.\n */\nexport const onErrorResumeNext = onErrorResumeNextWith;\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Groups pairs of consecutive emissions together and emits them as an array of\n * two values.\n *\n * <span class=\"informal\">Puts the current value and previous value together as\n * an array, and emits that.</span>\n *\n * \n *\n * The Nth emission from the source Observable will cause the output Observable\n * to emit an array [(N-1)th, Nth] of the previous and the current value, as a\n * pair. For this reason, `pairwise` emits on the second and subsequent\n * emissions from the source Observable, but not on the first emission, because\n * there is no previous value in that case.\n *\n * ## Example\n *\n * On every click (starting from the second), emit the relative distance to the previous click\n *\n * ```ts\n * import { fromEvent, pairwise, map } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const pairs = clicks.pipe(pairwise());\n * const distance = pairs.pipe(\n * map(([first, second]) => {\n * const x0 = first.clientX;\n * const y0 = first.clientY;\n * const x1 = second.clientX;\n * const y1 = second.clientY;\n * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));\n * })\n * );\n *\n * distance.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n *\n * @return A function that returns an Observable of pairs (as arrays) of\n * consecutive values from the source Observable.\n */\nexport function pairwise<T>(): OperatorFunction<T, [T, T]> {\n return operate((source, subscriber) => {\n let prev: T;\n let hasPrev = false;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const p = prev;\n prev = value;\n hasPrev && subscriber.next([p, value]);\n hasPrev = true;\n })\n );\n });\n}\n","import { map } from './map';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T>(k1: K1): OperatorFunction<T, T[K1]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1]>(k1: K1, k2: K2): OperatorFunction<T, T[K1][K2]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(\n k1: K1,\n k2: K2,\n k3: K3\n): OperatorFunction<T, T[K1][K2][K3]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3]>(\n k1: K1,\n k2: K2,\n k3: K3,\n k4: K4\n): OperatorFunction<T, T[K1][K2][K3][K4]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<\n T,\n K1 extends keyof T,\n K2 extends keyof T[K1],\n K3 extends keyof T[K1][K2],\n K4 extends keyof T[K1][K2][K3],\n K5 extends keyof T[K1][K2][K3][K4]\n>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5): OperatorFunction<T, T[K1][K2][K3][K4][K5]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<\n T,\n K1 extends keyof T,\n K2 extends keyof T[K1],\n K3 extends keyof T[K1][K2],\n K4 extends keyof T[K1][K2][K3],\n K5 extends keyof T[K1][K2][K3][K4],\n K6 extends keyof T[K1][K2][K3][K4][K5]\n>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5, k6: K6): OperatorFunction<T, T[K1][K2][K3][K4][K5][K6]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<\n T,\n K1 extends keyof T,\n K2 extends keyof T[K1],\n K3 extends keyof T[K1][K2],\n K4 extends keyof T[K1][K2][K3],\n K5 extends keyof T[K1][K2][K3][K4],\n K6 extends keyof T[K1][K2][K3][K4][K5]\n>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5, k6: K6, ...rest: string[]): OperatorFunction<T, unknown>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T>(...properties: string[]): OperatorFunction<T, unknown>;\n/* tslint:enable:max-line-length */\n\n/**\n * Maps each source value to its specified nested property.\n *\n * <span class=\"informal\">Like {@link map}, but meant only for picking one of\n * the nested properties of every emitted value.</span>\n *\n * \n *\n * Given a list of strings or numbers describing a path to a property, retrieves\n * the value of a specified nested property from all values in the source\n * Observable. If a property can't be resolved, it will return `undefined` for\n * that value.\n *\n * ## Example\n *\n * Map every click to the tagName of the clicked target element\n *\n * ```ts\n * import { fromEvent, pluck } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const tagNames = clicks.pipe(pluck('target', 'tagName'));\n *\n * tagNames.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param properties The nested properties to pluck from each source\n * value.\n * @return A function that returns an Observable of property values from the\n * source values.\n * @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8.\n */\nexport function pluck<T, R>(...properties: Array<string | number | symbol>): OperatorFunction<T, R> {\n const length = properties.length;\n if (length === 0) {\n throw new Error('list of properties cannot be empty.');\n }\n return map((x) => {\n let currentProp: any = x;\n for (let i = 0; i < length; i++) {\n const p = currentProp?.[properties[i]];\n if (typeof p !== 'undefined') {\n currentProp = p;\n } else {\n return undefined;\n }\n }\n return currentProp;\n });\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { connect } from './connect';\n\n/**\n * Returns a connectable observable that, when connected, will multicast\n * all values through a single underlying {@link Subject} instance.\n *\n * @deprecated Will be removed in v8. To create a connectable observable, use {@link connectable}.\n * `source.pipe(publish())` is equivalent to\n * `connectable(source, { connector: () => new Subject(), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publish`, use {@link share} operator instead.\n * `source.pipe(publish(), refCount())` is equivalent to\n * `source.pipe(share({ resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publish<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\n\n/**\n * Returns an observable, that when subscribed to, creates an underlying {@link Subject},\n * provides an observable view of it to a `selector` function, takes the observable result of\n * that selector function and subscribes to it, sending its values to the consumer, _then_ connects\n * the subject to the original source.\n *\n * @param selector A function used to setup multicasting prior to automatic connection.\n *\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `publish(selector)` is equivalent to `connect(selector)`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publish<T, O extends ObservableInput<any>>(selector: (shared: Observable<T>) => O): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called\n * before it begins emitting items to those Observers that have subscribed to it.\n *\n * <span class=\"informal\">Makes a cold Observable hot</span>\n *\n * \n *\n * ## Examples\n *\n * Make `source$` hot by applying `publish` operator, then merge each inner observable into a single one\n * and subscribe\n *\n * ```ts\n * import { zip, interval, of, map, publish, merge, tap } from 'rxjs';\n *\n * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9))\n * .pipe(map(([, number]) => number));\n *\n * source$\n * .pipe(\n * publish(multicasted$ =>\n * merge(\n * multicasted$.pipe(tap(x => console.log('Stream 1:', x))),\n * multicasted$.pipe(tap(x => console.log('Stream 2:', x))),\n * multicasted$.pipe(tap(x => console.log('Stream 3:', x)))\n * )\n * )\n * )\n * .subscribe();\n *\n * // Results every two seconds\n * // Stream 1: 1\n * // Stream 2: 1\n * // Stream 3: 1\n * // ...\n * // Stream 1: 9\n * // Stream 2: 9\n * // Stream 3: 9\n * ```\n *\n * @see {@link publishLast}\n * @see {@link publishReplay}\n * @see {@link publishBehavior}\n *\n * @param selector Optional selector function which can use the multicasted source sequence as many times\n * as needed, without causing multiple subscriptions to the source sequence.\n * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.\n * @return A function that returns a ConnectableObservable that upon connection\n * causes the source Observable to emit items to its Observers.\n * @deprecated Will be removed in v8. Use the {@link connectable} observable, the {@link connect} operator or the\n * {@link share} operator instead. See the overloads below for equivalent replacement examples of this operator's\n * behaviors.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publish<T, R>(selector?: OperatorFunction<T, R>): MonoTypeOperatorFunction<T> | OperatorFunction<T, R> {\n return selector ? (source) => connect(selector)(source) : (source) => multicast(new Subject<T>())(source);\n}\n","import { Observable } from '../Observable';\nimport { BehaviorSubject } from '../BehaviorSubject';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Creates a {@link ConnectableObservable} that utilizes a {@link BehaviorSubject}.\n *\n * @param initialValue The initial value passed to the {@link BehaviorSubject}.\n * @return A function that returns a {@link ConnectableObservable}\n * @deprecated Will be removed in v8. To create a connectable observable that uses a\n * {@link BehaviorSubject} under the hood, use {@link connectable}.\n * `source.pipe(publishBehavior(initValue))` is equivalent to\n * `connectable(source, { connector: () => new BehaviorSubject(initValue), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishBehavior`, use the {@link share} operator instead.\n * `source.pipe(publishBehavior(initValue), refCount())` is equivalent to\n * `source.pipe(share({ connector: () => new BehaviorSubject(initValue), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishBehavior<T>(initialValue: T): UnaryFunction<Observable<T>, ConnectableObservable<T>> {\n // Note that this has *never* supported the selector function.\n return (source) => {\n const subject = new BehaviorSubject<T>(initialValue);\n return new ConnectableObservable(source, () => subject);\n };\n}\n","import { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Returns a connectable observable sequence that shares a single subscription to the\n * underlying sequence containing only the last notification.\n *\n * \n *\n * Similar to {@link publish}, but it waits until the source observable completes and stores\n * the last emitted value.\n * Similarly to {@link publishReplay} and {@link publishBehavior}, this keeps storing the last\n * value even if it has no more subscribers. If subsequent subscriptions happen, they will\n * immediately get that last stored value and complete.\n *\n * ## Example\n *\n * ```ts\n * import { ConnectableObservable, interval, publishLast, tap, take } from 'rxjs';\n *\n * const connectable = <ConnectableObservable<number>>interval(1000)\n * .pipe(\n * tap(x => console.log('side effect', x)),\n * take(3),\n * publishLast()\n * );\n *\n * connectable.subscribe({\n * next: x => console.log('Sub. A', x),\n * error: err => console.log('Sub. A Error', err),\n * complete: () => console.log('Sub. A Complete')\n * });\n *\n * connectable.subscribe({\n * next: x => console.log('Sub. B', x),\n * error: err => console.log('Sub. B Error', err),\n * complete: () => console.log('Sub. B Complete')\n * });\n *\n * connectable.connect();\n *\n * // Results:\n * // 'side effect 0' - after one second\n * // 'side effect 1' - after two seconds\n * // 'side effect 2' - after three seconds\n * // 'Sub. A 2' - immediately after 'side effect 2'\n * // 'Sub. B 2'\n * // 'Sub. A Complete'\n * // 'Sub. B Complete'\n * ```\n *\n * @see {@link ConnectableObservable}\n * @see {@link publish}\n * @see {@link publishReplay}\n * @see {@link publishBehavior}\n *\n * @return A function that returns an Observable that emits elements of a\n * sequence produced by multicasting the source sequence.\n * @deprecated Will be removed in v8. To create a connectable observable with an\n * {@link AsyncSubject} under the hood, use {@link connectable}.\n * `source.pipe(publishLast())` is equivalent to\n * `connectable(source, { connector: () => new AsyncSubject(), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishLast`, use the {@link share} operator instead.\n * `source.pipe(publishLast(), refCount())` is equivalent to\n * `source.pipe(share({ connector: () => new AsyncSubject(), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishLast<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>> {\n // Note that this has *never* supported a selector function like `publish` and `publishReplay`.\n return (source) => {\n const subject = new AsyncSubject<T>();\n return new ConnectableObservable(source, () => subject);\n };\n}\n","import { Observable } from '../Observable';\nimport { ReplaySubject } from '../ReplaySubject';\nimport { multicast } from './multicast';\nimport { MonoTypeOperatorFunction, OperatorFunction, TimestampProvider, ObservableInput, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * Creates a {@link ConnectableObservable} that uses a {@link ReplaySubject}\n * internally.\n *\n * @param bufferSize The buffer size for the underlying {@link ReplaySubject}.\n * @param windowTime The window time for the underlying {@link ReplaySubject}.\n * @param timestampProvider The timestamp provider for the underlying {@link ReplaySubject}.\n * @deprecated Will be removed in v8. To create a connectable observable that uses a\n * {@link ReplaySubject} under the hood, use {@link connectable}.\n * `source.pipe(publishReplay(size, time, scheduler))` is equivalent to\n * `connectable(source, { connector: () => new ReplaySubject(size, time, scheduler), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishReplay`, use the {@link share} operator instead.\n * `publishReplay(size, time, scheduler), refCount()` is equivalent to\n * `share({ connector: () => new ReplaySubject(size, time, scheduler), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T>(\n bufferSize?: number,\n windowTime?: number,\n timestampProvider?: TimestampProvider\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Creates an observable, that when subscribed to, will create a {@link ReplaySubject},\n * and pass an observable from it (using [asObservable](api/index/class/Subject#asObservable)) to\n * the `selector` function, which then returns an observable that is subscribed to before\n * \"connecting\" the source to the internal `ReplaySubject`.\n *\n * Since this is deprecated, for additional details see the documentation for {@link connect}.\n *\n * @param bufferSize The buffer size for the underlying {@link ReplaySubject}.\n * @param windowTime The window time for the underlying {@link ReplaySubject}.\n * @param selector A function used to setup the multicast.\n * @param timestampProvider The timestamp provider for the underlying {@link ReplaySubject}.\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `source.pipe(publishReplay(size, window, selector, scheduler))` is equivalent to\n * `source.pipe(connect(selector, { connector: () => new ReplaySubject(size, window, scheduler) }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T, O extends ObservableInput<any>>(\n bufferSize: number | undefined,\n windowTime: number | undefined,\n selector: (shared: Observable<T>) => O,\n timestampProvider?: TimestampProvider\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * Creates a {@link ConnectableObservable} that uses a {@link ReplaySubject}\n * internally.\n *\n * @param bufferSize The buffer size for the underlying {@link ReplaySubject}.\n * @param windowTime The window time for the underlying {@link ReplaySubject}.\n * @param selector Passing `undefined` here determines that this operator will return a {@link ConnectableObservable}.\n * @param timestampProvider The timestamp provider for the underlying {@link ReplaySubject}.\n * @deprecated Will be removed in v8. To create a connectable observable that uses a\n * {@link ReplaySubject} under the hood, use {@link connectable}.\n * `source.pipe(publishReplay(size, time, scheduler))` is equivalent to\n * `connectable(source, { connector: () => new ReplaySubject(size, time, scheduler), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishReplay`, use the {@link share} operator instead.\n * `publishReplay(size, time, scheduler), refCount()` is equivalent to\n * `share({ connector: () => new ReplaySubject(size, time, scheduler), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T, O extends ObservableInput<any>>(\n bufferSize: number | undefined,\n windowTime: number | undefined,\n selector: undefined,\n timestampProvider: TimestampProvider\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * @deprecated Will be removed in v8. Use the {@link connectable} observable, the {@link connect} operator or the\n * {@link share} operator instead. See the overloads below for equivalent replacement examples of this operator's\n * behaviors.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T, R>(\n bufferSize?: number,\n windowTime?: number,\n selectorOrScheduler?: TimestampProvider | OperatorFunction<T, R>,\n timestampProvider?: TimestampProvider\n) {\n if (selectorOrScheduler && !isFunction(selectorOrScheduler)) {\n timestampProvider = selectorOrScheduler;\n }\n const selector = isFunction(selectorOrScheduler) ? selectorOrScheduler : undefined;\n // Note, we're passing `selector!` here, because at runtime, `undefined` is an acceptable argument\n // but it makes our TypeScript signature for `multicast` unhappy (as it should, because it's gross).\n return (source: Observable<T>) => multicast(new ReplaySubject<T>(bufferSize, windowTime, timestampProvider), selector!)(source);\n}\n","import { OperatorFunction, ObservableInputTuple } from '../types';\nimport { raceInit } from '../observable/race';\nimport { operate } from '../util/lift';\nimport { identity } from '../util/identity';\n\n/**\n * Creates an Observable that mirrors the first source Observable to emit a next,\n * error or complete notification from the combination of the Observable to which\n * the operator is applied and supplied Observables.\n *\n * ## Example\n *\n * ```ts\n * import { interval, map, raceWith } from 'rxjs';\n *\n * const obs1 = interval(7000).pipe(map(() => 'slow one'));\n * const obs2 = interval(3000).pipe(map(() => 'fast one'));\n * const obs3 = interval(5000).pipe(map(() => 'medium one'));\n *\n * obs1\n * .pipe(raceWith(obs2, obs3))\n * .subscribe(winner => console.log(winner));\n *\n * // Outputs\n * // a series of 'fast one'\n * ```\n *\n * @param otherSources Sources used to race for which Observable emits first.\n * @return A function that returns an Observable that mirrors the output of the\n * first Observable to emit an item.\n */\nexport function raceWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n return !otherSources.length\n ? identity\n : operate((source, subscriber) => {\n raceInit<T | A[number]>([source, ...otherSources])(subscriber);\n });\n}\n","import { Subscription } from '../Subscription';\nimport { EMPTY } from '../observable/empty';\nimport { operate } from '../util/lift';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { timer } from '../observable/timer';\n\nexport interface RepeatConfig {\n /**\n * The number of times to repeat the source. Defaults to `Infinity`.\n */\n count?: number;\n\n /**\n * If a `number`, will delay the repeat of the source by that number of milliseconds.\n * If a function, it will provide the number of times the source has been subscribed to,\n * and the return value should be a valid observable input that will notify when the source\n * should be repeated. If the notifier observable is empty, the result will complete.\n */\n delay?: number | ((count: number) => ObservableInput<any>);\n}\n\n/**\n * Returns an Observable that will resubscribe to the source stream when the source stream completes.\n *\n * <span class=\"informal\">Repeats all values emitted on the source. It's like {@link retry}, but for non error cases.</span>\n *\n * \n *\n * Repeat will output values from a source until the source completes, then it will resubscribe to the\n * source a specified number of times, with a specified delay. Repeat can be particularly useful in\n * combination with closing operators like {@link take}, {@link takeUntil}, {@link first}, or {@link takeWhile},\n * as it can be used to restart a source again from scratch.\n *\n * Repeat is very similar to {@link retry}, where {@link retry} will resubscribe to the source in the error case, but\n * `repeat` will resubscribe if the source completes.\n *\n * Note that `repeat` will _not_ catch errors. Use {@link retry} for that.\n *\n * - `repeat(0)` returns an empty observable\n * - `repeat()` will repeat forever\n * - `repeat({ delay: 200 })` will repeat forever, with a delay of 200ms between repetitions.\n * - `repeat({ count: 2, delay: 400 })` will repeat twice, with a delay of 400ms between repetitions.\n * - `repeat({ delay: (count) => timer(count * 1000) })` will repeat forever, but will have a delay that grows by one second for each repetition.\n *\n * ## Example\n *\n * Repeat a message stream\n *\n * ```ts\n * import { of, repeat } from 'rxjs';\n *\n * const source = of('Repeat message');\n * const result = source.pipe(repeat(3));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Results\n * // 'Repeat message'\n * // 'Repeat message'\n * // 'Repeat message'\n * ```\n *\n * Repeat 3 values, 2 times\n *\n * ```ts\n * import { interval, take, repeat } from 'rxjs';\n *\n * const source = interval(1000);\n * const result = source.pipe(take(3), repeat(2));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Results every second\n * // 0\n * // 1\n * // 2\n * // 0\n * // 1\n * // 2\n * ```\n *\n * Defining two complex repeats with delays on the same source.\n * Note that the second repeat cannot be called until the first\n * repeat as exhausted it's count.\n *\n * ```ts\n * import { defer, of, repeat } from 'rxjs';\n *\n * const source = defer(() => {\n * return of(`Hello, it is ${new Date()}`)\n * });\n *\n * source.pipe(\n * // Repeat 3 times with a delay of 1 second between repetitions\n * repeat({\n * count: 3,\n * delay: 1000,\n * }),\n *\n * // *Then* repeat forever, but with an exponential step-back\n * // maxing out at 1 minute.\n * repeat({\n * delay: (count) => timer(Math.min(60000, 2 ^ count * 1000))\n * })\n * )\n * ```\n *\n * @see {@link repeatWhen}\n * @see {@link retry}\n *\n * @param countOrConfig Either the number of times the source Observable items are repeated\n * (a count of 0 will yield an empty Observable) or a {@link RepeatConfig} object.\n */\nexport function repeat<T>(countOrConfig?: number | RepeatConfig): MonoTypeOperatorFunction<T> {\n let count = Infinity;\n let delay: RepeatConfig['delay'];\n\n if (countOrConfig != null) {\n if (typeof countOrConfig === 'object') {\n ({ count = Infinity, delay } = countOrConfig);\n } else {\n count = countOrConfig;\n }\n }\n\n return count <= 0\n ? () => EMPTY\n : operate((source, subscriber) => {\n let soFar = 0;\n let sourceSub: Subscription | null;\n\n const resubscribe = () => {\n sourceSub?.unsubscribe();\n sourceSub = null;\n if (delay != null) {\n const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(soFar));\n const notifierSubscriber = createOperatorSubscriber(subscriber, () => {\n notifierSubscriber.unsubscribe();\n subscribeToSource();\n });\n notifier.subscribe(notifierSubscriber);\n } else {\n subscribeToSource();\n }\n };\n\n const subscribeToSource = () => {\n let syncUnsub = false;\n sourceSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, () => {\n if (++soFar < count) {\n if (sourceSub) {\n resubscribe();\n } else {\n syncUnsub = true;\n }\n } else {\n subscriber.complete();\n }\n })\n );\n\n if (syncUnsub) {\n resubscribe();\n }\n };\n\n subscribeToSource();\n });\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of a `complete`. If the source\n * Observable calls `complete`, this method will emit to the Observable returned from `notifier`. If that Observable\n * calls `complete` or `error`, then this method will call `complete` or `error` on the child subscription. Otherwise\n * this method will resubscribe to the source Observable.\n *\n * \n *\n * ## Example\n *\n * Repeat a message stream on click\n *\n * ```ts\n * import { of, fromEvent, repeatWhen } from 'rxjs';\n *\n * const source = of('Repeat message');\n * const documentClick$ = fromEvent(document, 'click');\n *\n * const result = source.pipe(repeatWhen(() => documentClick$));\n *\n * result.subscribe(data => console.log(data))\n * ```\n *\n * @see {@link repeat}\n * @see {@link retry}\n * @see {@link retryWhen}\n *\n * @param notifier Function that receives an Observable of notifications with\n * which a user can `complete` or `error`, aborting the repetition.\n * @return A function that returns an Observable that mirrors the source\n * Observable with the exception of a `complete`.\n * @deprecated Will be removed in v9 or v10. Use {@link repeat}'s {@link RepeatConfig#delay delay} option instead.\n * Instead of `repeatWhen(() => notify$)`, use: `repeat({ delay: () => notify$ })`.\n */\nexport function repeatWhen<T>(notifier: (notifications: Observable<void>) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null;\n let syncResub = false;\n let completions$: Subject<void>;\n let isNotifierComplete = false;\n let isMainComplete = false;\n\n /**\n * Checks to see if we can complete the result, completes it, and returns `true` if it was completed.\n */\n const checkComplete = () => isMainComplete && isNotifierComplete && (subscriber.complete(), true);\n /**\n * Gets the subject to send errors through. If it doesn't exist,\n * we know we need to setup the notifier.\n */\n const getCompletionSubject = () => {\n if (!completions$) {\n completions$ = new Subject();\n\n // If the call to `notifier` throws, it will be caught by the OperatorSubscriber\n // In the main subscription -- in `subscribeForRepeatWhen`.\n innerFrom(notifier(completions$)).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n if (innerSub) {\n subscribeForRepeatWhen();\n } else {\n // If we don't have an innerSub yet, that's because the inner subscription\n // call hasn't even returned yet. We've arrived here synchronously.\n // So we flag that we want to resub, such that we can ensure finalization\n // happens before we resubscribe.\n syncResub = true;\n }\n },\n () => {\n isNotifierComplete = true;\n checkComplete();\n }\n )\n );\n }\n return completions$;\n };\n\n const subscribeForRepeatWhen = () => {\n isMainComplete = false;\n\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, () => {\n isMainComplete = true;\n // Check to see if we are complete, and complete if so.\n // If we are not complete. Get the subject. This calls the `notifier` function.\n // If that function fails, it will throw and `.next()` will not be reached on this\n // line. The thrown error is caught by the _complete handler in this\n // `OperatorSubscriber` and handled appropriately.\n !checkComplete() && getCompletionSubject().next();\n })\n );\n\n if (syncResub) {\n // Ensure that the inner subscription is torn down before\n // moving on to the next subscription in the synchronous case.\n // If we don't do this here, all inner subscriptions will not be\n // torn down until the entire observable is done.\n innerSub.unsubscribe();\n // It is important to null this out. Not only to free up memory, but\n // to make sure code above knows we are in a subscribing state to\n // handle synchronous resubscription.\n innerSub = null;\n // We may need to do this multiple times, so reset the flags.\n syncResub = false;\n // Resubscribe\n subscribeForRepeatWhen();\n }\n };\n\n // Start the subscription\n subscribeForRepeatWhen();\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { Subscription } from '../Subscription';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { identity } from '../util/identity';\nimport { timer } from '../observable/timer';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * The {@link retry} operator configuration object. `retry` either accepts a `number`\n * or an object described by this interface.\n */\nexport interface RetryConfig {\n /**\n * The maximum number of times to retry. If `count` is omitted, `retry` will try to\n * resubscribe on errors infinite number of times.\n */\n count?: number;\n /**\n * The number of milliseconds to delay before retrying, OR a function to\n * return a notifier for delaying. If a function is given, that function should\n * return a notifier that, when it emits will retry the source. If the notifier\n * completes _without_ emitting, the resulting observable will complete without error,\n * if the notifier errors, the error will be pushed to the result.\n */\n delay?: number | ((error: any, retryCount: number) => ObservableInput<any>);\n /**\n * Whether or not to reset the retry counter when the retried subscription\n * emits its first value.\n */\n resetOnSuccess?: boolean;\n}\n\nexport function retry<T>(count?: number): MonoTypeOperatorFunction<T>;\nexport function retry<T>(config: RetryConfig): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`.\n *\n * If the source Observable calls `error`, this method will resubscribe to the source Observable for a maximum of\n * `count` resubscriptions rather than propagating the `error` call.\n *\n * \n *\n * The number of retries is determined by the `count` parameter. It can be set either by passing a number to\n * `retry` function or by setting `count` property when `retry` is configured using {@link RetryConfig}. If\n * `count` is omitted, `retry` will try to resubscribe on errors infinite number of times.\n *\n * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those\n * emitted during failed subscriptions. For example, if an Observable fails at first but emits `[1, 2]` then\n * succeeds the second time and emits: `[1, 2, 3, 4, 5, complete]` then the complete stream of emissions and\n * notifications would be: `[1, 2, 1, 2, 3, 4, 5, complete]`.\n *\n * ## Example\n *\n * ```ts\n * import { interval, mergeMap, throwError, of, retry } from 'rxjs';\n *\n * const source = interval(1000);\n * const result = source.pipe(\n * mergeMap(val => val > 5 ? throwError(() => 'Error!') : of(val)),\n * retry(2) // retry 2 times on error\n * );\n *\n * result.subscribe({\n * next: value => console.log(value),\n * error: err => console.log(`${ err }: Retried 2 times then quit!`)\n * });\n *\n * // Output:\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // 'Error!: Retried 2 times then quit!'\n * ```\n *\n * @see {@link retryWhen}\n *\n * @param configOrCount Either number of retry attempts before failing or a\n * {@link RetryConfig} object.\n * @return A function that returns an Observable that will resubscribe to the\n * source stream when the source stream errors, at most `count` times.\n */\nexport function retry<T>(configOrCount: number | RetryConfig = Infinity): MonoTypeOperatorFunction<T> {\n let config: RetryConfig;\n if (configOrCount && typeof configOrCount === 'object') {\n config = configOrCount;\n } else {\n config = {\n count: configOrCount as number,\n };\n }\n const { count = Infinity, delay, resetOnSuccess: resetOnSuccess = false } = config;\n\n return count <= 0\n ? identity\n : operate((source, subscriber) => {\n let soFar = 0;\n let innerSub: Subscription | null;\n const subscribeForRetry = () => {\n let syncUnsub = false;\n innerSub = source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // If we're resetting on success\n if (resetOnSuccess) {\n soFar = 0;\n }\n subscriber.next(value);\n },\n // Completions are passed through to consumer.\n undefined,\n (err) => {\n if (soFar++ < count) {\n // We are still under our retry count\n const resub = () => {\n if (innerSub) {\n innerSub.unsubscribe();\n innerSub = null;\n subscribeForRetry();\n } else {\n syncUnsub = true;\n }\n };\n\n if (delay != null) {\n // The user specified a retry delay.\n // They gave us a number, use a timer, otherwise, it's a function,\n // and we're going to call it to get a notifier.\n const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));\n const notifierSubscriber = createOperatorSubscriber(\n subscriber,\n () => {\n // After we get the first notification, we\n // unsubscribe from the notifier, because we don't want anymore\n // and we resubscribe to the source.\n notifierSubscriber.unsubscribe();\n resub();\n },\n () => {\n // The notifier completed without emitting.\n // The author is telling us they want to complete.\n subscriber.complete();\n }\n );\n notifier.subscribe(notifierSubscriber);\n } else {\n // There was no notifier given. Just resub immediately.\n resub();\n }\n } else {\n // We're past our maximum number of retries.\n // Just send along the error.\n subscriber.error(err);\n }\n }\n )\n );\n if (syncUnsub) {\n innerSub.unsubscribe();\n innerSub = null;\n subscribeForRetry();\n }\n };\n subscribeForRetry();\n });\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable\n * calls `error`, this method will emit the Throwable that caused the error to the `ObservableInput` returned from `notifier`.\n * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child\n * subscription. Otherwise this method will resubscribe to the source Observable.\n *\n * \n *\n * Retry an observable sequence on error based on custom criteria.\n *\n * ## Example\n *\n * ```ts\n * import { interval, map, retryWhen, tap, delayWhen, timer } from 'rxjs';\n *\n * const source = interval(1000);\n * const result = source.pipe(\n * map(value => {\n * if (value > 5) {\n * // error will be picked up by retryWhen\n * throw value;\n * }\n * return value;\n * }),\n * retryWhen(errors =>\n * errors.pipe(\n * // log error message\n * tap(value => console.log(`Value ${ value } was too high!`)),\n * // restart in 5 seconds\n * delayWhen(value => timer(value * 1000))\n * )\n * )\n * );\n *\n * result.subscribe(value => console.log(value));\n *\n * // results:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * // 'Value 6 was too high!'\n * // - Wait 5 seconds then repeat\n * ```\n *\n * @see {@link retry}\n *\n * @param notifier Function that receives an Observable of notifications with which a\n * user can `complete` or `error`, aborting the retry.\n * @return A function that returns an Observable that mirrors the source\n * Observable with the exception of an `error`.\n * @deprecated Will be removed in v9 or v10, use {@link retry}'s `delay` option instead.\n * Will be removed in v9 or v10. Use {@link retry}'s {@link RetryConfig#delay delay} option instead.\n * Instead of `retryWhen(() => notify$)`, use: `retry({ delay: () => notify$ })`.\n */\nexport function retryWhen<T>(notifier: (errors: Observable<any>) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null;\n let syncResub = false;\n let errors$: Subject<any>;\n\n const subscribeForRetryWhen = () => {\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, undefined, (err) => {\n if (!errors$) {\n errors$ = new Subject();\n innerFrom(notifier(errors$)).subscribe(\n createOperatorSubscriber(subscriber, () =>\n // If we have an innerSub, this was an asynchronous call, kick off the retry.\n // Otherwise, if we don't have an innerSub yet, that's because the inner subscription\n // call hasn't even returned yet. We've arrived here synchronously.\n // So we flag that we want to resub, such that we can ensure finalization\n // happens before we resubscribe.\n innerSub ? subscribeForRetryWhen() : (syncResub = true)\n )\n );\n }\n if (errors$) {\n // We have set up the notifier without error.\n errors$.next(err);\n }\n })\n );\n\n if (syncResub) {\n // Ensure that the inner subscription is torn down before\n // moving on to the next subscription in the synchronous case.\n // If we don't do this here, all inner subscriptions will not be\n // torn down until the entire observable is done.\n innerSub.unsubscribe();\n innerSub = null;\n // We may need to do this multiple times, so reset the flag.\n syncResub = false;\n // Resubscribe\n subscribeForRetryWhen();\n }\n };\n\n // Start the subscription\n subscribeForRetryWhen();\n });\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits the most recently emitted value from the source Observable whenever\n * another Observable, the `notifier`, emits.\n *\n * <span class=\"informal\">It's like {@link sampleTime}, but samples whenever\n * the `notifier` `ObservableInput` emits something.</span>\n *\n * \n *\n * Whenever the `notifier` `ObservableInput` emits a value, `sample`\n * looks at the source Observable and emits whichever value it has most recently\n * emitted since the previous sampling, unless the source has not emitted\n * anything since the previous sampling. The `notifier` is subscribed to as soon\n * as the output Observable is subscribed.\n *\n * ## Example\n *\n * On every click, sample the most recent `seconds` timer\n *\n * ```ts\n * import { fromEvent, interval, sample } from 'rxjs';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = seconds.pipe(sample(clicks));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param notifier The `ObservableInput` to use for sampling the\n * source Observable.\n * @return A function that returns an Observable that emits the results of\n * sampling the values emitted by the source Observable whenever the notifier\n * Observable emits value or completes.\n */\nexport function sample<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let lastValue: T | null = null;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n hasValue = true;\n lastValue = value;\n })\n );\n innerFrom(notifier).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n if (hasValue) {\n hasValue = false;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n },\n noop\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { sample } from './sample';\nimport { interval } from '../observable/interval';\n\n/**\n * Emits the most recently emitted value from the source Observable within\n * periodic time intervals.\n *\n * <span class=\"informal\">Samples the source Observable at periodic time\n * intervals, emitting what it samples.</span>\n *\n * \n *\n * `sampleTime` periodically looks at the source Observable and emits whichever\n * value it has most recently emitted since the previous sampling, unless the\n * source has not emitted anything since the previous sampling. The sampling\n * happens periodically in time every `period` milliseconds (or the time unit\n * defined by the optional `scheduler` argument). The sampling starts as soon as\n * the output Observable is subscribed.\n *\n * ## Example\n *\n * Every second, emit the most recent click at most once\n *\n * ```ts\n * import { fromEvent, sampleTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(sampleTime(1000));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param period The sampling period expressed in milliseconds or the time unit\n * determined internally by the optional `scheduler`.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers\n * that handle the sampling.\n * @return A function that returns an Observable that emits the results of\n * sampling the values emitted by the source Observable at the specified time\n * interval.\n */\nexport function sampleTime<T>(period: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n return sample(interval(period, scheduler));\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { scanInternals } from './scanInternals';\n\nexport function scan<V, A = V>(accumulator: (acc: A | V, value: V, index: number) => A): OperatorFunction<V, V | A>;\nexport function scan<V, A>(accumulator: (acc: A, value: V, index: number) => A, seed: A): OperatorFunction<V, A>;\nexport function scan<V, A, S>(accumulator: (acc: A | S, value: V, index: number) => A, seed: S): OperatorFunction<V, A>;\n\n// TODO: link to a \"redux pattern\" section in the guide (location TBD)\n\n/**\n * Useful for encapsulating and managing state. Applies an accumulator (or \"reducer function\")\n * to each value from the source after an initial state is established -- either via\n * a `seed` value (second argument), or from the first value from the source.\n *\n * <span class=\"informal\">It's like {@link reduce}, but emits the current\n * accumulation state after each update</span>\n *\n * \n *\n * This operator maintains an internal state and emits it after processing each value as follows:\n *\n * 1. First value arrives\n * - If a `seed` value was supplied (as the second argument to `scan`), let `state = seed` and `value = firstValue`.\n * - If NO `seed` value was supplied (no second argument), let `state = firstValue` and go to 3.\n * 2. Let `state = accumulator(state, value)`.\n * - If an error is thrown by `accumulator`, notify the consumer of an error. The process ends.\n * 3. Emit `state`.\n * 4. Next value arrives, let `value = nextValue`, go to 2.\n *\n * ## Examples\n *\n * An average of previous numbers. This example shows how\n * not providing a `seed` can prime the stream with the\n * first value from the source.\n *\n * ```ts\n * import { of, scan, map } from 'rxjs';\n *\n * const numbers$ = of(1, 2, 3);\n *\n * numbers$\n * .pipe(\n * // Get the sum of the numbers coming in.\n * scan((total, n) => total + n),\n * // Get the average by dividing the sum by the total number\n * // received so far (which is 1 more than the zero-based index).\n * map((sum, index) => sum / (index + 1))\n * )\n * .subscribe(console.log);\n * ```\n *\n * The Fibonacci sequence. This example shows how you can use\n * a seed to prime accumulation process. Also... you know... Fibonacci.\n * So important to like, computers and stuff that its whiteboarded\n * in job interviews. Now you can show them the Rx version! (Please don't, haha)\n *\n * ```ts\n * import { interval, scan, map, startWith } from 'rxjs';\n *\n * const firstTwoFibs = [0, 1];\n * // An endless stream of Fibonacci numbers.\n * const fibonacci$ = interval(1000).pipe(\n * // Scan to get the fibonacci numbers (after 0, 1)\n * scan(([a, b]) => [b, a + b], firstTwoFibs),\n * // Get the second number in the tuple, it's the one you calculated\n * map(([, n]) => n),\n * // Start with our first two digits :)\n * startWith(...firstTwoFibs)\n * );\n *\n * fibonacci$.subscribe(console.log);\n * ```\n *\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link reduce}\n * @see {@link switchScan}\n *\n * @param accumulator A \"reducer function\". This will be called for each value after an initial state is\n * acquired.\n * @param seed The initial state. If this is not provided, the first value from the source will\n * be used as the initial state, and emitted without going through the accumulator. All subsequent values\n * will be processed by the accumulator function. If this is provided, all values will go through\n * the accumulator function.\n * @return A function that returns an Observable of the accumulated values.\n */\nexport function scan<V, A, S>(accumulator: (acc: V | A | S, value: V, index: number) => A, seed?: S): OperatorFunction<V, V | A> {\n // providing a seed of `undefined` *should* be valid and trigger\n // hasSeed! so don't use `seed !== undefined` checks!\n // For this reason, we have to check it here at the original call site\n // otherwise inside Operator/Subscriber we won't know if `undefined`\n // means they didn't provide anything or if they literally provided `undefined`\n return operate(scanInternals(accumulator, seed as S, arguments.length >= 2, true));\n}\n","import { OperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Compares all values of two observables in sequence using an optional comparator function\n * and returns an observable of a single boolean value representing whether or not the two sequences\n * are equal.\n *\n * <span class=\"informal\">Checks to see of all values emitted by both observables are equal, in order.</span>\n *\n * \n *\n * `sequenceEqual` subscribes to source observable and `compareTo` `ObservableInput` (that internally\n * gets converted to an observable) and buffers incoming values from each observable. Whenever either\n * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom\n * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the\n * observables completes, the operator will wait for the other observable to complete; If the other\n * observable emits before completing, the returned observable will emit `false` and complete. If one observable never\n * completes or emits after the other completes, the returned observable will never complete.\n *\n * ## Example\n *\n * Figure out if the Konami code matches\n *\n * ```ts\n * import { from, fromEvent, map, bufferCount, mergeMap, sequenceEqual } from 'rxjs';\n *\n * const codes = from([\n * 'ArrowUp',\n * 'ArrowUp',\n * 'ArrowDown',\n * 'ArrowDown',\n * 'ArrowLeft',\n * 'ArrowRight',\n * 'ArrowLeft',\n * 'ArrowRight',\n * 'KeyB',\n * 'KeyA',\n * 'Enter', // no start key, clearly.\n * ]);\n *\n * const keys = fromEvent<KeyboardEvent>(document, 'keyup').pipe(map(e => e.code));\n * const matches = keys.pipe(\n * bufferCount(11, 1),\n * mergeMap(last11 => from(last11).pipe(sequenceEqual(codes)))\n * );\n * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n * @see {@link withLatestFrom}\n *\n * @param compareTo The `ObservableInput` sequence to compare the source sequence to.\n * @param comparator An optional function to compare each value pair.\n *\n * @return A function that returns an Observable that emits a single boolean\n * value representing whether or not the values emitted by the source\n * Observable and provided `ObservableInput` were equal in sequence.\n */\nexport function sequenceEqual<T>(\n compareTo: ObservableInput<T>,\n comparator: (a: T, b: T) => boolean = (a, b) => a === b\n): OperatorFunction<T, boolean> {\n return operate((source, subscriber) => {\n // The state for the source observable\n const aState = createState<T>();\n // The state for the compareTo observable;\n const bState = createState<T>();\n\n /** A utility to emit and complete */\n const emit = (isEqual: boolean) => {\n subscriber.next(isEqual);\n subscriber.complete();\n };\n\n /**\n * Creates a subscriber that subscribes to one of the sources, and compares its collected\n * state -- `selfState` -- to the other source's collected state -- `otherState`. This\n * is used for both streams.\n */\n const createSubscriber = (selfState: SequenceState<T>, otherState: SequenceState<T>) => {\n const sequenceEqualSubscriber = createOperatorSubscriber(\n subscriber,\n (a: T) => {\n const { buffer, complete } = otherState;\n if (buffer.length === 0) {\n // If there's no values in the other buffer\n // and the other stream is complete, we know\n // this isn't a match, because we got one more value.\n // Otherwise, we push onto our buffer, so when the other\n // stream emits, it can pull this value off our buffer and check it\n // at the appropriate time.\n complete ? emit(false) : selfState.buffer.push(a);\n } else {\n // If the other stream *does* have values in its buffer,\n // pull the oldest one off so we can compare it to what we\n // just got. If it wasn't a match, emit `false` and complete.\n !comparator(a, buffer.shift()!) && emit(false);\n }\n },\n () => {\n // Or observable completed\n selfState.complete = true;\n const { complete, buffer } = otherState;\n // If the other observable is also complete, and there's\n // still stuff left in their buffer, it doesn't match, if their\n // buffer is empty, then it does match. This is because we can't\n // possibly get more values here anymore.\n complete && emit(buffer.length === 0);\n // Be sure to clean up our stream as soon as possible if we can.\n sequenceEqualSubscriber?.unsubscribe();\n }\n );\n\n return sequenceEqualSubscriber;\n };\n\n // Subscribe to each source.\n source.subscribe(createSubscriber(aState, bState));\n innerFrom(compareTo).subscribe(createSubscriber(bState, aState));\n });\n}\n\n/**\n * A simple structure for the data used to test each sequence\n */\ninterface SequenceState<T> {\n /** A temporary store for arrived values before they are checked */\n buffer: T[];\n /** Whether or not the sequence source has completed. */\n complete: boolean;\n}\n\n/**\n * Creates a simple structure that is used to represent\n * data used to test each sequence.\n */\nfunction createState<T>(): SequenceState<T> {\n return {\n buffer: [],\n complete: false,\n };\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { SafeSubscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SubjectLike, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\n\nexport interface ShareConfig<T> {\n /**\n * The factory used to create the subject that will connect the source observable to\n * multicast consumers.\n */\n connector?: () => SubjectLike<T>;\n /**\n * If `true`, the resulting observable will reset internal state on error from source and return to a \"cold\" state. This\n * allows the resulting observable to be \"retried\" in the event of an error.\n * If `false`, when an error comes from the source it will push the error into the connecting subject, and the subject\n * will remain the connecting subject, meaning the resulting observable will not go \"cold\" again, and subsequent retries\n * or resubscriptions will resubscribe to that same subject. In all cases, RxJS subjects will emit the same error again, however\n * {@link ReplaySubject} will also push its buffered values before pushing the error.\n * It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained\n * control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.\n */\n resetOnError?: boolean | ((error: any) => ObservableInput<any>);\n /**\n * If `true`, the resulting observable will reset internal state on completion from source and return to a \"cold\" state. This\n * allows the resulting observable to be \"repeated\" after it is done.\n * If `false`, when the source completes, it will push the completion through the connecting subject, and the subject\n * will remain the connecting subject, meaning the resulting observable will not go \"cold\" again, and subsequent repeats\n * or resubscriptions will resubscribe to that same subject.\n * It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained\n * control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.\n */\n resetOnComplete?: boolean | (() => ObservableInput<any>);\n /**\n * If `true`, when the number of subscribers to the resulting observable reaches zero due to those subscribers unsubscribing, the\n * internal state will be reset and the resulting observable will return to a \"cold\" state. This means that the next\n * time the resulting observable is subscribed to, a new subject will be created and the source will be subscribed to\n * again.\n * If `false`, when the number of subscribers to the resulting observable reaches zero due to unsubscription, the subject\n * will remain connected to the source, and new subscriptions to the result will be connected through that same subject.\n * It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained\n * control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.\n */\n resetOnRefCountZero?: boolean | (() => ObservableInput<any>);\n}\n\nexport function share<T>(): MonoTypeOperatorFunction<T>;\n\nexport function share<T>(options: ShareConfig<T>): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one\n * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will\n * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.\n * This is an alias for `multicast(() => new Subject()), refCount()`.\n *\n * The subscription to the underlying source Observable can be reset (unsubscribe and resubscribe for new subscribers),\n * if the subscriber count to the shared observable drops to 0, or if the source Observable errors or completes. It is\n * possible to use notifier factories for the resets to allow for behaviors like conditional or delayed resets. Please\n * note that resetting on error or complete of the source Observable does not behave like a transparent retry or restart\n * of the source because the error or complete will be forwarded to all subscribers and their subscription will be\n * closed. Only new subscribers after a reset on error or complete happened will cause a fresh subscription to the\n * source. To achieve transparent retries or restarts pipe the source through appropriate operators before sharing.\n *\n * \n *\n * ## Example\n *\n * Generate new multicast Observable from the `source` Observable value\n *\n * ```ts\n * import { interval, tap, map, take, share } from 'rxjs';\n *\n * const source = interval(1000).pipe(\n * tap(x => console.log('Processing: ', x)),\n * map(x => x * x),\n * take(6),\n * share()\n * );\n *\n * source.subscribe(x => console.log('subscription 1: ', x));\n * source.subscribe(x => console.log('subscription 2: ', x));\n *\n * // Logs:\n * // Processing: 0\n * // subscription 1: 0\n * // subscription 2: 0\n * // Processing: 1\n * // subscription 1: 1\n * // subscription 2: 1\n * // Processing: 2\n * // subscription 1: 4\n * // subscription 2: 4\n * // Processing: 3\n * // subscription 1: 9\n * // subscription 2: 9\n * // Processing: 4\n * // subscription 1: 16\n * // subscription 2: 16\n * // Processing: 5\n * // subscription 1: 25\n * // subscription 2: 25\n * ```\n *\n * ## Example with notifier factory: Delayed reset\n *\n * ```ts\n * import { interval, take, share, timer } from 'rxjs';\n *\n * const source = interval(1000).pipe(\n * take(3),\n * share({\n * resetOnRefCountZero: () => timer(1000)\n * })\n * );\n *\n * const subscriptionOne = source.subscribe(x => console.log('subscription 1: ', x));\n * setTimeout(() => subscriptionOne.unsubscribe(), 1300);\n *\n * setTimeout(() => source.subscribe(x => console.log('subscription 2: ', x)), 1700);\n *\n * setTimeout(() => source.subscribe(x => console.log('subscription 3: ', x)), 5000);\n *\n * // Logs:\n * // subscription 1: 0\n * // (subscription 1 unsubscribes here)\n * // (subscription 2 subscribes here ~400ms later, source was not reset)\n * // subscription 2: 1\n * // subscription 2: 2\n * // (subscription 2 unsubscribes here)\n * // (subscription 3 subscribes here ~2000ms later, source did reset before)\n * // subscription 3: 0\n * // subscription 3: 1\n * // subscription 3: 2\n * ```\n *\n * @see {@link shareReplay}\n *\n * @return A function that returns an Observable that mirrors the source.\n */\nexport function share<T>(options: ShareConfig<T> = {}): MonoTypeOperatorFunction<T> {\n const { connector = () => new Subject<T>(), resetOnError = true, resetOnComplete = true, resetOnRefCountZero = true } = options;\n // It's necessary to use a wrapper here, as the _operator_ must be\n // referentially transparent. Otherwise, it cannot be used in calls to the\n // static `pipe` function - to create a partial pipeline.\n //\n // The _operator function_ - the function returned by the _operator_ - will\n // not be referentially transparent - as it shares its source - but the\n // _operator function_ is called when the complete pipeline is composed via a\n // call to a source observable's `pipe` method - not when the static `pipe`\n // function is called.\n return (wrapperSource) => {\n let connection: SafeSubscriber<T> | undefined;\n let resetConnection: Subscription | undefined;\n let subject: SubjectLike<T> | undefined;\n let refCount = 0;\n let hasCompleted = false;\n let hasErrored = false;\n\n const cancelReset = () => {\n resetConnection?.unsubscribe();\n resetConnection = undefined;\n };\n // Used to reset the internal state to a \"cold\"\n // state, as though it had never been subscribed to.\n const reset = () => {\n cancelReset();\n connection = subject = undefined;\n hasCompleted = hasErrored = false;\n };\n const resetAndUnsubscribe = () => {\n // We need to capture the connection before\n // we reset (if we need to reset).\n const conn = connection;\n reset();\n conn?.unsubscribe();\n };\n\n return operate<T, T>((source, subscriber) => {\n refCount++;\n if (!hasErrored && !hasCompleted) {\n cancelReset();\n }\n\n // Create the subject if we don't have one yet. Grab a local reference to\n // it as well, which avoids non-null assertions when using it and, if we\n // connect to it now, then error/complete need a reference after it was\n // reset.\n const dest = (subject = subject ?? connector());\n\n // Add the finalization directly to the subscriber - instead of returning it -\n // so that the handling of the subscriber's unsubscription will be wired\n // up _before_ the subscription to the source occurs. This is done so that\n // the assignment to the source connection's `closed` property will be seen\n // by synchronous firehose sources.\n subscriber.add(() => {\n refCount--;\n\n // If we're resetting on refCount === 0, and it's 0, we only want to do\n // that on \"unsubscribe\", really. Resetting on error or completion is a different\n // configuration.\n if (refCount === 0 && !hasErrored && !hasCompleted) {\n resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);\n }\n });\n\n // The following line adds the subscription to the subscriber passed.\n // Basically, `subscriber === dest.subscribe(subscriber)` is `true`.\n dest.subscribe(subscriber);\n\n if (\n !connection &&\n // Check this shareReplay is still activate - it can be reset to 0\n // and be \"unsubscribed\" _before_ it actually subscribes.\n // If we were to subscribe then, it'd leak and get stuck.\n refCount > 0\n ) {\n // We need to create a subscriber here - rather than pass an observer and\n // assign the returned subscription to connection - because it's possible\n // for reentrant subscriptions to the shared observable to occur and in\n // those situations we want connection to be already-assigned so that we\n // don't create another connection to the source.\n connection = new SafeSubscriber({\n next: (value) => dest.next(value),\n error: (err) => {\n hasErrored = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnError, err);\n dest.error(err);\n },\n complete: () => {\n hasCompleted = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnComplete);\n dest.complete();\n },\n });\n innerFrom(source).subscribe(connection);\n }\n })(wrapperSource);\n };\n}\n\nfunction handleReset<T extends unknown[] = never[]>(\n reset: () => void,\n on: boolean | ((...args: T) => ObservableInput<any>),\n ...args: T\n): Subscription | undefined {\n if (on === true) {\n reset();\n return;\n }\n\n if (on === false) {\n return;\n }\n\n const onSubscriber = new SafeSubscriber({\n next: () => {\n onSubscriber.unsubscribe();\n reset();\n },\n });\n\n return innerFrom(on(...args)).subscribe(onSubscriber);\n}\n","import { ReplaySubject } from '../ReplaySubject';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { share } from './share';\n\nexport interface ShareReplayConfig {\n bufferSize?: number;\n windowTime?: number;\n refCount: boolean;\n scheduler?: SchedulerLike;\n}\n\nexport function shareReplay<T>(config: ShareReplayConfig): MonoTypeOperatorFunction<T>;\nexport function shareReplay<T>(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n\n/**\n * Share source and replay specified number of emissions on subscription.\n *\n * This operator is a specialization of `replay` that connects to a source observable\n * and multicasts through a `ReplaySubject` constructed with the specified arguments.\n * A successfully completed source will stay cached in the `shareReplay`ed observable forever,\n * but an errored source can be retried.\n *\n * ## Why use `shareReplay`?\n *\n * You generally want to use `shareReplay` when you have side-effects or taxing computations\n * that you do not wish to be executed amongst multiple subscribers.\n * It may also be valuable in situations where you know you will have late subscribers to\n * a stream that need access to previously emitted values.\n * This ability to replay values on subscription is what differentiates {@link share} and `shareReplay`.\n *\n * ## Reference counting\n *\n * By default `shareReplay` will use `refCount` of false, meaning that it will _not_ unsubscribe the\n * source when the reference counter drops to zero, i.e. the inner `ReplaySubject` will _not_ be unsubscribed\n * (and potentially run for ever).\n * This is the default as it is expected that `shareReplay` is often used to keep around expensive to setup\n * observables which we want to keep running instead of having to do the expensive setup again.\n *\n * As of RXJS version 6.4.0 a new overload signature was added to allow for manual control over what\n * happens when the operators internal reference counter drops to zero.\n * If `refCount` is true, the source will be unsubscribed from once the reference count drops to zero, i.e.\n * the inner `ReplaySubject` will be unsubscribed. All new subscribers will receive value emissions from a\n * new `ReplaySubject` which in turn will cause a new subscription to the source observable.\n *\n * ## Examples\n *\n * Example with a third subscriber coming late to the party\n *\n * ```ts\n * import { interval, take, shareReplay } from 'rxjs';\n *\n * const shared$ = interval(2000).pipe(\n * take(6),\n * shareReplay(3)\n * );\n *\n * shared$.subscribe(x => console.log('sub A: ', x));\n * shared$.subscribe(y => console.log('sub B: ', y));\n *\n * setTimeout(() => {\n * shared$.subscribe(y => console.log('sub C: ', y));\n * }, 11000);\n *\n * // Logs:\n * // (after ~2000 ms)\n * // sub A: 0\n * // sub B: 0\n * // (after ~4000 ms)\n * // sub A: 1\n * // sub B: 1\n * // (after ~6000 ms)\n * // sub A: 2\n * // sub B: 2\n * // (after ~8000 ms)\n * // sub A: 3\n * // sub B: 3\n * // (after ~10000 ms)\n * // sub A: 4\n * // sub B: 4\n * // (after ~11000 ms, sub C gets the last 3 values)\n * // sub C: 2\n * // sub C: 3\n * // sub C: 4\n * // (after ~12000 ms)\n * // sub A: 5\n * // sub B: 5\n * // sub C: 5\n * ```\n *\n * Example for `refCount` usage\n *\n * ```ts\n * import { Observable, tap, interval, shareReplay, take } from 'rxjs';\n *\n * const log = <T>(name: string, source: Observable<T>) => source.pipe(\n * tap({\n * subscribe: () => console.log(`${ name }: subscribed`),\n * next: value => console.log(`${ name }: ${ value }`),\n * complete: () => console.log(`${ name }: completed`),\n * finalize: () => console.log(`${ name }: unsubscribed`)\n * })\n * );\n *\n * const obs$ = log('source', interval(1000));\n *\n * const shared$ = log('shared', obs$.pipe(\n * shareReplay({ bufferSize: 1, refCount: true }),\n * take(2)\n * ));\n *\n * shared$.subscribe(x => console.log('sub A: ', x));\n * shared$.subscribe(y => console.log('sub B: ', y));\n *\n * // PRINTS:\n * // shared: subscribed <-- reference count = 1\n * // source: subscribed\n * // shared: subscribed <-- reference count = 2\n * // source: 0\n * // shared: 0\n * // sub A: 0\n * // shared: 0\n * // sub B: 0\n * // source: 1\n * // shared: 1\n * // sub A: 1\n * // shared: completed <-- take(2) completes the subscription for sub A\n * // shared: unsubscribed <-- reference count = 1\n * // shared: 1\n * // sub B: 1\n * // shared: completed <-- take(2) completes the subscription for sub B\n * // shared: unsubscribed <-- reference count = 0\n * // source: unsubscribed <-- replaySubject unsubscribes from source observable because the reference count dropped to 0 and refCount is true\n *\n * // In case of refCount being false, the unsubscribe is never called on the source and the source would keep on emitting, even if no subscribers\n * // are listening.\n * // source: 2\n * // source: 3\n * // source: 4\n * // ...\n * ```\n *\n * @see {@link publish}\n * @see {@link share}\n * @see {@link publishReplay}\n *\n * @param configOrBufferSize Maximum element count of the replay buffer or {@link ShareReplayConfig configuration}\n * object.\n * @param windowTime Maximum time length of the replay buffer in milliseconds.\n * @param scheduler Scheduler where connected observers within the selector function\n * will be invoked on.\n * @return A function that returns an Observable sequence that contains the\n * elements of a sequence produced by multicasting the source sequence within a\n * selector function.\n */\nexport function shareReplay<T>(\n configOrBufferSize?: ShareReplayConfig | number,\n windowTime?: number,\n scheduler?: SchedulerLike\n): MonoTypeOperatorFunction<T> {\n let bufferSize: number;\n let refCount = false;\n if (configOrBufferSize && typeof configOrBufferSize === 'object') {\n ({ bufferSize = Infinity, windowTime = Infinity, refCount = false, scheduler } = configOrBufferSize);\n } else {\n bufferSize = (configOrBufferSize ?? Infinity) as number;\n }\n return share<T>({\n connector: () => new ReplaySubject(bufferSize, windowTime, scheduler),\n resetOnError: true,\n resetOnComplete: false,\n resetOnRefCountZero: refCount,\n });\n}\n","import { Observable } from '../Observable';\nimport { EmptyError } from '../util/EmptyError';\n\nimport { MonoTypeOperatorFunction, OperatorFunction, TruthyTypesOf } from '../types';\nimport { SequenceError } from '../util/SequenceError';\nimport { NotFoundError } from '../util/NotFoundError';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function single<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function single<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an observable that asserts that only one value is\n * emitted from the observable that matches the predicate. If no\n * predicate is provided, then it will assert that the observable\n * only emits one value.\n *\n * If the source Observable did not emit `next` before completion, it\n * will emit an {@link EmptyError} to the Observer's `error` callback.\n *\n * In the event that two values are found that match the predicate,\n * or when there are two values emitted and no predicate, it will\n * emit a {@link SequenceError} to the Observer's `error` callback.\n *\n * In the event that no values match the predicate, if one is provided,\n * it will emit a {@link NotFoundError} to the Observer's `error` callback.\n *\n * ## Example\n *\n * Expect only `name` beginning with `'B'`\n *\n * ```ts\n * import { of, single } from 'rxjs';\n *\n * const source1 = of(\n * { name: 'Ben' },\n * { name: 'Tracy' },\n * { name: 'Laney' },\n * { name: 'Lily' }\n * );\n *\n * source1\n * .pipe(single(x => x.name.startsWith('B')))\n * .subscribe(x => console.log(x));\n * // Emits 'Ben'\n *\n *\n * const source2 = of(\n * { name: 'Ben' },\n * { name: 'Tracy' },\n * { name: 'Bradley' },\n * { name: 'Lincoln' }\n * );\n *\n * source2\n * .pipe(single(x => x.name.startsWith('B')))\n * .subscribe({ error: err => console.error(err) });\n * // Error emitted: SequenceError('Too many values match')\n *\n *\n * const source3 = of(\n * { name: 'Laney' },\n * { name: 'Tracy' },\n * { name: 'Lily' },\n * { name: 'Lincoln' }\n * );\n *\n * source3\n * .pipe(single(x => x.name.startsWith('B')))\n * .subscribe({ error: err => console.error(err) });\n * // Error emitted: NotFoundError('No values match')\n * ```\n *\n * @see {@link first}\n * @see {@link find}\n * @see {@link findIndex}\n * @see {@link elementAt}\n *\n * @throws {NotFoundError} Delivers a `NotFoundError` to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * @throws {SequenceError} Delivers a `SequenceError` if more than one value is\n * emitted that matches the provided predicate. If no predicate is provided, it\n * will deliver a `SequenceError` if more than one value comes from the source.\n * @throws {EmptyError} Delivers an `EmptyError` if no values were `next`ed prior\n * to completion.\n *\n * @param predicate A predicate function to evaluate items emitted by the source\n * Observable.\n * @return A function that returns an Observable that emits the single item\n * emitted by the source Observable that matches the predicate.\n */\nexport function single<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let singleValue: T;\n let seenValue = false;\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n seenValue = true;\n if (!predicate || predicate(value, index++, source)) {\n hasValue && subscriber.error(new SequenceError('Too many matching values'));\n hasValue = true;\n singleValue = value;\n }\n },\n () => {\n if (hasValue) {\n subscriber.next(singleValue);\n subscriber.complete();\n } else {\n subscriber.error(seenValue ? new NotFoundError('No matching values') : new EmptyError());\n }\n }\n )\n );\n });\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { filter } from './filter';\n\n/**\n * Returns an Observable that skips the first `count` items emitted by the source Observable.\n *\n * \n *\n * Skips the values until the sent notifications are equal or less than provided skip count. It raises\n * an error if skip count is equal or more than the actual number of emits and source raises an error.\n *\n * ## Example\n *\n * Skip the values before the emission\n *\n * ```ts\n * import { interval, skip } from 'rxjs';\n *\n * // emit every half second\n * const source = interval(500);\n * // skip the first 10 emitted values\n * const result = source.pipe(skip(10));\n *\n * result.subscribe(value => console.log(value));\n * // output: 10...11...12...13...\n * ```\n *\n * @see {@link last}\n * @see {@link skipWhile}\n * @see {@link skipUntil}\n * @see {@link skipLast}\n *\n * @param count The number of times, items emitted by source Observable should be skipped.\n * @return A function that returns an Observable that skips the first `count`\n * values emitted by the source Observable.\n */\nexport function skip<T>(count: number): MonoTypeOperatorFunction<T> {\n return filter((_, index) => count <= index);\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { identity } from '../util/identity';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Skip a specified number of values before the completion of an observable.\n *\n * \n *\n * Returns an observable that will emit values as soon as it can, given a number of\n * skipped values. For example, if you `skipLast(3)` on a source, when the source\n * emits its fourth value, the first value the source emitted will finally be emitted\n * from the returned observable, as it is no longer part of what needs to be skipped.\n *\n * All values emitted by the result of `skipLast(N)` will be delayed by `N` emissions,\n * as each value is held in a buffer until enough values have been emitted that that\n * the buffered value may finally be sent to the consumer.\n *\n * After subscribing, unsubscribing will not result in the emission of the buffered\n * skipped values.\n *\n * ## Example\n *\n * Skip the last 2 values of an observable with many values\n *\n * ```ts\n * import { of, skipLast } from 'rxjs';\n *\n * const numbers = of(1, 2, 3, 4, 5);\n * const skipLastTwo = numbers.pipe(skipLast(2));\n * skipLastTwo.subscribe(x => console.log(x));\n *\n * // Results in:\n * // 1 2 3\n * // (4 and 5 are skipped)\n * ```\n *\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipWhile}\n * @see {@link take}\n *\n * @param skipCount Number of elements to skip from the end of the source Observable.\n * @return A function that returns an Observable that skips the last `count`\n * values emitted by the source Observable.\n */\nexport function skipLast<T>(skipCount: number): MonoTypeOperatorFunction<T> {\n return skipCount <= 0\n ? // For skipCounts less than or equal to zero, we are just mirroring the source.\n identity\n : operate((source, subscriber) => {\n // A ring buffer to hold the values while we wait to see\n // if we can emit it or it's part of the \"skipped\" last values.\n // Note that it is the _same size_ as the skip count.\n let ring: T[] = new Array(skipCount);\n // The number of values seen so far. This is used to get\n // the index of the current value when it arrives.\n let seen = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n // Get the index of the value we have right now\n // relative to all other values we've seen, then\n // increment `seen`. This ensures we've moved to\n // the next slot in our ring buffer.\n const valueIndex = seen++;\n if (valueIndex < skipCount) {\n // If we haven't seen enough values to fill our buffer yet,\n // Then we aren't to a number of seen values where we can\n // emit anything, so let's just start by filling the ring buffer.\n ring[valueIndex] = value;\n } else {\n // We are traversing over the ring array in such\n // a way that when we get to the end, we loop back\n // and go to the start.\n const index = valueIndex % skipCount;\n // Pull the oldest value out so we can emit it,\n // and stuff the new value in it's place.\n const oldValue = ring[index];\n ring[index] = value;\n // Emit the old value. It is important that this happens\n // after we swap the value in the buffer, if it happens\n // before we swap the value in the buffer, then a synchronous\n // source can get the buffer out of whack.\n subscriber.next(oldValue);\n }\n })\n );\n\n return () => {\n // Release our values in memory\n ring = null!;\n };\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { noop } from '../util/noop';\n\n/**\n * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.\n *\n * The `skipUntil` operator causes the observable stream to skip the emission of values until the passed in observable\n * emits the first value. This can be particularly useful in combination with user interactions, responses of HTTP\n * requests or waiting for specific times to pass by.\n *\n * \n *\n * Internally, the `skipUntil` operator subscribes to the passed in `notifier` `ObservableInput` (which gets converted\n * to an Observable) in order to recognize the emission of its first value. When `notifier` emits next, the operator\n * unsubscribes from it and starts emitting the values of the *source* observable until it completes or errors. It\n * will never let the *source* observable emit any values if the `notifier` completes or throws an error without\n * emitting a value before.\n *\n * ## Example\n *\n * In the following example, all emitted values of the interval observable are skipped until the user clicks anywhere\n * within the page\n *\n * ```ts\n * import { interval, fromEvent, skipUntil } from 'rxjs';\n *\n * const intervalObservable = interval(1000);\n * const click = fromEvent(document, 'click');\n *\n * const emitAfterClick = intervalObservable.pipe(\n * skipUntil(click)\n * );\n * // clicked at 4.6s. output: 5...6...7...8........ or\n * // clicked at 7.3s. output: 8...9...10..11.......\n * emitAfterClick.subscribe(value => console.log(value));\n * ```\n *\n * @see {@link last}\n * @see {@link skip}\n * @see {@link skipWhile}\n * @see {@link skipLast}\n *\n * @param notifier An `ObservableInput` that has to emit an item before the source Observable elements begin to\n * be mirrored by the resulting Observable.\n * @return A function that returns an Observable that skips items from the\n * source Observable until the `notifier` Observable emits an item, then emits the\n * remaining items.\n */\nexport function skipUntil<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let taking = false;\n\n const skipSubscriber = createOperatorSubscriber(\n subscriber,\n () => {\n skipSubscriber?.unsubscribe();\n taking = true;\n },\n noop\n );\n\n innerFrom(notifier).subscribe(skipSubscriber);\n\n source.subscribe(createOperatorSubscriber(subscriber, (value) => taking && subscriber.next(value)));\n });\n}\n","import { Falsy, MonoTypeOperatorFunction, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function skipWhile<T>(predicate: BooleanConstructor): OperatorFunction<T, Extract<T, Falsy> extends never ? never : T>;\nexport function skipWhile<T>(predicate: (value: T, index: number) => true): OperatorFunction<T, never>;\nexport function skipWhile<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds\n * true, but emits all further source items as soon as the condition becomes false.\n *\n * \n *\n * Skips all the notifications with a truthy predicate. It will not skip the notifications when the predicate is falsy.\n * It can also be skipped using index. Once the predicate is true, it will not be called again.\n *\n * ## Example\n *\n * Skip some super heroes\n *\n * ```ts\n * import { from, skipWhile } from 'rxjs';\n *\n * const source = from(['Green Arrow', 'SuperMan', 'Flash', 'SuperGirl', 'Black Canary'])\n * // Skip the heroes until SuperGirl\n * const example = source.pipe(skipWhile(hero => hero !== 'SuperGirl'));\n * // output: SuperGirl, Black Canary\n * example.subscribe(femaleHero => console.log(femaleHero));\n * ```\n *\n * Skip values from the array until index 5\n *\n * ```ts\n * import { from, skipWhile } from 'rxjs';\n *\n * const source = from([1, 2, 3, 4, 5, 6, 7, 9, 10]);\n * const example = source.pipe(skipWhile((_, i) => i !== 5));\n * // output: 6, 7, 9, 10\n * example.subscribe(value => console.log(value));\n * ```\n *\n * @see {@link last}\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipLast}\n *\n * @param predicate A function to test each item emitted from the source Observable.\n * @return A function that returns an Observable that begins emitting items\n * emitted by the source Observable when the specified predicate becomes false.\n */\nexport function skipWhile<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let taking = false;\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => (taking || (taking = !predicate(value, index++))) && subscriber.next(value))\n );\n });\n}\n","import { concat } from '../observable/concat';\nimport { OperatorFunction, SchedulerLike, ValueFromArray } from '../types';\nimport { popScheduler } from '../util/args';\nimport { operate } from '../util/lift';\n\n// Devs are more likely to pass null or undefined than they are a scheduler\n// without accompanying values. To make things easier for (naughty) devs who\n// use the `strictNullChecks: false` TypeScript compiler option, these\n// overloads with explicit null and undefined values are included.\n\nexport function startWith<T>(value: null): OperatorFunction<T, T | null>;\nexport function startWith<T>(value: undefined): OperatorFunction<T, T | undefined>;\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function startWith<T, A extends readonly unknown[] = T[]>(\n ...valuesAndScheduler: [...A, SchedulerLike]\n): OperatorFunction<T, T | ValueFromArray<A>>;\nexport function startWith<T, A extends readonly unknown[] = T[]>(...values: A): OperatorFunction<T, T | ValueFromArray<A>>;\n\n/**\n * Returns an observable that, at the moment of subscription, will synchronously emit all\n * values provided to this operator, then subscribe to the source and mirror all of its emissions\n * to subscribers.\n *\n * This is a useful way to know when subscription has occurred on an existing observable.\n *\n * <span class=\"informal\">First emits its arguments in order, and then any\n * emissions from the source.</span>\n *\n * \n *\n * ## Examples\n *\n * Emit a value when a timer starts.\n *\n * ```ts\n * import { timer, map, startWith } from 'rxjs';\n *\n * timer(1000)\n * .pipe(\n * map(() => 'timer emit'),\n * startWith('timer start')\n * )\n * .subscribe(x => console.log(x));\n *\n * // results:\n * // 'timer start'\n * // 'timer emit'\n * ```\n *\n * @param values Items you want the modified Observable to emit first.\n * @return A function that returns an Observable that synchronously emits\n * provided values before subscribing to the source Observable.\n *\n * @see {@link endWith}\n * @see {@link finalize}\n * @see {@link concat}\n */\nexport function startWith<T, D>(...values: D[]): OperatorFunction<T, T | D> {\n const scheduler = popScheduler(values);\n return operate((source, subscriber) => {\n // Here we can't pass `undefined` as a scheduler, because if we did, the\n // code inside of `concat` would be confused by the `undefined`, and treat it\n // like an invalid observable. So we have to split it two different ways.\n (scheduler ? concat(values, source, scheduler) : concat(values, source)).subscribe(subscriber);\n });\n}\n","import { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/* tslint:disable:max-line-length */\nexport function switchMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, emitting values only from the most recently projected Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link switchAll}.</span>\n *\n * \n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n *\n * Generate new Observable according to source Observable values\n *\n * ```ts\n * import { of, switchMap } from 'rxjs';\n *\n * const switched = of(1, 2, 3).pipe(switchMap(x => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // 3\n * // 9\n * // 27\n * ```\n *\n * Restart an interval Observable on every click event\n *\n * ```ts\n * import { fromEvent, switchMap, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap(() => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and taking\n * only the values from the most recently projected inner Observable.\n */\nexport function switchMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return operate((source, subscriber) => {\n let innerSubscriber: Subscriber<ObservedValueOf<O>> | null = null;\n let index = 0;\n // Whether or not the source subscription has completed\n let isComplete = false;\n\n // We only complete the result if the source is complete AND we don't have an active inner subscription.\n // This is called both when the source completes and when the inners complete.\n const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Cancel the previous inner subscription if there was one\n innerSubscriber?.unsubscribe();\n let innerIndex = 0;\n const outerIndex = index++;\n // Start the next inner subscription\n innerFrom(project(value, outerIndex)).subscribe(\n (innerSubscriber = createOperatorSubscriber(\n subscriber,\n // When we get a new inner value, next it through. Note that this is\n // handling the deprecate result selector here. This is because with this architecture\n // it ends up being smaller than using the map operator.\n (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue),\n () => {\n // The inner has completed. Null out the inner subscriber to\n // free up memory and to signal that we have no inner subscription\n // currently.\n innerSubscriber = null!;\n checkComplete();\n }\n ))\n );\n },\n () => {\n isComplete = true;\n checkComplete();\n }\n )\n );\n });\n}\n","import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { switchMap } from './switchMap';\nimport { identity } from '../util/identity';\n\n/**\n * Converts a higher-order Observable into a first-order Observable\n * producing values only from the most recent observable sequence\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * \n *\n * `switchAll` subscribes to a source that is an observable of observables, also known as a\n * \"higher-order observable\" (or `Observable<Observable<T>>`). It subscribes to the most recently\n * provided \"inner observable\" emitted by the source, unsubscribing from any previously subscribed\n * to inner observable, such that only the most recent inner observable may be subscribed to at\n * any point in time. The resulting observable returned by `switchAll` will only complete if the\n * source observable completes, *and* any currently subscribed to inner observable also has completed,\n * if there are any.\n *\n * ## Examples\n *\n * Spawn a new interval observable for each click event, but for every new\n * click, cancel the previous interval and subscribe to the new one\n *\n * ```ts\n * import { fromEvent, tap, map, interval, switchAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click')));\n * const source = clicks.pipe(map(() => interval(1000)));\n *\n * source\n * .pipe(switchAll())\n * .subscribe(x => console.log(x));\n *\n * // Output\n * // click\n * // 0\n * // 1\n * // 2\n * // 3\n * // ...\n * // click\n * // 0\n * // 1\n * // 2\n * // ...\n * // click\n * // ...\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link exhaustAll}\n * @see {@link switchMap}\n * @see {@link switchMapTo}\n * @see {@link mergeAll}\n *\n * @return A function that returns an Observable that converts a higher-order\n * Observable into a first-order Observable producing values only from the most\n * recent Observable sequence.\n */\nexport function switchAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {\n return switchMap(identity);\n}\n","import { switchMap } from './switchMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/** @deprecated Will be removed in v9. Use {@link switchMap} instead: `switchMap(() => result)` */\nexport function switchMapTo<O extends ObservableInput<unknown>>(observable: O): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMapTo<O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: undefined\n): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMapTo<T, R, O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n\n/**\n * Projects each source value to the same Observable which is flattened multiple\n * times with {@link switchMap} in the output Observable.\n *\n * <span class=\"informal\">It's like {@link switchMap}, but maps each value\n * always to the same inner Observable.</span>\n *\n * \n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. The output Observables\n * emits values only from the most recently emitted instance of\n * `innerObservable`.\n *\n * ## Example\n *\n * Restart an interval Observable on every click event\n *\n * ```ts\n * import { fromEvent, switchMapTo, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMapTo(interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeMapTo}\n *\n * @param innerObservable An `ObservableInput` to replace each value from the\n * source Observable.\n * @return A function that returns an Observable that emits items from the\n * given `innerObservable` (and optionally transformed through the deprecated\n * `resultSelector`) every time a value is emitted on the source Observable,\n * and taking only the values from the most recently projected inner\n * Observable.\n * @deprecated Will be removed in v9. Use {@link switchMap} instead: `switchMap(() => result)`\n */\nexport function switchMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return isFunction(resultSelector) ? switchMap(() => innerObservable, resultSelector) : switchMap(() => innerObservable);\n}\n","import { ObservableInput, ObservedValueOf, OperatorFunction } from '../types';\nimport { switchMap } from './switchMap';\nimport { operate } from '../util/lift';\n\n// TODO: Generate a marble diagram for these docs.\n\n/**\n * Applies an accumulator function over the source Observable where the\n * accumulator function itself returns an Observable, emitting values\n * only from the most recently returned Observable.\n *\n * <span class=\"informal\">It's like {@link mergeScan}, but only the most recent\n * Observable returned by the accumulator is merged into the outer Observable.</span>\n *\n * @see {@link scan}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param accumulator\n * The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @return A function that returns an observable of the accumulated values.\n */\nexport function switchScan<T, R, O extends ObservableInput<any>>(\n accumulator: (acc: R, value: T, index: number) => O,\n seed: R\n): OperatorFunction<T, ObservedValueOf<O>> {\n return operate((source, subscriber) => {\n // The state we will keep up to date to pass into our\n // accumulator function at each new value from the source.\n let state = seed;\n\n // Use `switchMap` on our `source` to do the work of creating\n // this operator. Note the backwards order here of `switchMap()(source)`\n // to avoid needing to use `pipe` unnecessarily\n switchMap(\n // On each value from the source, call the accumulator with\n // our previous state, the value and the index.\n (value: T, index) => accumulator(state, value, index),\n // Using the deprecated result selector here as a dirty trick\n // to update our state with the flattened value.\n (_, innerValue) => ((state = innerValue), innerValue)\n )(source).subscribe(subscriber);\n\n return () => {\n // Release state on finalization\n state = null!;\n };\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { noop } from '../util/noop';\n\n/**\n * Emits the values emitted by the source Observable until a `notifier`\n * Observable emits a value.\n *\n * <span class=\"informal\">Lets values pass until a second Observable,\n * `notifier`, emits a value. Then, it completes.</span>\n *\n * \n *\n * `takeUntil` subscribes and begins mirroring the source Observable. It also\n * monitors a second Observable, `notifier` that you provide. If the `notifier`\n * emits a value, the output Observable stops mirroring the source Observable\n * and completes. If the `notifier` doesn't emit any value and completes\n * then `takeUntil` will pass all values.\n *\n * ## Example\n *\n * Tick every second until the first click happens\n *\n * ```ts\n * import { interval, fromEvent, takeUntil } from 'rxjs';\n *\n * const source = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = source.pipe(takeUntil(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param notifier The `ObservableInput` whose first emitted value will cause the output\n * Observable of `takeUntil` to stop emitting values from the source Observable.\n * @return A function that returns an Observable that emits the values from the\n * source Observable until `notifier` emits its first value.\n */\nexport function takeUntil<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, () => subscriber.complete(), noop));\n !subscriber.closed && source.subscribe(subscriber);\n });\n}\n","import { OperatorFunction, MonoTypeOperatorFunction, TruthyTypesOf } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function takeWhile<T>(predicate: BooleanConstructor, inclusive: true): MonoTypeOperatorFunction<T>;\nexport function takeWhile<T>(predicate: BooleanConstructor, inclusive: false): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function takeWhile<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;\nexport function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S, inclusive: false): OperatorFunction<T, S>;\nexport function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive?: boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Emits values emitted by the source Observable so long as each value satisfies\n * the given `predicate`, and then completes as soon as this `predicate` is not\n * satisfied.\n *\n * <span class=\"informal\">Takes values from the source only while they pass the\n * condition given. When the first value does not satisfy, it completes.</span>\n *\n * \n *\n * `takeWhile` subscribes and begins mirroring the source Observable. Each value\n * emitted on the source is given to the `predicate` function which returns a\n * boolean, representing a condition to be satisfied by the source values. The\n * output Observable emits the source values until such time as the `predicate`\n * returns false, at which point `takeWhile` stops mirroring the source\n * Observable and completes the output Observable.\n *\n * ## Example\n *\n * Emit click events only while the clientX property is greater than 200\n *\n * ```ts\n * import { fromEvent, takeWhile } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const result = clicks.pipe(takeWhile(ev => ev.clientX > 200));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link skip}\n *\n * @param predicate A function that evaluates a value emitted by the source\n * Observable and returns a boolean. Also takes the (zero-based) index as the\n * second argument.\n * @param inclusive When set to `true` the value that caused `predicate` to\n * return `false` will also be emitted.\n * @return A function that returns an Observable that emits values from the\n * source Observable so long as each value satisfies the condition defined by\n * the `predicate`, then completes.\n */\nexport function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive = false): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const result = predicate(value, index++);\n (result || inclusive) && subscriber.next(value);\n !result && subscriber.complete();\n })\n );\n });\n}\n","import { MonoTypeOperatorFunction, Observer } from '../types';\nimport { isFunction } from '../util/isFunction';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { identity } from '../util/identity';\n\n/**\n * An extension to the {@link Observer} interface used only by the {@link tap} operator.\n *\n * It provides a useful set of callbacks a user can register to do side-effects in\n * cases other than what the usual {@link Observer} callbacks are\n * ({@link guide/glossary-and-semantics#next next},\n * {@link guide/glossary-and-semantics#error error} and/or\n * {@link guide/glossary-and-semantics#complete complete}).\n *\n * ## Example\n *\n * ```ts\n * import { fromEvent, switchMap, tap, interval, take } from 'rxjs';\n *\n * const source$ = fromEvent(document, 'click');\n * const result$ = source$.pipe(\n * switchMap((_, i) => i % 2 === 0\n * ? fromEvent(document, 'mousemove').pipe(\n * tap({\n * subscribe: () => console.log('Subscribed to the mouse move events after click #' + i),\n * unsubscribe: () => console.log('Mouse move events #' + i + ' unsubscribed'),\n * finalize: () => console.log('Mouse move events #' + i + ' finalized')\n * })\n * )\n * : interval(1_000).pipe(\n * take(5),\n * tap({\n * subscribe: () => console.log('Subscribed to the 1-second interval events after click #' + i),\n * unsubscribe: () => console.log('1-second interval events #' + i + ' unsubscribed'),\n * finalize: () => console.log('1-second interval events #' + i + ' finalized')\n * })\n * )\n * )\n * );\n *\n * const subscription = result$.subscribe({\n * next: console.log\n * });\n *\n * setTimeout(() => {\n * console.log('Unsubscribe after 60 seconds');\n * subscription.unsubscribe();\n * }, 60_000);\n * ```\n */\nexport interface TapObserver<T> extends Observer<T> {\n /**\n * The callback that `tap` operator invokes at the moment when the source Observable\n * gets subscribed to.\n */\n subscribe: () => void;\n /**\n * The callback that `tap` operator invokes when an explicit\n * {@link guide/glossary-and-semantics#unsubscription unsubscribe} happens. It won't get invoked on\n * `error` or `complete` events.\n */\n unsubscribe: () => void;\n /**\n * The callback that `tap` operator invokes when any kind of\n * {@link guide/glossary-and-semantics#finalization finalization} happens - either when\n * the source Observable `error`s or `complete`s or when it gets explicitly unsubscribed\n * by the user. There is no difference in using this callback or the {@link finalize}\n * operator, but if you're already using `tap` operator, you can use this callback\n * instead. You'd get the same result in either case.\n */\n finalize: () => void;\n}\nexport function tap<T>(observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void)): MonoTypeOperatorFunction<T>;\n/** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\nexport function tap<T>(\n next?: ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Used to perform side-effects for notifications from the source observable\n *\n * <span class=\"informal\">Used when you want to affect outside state with a notification without altering the notification</span>\n *\n * \n *\n * Tap is designed to allow the developer a designated place to perform side effects. While you _could_ perform side-effects\n * inside of a `map` or a `mergeMap`, that would make their mapping functions impure, which isn't always a big deal, but will\n * make it so you can't do things like memoize those functions. The `tap` operator is designed solely for such side-effects to\n * help you remove side-effects from other operations.\n *\n * For any notification, next, error, or complete, `tap` will call the appropriate callback you have provided to it, via a function\n * reference, or a partial observer, then pass that notification down the stream.\n *\n * The observable returned by `tap` is an exact mirror of the source, with one exception: Any error that occurs -- synchronously -- in a handler\n * provided to `tap` will be emitted as an error from the returned observable.\n *\n * > Be careful! You can mutate objects as they pass through the `tap` operator's handlers.\n *\n * The most common use of `tap` is actually for debugging. You can place a `tap(console.log)` anywhere\n * in your observable `pipe`, log out the notifications as they are emitted by the source returned by the previous\n * operation.\n *\n * ## Examples\n *\n * Check a random number before it is handled. Below is an observable that will use a random number between 0 and 1,\n * and emit `'big'` or `'small'` depending on the size of that number. But we wanted to log what the original number\n * was, so we have added a `tap(console.log)`.\n *\n * ```ts\n * import { of, tap, map } from 'rxjs';\n *\n * of(Math.random()).pipe(\n * tap(console.log),\n * map(n => n > 0.5 ? 'big' : 'small')\n * ).subscribe(console.log);\n * ```\n *\n * Using `tap` to analyze a value and force an error. Below is an observable where in our system we only\n * want to emit numbers 3 or less we get from another source. We can force our observable to error\n * using `tap`.\n *\n * ```ts\n * import { of, tap } from 'rxjs';\n *\n * const source = of(1, 2, 3, 4, 5);\n *\n * source.pipe(\n * tap(n => {\n * if (n > 3) {\n * throw new TypeError(`Value ${ n } is greater than 3`);\n * }\n * })\n * )\n * .subscribe({ next: console.log, error: err => console.log(err.message) });\n * ```\n *\n * We want to know when an observable completes before moving on to the next observable. The system\n * below will emit a random series of `'X'` characters from 3 different observables in sequence. The\n * only way we know when one observable completes and moves to the next one, in this case, is because\n * we have added a `tap` with the side effect of logging to console.\n *\n * ```ts\n * import { of, concatMap, interval, take, map, tap } from 'rxjs';\n *\n * of(1, 2, 3).pipe(\n * concatMap(n => interval(1000).pipe(\n * take(Math.round(Math.random() * 10)),\n * map(() => 'X'),\n * tap({ complete: () => console.log(`Done with ${ n }`) })\n * ))\n * )\n * .subscribe(console.log);\n * ```\n *\n * @see {@link finalize}\n * @see {@link TapObserver}\n *\n * @param observerOrNext A next handler or partial observer\n * @param error An error handler\n * @param complete A completion handler\n * @return A function that returns an Observable identical to the source, but\n * runs the specified Observer or callback(s) for each item.\n */\nexport function tap<T>(\n observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void) | null,\n error?: ((e: any) => void) | null,\n complete?: (() => void) | null\n): MonoTypeOperatorFunction<T> {\n // We have to check to see not only if next is a function,\n // but if error or complete were passed. This is because someone\n // could technically call tap like `tap(null, fn)` or `tap(null, null, fn)`.\n const tapObserver =\n isFunction(observerOrNext) || error || complete\n ? // tslint:disable-next-line: no-object-literal-type-assertion\n ({ next: observerOrNext as Exclude<typeof observerOrNext, Partial<TapObserver<T>>>, error, complete } as Partial<TapObserver<T>>)\n : observerOrNext;\n\n return tapObserver\n ? operate((source, subscriber) => {\n tapObserver.subscribe?.();\n let isUnsub = true;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n tapObserver.next?.(value);\n subscriber.next(value);\n },\n () => {\n isUnsub = false;\n tapObserver.complete?.();\n subscriber.complete();\n },\n (err) => {\n isUnsub = false;\n tapObserver.error?.(err);\n subscriber.error(err);\n },\n () => {\n if (isUnsub) {\n tapObserver.unsubscribe?.();\n }\n tapObserver.finalize?.();\n }\n )\n );\n })\n : // Tap was called with no valid tap observer or handler\n // (e.g. `tap(null, null, null)` or `tap(null)` or `tap()`)\n // so we're going to just mirror the source.\n identity;\n}\n","import { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * An object interface used by {@link throttle} or {@link throttleTime} that ensure\n * configuration options of these operators.\n *\n * @see {@link throttle}\n * @see {@link throttleTime}\n */\nexport interface ThrottleConfig {\n /**\n * If `true`, the resulting Observable will emit the first value from the source\n * Observable at the **start** of the \"throttling\" process (when starting an\n * internal timer that prevents other emissions from the source to pass through).\n * If `false`, it will not emit the first value from the source Observable at the\n * start of the \"throttling\" process.\n *\n * If not provided, defaults to: `true`.\n */\n leading?: boolean;\n /**\n * If `true`, the resulting Observable will emit the last value from the source\n * Observable at the **end** of the \"throttling\" process (when ending an internal\n * timer that prevents other emissions from the source to pass through).\n * If `false`, it will not emit the last value from the source Observable at the\n * end of the \"throttling\" process.\n *\n * If not provided, defaults to: `false`.\n */\n trailing?: boolean;\n}\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for a duration determined by another Observable, then repeats this\n * process.\n *\n * <span class=\"informal\">It's like {@link throttleTime}, but the silencing\n * duration is determined by a second Observable.</span>\n *\n * \n *\n * `throttle` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled by calling the `durationSelector` function with the source value,\n * which returns the \"duration\" Observable. When the duration Observable emits a\n * value, the timer is disabled, and this process repeats for the\n * next source value.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, throttle, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttle(() => interval(1000)));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param durationSelector A function that receives a value from the source\n * Observable, for computing the silencing duration for each source value,\n * returned as an `ObservableInput`.\n * @param config A configuration object to define `leading` and `trailing`\n * behavior. Defaults to `{ leading: true, trailing: false }`.\n * @return A function that returns an Observable that performs the throttle\n * operation to limit the rate of emissions from the source.\n */\nexport function throttle<T>(durationSelector: (value: T) => ObservableInput<any>, config?: ThrottleConfig): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n const { leading = true, trailing = false } = config ?? {};\n let hasValue = false;\n let sendValue: T | null = null;\n let throttled: Subscription | null = null;\n let isComplete = false;\n\n const endThrottling = () => {\n throttled?.unsubscribe();\n throttled = null;\n if (trailing) {\n send();\n isComplete && subscriber.complete();\n }\n };\n\n const cleanupThrottling = () => {\n throttled = null;\n isComplete && subscriber.complete();\n };\n\n const startThrottle = (value: T) =>\n (throttled = innerFrom(durationSelector(value)).subscribe(createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling)));\n\n const send = () => {\n if (hasValue) {\n // Ensure we clear out our value and hasValue flag\n // before we emit, otherwise reentrant code can cause\n // issues here.\n hasValue = false;\n const value = sendValue!;\n sendValue = null;\n // Emit the value.\n subscriber.next(value);\n !isComplete && startThrottle(value);\n }\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n // Regarding the presence of throttled.closed in the following\n // conditions, if a synchronous duration selector is specified - weird,\n // but legal - an already-closed subscription will be assigned to\n // throttled, so the subscription's closed property needs to be checked,\n // too.\n (value) => {\n hasValue = true;\n sendValue = value;\n !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));\n },\n () => {\n isComplete = true;\n !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();\n }\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { throttle, ThrottleConfig } from './throttle';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { timer } from '../observable/timer';\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for `duration` milliseconds, then repeats this process.\n *\n * <span class=\"informal\">Lets a value pass, then ignores source values for the\n * next `duration` milliseconds.</span>\n *\n * \n *\n * `throttleTime` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled. After `duration` milliseconds (or the time unit determined\n * internally by the optional `scheduler`) has passed, the timer is disabled,\n * and this process repeats for the next source value. Optionally takes a\n * {@link SchedulerLike} for managing timers.\n *\n * ## Examples\n *\n * ### Limit click rate\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, throttleTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttleTime(1000));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param duration Time to wait before emitting another value after\n * emitting the last value, measured in milliseconds or the time unit determined\n * internally by the optional `scheduler`.\n * @param scheduler The {@link SchedulerLike} to use for\n * managing the timers that handle the throttling. Defaults to {@link asyncScheduler}.\n * @param config A configuration object to define `leading` and\n * `trailing` behavior. Defaults to `{ leading: true, trailing: false }`.\n * @return A function that returns an Observable that performs the throttle\n * operation to limit the rate of emissions from the source.\n */\nexport function throttleTime<T>(\n duration: number,\n scheduler: SchedulerLike = asyncScheduler,\n config?: ThrottleConfig\n): MonoTypeOperatorFunction<T> {\n const duration$ = timer(duration, scheduler);\n return throttle(() => duration$, config);\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { SchedulerLike, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits an object containing the current value, and the time that has\n * passed between emitting the current value and the previous value, which is\n * calculated by using the provided `scheduler`'s `now()` method to retrieve\n * the current time at each emission, then calculating the difference. The `scheduler`\n * defaults to {@link asyncScheduler}, so by default, the `interval` will be in\n * milliseconds.\n *\n * <span class=\"informal\">Convert an Observable that emits items into one that\n * emits indications of the amount of time elapsed between those emissions.</span>\n *\n * \n *\n * ## Example\n *\n * Emit interval between current value with the last value\n *\n * ```ts\n * import { interval, timeInterval } from 'rxjs';\n *\n * const seconds = interval(1000);\n *\n * seconds\n * .pipe(timeInterval())\n * .subscribe(value => console.log(value));\n *\n * // NOTE: The values will never be this precise,\n * // intervals created with `interval` or `setInterval`\n * // are non-deterministic.\n *\n * // { value: 0, interval: 1000 }\n * // { value: 1, interval: 1000 }\n * // { value: 2, interval: 1000 }\n * ```\n *\n * @param scheduler Scheduler used to get the current time.\n * @return A function that returns an Observable that emits information about\n * value and interval.\n */\nexport function timeInterval<T>(scheduler: SchedulerLike = asyncScheduler): OperatorFunction<T, TimeInterval<T>> {\n return operate((source, subscriber) => {\n let last = scheduler.now();\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const now = scheduler.now();\n const interval = now - last;\n last = now;\n subscriber.next(new TimeInterval(value, interval));\n })\n );\n });\n}\n\n// TODO(benlesh): make this an interface, export the interface, but not the implemented class,\n// there's no reason users should be manually creating this type.\n\nexport class TimeInterval<T> {\n /**\n * @deprecated Internal implementation detail, do not construct directly. Will be made an interface in v8.\n */\n constructor(public value: T, public interval: number) {}\n}\n","import { async } from '../scheduler/async';\nimport { isValidDate } from '../util/isDate';\nimport { ObservableInput, OperatorFunction, SchedulerLike } from '../types';\nimport { timeout } from './timeout';\n\n/** @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(someDate, a$, scheduler)`, use the configuration object\n * `timeout({ first: someDate, with: () => a$, scheduler })`. Will be removed in v8. */\nexport function timeoutWith<T, R>(dueBy: Date, switchTo: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n/** @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(100, a$, scheduler)`, use the configuration object\n * `timeout({ each: 100, with: () => a$, scheduler })`. Will be removed in v8. */\nexport function timeoutWith<T, R>(waitFor: number, switchTo: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n\n/**\n * When the passed timespan elapses before the source emits any given value, it will unsubscribe from the source,\n * and switch the subscription to another observable.\n *\n * <span class=\"informal\">Used to switch to a different observable if your source is being slow.</span>\n *\n * Useful in cases where:\n *\n * - You want to switch to a different source that may be faster.\n * - You want to notify a user that the data stream is slow.\n * - You want to emit a custom error rather than the {@link TimeoutError} emitted\n * by the default usage of {@link timeout}.\n *\n * If the first parameter is passed as Date and the time of the Date arrives before the first value arrives from the source,\n * it will unsubscribe from the source and switch the subscription to another observable.\n *\n * <span class=\"informal\">Use Date object to switch to a different observable if the first value doesn't arrive by a specific time.</span>\n *\n * Can be used to set a timeout only for the first value, however it's recommended to use the {@link timeout} operator with\n * the `first` configuration to get the same effect.\n *\n * ## Examples\n *\n * Fallback to a faster observable\n *\n * ```ts\n * import { interval, timeoutWith } from 'rxjs';\n *\n * const slow$ = interval(1000);\n * const faster$ = interval(500);\n *\n * slow$\n * .pipe(timeoutWith(900, faster$))\n * .subscribe(console.log);\n * ```\n *\n * Emit your own custom timeout error\n *\n * ```ts\n * import { interval, timeoutWith, throwError } from 'rxjs';\n *\n * class CustomTimeoutError extends Error {\n * constructor() {\n * super('It was too slow');\n * this.name = 'CustomTimeoutError';\n * }\n * }\n *\n * const slow$ = interval(1000);\n *\n * slow$\n * .pipe(timeoutWith(900, throwError(() => new CustomTimeoutError())))\n * .subscribe({\n * error: err => console.error(err.message)\n * });\n * ```\n *\n * @see {@link timeout}\n *\n * @param due When passed a number, used as the time (in milliseconds) allowed between each value from the source before timeout\n * is triggered. When passed a Date, used as the exact time at which the timeout will be triggered if the first value does not arrive.\n * @param withObservable The observable to switch to when timeout occurs.\n * @param scheduler The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler}\n * @return A function that returns an Observable that mirrors behaviour of the\n * source Observable, unless timeout happens when it starts emitting values\n * from the `ObservableInput` passed as a second parameter.\n * @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(100, a$, scheduler)`, use {@link timeout} with the configuration\n * object: `timeout({ each: 100, with: () => a$, scheduler })`. Instead of `timeoutWith(someDate, a$, scheduler)`, use {@link timeout}\n * with the configuration object: `timeout({ first: someDate, with: () => a$, scheduler })`. Will be removed in v8.\n */\nexport function timeoutWith<T, R>(\n due: number | Date,\n withObservable: ObservableInput<R>,\n scheduler?: SchedulerLike\n): OperatorFunction<T, T | R> {\n let first: number | Date | undefined;\n let each: number | undefined;\n let _with: () => ObservableInput<R>;\n scheduler = scheduler ?? async;\n\n if (isValidDate(due)) {\n first = due;\n } else if (typeof due === 'number') {\n each = due;\n }\n\n if (withObservable) {\n _with = () => withObservable;\n } else {\n throw new TypeError('No observable provided to switch to');\n }\n\n if (first == null && each == null) {\n // Ensure timeout was provided at runtime.\n throw new TypeError('No timeout provided.');\n }\n\n return timeout<T, ObservableInput<R>>({\n first,\n each,\n scheduler,\n with: _with,\n });\n}\n","import { OperatorFunction, TimestampProvider, Timestamp } from '../types';\nimport { dateTimestampProvider } from '../scheduler/dateTimestampProvider';\nimport { map } from './map';\n\n/**\n * Attaches a timestamp to each item emitted by an observable indicating when it was emitted\n *\n * The `timestamp` operator maps the *source* observable stream to an object of type\n * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value\n * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By\n * default, it uses the `asyncScheduler` which simply returns `Date.now()` (milliseconds since 1970/01/01\n * 00:00:00:000) and therefore is of type `number`.\n *\n * \n *\n * ## Example\n *\n * In this example there is a timestamp attached to the document's click events\n *\n * ```ts\n * import { fromEvent, timestamp } from 'rxjs';\n *\n * const clickWithTimestamp = fromEvent(document, 'click').pipe(\n * timestamp()\n * );\n *\n * // Emits data of type { value: PointerEvent, timestamp: number }\n * clickWithTimestamp.subscribe(data => {\n * console.log(data);\n * });\n * ```\n *\n * @param timestampProvider An object with a `now()` method used to get the current timestamp.\n * @return A function that returns an Observable that attaches a timestamp to\n * each item emitted by the source Observable indicating when it was emitted.\n */\nexport function timestamp<T>(timestampProvider: TimestampProvider = dateTimestampProvider): OperatorFunction<T, Timestamp<T>> {\n return map((value: T) => ({ value, timestamp: timestampProvider.now() }));\n}\n","import { Observable } from '../Observable';\nimport { OperatorFunction, ObservableInput } from '../types';\nimport { Subject } from '../Subject';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Branch out the source Observable values as a nested Observable whenever\n * `windowBoundaries` emits.\n *\n * <span class=\"informal\">It's like {@link buffer}, but emits a nested Observable\n * instead of an array.</span>\n *\n * \n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping\n * windows. It emits the current window and opens a new one whenever the\n * `windowBoundaries` emits an item. `windowBoundaries` can be any type that\n * `ObservableInput` accepts. It internally gets converted to an Observable.\n * Because each window is an Observable, the output is a higher-order Observable.\n *\n * ## Example\n *\n * In every window of 1 second each, emit at most 2 click events\n *\n * ```ts\n * import { fromEvent, interval, window, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const sec = interval(1000);\n * const result = clicks.pipe(\n * window(sec),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link buffer}\n *\n * @param windowBoundaries An `ObservableInput` that completes the\n * previous window and starts a new window.\n * @return A function that returns an Observable of windows, which are\n * Observables emitting values of the source Observable.\n */\nexport function window<T>(windowBoundaries: ObservableInput<any>): OperatorFunction<T, Observable<T>> {\n return operate((source, subscriber) => {\n let windowSubject: Subject<T> = new Subject<T>();\n\n subscriber.next(windowSubject.asObservable());\n\n const errorHandler = (err: any) => {\n windowSubject.error(err);\n subscriber.error(err);\n };\n\n // Subscribe to our source\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => windowSubject?.next(value),\n () => {\n windowSubject.complete();\n subscriber.complete();\n },\n errorHandler\n )\n );\n\n // Subscribe to the window boundaries.\n innerFrom(windowBoundaries).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n windowSubject.complete();\n subscriber.next((windowSubject = new Subject()));\n },\n noop,\n errorHandler\n )\n );\n\n return () => {\n // Unsubscribing the subject ensures that anyone who has captured\n // a reference to this window that tries to use it after it can\n // no longer get values from the source will get an ObjectUnsubscribedError.\n windowSubject?.unsubscribe();\n windowSubject = null!;\n };\n });\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Branch out the source Observable values as a nested Observable with each\n * nested Observable emitting at most `windowSize` values.\n *\n * <span class=\"informal\">It's like {@link bufferCount}, but emits a nested\n * Observable instead of an array.</span>\n *\n * \n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows every `startWindowEvery`\n * items, each containing no more than `windowSize` items. When the source\n * Observable completes or encounters an error, the output Observable emits\n * the current window and propagates the notification from the source\n * Observable. If `startWindowEvery` is not provided, then new windows are\n * started immediately at the start of the source and when each window completes\n * with size `windowSize`.\n *\n * ## Examples\n *\n * Ignore every 3rd click event, starting from the first one\n *\n * ```ts\n * import { fromEvent, windowCount, map, skip, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowCount(3),\n * map(win => win.pipe(skip(1))), // skip first of every 3 clicks\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Ignore every 3rd click event, starting from the third one\n *\n * ```ts\n * import { fromEvent, windowCount, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowCount(2, 3),\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferCount}\n *\n * @param windowSize The maximum number of values emitted by each window.\n * @param startWindowEvery Interval at which to start a new window. For example\n * if `startWindowEvery` is `2`, then a new window will be started on every\n * other value from the source. A new window is started at the beginning of the\n * source by default.\n * @return A function that returns an Observable of windows, which in turn are\n * Observable of values.\n */\nexport function windowCount<T>(windowSize: number, startWindowEvery: number = 0): OperatorFunction<T, Observable<T>> {\n const startEvery = startWindowEvery > 0 ? startWindowEvery : windowSize;\n\n return operate((source, subscriber) => {\n let windows = [new Subject<T>()];\n let starts: number[] = [];\n let count = 0;\n\n // Open the first window.\n subscriber.next(windows[0].asObservable());\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Emit the value through all current windows.\n // We don't need to create a new window yet, we\n // do that as soon as we close one.\n for (const window of windows) {\n window.next(value);\n }\n // Here we're using the size of the window array to figure\n // out if the oldest window has emitted enough values. We can do this\n // because the size of the window array is a function of the values\n // seen by the subscription. If it's time to close it, we complete\n // it and remove it.\n const c = count - windowSize + 1;\n if (c >= 0 && c % startEvery === 0) {\n windows.shift()!.complete();\n }\n\n // Look to see if the next count tells us it's time to open a new window.\n // TODO: We need to figure out if this really makes sense. We're technically\n // emitting windows *before* we have a value to emit them for. It's probably\n // more expected that we should be emitting the window when the start\n // count is reached -- not before.\n if (++count % startEvery === 0) {\n const window = new Subject<T>();\n windows.push(window);\n subscriber.next(window.asObservable());\n }\n },\n () => {\n while (windows.length > 0) {\n windows.shift()!.complete();\n }\n subscriber.complete();\n },\n (err) => {\n while (windows.length > 0) {\n windows.shift()!.error(err);\n }\n subscriber.error(err);\n },\n () => {\n starts = null!;\n windows = null!;\n }\n )\n );\n });\n}\n","import { Subject } from '../Subject';\nimport { asyncScheduler } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { Observer, OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { arrRemove } from '../util/arrRemove';\nimport { popScheduler } from '../util/args';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function windowTime<T>(windowTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, Observable<T>>;\nexport function windowTime<T>(\n windowTimeSpan: number,\n windowCreationInterval: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, Observable<T>>;\nexport function windowTime<T>(\n windowTimeSpan: number,\n windowCreationInterval: number | null | void,\n maxWindowSize: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, Observable<T>>;\n\n/**\n * Branch out the source Observable values as a nested Observable periodically\n * in time.\n *\n * <span class=\"informal\">It's like {@link bufferTime}, but emits a nested\n * Observable instead of an array.</span>\n *\n * \n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable starts a new window periodically, as\n * determined by the `windowCreationInterval` argument. It emits each window\n * after a fixed timespan, specified by the `windowTimeSpan` argument. When the\n * source Observable completes or encounters an error, the output Observable\n * emits the current window and propagates the notification from the source\n * Observable. If `windowCreationInterval` is not provided, the output\n * Observable starts a new window when the previous window of duration\n * `windowTimeSpan` completes. If `maxWindowCount` is provided, each window\n * will emit at most fixed number of values. Window will complete immediately\n * after emitting last value and next one still will open as specified by\n * `windowTimeSpan` and `windowCreationInterval` arguments.\n *\n * ## Examples\n *\n * In every window of 1 second each, emit at most 2 click events\n *\n * ```ts\n * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds start a window 1 second long, and emit at most 2 click events per window\n *\n * ```ts\n * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000, 5000),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Same as example above but with `maxWindowCount` instead of `take`\n *\n * ```ts\n * import { fromEvent, windowTime, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000, 5000, 2), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferTime}\n *\n * @param windowTimeSpan The amount of time, in milliseconds, to fill each window.\n * @param windowCreationInterval The interval at which to start new\n * windows.\n * @param maxWindowSize Max number of\n * values each window can emit before completion.\n * @param scheduler The scheduler on which to schedule the\n * intervals that determine window boundaries.\n * @return A function that returns an Observable of windows, which in turn are\n * Observables.\n */\nexport function windowTime<T>(windowTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, Observable<T>> {\n const scheduler = popScheduler(otherArgs) ?? asyncScheduler;\n const windowCreationInterval = (otherArgs[0] as number) ?? null;\n const maxWindowSize = (otherArgs[1] as number) || Infinity;\n\n return operate((source, subscriber) => {\n // The active windows, their related subscriptions, and removal functions.\n let windowRecords: WindowRecord<T>[] | null = [];\n // If true, it means that every time we close a window, we want to start a new window.\n // This is only really used for when *just* the time span is passed.\n let restartOnClose = false;\n\n const closeWindow = (record: { window: Subject<T>; subs: Subscription }) => {\n const { window, subs } = record;\n window.complete();\n subs.unsubscribe();\n arrRemove(windowRecords, record);\n restartOnClose && startWindow();\n };\n\n /**\n * Called every time we start a new window. This also does\n * the work of scheduling the job to close the window.\n */\n const startWindow = () => {\n if (windowRecords) {\n const subs = new Subscription();\n subscriber.add(subs);\n const window = new Subject<T>();\n const record = {\n window,\n subs,\n seen: 0,\n };\n windowRecords.push(record);\n subscriber.next(window.asObservable());\n executeSchedule(subs, scheduler, () => closeWindow(record), windowTimeSpan);\n }\n };\n\n if (windowCreationInterval !== null && windowCreationInterval >= 0) {\n // The user passed both a windowTimeSpan (required), and a creation interval\n // That means we need to start new window on the interval, and those windows need\n // to wait the required time span before completing.\n executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);\n } else {\n restartOnClose = true;\n }\n\n startWindow();\n\n /**\n * We need to loop over a copy of the window records several times in this operator.\n * This is to save bytes over the wire more than anything.\n * The reason we copy the array is that reentrant code could mutate the array while\n * we are iterating over it.\n */\n const loop = (cb: (record: WindowRecord<T>) => void) => windowRecords!.slice().forEach(cb);\n\n /**\n * Used to notify all of the windows and the subscriber in the same way\n * in the error and complete handlers.\n */\n const terminate = (cb: (consumer: Observer<any>) => void) => {\n loop(({ window }) => cb(window));\n cb(subscriber);\n subscriber.unsubscribe();\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Notify all windows of the value.\n loop((record) => {\n record.window.next(value);\n // If the window is over the max size, we need to close it.\n maxWindowSize <= ++record.seen && closeWindow(record);\n });\n },\n // Complete the windows and the downstream subscriber and clean up.\n () => terminate((consumer) => consumer.complete()),\n // Notify the windows and the downstream subscriber of the error and clean up.\n (err) => terminate((consumer) => consumer.error(err))\n )\n );\n\n // Additional finalization. This will be called when the\n // destination tears down. Other finalizations are registered implicitly\n // above via subscription.\n return () => {\n // Ensure that the buffer is released.\n windowRecords = null!;\n };\n });\n}\n\ninterface WindowRecord<T> {\n seen: number;\n window: Subject<T>;\n subs: Subscription;\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { arrRemove } from '../util/arrRemove';\n\n/**\n * Branch out the source Observable values as a nested Observable starting from\n * an emission from `openings` and ending when the output of `closingSelector`\n * emits.\n *\n * <span class=\"informal\">It's like {@link bufferToggle}, but emits a nested\n * Observable instead of an array.</span>\n *\n * \n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows that contain those items\n * emitted by the source Observable between the time when the `openings`\n * Observable emits an item and when the Observable returned by\n * `closingSelector` emits an item.\n *\n * ## Example\n *\n * Every other second, emit the click events from the next 500ms\n *\n * ```ts\n * import { fromEvent, interval, windowToggle, EMPTY, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const result = clicks.pipe(\n * windowToggle(openings, i => i % 2 ? interval(500) : EMPTY),\n * mergeAll()\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowWhen}\n * @see {@link bufferToggle}\n *\n * @param openings An observable of notifications to start new windows.\n * @param closingSelector A function that takes the value emitted by the\n * `openings` observable and returns an Observable, which, when it emits a next\n * notification, signals that the associated window should complete.\n * @return A function that returns an Observable of windows, which in turn are\n * Observables.\n */\nexport function windowToggle<T, O>(\n openings: ObservableInput<O>,\n closingSelector: (openValue: O) => ObservableInput<any>\n): OperatorFunction<T, Observable<T>> {\n return operate((source, subscriber) => {\n const windows: Subject<T>[] = [];\n\n const handleError = (err: any) => {\n while (0 < windows.length) {\n windows.shift()!.error(err);\n }\n subscriber.error(err);\n };\n\n innerFrom(openings).subscribe(\n createOperatorSubscriber(\n subscriber,\n (openValue) => {\n const window = new Subject<T>();\n windows.push(window);\n const closingSubscription = new Subscription();\n const closeWindow = () => {\n arrRemove(windows, window);\n window.complete();\n closingSubscription.unsubscribe();\n };\n\n let closingNotifier: Observable<any>;\n try {\n closingNotifier = innerFrom(closingSelector(openValue));\n } catch (err) {\n handleError(err);\n return;\n }\n\n subscriber.next(window.asObservable());\n\n closingSubscription.add(closingNotifier.subscribe(createOperatorSubscriber(subscriber, closeWindow, noop, handleError)));\n },\n noop\n )\n );\n\n // Subscribe to the source to get things started.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Copy the windows array before we emit to\n // make sure we don't have issues with reentrant code.\n const windowsCopy = windows.slice();\n for (const window of windowsCopy) {\n window.next(value);\n }\n },\n () => {\n // Complete all of our windows before we complete.\n while (0 < windows.length) {\n windows.shift()!.complete();\n }\n subscriber.complete();\n },\n handleError,\n () => {\n // Add this finalization so that all window subjects are\n // disposed of. This way, if a user tries to subscribe\n // to a window *after* the outer subscription has been unsubscribed,\n // they will get an error, instead of waiting forever to\n // see if a value arrives.\n while (0 < windows.length) {\n windows.shift()!.unsubscribe();\n }\n }\n )\n );\n });\n}\n","import { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Branch out the source Observable values as a nested Observable using a\n * factory function of closing Observables to determine when to start a new\n * window.\n *\n * <span class=\"informal\">It's like {@link bufferWhen}, but emits a nested\n * Observable instead of an array.</span>\n *\n * \n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping windows.\n * It emits the current window and opens a new one whenever the Observable\n * produced by the specified `closingSelector` function emits an item. The first\n * window is opened immediately when subscribing to the output Observable.\n *\n * ## Example\n *\n * Emit only the first two clicks events in every window of [1-5] random seconds\n *\n * ```ts\n * import { fromEvent, windowWhen, interval, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowWhen(() => interval(1000 + Math.random() * 4000)),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link bufferWhen}\n *\n * @param closingSelector A function that takes no arguments and returns an\n * {@link ObservableInput} (that gets converted to Observable) that signals\n * (on either `next` or `complete`) when to close the previous window and\n * start a new one.\n * @return A function that returns an Observable of windows, which in turn are\n * Observables.\n */\nexport function windowWhen<T>(closingSelector: () => ObservableInput<any>): OperatorFunction<T, Observable<T>> {\n return operate((source, subscriber) => {\n let window: Subject<T> | null;\n let closingSubscriber: Subscriber<any> | undefined;\n\n /**\n * When we get an error, we have to notify both the\n * destination subscriber and the window.\n */\n const handleError = (err: any) => {\n window!.error(err);\n subscriber.error(err);\n };\n\n /**\n * Called every time we need to open a window.\n * Recursive, as it will start the closing notifier, which\n * inevitably *should* call openWindow -- but may not if\n * it is a \"never\" observable.\n */\n const openWindow = () => {\n // We need to clean up our closing subscription,\n // we only cared about the first next or complete notification.\n closingSubscriber?.unsubscribe();\n\n // Close our window before starting a new one.\n window?.complete();\n\n // Start the new window.\n window = new Subject<T>();\n subscriber.next(window.asObservable());\n\n // Get our closing notifier.\n let closingNotifier: Observable<any>;\n try {\n closingNotifier = innerFrom(closingSelector());\n } catch (err) {\n handleError(err);\n return;\n }\n\n // Subscribe to the closing notifier, be sure\n // to capture the subscriber (aka Subscription)\n // so we can clean it up when we close the window\n // and open a new one.\n closingNotifier.subscribe((closingSubscriber = createOperatorSubscriber(subscriber, openWindow, openWindow, handleError)));\n };\n\n // Start the first window.\n openWindow();\n\n // Subscribe to the source\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => window!.next(value),\n () => {\n // The source completed, close the window and complete.\n window!.complete();\n subscriber.complete();\n },\n handleError,\n () => {\n // Be sure to clean up our closing subscription\n // when this tears down.\n closingSubscriber?.unsubscribe();\n window = null!;\n }\n )\n );\n });\n}\n","import { OperatorFunction, ObservableInputTuple } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { identity } from '../util/identity';\nimport { noop } from '../util/noop';\nimport { popResultSelector } from '../util/args';\n\nexport function withLatestFrom<T, O extends unknown[]>(...inputs: [...ObservableInputTuple<O>]): OperatorFunction<T, [T, ...O]>;\n\nexport function withLatestFrom<T, O extends unknown[], R>(\n ...inputs: [...ObservableInputTuple<O>, (...value: [T, ...O]) => R]\n): OperatorFunction<T, R>;\n\n/**\n * Combines the source Observable with other Observables to create an Observable\n * whose values are calculated from the latest values of each, only when the\n * source emits.\n *\n * <span class=\"informal\">Whenever the source Observable emits a value, it\n * computes a formula using that value plus the latest values from other input\n * Observables, then emits the output of that formula.</span>\n *\n * \n *\n * `withLatestFrom` combines each value from the source Observable (the\n * instance) with the latest values from the other input Observables only when\n * the source emits a value, optionally using a `project` function to determine\n * the value to be emitted on the output Observable. All input Observables must\n * emit at least one value before the output Observable will emit a value.\n *\n * ## Example\n *\n * On every click event, emit an array with the latest timer event plus the click event\n *\n * ```ts\n * import { fromEvent, interval, withLatestFrom } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const result = clicks.pipe(withLatestFrom(timer));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n *\n * @param inputs An input Observable to combine with the source Observable. More\n * than one input Observables may be given as argument. If the last parameter is\n * a function, it will be used as a projection function for combining values\n * together. When the function is called, it receives all values in order of the\n * Observables passed, where the first parameter is a value from the source\n * Observable. (e.g.\n * `a.pipe(withLatestFrom(b, c), map(([a1, b1, c1]) => a1 + b1 + c1))`). If this\n * is not passed, arrays will be emitted on the output Observable.\n * @return A function that returns an Observable of projected values from the\n * most recent values from each input Observable, or an array of the most\n * recent values from each input Observable.\n */\nexport function withLatestFrom<T, R>(...inputs: any[]): OperatorFunction<T, R | any[]> {\n const project = popResultSelector(inputs) as ((...args: any[]) => R) | undefined;\n\n return operate((source, subscriber) => {\n const len = inputs.length;\n const otherValues = new Array(len);\n // An array of whether or not the other sources have emitted. Matched with them by index.\n // TODO: At somepoint, we should investigate the performance implications here, and look\n // into using a `Set()` and checking the `size` to see if we're ready.\n let hasValue = inputs.map(() => false);\n // Flipped true when we have at least one value from all other sources and\n // we are ready to start emitting values.\n let ready = false;\n\n // Other sources. Note that here we are not checking `subscriber.closed`,\n // this causes all inputs to be subscribed to, even if nothing can be emitted\n // from them. This is an important distinction because subscription constitutes\n // a side-effect.\n for (let i = 0; i < len; i++) {\n innerFrom(inputs[i]).subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n otherValues[i] = value;\n if (!ready && !hasValue[i]) {\n // If we're not ready yet, flag to show this observable has emitted.\n hasValue[i] = true;\n // Intentionally terse code.\n // If all of our other observables have emitted, set `ready` to `true`,\n // so we know we can start emitting values, then clean up the `hasValue` array,\n // because we don't need it anymore.\n (ready = hasValue.every(identity)) && (hasValue = null!);\n }\n },\n // Completing one of the other sources has\n // no bearing on the completion of our result.\n noop\n )\n );\n }\n\n // Source subscription\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n if (ready) {\n // We have at least one value from the other sources. Go ahead and emit.\n const values = [value, ...otherValues];\n subscriber.next(project ? project(...values) : values);\n }\n })\n );\n });\n}\n","import { OperatorFunction, ObservableInput } from '../types';\nimport { zip } from '../observable/zip';\nimport { joinAllInternals } from './joinAllInternals';\n\n/**\n * Collects all observable inner sources from the source, once the source completes,\n * it will subscribe to all inner sources, combining their values by index and emitting\n * them.\n *\n * @see {@link zipWith}\n * @see {@link zip}\n */\nexport function zipAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;\nexport function zipAll<T>(): OperatorFunction<any, T[]>;\nexport function zipAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;\nexport function zipAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;\n\nexport function zipAll<T, R>(project?: (...values: T[]) => R) {\n return joinAllInternals(zip, project);\n}\n","import { zip as zipStatic } from '../observable/zip';\nimport { ObservableInput, ObservableInputTuple, OperatorFunction, Cons } from '../types';\nimport { operate } from '../util/lift';\n\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[]>(otherInputs: [...ObservableInputTuple<A>]): OperatorFunction<T, Cons<T, A>>;\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[], R>(\n otherInputsAndProject: [...ObservableInputTuple<A>],\n project: (...values: Cons<T, A>) => R\n): OperatorFunction<T, R>;\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[]>(...otherInputs: [...ObservableInputTuple<A>]): OperatorFunction<T, Cons<T, A>>;\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[], R>(\n ...otherInputsAndProject: [...ObservableInputTuple<A>, (...values: Cons<T, A>) => R]\n): OperatorFunction<T, R>;\n\n/**\n * @deprecated Replaced with {@link zipWith}. Will be removed in v8.\n */\nexport function zip<T, R>(...sources: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): OperatorFunction<T, any> {\n return operate((source, subscriber) => {\n zipStatic(source as ObservableInput<any>, ...(sources as Array<ObservableInput<any>>)).subscribe(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction, Cons } from '../types';\nimport { zip } from './zip';\n\n/**\n * Subscribes to the source, and the observable inputs provided as arguments, and combines their values, by index, into arrays.\n *\n * What is meant by \"combine by index\": The first value from each will be made into a single array, then emitted,\n * then the second value from each will be combined into a single array and emitted, then the third value\n * from each will be combined into a single array and emitted, and so on.\n *\n * This will continue until it is no longer able to combine values of the same index into an array.\n *\n * After the last value from any one completed source is emitted in an array, the resulting observable will complete,\n * as there is no way to continue \"zipping\" values together by index.\n *\n * Use-cases for this operator are limited. There are memory concerns if one of the streams is emitting\n * values at a much faster rate than the others. Usage should likely be limited to streams that emit\n * at a similar pace, or finite streams of known length.\n *\n * In many cases, authors want `combineLatestWith` and not `zipWith`.\n *\n * @param otherInputs other observable inputs to collate values from.\n * @return A function that returns an Observable that emits items by index\n * combined from the source Observable and provided Observables, in form of an\n * array.\n */\nexport function zipWith<T, A extends readonly unknown[]>(...otherInputs: [...ObservableInputTuple<A>]): OperatorFunction<T, Cons<T, A>> {\n return zip(...otherInputs);\n}\n","//////////////////////////////////////////////////////////\n// Here we need to reference our other deep imports\n// so VS code will figure out where they are\n// see conversation here:\n// https://github.com/microsoft/TypeScript/issues/43034\n//////////////////////////////////////////////////////////\n\n// tslint:disable: no-reference\n// It's tempting to add references to all of the deep-import locations, but\n// adding references to those that require DOM types breaks Node projects.\n/// <reference path=\"./operators/index.ts\" />\n/// <reference path=\"./testing/index.ts\" />\n// tslint:enable: no-reference\n\n/* Observable */\nexport { Observable } from './internal/Observable';\nexport { ConnectableObservable } from './internal/observable/ConnectableObservable';\nexport { GroupedObservable } from './internal/operators/groupBy';\nexport { Operator } from './internal/Operator';\nexport { observable } from './internal/symbol/observable';\nexport { animationFrames } from './internal/observable/dom/animationFrames';\n\n/* Subjects */\nexport { Subject } from './internal/Subject';\nexport { BehaviorSubject } from './internal/BehaviorSubject';\nexport { ReplaySubject } from './internal/ReplaySubject';\nexport { AsyncSubject } from './internal/AsyncSubject';\n\n/* Schedulers */\nexport { asap, asapScheduler } from './internal/scheduler/asap';\nexport { async, asyncScheduler } from './internal/scheduler/async';\nexport { queue, queueScheduler } from './internal/scheduler/queue';\nexport { animationFrame, animationFrameScheduler } from './internal/scheduler/animationFrame';\nexport { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/VirtualTimeScheduler';\nexport { Scheduler } from './internal/Scheduler';\n\n/* Subscription */\nexport { Subscription } from './internal/Subscription';\nexport { Subscriber } from './internal/Subscriber';\n\n/* Notification */\nexport { Notification, NotificationKind } from './internal/Notification';\n\n/* Utils */\nexport { pipe } from './internal/util/pipe';\nexport { noop } from './internal/util/noop';\nexport { identity } from './internal/util/identity';\nexport { isObservable } from './internal/util/isObservable';\n\n/* Promise Conversion */\nexport { lastValueFrom } from './internal/lastValueFrom';\nexport { firstValueFrom } from './internal/firstValueFrom';\n\n/* Error types */\nexport { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';\nexport { EmptyError } from './internal/util/EmptyError';\nexport { NotFoundError } from './internal/util/NotFoundError';\nexport { ObjectUnsubscribedError } from './internal/util/ObjectUnsubscribedError';\nexport { SequenceError } from './internal/util/SequenceError';\nexport { TimeoutError } from './internal/operators/timeout';\nexport { UnsubscriptionError } from './internal/util/UnsubscriptionError';\n\n/* Static observable creation exports */\nexport { bindCallback } from './internal/observable/bindCallback';\nexport { bindNodeCallback } from './internal/observable/bindNodeCallback';\nexport { combineLatest } from './internal/observable/combineLatest';\nexport { concat } from './internal/observable/concat';\nexport { connectable } from './internal/observable/connectable';\nexport { defer } from './internal/observable/defer';\nexport { empty } from './internal/observable/empty';\nexport { forkJoin } from './internal/observable/forkJoin';\nexport { from } from './internal/observable/from';\nexport { fromEvent } from './internal/observable/fromEvent';\nexport { fromEventPattern } from './internal/observable/fromEventPattern';\nexport { generate } from './internal/observable/generate';\nexport { iif } from './internal/observable/iif';\nexport { interval } from './internal/observable/interval';\nexport { merge } from './internal/observable/merge';\nexport { never } from './internal/observable/never';\nexport { of } from './internal/observable/of';\nexport { onErrorResumeNext } from './internal/observable/onErrorResumeNext';\nexport { pairs } from './internal/observable/pairs';\nexport { partition } from './internal/observable/partition';\nexport { race } from './internal/observable/race';\nexport { range } from './internal/observable/range';\nexport { throwError } from './internal/observable/throwError';\nexport { timer } from './internal/observable/timer';\nexport { using } from './internal/observable/using';\nexport { zip } from './internal/observable/zip';\nexport { scheduled } from './internal/scheduled/scheduled';\n\n/* Constants */\nexport { EMPTY } from './internal/observable/empty';\nexport { NEVER } from './internal/observable/never';\n\n/* Types */\nexport * from './internal/types';\n\n/* Config */\nexport { config, GlobalConfig } from './internal/config';\n\n/* Operators */\nexport { audit } from './internal/operators/audit';\nexport { auditTime } from './internal/operators/auditTime';\nexport { buffer } from './internal/operators/buffer';\nexport { bufferCount } from './internal/operators/bufferCount';\nexport { bufferTime } from './internal/operators/bufferTime';\nexport { bufferToggle } from './internal/operators/bufferToggle';\nexport { bufferWhen } from './internal/operators/bufferWhen';\nexport { catchError } from './internal/operators/catchError';\nexport { combineAll } from './internal/operators/combineAll';\nexport { combineLatestAll } from './internal/operators/combineLatestAll';\nexport { combineLatestWith } from './internal/operators/combineLatestWith';\nexport { concatAll } from './internal/operators/concatAll';\nexport { concatMap } from './internal/operators/concatMap';\nexport { concatMapTo } from './internal/operators/concatMapTo';\nexport { concatWith } from './internal/operators/concatWith';\nexport { connect, ConnectConfig } from './internal/operators/connect';\nexport { count } from './internal/operators/count';\nexport { debounce } from './internal/operators/debounce';\nexport { debounceTime } from './internal/operators/debounceTime';\nexport { defaultIfEmpty } from './internal/operators/defaultIfEmpty';\nexport { delay } from './internal/operators/delay';\nexport { delayWhen } from './internal/operators/delayWhen';\nexport { dematerialize } from './internal/operators/dematerialize';\nexport { distinct } from './internal/operators/distinct';\nexport { distinctUntilChanged } from './internal/operators/distinctUntilChanged';\nexport { distinctUntilKeyChanged } from './internal/operators/distinctUntilKeyChanged';\nexport { elementAt } from './internal/operators/elementAt';\nexport { endWith } from './internal/operators/endWith';\nexport { every } from './internal/operators/every';\nexport { exhaust } from './internal/operators/exhaust';\nexport { exhaustAll } from './internal/operators/exhaustAll';\nexport { exhaustMap } from './internal/operators/exhaustMap';\nexport { expand } from './internal/operators/expand';\nexport { filter } from './internal/operators/filter';\nexport { finalize } from './internal/operators/finalize';\nexport { find } from './internal/operators/find';\nexport { findIndex } from './internal/operators/findIndex';\nexport { first } from './internal/operators/first';\nexport { groupBy, BasicGroupByOptions, GroupByOptionsWithElement } from './internal/operators/groupBy';\nexport { ignoreElements } from './internal/operators/ignoreElements';\nexport { isEmpty } from './internal/operators/isEmpty';\nexport { last } from './internal/operators/last';\nexport { map } from './internal/operators/map';\nexport { mapTo } from './internal/operators/mapTo';\nexport { materialize } from './internal/operators/materialize';\nexport { max } from './internal/operators/max';\nexport { mergeAll } from './internal/operators/mergeAll';\nexport { flatMap } from './internal/operators/flatMap';\nexport { mergeMap } from './internal/operators/mergeMap';\nexport { mergeMapTo } from './internal/operators/mergeMapTo';\nexport { mergeScan } from './internal/operators/mergeScan';\nexport { mergeWith } from './internal/operators/mergeWith';\nexport { min } from './internal/operators/min';\nexport { multicast } from './internal/operators/multicast';\nexport { observeOn } from './internal/operators/observeOn';\nexport { onErrorResumeNextWith } from './internal/operators/onErrorResumeNextWith';\nexport { pairwise } from './internal/operators/pairwise';\nexport { pluck } from './internal/operators/pluck';\nexport { publish } from './internal/operators/publish';\nexport { publishBehavior } from './internal/operators/publishBehavior';\nexport { publishLast } from './internal/operators/publishLast';\nexport { publishReplay } from './internal/operators/publishReplay';\nexport { raceWith } from './internal/operators/raceWith';\nexport { reduce } from './internal/operators/reduce';\nexport { repeat, RepeatConfig } from './internal/operators/repeat';\nexport { repeatWhen } from './internal/operators/repeatWhen';\nexport { retry, RetryConfig } from './internal/operators/retry';\nexport { retryWhen } from './internal/operators/retryWhen';\nexport { refCount } from './internal/operators/refCount';\nexport { sample } from './internal/operators/sample';\nexport { sampleTime } from './internal/operators/sampleTime';\nexport { scan } from './internal/operators/scan';\nexport { sequenceEqual } from './internal/operators/sequenceEqual';\nexport { share, ShareConfig } from './internal/operators/share';\nexport { shareReplay, ShareReplayConfig } from './internal/operators/shareReplay';\nexport { single } from './internal/operators/single';\nexport { skip } from './internal/operators/skip';\nexport { skipLast } from './internal/operators/skipLast';\nexport { skipUntil } from './internal/operators/skipUntil';\nexport { skipWhile } from './internal/operators/skipWhile';\nexport { startWith } from './internal/operators/startWith';\nexport { subscribeOn } from './internal/operators/subscribeOn';\nexport { switchAll } from './internal/operators/switchAll';\nexport { switchMap } from './internal/operators/switchMap';\nexport { switchMapTo } from './internal/operators/switchMapTo';\nexport { switchScan } from './internal/operators/switchScan';\nexport { take } from './internal/operators/take';\nexport { takeLast } from './internal/operators/takeLast';\nexport { takeUntil } from './internal/operators/takeUntil';\nexport { takeWhile } from './internal/operators/takeWhile';\nexport { tap, TapObserver } from './internal/operators/tap';\nexport { throttle, ThrottleConfig } from './internal/operators/throttle';\nexport { throttleTime } from './internal/operators/throttleTime';\nexport { throwIfEmpty } from './internal/operators/throwIfEmpty';\nexport { timeInterval } from './internal/operators/timeInterval';\nexport { timeout, TimeoutConfig, TimeoutInfo } from './internal/operators/timeout';\nexport { timeoutWith } from './internal/operators/timeoutWith';\nexport { timestamp } from './internal/operators/timestamp';\nexport { toArray } from './internal/operators/toArray';\nexport { window } from './internal/operators/window';\nexport { windowCount } from './internal/operators/windowCount';\nexport { windowTime } from './internal/operators/windowTime';\nexport { windowToggle } from './internal/operators/windowToggle';\nexport { windowWhen } from './internal/operators/windowWhen';\nexport { withLatestFrom } from './internal/operators/withLatestFrom';\nexport { zipAll } from './internal/operators/zipAll';\nexport { zipWith } from './internal/operators/zipWith';\n","import { ApitallyConsumer } from \"./types.js\";\n\nexport const consumerFromStringOrObject = (\n consumer: ApitallyConsumer | string,\n) => {\n if (typeof consumer === \"string\") {\n consumer = String(consumer).trim().substring(0, 128);\n return consumer ? { identifier: consumer } : null;\n } else {\n consumer.identifier = String(consumer.identifier).trim().substring(0, 128);\n consumer.name = consumer.name?.trim().substring(0, 64);\n consumer.group = consumer.group?.trim().substring(0, 64);\n return consumer.identifier ? consumer : null;\n }\n};\n\nexport default class ConsumerRegistry {\n private consumers: Map<string, ApitallyConsumer>;\n private updated: Set<string>;\n\n constructor() {\n this.consumers = new Map();\n this.updated = new Set();\n }\n\n public addOrUpdateConsumer(consumer?: ApitallyConsumer | null) {\n if (!consumer || (!consumer.name && !consumer.group)) {\n return;\n }\n const existing = this.consumers.get(consumer.identifier);\n if (!existing) {\n this.consumers.set(consumer.identifier, consumer);\n this.updated.add(consumer.identifier);\n } else {\n if (consumer.name && consumer.name !== existing.name) {\n existing.name = consumer.name;\n this.updated.add(consumer.identifier);\n }\n if (consumer.group && consumer.group !== existing.group) {\n existing.group = consumer.group;\n this.updated.add(consumer.identifier);\n }\n }\n }\n\n public getAndResetUpdatedConsumers() {\n const data: Array<ApitallyConsumer> = [];\n this.updated.forEach((identifier) => {\n const consumer = this.consumers.get(identifier);\n if (consumer) {\n data.push(consumer);\n }\n });\n this.updated.clear();\n return data;\n }\n}\n","import { createLogger, format, transports } from \"winston\";\n\nexport interface Logger {\n debug: (message: string, meta?: object) => void;\n info: (message: string, meta?: object) => void;\n warn: (message: string, meta?: object) => void;\n error: (message: string, meta?: object) => void;\n}\n\nexport function getLogger() {\n return createLogger({\n level: process.env.APITALLY_DEBUG ? \"debug\" : \"warn\",\n format: format.combine(\n format.colorize(),\n format.timestamp(),\n format.printf(\n (info) => `${info.timestamp} ${info.level}: ${info.message}`,\n ),\n ),\n transports: [new transports.Console()],\n });\n}\n","export function isValidClientId(clientId: string): boolean {\n const regexExp =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n return regexExp.test(clientId);\n}\n\nexport function isValidEnv(env: string): boolean {\n const regexExp = /^[\\w-]{1,32}$/;\n return regexExp.test(env);\n}\n","import { RequestInfo, RequestsItem } from \"./types.js\";\n\nexport default class RequestCounter {\n private requestCounts: Map<string, number>;\n private requestSizeSums: Map<string, number>;\n private responseSizeSums: Map<string, number>;\n private responseTimes: Map<string, Map<number, number>>;\n private requestSizes: Map<string, Map<number, number>>;\n private responseSizes: Map<string, Map<number, number>>;\n\n constructor() {\n this.requestCounts = new Map<string, number>();\n this.requestSizeSums = new Map<string, number>();\n this.responseSizeSums = new Map<string, number>();\n this.responseTimes = new Map<string, Map<number, number>>();\n this.requestSizes = new Map<string, Map<number, number>>();\n this.responseSizes = new Map<string, Map<number, number>>();\n }\n\n private getKey(requestInfo: RequestInfo) {\n return [\n requestInfo.consumer || \"\",\n requestInfo.method.toUpperCase(),\n requestInfo.path,\n requestInfo.statusCode,\n ].join(\"|\");\n }\n\n addRequest(requestInfo: RequestInfo) {\n const key = this.getKey(requestInfo);\n\n // Increment request count\n this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);\n\n // Add response time\n if (!this.responseTimes.has(key)) {\n this.responseTimes.set(key, new Map<number, number>());\n }\n const responseTimeMap = this.responseTimes.get(key)!;\n const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10; // Rounded to nearest 10ms\n responseTimeMap.set(\n responseTimeMsBin,\n (responseTimeMap.get(responseTimeMsBin) || 0) + 1,\n );\n\n // Add request size\n if (requestInfo.requestSize !== undefined) {\n requestInfo.requestSize = Number(requestInfo.requestSize);\n this.requestSizeSums.set(\n key,\n (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize,\n );\n if (!this.requestSizes.has(key)) {\n this.requestSizes.set(key, new Map<number, number>());\n }\n const requestSizeMap = this.requestSizes.get(key)!;\n const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1000); // Rounded down to nearest KB\n requestSizeMap.set(\n requestSizeKbBin,\n (requestSizeMap.get(requestSizeKbBin) || 0) + 1,\n );\n }\n\n // Add response size\n if (requestInfo.responseSize !== undefined) {\n requestInfo.responseSize = Number(requestInfo.responseSize);\n this.responseSizeSums.set(\n key,\n (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize,\n );\n if (!this.responseSizes.has(key)) {\n this.responseSizes.set(key, new Map<number, number>());\n }\n const responseSizeMap = this.responseSizes.get(key)!;\n const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1000); // Rounded down to nearest KB\n responseSizeMap.set(\n responseSizeKbBin,\n (responseSizeMap.get(responseSizeKbBin) || 0) + 1,\n );\n }\n }\n\n getAndResetRequests() {\n const data: Array<RequestsItem> = [];\n this.requestCounts.forEach((count, key) => {\n const [consumer, method, path, statusCodeStr] = key.split(\"|\");\n const responseTimes =\n this.responseTimes.get(key) || new Map<number, number>();\n const requestSizes =\n this.requestSizes.get(key) || new Map<number, number>();\n const responseSizes =\n this.responseSizes.get(key) || new Map<number, number>();\n data.push({\n consumer: consumer || null,\n method,\n path,\n status_code: parseInt(statusCodeStr),\n request_count: count,\n request_size_sum: this.requestSizeSums.get(key) || 0,\n response_size_sum: this.responseSizeSums.get(key) || 0,\n response_times: Object.fromEntries(responseTimes),\n request_sizes: Object.fromEntries(requestSizes),\n response_sizes: Object.fromEntries(responseSizes),\n });\n });\n\n // Reset the counts and times\n this.requestCounts.clear();\n this.requestSizeSums.clear();\n this.responseSizeSums.clear();\n this.responseTimes.clear();\n this.requestSizes.clear();\n this.responseSizes.clear();\n\n return data;\n }\n}\n","import type * as Sentry from \"@sentry/node\";\n\nlet sentry: typeof Sentry | undefined;\n\n// Initialize Sentry when the module is loaded\n(async () => {\n try {\n sentry = await import(\"@sentry/node\");\n } catch (e) {\n // Sentry SDK is not installed, ignore\n }\n})();\n\n/**\n * Returns the last Sentry event ID if available\n */\nexport function getSentryEventId(): string | undefined {\n if (sentry && sentry.lastEventId) {\n return sentry.lastEventId();\n }\n return undefined;\n}\n","import { createHash } from \"node:crypto\";\n\nimport { getSentryEventId } from \"./sentry.js\";\nimport { ConsumerMethodPath, ServerError, ServerErrorsItem } from \"./types.js\";\n\nconst MAX_MSG_LENGTH = 2048;\nconst MAX_STACKTRACE_LENGTH = 65536;\n\nexport default class ServerErrorCounter {\n private errorCounts: Map<string, number>;\n private errorDetails: Map<string, ConsumerMethodPath & ServerError>;\n private sentryEventIds: Map<string, string>;\n\n constructor() {\n this.errorCounts = new Map();\n this.errorDetails = new Map();\n this.sentryEventIds = new Map();\n }\n\n public addServerError(serverError: ConsumerMethodPath & ServerError) {\n const key = this.getKey(serverError);\n if (!this.errorDetails.has(key)) {\n this.errorDetails.set(key, serverError);\n }\n this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);\n\n const sentryEventId = getSentryEventId();\n if (sentryEventId) {\n this.sentryEventIds.set(key, sentryEventId);\n }\n }\n\n public getAndResetServerErrors() {\n const data: Array<ServerErrorsItem> = [];\n this.errorCounts.forEach((count, key) => {\n const serverError = this.errorDetails.get(key);\n if (serverError) {\n data.push({\n consumer: serverError.consumer || null,\n method: serverError.method,\n path: serverError.path,\n type: serverError.type,\n msg: truncateExceptionMessage(serverError.msg),\n traceback: truncateExceptionStackTrace(serverError.traceback),\n sentry_event_id: this.sentryEventIds.get(key) || null,\n error_count: count,\n });\n }\n });\n this.errorCounts.clear();\n this.errorDetails.clear();\n this.sentryEventIds.clear();\n return data;\n }\n\n private getKey(serverError: ConsumerMethodPath & ServerError) {\n const hashInput = [\n serverError.consumer || \"\",\n serverError.method.toUpperCase(),\n serverError.path,\n serverError.type,\n serverError.msg.trim(),\n serverError.traceback.trim(),\n ].join(\"|\");\n return createHash(\"md5\").update(hashInput).digest(\"hex\");\n }\n}\n\nexport function truncateExceptionMessage(msg: string) {\n if (msg.length <= MAX_MSG_LENGTH) {\n return msg;\n }\n const suffix = \"... (truncated)\";\n const cutoff = MAX_MSG_LENGTH - suffix.length;\n return msg.substring(0, cutoff) + suffix;\n}\n\nexport function truncateExceptionStackTrace(stack: string) {\n const suffix = \"... (truncated) ...\";\n const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;\n const lines = stack.trim().split(\"\\n\");\n const truncatedLines: string[] = [];\n let length = 0;\n for (const line of lines) {\n if (length + line.length + 1 > cutoff) {\n truncatedLines.push(suffix);\n break;\n }\n truncatedLines.push(line);\n length += line.length + 1;\n }\n return truncatedLines.join(\"\\n\");\n}\n","import { Buffer } from \"node:buffer\";\nimport { randomUUID } from \"node:crypto\";\nimport { createWriteStream, readFile, WriteStream } from \"node:fs\";\nimport { unlink } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { createGzip, Gzip } from \"node:zlib\";\n\nexport default class TempGzipFile {\n public uuid: string;\n private filePath: string;\n private gzip: Gzip;\n private writeStream: WriteStream;\n private readyPromise: Promise<void>;\n private closedPromise: Promise<void>;\n\n constructor() {\n this.uuid = randomUUID();\n this.filePath = join(tmpdir(), `apitally-${this.uuid}.gz`);\n this.writeStream = createWriteStream(this.filePath);\n this.readyPromise = new Promise<void>((resolve, reject) => {\n this.writeStream.once(\"ready\", resolve);\n this.writeStream.once(\"error\", reject);\n });\n this.closedPromise = new Promise<void>((resolve, reject) => {\n this.writeStream.once(\"close\", resolve);\n this.writeStream.once(\"error\", reject);\n });\n this.gzip = createGzip();\n this.gzip.pipe(this.writeStream);\n }\n\n get size() {\n return this.writeStream.bytesWritten;\n }\n\n async writeLine(data: Buffer) {\n await this.readyPromise;\n return new Promise<void>((resolve, reject) => {\n this.gzip.write(Buffer.concat([data, Buffer.from(\"\\n\")]), (error) => {\n if (error) {\n reject(error);\n } else {\n resolve();\n }\n });\n });\n }\n\n async getContent() {\n return new Promise<Buffer>((resolve, reject) => {\n readFile(this.filePath, (error, data) => {\n if (error) {\n reject(error);\n } else {\n resolve(data);\n }\n });\n });\n }\n\n async close() {\n await new Promise<void>((resolve) => {\n this.gzip.end(() => {\n resolve();\n });\n });\n await this.closedPromise;\n }\n\n async delete() {\n await this.close();\n await unlink(this.filePath);\n }\n}\n","import AsyncLock from \"async-lock\";\nimport { Buffer } from \"node:buffer\";\nimport { randomUUID } from \"node:crypto\";\nimport { unlinkSync, writeFileSync } from \"node:fs\";\nimport { IncomingHttpHeaders, OutgoingHttpHeaders } from \"node:http\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { getSentryEventId } from \"./sentry.js\";\nimport {\n truncateExceptionMessage,\n truncateExceptionStackTrace,\n} from \"./serverErrorCounter.js\";\nimport TempGzipFile from \"./tempGzipFile.js\";\n\nconst MAX_BODY_SIZE = 50_000; // 50 KB (uncompressed)\nconst MAX_FILE_SIZE = 1_000_000; // 1 MB (compressed)\nconst MAX_FILES = 50;\nconst MAX_PENDING_WRITES = 100;\nconst MAX_LOG_MSG_LENGTH = 2048;\nconst BODY_TOO_LARGE = Buffer.from(\"<body too large>\");\nconst BODY_MASKED = Buffer.from(\"<masked>\");\nconst MASKED = \"******\";\nconst ALLOWED_CONTENT_TYPES = [\n \"application/json\",\n \"application/problem+json\",\n \"application/vnd.api+json\",\n \"text/plain\",\n];\nconst EXCLUDE_PATH_PATTERNS = [\n /\\/_?healthz?$/i,\n /\\/_?health[_-]?checks?$/i,\n /\\/_?heart[_-]?beats?$/i,\n /\\/ping$/i,\n /\\/ready$/i,\n /\\/live$/i,\n];\nconst EXCLUDE_USER_AGENT_PATTERNS = [\n /health[-_ ]?check/i,\n /microsoft-azure-application-lb/i,\n /googlehc/i,\n /kube-probe/i,\n];\nconst MASK_QUERY_PARAM_PATTERNS = [\n /auth/i,\n /api-?key/i,\n /secret/i,\n /token/i,\n /password/i,\n /pwd/i,\n];\nconst MASK_HEADER_PATTERNS = [\n /auth/i,\n /api-?key/i,\n /secret/i,\n /token/i,\n /cookie/i,\n];\nconst MASK_BODY_FIELD_PATTERNS = [\n /password/i,\n /pwd/i,\n /token/i,\n /secret/i,\n /auth/i,\n /card[-_ ]?number/i,\n /ccv/i,\n /ssn/i,\n];\n\nexport type Request = {\n timestamp: number;\n method: string;\n path?: string;\n url: string;\n headers: [string, string][];\n size?: number;\n consumer?: string;\n body?: Buffer;\n};\n\nexport type Response = {\n statusCode: number;\n responseTime: number;\n headers: [string, string][];\n size?: number;\n body?: Buffer;\n};\n\nexport type LogRecord = {\n timestamp: number;\n logger?: string;\n level: string;\n message: string;\n};\n\nexport type RequestLoggingConfig = {\n enabled: boolean;\n logQueryParams: boolean;\n logRequestHeaders: boolean;\n logRequestBody: boolean;\n logResponseHeaders: boolean;\n logResponseBody: boolean;\n logException: boolean;\n captureLogs: boolean;\n maskQueryParams: RegExp[];\n maskHeaders: RegExp[];\n maskBodyFields: RegExp[];\n maskRequestBodyCallback?: (request: Request) => Buffer | null | undefined;\n maskResponseBodyCallback?: (\n request: Request,\n response: Response,\n ) => Buffer | null | undefined;\n excludePaths: RegExp[];\n excludeCallback?: (request: Request, response: Response) => boolean;\n};\n\nconst DEFAULT_CONFIG: RequestLoggingConfig = {\n enabled: false,\n logQueryParams: true,\n logRequestHeaders: false,\n logRequestBody: false,\n logResponseHeaders: true,\n logResponseBody: false,\n logException: true,\n captureLogs: false,\n maskQueryParams: [],\n maskHeaders: [],\n maskBodyFields: [],\n excludePaths: [],\n};\n\ntype RequestLogItem = {\n uuid: string;\n request: Request;\n response: Response;\n exception?: {\n type: string;\n message: string;\n stacktrace: string;\n sentryEventId?: string;\n };\n logs?: LogRecord[];\n};\n\nexport default class RequestLogger {\n public config: RequestLoggingConfig;\n public enabled: boolean;\n public suspendUntil: number | null = null;\n private pendingWrites: RequestLogItem[] = [];\n private currentFile: TempGzipFile | null = null;\n private files: TempGzipFile[] = [];\n private maintainIntervalId?: NodeJS.Timeout;\n private lock = new AsyncLock();\n\n constructor(config?: Partial<RequestLoggingConfig>) {\n this.config = { ...DEFAULT_CONFIG, ...config };\n this.enabled = this.config.enabled && checkWritableFs();\n\n if (this.enabled) {\n this.maintainIntervalId = setInterval(() => {\n this.maintain();\n }, 1000);\n }\n }\n\n get maxBodySize() {\n return MAX_BODY_SIZE;\n }\n\n private shouldExcludePath(urlPath: string) {\n const patterns = [...this.config.excludePaths, ...EXCLUDE_PATH_PATTERNS];\n return matchPatterns(urlPath, patterns);\n }\n\n private shouldExcludeUserAgent(userAgent?: string) {\n return userAgent\n ? matchPatterns(userAgent, EXCLUDE_USER_AGENT_PATTERNS)\n : false;\n }\n\n private shouldMaskQueryParam(name: string) {\n const patterns = [\n ...this.config.maskQueryParams,\n ...MASK_QUERY_PARAM_PATTERNS,\n ];\n return matchPatterns(name, patterns);\n }\n\n private shouldMaskHeader(name: string) {\n const patterns = [...this.config.maskHeaders, ...MASK_HEADER_PATTERNS];\n return matchPatterns(name, patterns);\n }\n\n private shouldMaskBodyField(name: string) {\n const patterns = [\n ...this.config.maskBodyFields,\n ...MASK_BODY_FIELD_PATTERNS,\n ];\n return matchPatterns(name, patterns);\n }\n\n private hasSupportedContentType(headers: [string, string][]) {\n const contentType = headers.find(\n ([k]) => k.toLowerCase() === \"content-type\",\n )?.[1];\n return this.isSupportedContentType(contentType);\n }\n\n private hasJsonContentType(headers: [string, string][]) {\n const contentType = headers.find(\n ([k]) => k.toLowerCase() === \"content-type\",\n )?.[1];\n return contentType ? /\\bjson\\b/i.test(contentType) : null;\n }\n\n public isSupportedContentType(contentType?: string | null) {\n return (\n typeof contentType === \"string\" &&\n ALLOWED_CONTENT_TYPES.some((t) => contentType.startsWith(t))\n );\n }\n\n private maskQueryParams(search: string) {\n const params = new URLSearchParams(search);\n for (const [key] of params) {\n if (this.shouldMaskQueryParam(key)) {\n params.set(key, MASKED);\n }\n }\n return params.toString();\n }\n\n private maskHeaders(headers: [string, string][]): [string, string][] {\n return headers.map(([k, v]) => [k, this.shouldMaskHeader(k) ? MASKED : v]);\n }\n\n private maskBody(data: any): any {\n if (typeof data === \"object\" && data !== null && !Array.isArray(data)) {\n const result: any = {};\n for (const [key, value] of Object.entries(data)) {\n if (typeof value === \"string\" && this.shouldMaskBodyField(key)) {\n result[key] = MASKED;\n } else {\n result[key] = this.maskBody(value);\n }\n }\n return result;\n }\n if (Array.isArray(data)) {\n return data.map((item) => this.maskBody(item));\n }\n return data;\n }\n\n private applyMasking(item: RequestLogItem) {\n // Apply user-provided maskRequestBodyCallback function\n if (\n this.config.maskRequestBodyCallback &&\n item.request.body &&\n item.request.body !== BODY_TOO_LARGE\n ) {\n try {\n const maskedBody = this.config.maskRequestBodyCallback(item.request);\n item.request.body = maskedBody ?? BODY_MASKED;\n } catch {\n item.request.body = undefined;\n }\n }\n\n // Apply user-provided maskResponseBodyCallback function\n if (\n this.config.maskResponseBodyCallback &&\n item.response.body &&\n item.response.body !== BODY_TOO_LARGE\n ) {\n try {\n const maskedBody = this.config.maskResponseBodyCallback(\n item.request,\n item.response,\n );\n item.response.body = maskedBody ?? BODY_MASKED;\n } catch {\n item.response.body = undefined;\n }\n }\n\n // Check request and response body sizes\n if (item.request.body && item.request.body.length > MAX_BODY_SIZE) {\n item.request.body = BODY_TOO_LARGE;\n }\n if (item.response.body && item.response.body.length > MAX_BODY_SIZE) {\n item.response.body = BODY_TOO_LARGE;\n }\n\n // Mask request and response body fields\n for (const key of [\"request\", \"response\"] as const) {\n const bodyData = item[key].body;\n if (\n !bodyData ||\n bodyData === BODY_TOO_LARGE ||\n bodyData === BODY_MASKED\n ) {\n continue;\n }\n\n const headers = item[key].headers;\n const hasJsonContent = this.hasJsonContentType(headers);\n if (hasJsonContent === null || hasJsonContent) {\n try {\n const parsedBody = JSON.parse(bodyData.toString());\n const maskedBody = this.maskBody(parsedBody);\n item[key].body = Buffer.from(JSON.stringify(maskedBody));\n } catch {\n // If parsing fails, leave body as is\n }\n }\n }\n\n // Mask request and response headers\n item.request.headers = this.config.logRequestHeaders\n ? this.maskHeaders(item.request.headers)\n : [];\n item.response.headers = this.config.logResponseHeaders\n ? this.maskHeaders(item.response.headers)\n : [];\n\n // Mask query params\n const url = new URL(item.request.url);\n url.search = this.config.logQueryParams\n ? this.maskQueryParams(url.search)\n : \"\";\n item.request.url = url.toString();\n\n return item;\n }\n\n logRequest(\n request: Request,\n response: Response,\n error?: Error,\n logs?: LogRecord[],\n ) {\n if (!this.enabled || this.suspendUntil !== null) return;\n\n const url = new URL(request.url);\n const path = request.path ?? url.pathname;\n const userAgent = request.headers.find(\n ([k]) => k.toLowerCase() === \"user-agent\",\n )?.[1];\n\n if (\n this.shouldExcludePath(path) ||\n this.shouldExcludeUserAgent(userAgent) ||\n (this.config.excludeCallback?.(request, response) ?? false)\n ) {\n return;\n }\n\n if (\n !this.config.logRequestBody ||\n !this.hasSupportedContentType(request.headers)\n ) {\n request.body = undefined;\n }\n if (\n !this.config.logResponseBody ||\n !this.hasSupportedContentType(response.headers)\n ) {\n response.body = undefined;\n }\n\n if (request.size !== undefined && request.size < 0) {\n request.size = undefined;\n }\n if (response.size !== undefined && response.size < 0) {\n response.size = undefined;\n }\n\n const item: RequestLogItem = {\n uuid: randomUUID(),\n request: request,\n response: response,\n exception:\n error && this.config.logException\n ? {\n type: error.name,\n message: truncateExceptionMessage(error.message),\n stacktrace: truncateExceptionStackTrace(error.stack || \"\"),\n sentryEventId: getSentryEventId(),\n }\n : undefined,\n };\n\n if (logs && logs.length > 0) {\n item.logs = logs.map((log) => ({\n timestamp: log.timestamp,\n logger: log.logger,\n level: log.level,\n message: truncateLogMessage(log.message),\n }));\n }\n this.pendingWrites.push(item);\n\n if (this.pendingWrites.length > MAX_PENDING_WRITES) {\n this.pendingWrites.shift();\n }\n }\n\n async writeToFile() {\n if (!this.enabled || this.pendingWrites.length === 0) {\n return;\n }\n return this.lock.acquire(\"file\", async () => {\n if (!this.currentFile) {\n this.currentFile = new TempGzipFile();\n }\n while (this.pendingWrites.length > 0) {\n let item = this.pendingWrites.shift();\n if (item) {\n item = this.applyMasking(item);\n\n const finalItem = {\n uuid: item.uuid,\n request: skipEmptyValues(item.request),\n response: skipEmptyValues(item.response),\n exception: item.exception,\n logs: item.logs,\n };\n\n // Set up body serialization for JSON\n [finalItem.request.body, finalItem.response.body].forEach((body) => {\n if (body) {\n // @ts-expect-error Override Buffer's default JSON serialization\n body.toJSON = function () {\n return this.toString(\"base64\");\n };\n }\n });\n\n await this.currentFile.writeLine(\n Buffer.from(JSON.stringify(finalItem)),\n );\n }\n }\n });\n }\n\n getFile() {\n return this.files.shift();\n }\n\n retryFileLater(file: TempGzipFile) {\n this.files.unshift(file);\n }\n\n async rotateFile() {\n return this.lock.acquire(\"file\", async () => {\n if (this.currentFile) {\n await this.currentFile.close();\n this.files.push(this.currentFile);\n this.currentFile = null;\n }\n });\n }\n\n async maintain() {\n await this.writeToFile();\n if (this.currentFile && this.currentFile.size > MAX_FILE_SIZE) {\n await this.rotateFile();\n }\n while (this.files.length > MAX_FILES) {\n const file = this.files.shift();\n file?.delete();\n }\n if (this.suspendUntil !== null && this.suspendUntil < Date.now()) {\n this.suspendUntil = null;\n }\n }\n\n async clear() {\n this.pendingWrites = [];\n await this.rotateFile();\n this.files.forEach((file) => {\n file.delete();\n });\n this.files = [];\n }\n\n async close() {\n this.enabled = false;\n await this.clear();\n if (this.maintainIntervalId) {\n clearInterval(this.maintainIntervalId);\n }\n }\n}\n\nexport function convertHeaders(\n headers:\n | Headers\n | IncomingHttpHeaders\n | OutgoingHttpHeaders\n | Record<string, string | string[] | number | undefined>\n | undefined,\n) {\n if (!headers) {\n return [];\n }\n if (headers instanceof Headers) {\n return Array.from(headers.entries());\n }\n return Object.entries(headers).flatMap(([key, value]) => {\n if (value === undefined) {\n return [];\n }\n if (Array.isArray(value)) {\n return value.map((v) => [key, v]);\n }\n return [[key, value.toString()]];\n }) as [string, string][];\n}\n\nexport function convertBody(body: any, contentType?: string | null) {\n if (!body || !contentType) {\n return;\n }\n try {\n if (contentType.startsWith(\"application/json\")) {\n if (isValidJsonString(body)) {\n return Buffer.from(body);\n } else {\n return Buffer.from(JSON.stringify(body));\n }\n }\n if (contentType.startsWith(\"text/\") && typeof body === \"string\") {\n return Buffer.from(body);\n }\n } catch (error) {\n return;\n }\n}\n\nfunction isValidJsonString(body: any) {\n if (typeof body !== \"string\") {\n return false;\n }\n try {\n JSON.parse(body);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction matchPatterns(value: string, patterns: RegExp[]) {\n return patterns.some((pattern) => {\n return pattern.test(value);\n });\n}\n\nfunction skipEmptyValues<T extends Record<string, any>>(data: T) {\n return Object.fromEntries(\n Object.entries(data).filter(([_, v]) => {\n if (v == null || Number.isNaN(v)) return false;\n if (Array.isArray(v) || Buffer.isBuffer(v) || typeof v === \"string\") {\n return v.length > 0;\n }\n return true;\n }),\n ) as Partial<T>;\n}\n\nfunction truncateLogMessage(msg: string) {\n if (msg.length > MAX_LOG_MSG_LENGTH) {\n const suffix = \"... (truncated)\";\n return msg.slice(0, MAX_LOG_MSG_LENGTH - suffix.length) + suffix;\n }\n return msg;\n}\n\nfunction checkWritableFs() {\n try {\n const testPath = join(tmpdir(), `apitally-${randomUUID()}`);\n writeFileSync(testPath, \"test\");\n unlinkSync(testPath);\n return true;\n } catch (error) {\n return false;\n }\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n ConsumerMethodPath,\n ValidationError,\n ValidationErrorsItem,\n} from \"./types.js\";\n\nexport default class ValidationErrorCounter {\n private errorCounts: Map<string, number>;\n private errorDetails: Map<string, ConsumerMethodPath & ValidationError>;\n\n constructor() {\n this.errorCounts = new Map();\n this.errorDetails = new Map();\n }\n\n public addValidationError(\n validationError: ConsumerMethodPath & ValidationError,\n ) {\n const key = this.getKey(validationError);\n if (!this.errorDetails.has(key)) {\n this.errorDetails.set(key, validationError);\n }\n this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);\n }\n\n public getAndResetValidationErrors() {\n const data: Array<ValidationErrorsItem> = [];\n this.errorCounts.forEach((count, key) => {\n const validationError = this.errorDetails.get(key);\n if (validationError) {\n data.push({\n consumer: validationError.consumer || null,\n method: validationError.method,\n path: validationError.path,\n loc: validationError.loc.split(\".\").filter(Boolean),\n msg: validationError.msg,\n type: validationError.type,\n error_count: count,\n });\n }\n });\n this.errorCounts.clear();\n this.errorDetails.clear();\n return data;\n }\n\n private getKey(validationError: ConsumerMethodPath & ValidationError) {\n const hashInput = [\n validationError.consumer || \"\",\n validationError.method.toUpperCase(),\n validationError.path,\n validationError.loc.split(\".\").filter(Boolean),\n validationError.msg.trim(),\n validationError.type,\n ].join(\"|\");\n return createHash(\"md5\").update(hashInput).digest(\"hex\");\n }\n}\n","import fetchRetry from \"fetch-retry\";\nimport { randomUUID } from \"node:crypto\";\n\nimport ConsumerRegistry from \"./consumerRegistry.js\";\nimport { Logger, getLogger } from \"./logging.js\";\nimport { isValidClientId, isValidEnv } from \"./paramValidation.js\";\nimport RequestCounter from \"./requestCounter.js\";\nimport RequestLogger from \"./requestLogger.js\";\nimport ServerErrorCounter from \"./serverErrorCounter.js\";\nimport {\n ApitallyConfig,\n StartupData,\n StartupPayload,\n SyncPayload,\n} from \"./types.js\";\nimport ValidationErrorCounter from \"./validationErrorCounter.js\";\n\nconst SYNC_INTERVAL = 60000; // 60 seconds\nconst INITIAL_SYNC_INTERVAL = 10000; // 10 seconds\nconst INITIAL_SYNC_INTERVAL_DURATION = 3600000; // 1 hour\nconst MAX_QUEUE_TIME = 3.6e6; // 1 hour\n\nclass HTTPError extends Error {\n public response: Response;\n\n constructor(response: Response) {\n const reason = response.status\n ? `status code ${response.status}`\n : \"an unknown error\";\n super(`Request failed with ${reason}`);\n this.response = response;\n }\n}\n\nexport class ApitallyClient {\n private clientId: string;\n private env: string;\n\n private static instance?: ApitallyClient;\n private instanceUuid: string;\n private syncDataQueue: SyncPayload[];\n private syncIntervalId?: NodeJS.Timeout;\n public startupData?: StartupData;\n private startupDataSent: boolean = false;\n private enabled: boolean = true;\n\n public requestCounter: RequestCounter;\n public requestLogger: RequestLogger;\n public validationErrorCounter: ValidationErrorCounter;\n public serverErrorCounter: ServerErrorCounter;\n public consumerRegistry: ConsumerRegistry;\n public logger: Logger;\n\n constructor({\n clientId,\n env = \"dev\",\n requestLogging,\n requestLoggingConfig,\n logger,\n }: ApitallyConfig) {\n if (ApitallyClient.instance) {\n throw new Error(\"Apitally client is already initialized\");\n }\n if (!isValidClientId(clientId)) {\n throw new Error(\n `Invalid Apitally client ID '${clientId}' (expecting hexadecimal UUID format)`,\n );\n }\n if (!isValidEnv(env)) {\n throw new Error(\n `Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`,\n );\n }\n if (requestLoggingConfig && !requestLogging) {\n console.warn(\n \"requestLoggingConfig is deprecated, use requestLogging instead.\",\n );\n }\n\n ApitallyClient.instance = this;\n this.clientId = clientId;\n this.env = env;\n this.instanceUuid = randomUUID();\n this.syncDataQueue = [];\n this.requestCounter = new RequestCounter();\n this.requestLogger = new RequestLogger(\n requestLogging ?? requestLoggingConfig,\n );\n this.validationErrorCounter = new ValidationErrorCounter();\n this.serverErrorCounter = new ServerErrorCounter();\n this.consumerRegistry = new ConsumerRegistry();\n this.logger = logger ?? getLogger();\n\n this.startSync();\n this.handleShutdown = this.handleShutdown.bind(this);\n }\n\n public static getInstance() {\n if (!ApitallyClient.instance) {\n throw new Error(\"Apitally client is not initialized\");\n }\n return ApitallyClient.instance;\n }\n\n public isEnabled() {\n return this.enabled;\n }\n\n public static async shutdown() {\n if (ApitallyClient.instance) {\n await ApitallyClient.instance.handleShutdown();\n }\n }\n\n public async handleShutdown() {\n this.enabled = false;\n this.stopSync();\n await this.sendSyncData();\n await this.sendLogData();\n await this.requestLogger.close();\n ApitallyClient.instance = undefined;\n }\n\n private getHubUrlPrefix() {\n const baseURL =\n process.env.APITALLY_HUB_BASE_URL || \"https://hub.apitally.io\";\n const version = \"v2\";\n return `${baseURL}/${version}/${this.clientId}/${this.env}/`;\n }\n\n private async sendData(url: string, payload: any) {\n const fetchWithRetry = fetchRetry(fetch, {\n retries: 3,\n retryDelay: 1000,\n retryOn: [408, 429, 500, 502, 503, 504],\n });\n const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {\n method: \"POST\",\n body: JSON.stringify(payload),\n headers: { \"Content-Type\": \"application/json\" },\n });\n if (!response.ok) {\n throw new HTTPError(response);\n }\n }\n\n private startSync() {\n this.sync();\n this.syncIntervalId = setInterval(() => {\n this.sync();\n }, INITIAL_SYNC_INTERVAL);\n setTimeout(() => {\n clearInterval(this.syncIntervalId);\n this.syncIntervalId = setInterval(() => {\n this.sync();\n }, SYNC_INTERVAL);\n }, INITIAL_SYNC_INTERVAL_DURATION);\n }\n\n private async sync() {\n try {\n const promises = [this.sendSyncData(), this.sendLogData()];\n if (!this.startupDataSent) {\n promises.push(this.sendStartupData());\n }\n await Promise.all(promises);\n } catch (error) {\n this.logger.error(\"Error while syncing with Apitally Hub\", {\n error,\n });\n }\n }\n\n private stopSync() {\n if (this.syncIntervalId) {\n clearInterval(this.syncIntervalId);\n this.syncIntervalId = undefined;\n }\n }\n\n public setStartupData(data: StartupData) {\n this.startupData = data;\n this.startupDataSent = false;\n this.sendStartupData();\n }\n\n private async sendStartupData() {\n if (this.startupData) {\n this.logger.debug(\"Sending startup data to Apitally Hub\");\n const payload: StartupPayload = {\n instance_uuid: this.instanceUuid,\n message_uuid: randomUUID(),\n ...this.startupData,\n };\n try {\n await this.sendData(\"startup\", payload);\n this.startupDataSent = true;\n } catch (error) {\n const handled = this.handleHubError(error);\n if (!handled) {\n this.logger.error((error as Error).message);\n this.logger.debug(\n \"Error while sending startup data to Apitally Hub (will retry)\",\n { error },\n );\n }\n }\n }\n }\n\n private async sendSyncData() {\n this.logger.debug(\"Synchronizing data with Apitally Hub\");\n const newPayload: SyncPayload = {\n timestamp: Date.now() / 1000,\n instance_uuid: this.instanceUuid,\n message_uuid: randomUUID(),\n requests: this.requestCounter.getAndResetRequests(),\n validation_errors:\n this.validationErrorCounter.getAndResetValidationErrors(),\n server_errors: this.serverErrorCounter.getAndResetServerErrors(),\n consumers: this.consumerRegistry.getAndResetUpdatedConsumers(),\n };\n this.syncDataQueue.push(newPayload);\n\n let i = 0;\n while (this.syncDataQueue.length > 0) {\n const payload = this.syncDataQueue.shift();\n if (payload) {\n try {\n if (Date.now() - payload.timestamp * 1000 <= MAX_QUEUE_TIME) {\n if (i > 0) {\n await this.randomDelay();\n }\n await this.sendData(\"sync\", payload);\n i += 1;\n }\n } catch (error) {\n const handled = this.handleHubError(error);\n if (!handled) {\n this.logger.debug(\n \"Error while synchronizing data with Apitally Hub (will retry)\",\n { error },\n );\n this.syncDataQueue.push(payload);\n break;\n }\n }\n }\n }\n }\n\n private async sendLogData() {\n this.logger.debug(\"Sending request log data to Apitally Hub\");\n await this.requestLogger.rotateFile();\n\n const fetchWithRetry = fetchRetry(fetch, {\n retries: 3,\n retryDelay: 1000,\n retryOn: [408, 429, 500, 502, 503, 504],\n });\n\n let i = 0;\n let logFile;\n while ((logFile = this.requestLogger.getFile())) {\n if (i > 0) {\n await this.randomDelay();\n }\n\n try {\n const response = await fetchWithRetry(\n `${this.getHubUrlPrefix()}log?uuid=${logFile.uuid}`,\n {\n method: \"POST\",\n body: (await logFile.getContent()) as any,\n },\n );\n\n if (response.status === 402 && response.headers.has(\"Retry-After\")) {\n const retryAfter = parseInt(\n response.headers.get(\"Retry-After\") ?? \"0\",\n );\n if (retryAfter > 0) {\n this.requestLogger.suspendUntil = Date.now() + retryAfter * 1000;\n this.requestLogger.clear();\n return;\n }\n }\n\n if (!response.ok) {\n throw new HTTPError(response);\n }\n\n logFile.delete();\n } catch (error) {\n this.requestLogger.retryFileLater(logFile);\n break;\n }\n\n i++;\n if (i >= 10) break;\n }\n }\n\n private handleHubError(error: unknown) {\n if (error instanceof HTTPError) {\n if (error.response.status === 404) {\n this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);\n this.enabled = false;\n this.stopSync();\n return true;\n }\n if (error.response.status === 422) {\n this.logger.error(\"Received validation error from Apitally Hub\");\n return true;\n }\n }\n return false;\n }\n\n private async randomDelay() {\n const delay = 100 + Math.random() * 400;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n}\n","import { OutgoingHttpHeader } from \"node:http\";\n\nexport function parseContentLength(\n contentLength: OutgoingHttpHeader | undefined | null,\n): number | undefined {\n if (contentLength === undefined || contentLength === null) {\n return undefined;\n }\n if (typeof contentLength === \"number\") {\n return contentLength;\n }\n if (typeof contentLength === \"string\") {\n const parsed = parseInt(contentLength);\n return isNaN(parsed) ? undefined : parsed;\n }\n if (Array.isArray(contentLength)) {\n return parseContentLength(contentLength[0]);\n }\n return undefined;\n}\n\nexport function mergeHeaders(base: Headers, merge: Headers) {\n const mergedHeaders = new Headers(base);\n for (const [name, value] of merge)\n if (name === \"set-cookie\") mergedHeaders.append(name, value);\n else mergedHeaders.set(name, value);\n return mergedHeaders;\n}\n","import { createRequire } from \"node:module\";\n\nexport function getPackageVersion(name: string): string | null {\n const packageJsonPath = `${name}/package.json`;\n try {\n return require(packageJsonPath).version || null;\n } catch (error) {\n try {\n const _require = createRequire(import.meta.url);\n return _require(packageJsonPath).version || null;\n } catch (error) {\n return null;\n }\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { format } from \"node:util\";\n\nimport type { LogRecord } from \"../common/requestLogger.js\";\n\ntype LogLevel = \"log\" | \"warn\" | \"error\" | \"info\" | \"debug\";\n\nconst MAX_BUFFER_SIZE = 1000;\n\nlet isPatched = false;\nlet globalLogsContext: AsyncLocalStorage<LogRecord[]>;\n\nexport function patchConsole(logsContext: AsyncLocalStorage<LogRecord[]>) {\n globalLogsContext = logsContext;\n\n if (isPatched) {\n return;\n }\n\n const logMethods: LogLevel[] = [\"log\", \"warn\", \"error\", \"info\", \"debug\"];\n logMethods.forEach((method) => {\n const originalMethod = console[method];\n console[method] = function (...args: any[]) {\n captureLog(method, args);\n return originalMethod.apply(console, args);\n };\n });\n\n isPatched = true;\n}\n\nfunction captureLog(level: LogLevel, args: any[]) {\n const logs = globalLogsContext?.getStore();\n if (logs && logs.length < MAX_BUFFER_SIZE) {\n logs.push({\n timestamp: Date.now() / 1000,\n logger: \"console\",\n level,\n message: format(...args),\n });\n }\n}\n","import { format } from \"node:util\";\n\nexport function formatMessage(message: any, ...args: any[]) {\n return [message, ...args]\n .map(formatArg)\n .filter((arg) => arg !== \"\")\n .join(\"\\n\");\n}\n\nexport function removeKeys(obj: any, keys: string[]) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key)),\n );\n}\n\nfunction formatArg(arg: any) {\n if (typeof arg === \"string\") {\n return arg.trim();\n }\n if (arg instanceof Error) {\n return format(arg).trim();\n }\n if (arg === undefined || arg === null || isEmptyObject(arg)) {\n return \"\";\n }\n try {\n return JSON.stringify(arg);\n } catch {\n return format(arg).trim();\n }\n}\n\nfunction isEmptyObject(obj: any) {\n return (\n obj !== null &&\n typeof obj === \"object\" &&\n Object.getPrototypeOf(obj) === Object.prototype &&\n Object.keys(obj).length === 0\n );\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { formatMessage } from \"./utils.js\";\n\ntype LogLevel = \"log\" | \"error\" | \"warn\" | \"debug\" | \"verbose\" | \"fatal\";\n\nconst MAX_BUFFER_SIZE = 1000;\n\nlet isPatched = false;\nlet globalLogsContext: AsyncLocalStorage<LogRecord[]>;\n\nexport async function patchNestLogger(\n logsContext: AsyncLocalStorage<LogRecord[]>,\n) {\n globalLogsContext = logsContext;\n\n if (isPatched) {\n return;\n }\n\n try {\n const { Logger } = await import(\"@nestjs/common\");\n const logMethods: LogLevel[] = [\n \"log\",\n \"error\",\n \"warn\",\n \"debug\",\n \"verbose\",\n \"fatal\",\n ];\n\n // Patch static methods\n logMethods.forEach((method) => {\n const originalMethod = Logger[method];\n Logger[method] = function (message: any, ...args: any[]) {\n captureLog(method, [message, ...args]);\n return originalMethod.apply(Logger, [message, ...args]);\n };\n });\n\n // Patch prototype methods to affect all instances (new and existing)\n logMethods.forEach((method) => {\n const originalMethod = Logger.prototype[method];\n Logger.prototype[method] = function (message: any, ...args: any[]) {\n captureLog(method, [message, ...args], this.context);\n return originalMethod.apply(this, [message, ...args]);\n };\n });\n\n isPatched = true;\n } catch {\n // @nestjs/common is not installed, silently ignore\n }\n}\n\nfunction captureLog(level: LogLevel, args: any[], context?: string) {\n const logs = globalLogsContext?.getStore();\n if (logs && logs.length < MAX_BUFFER_SIZE) {\n logs.push({\n timestamp: Date.now() / 1000,\n logger: context,\n level,\n message: formatMessage(args[0], ...args.slice(1)),\n });\n }\n}\n","'use strict'\n\n// **************************************************************\n// * Code initially copied/adapted from \"pony-cause\" npm module *\n// * Please upstream improvements there *\n// **************************************************************\n\nconst isErrorLike = (err) => {\n return err && typeof err.message === 'string'\n}\n\n/**\n * @param {Error|{ cause?: unknown|(()=>err)}} err\n * @returns {Error|Object|undefined}\n */\nconst getErrorCause = (err) => {\n if (!err) return\n\n /** @type {unknown} */\n // @ts-ignore\n const cause = err.cause\n\n // VError / NError style causes\n if (typeof cause === 'function') {\n // @ts-ignore\n const causeResult = err.cause()\n\n return isErrorLike(causeResult)\n ? causeResult\n : undefined\n } else {\n return isErrorLike(cause)\n ? cause\n : undefined\n }\n}\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set<Error>} seen\n * @returns {string}\n */\nconst _stackWithCauses = (err, seen) => {\n if (!isErrorLike(err)) return ''\n\n const stack = err.stack || ''\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return stack + '\\ncauses have become circular...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n return (stack + '\\ncaused by: ' + _stackWithCauses(cause, seen))\n } else {\n return stack\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst stackWithCauses = (err) => _stackWithCauses(err, new Set())\n\n/**\n * Internal method that keeps a track of which error we have already added, to avoid circular recursion\n *\n * @private\n * @param {Error} err\n * @param {Set<Error>} seen\n * @param {boolean} [skip]\n * @returns {string}\n */\nconst _messageWithCauses = (err, seen, skip) => {\n if (!isErrorLike(err)) return ''\n\n const message = skip ? '' : (err.message || '')\n\n // Ensure we don't go circular or crazily deep\n if (seen.has(err)) {\n return message + ': ...'\n }\n\n const cause = getErrorCause(err)\n\n if (cause) {\n seen.add(err)\n\n // @ts-ignore\n const skipIfVErrorStyleCause = typeof err.cause === 'function'\n\n return (message +\n (skipIfVErrorStyleCause ? '' : ': ') +\n _messageWithCauses(cause, seen, skipIfVErrorStyleCause))\n } else {\n return message\n }\n}\n\n/**\n * @param {Error} err\n * @returns {string}\n */\nconst messageWithCauses = (err) => _messageWithCauses(err, new Set())\n\nmodule.exports = {\n isErrorLike,\n getErrorCause,\n stackWithCauses,\n messageWithCauses\n}\n","'use strict'\n\nconst seen = Symbol('circular-ref-tag')\nconst rawSymbol = Symbol('pino-raw-err-ref')\n\nconst pinoErrProto = Object.create({}, {\n type: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n message: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n stack: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n aggregateErrors: {\n enumerable: true,\n writable: true,\n value: undefined\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoErrProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nmodule.exports = {\n pinoErrProto,\n pinoErrorSymbols: {\n seen,\n rawSymbol\n }\n}\n","'use strict'\n\nmodule.exports = errSerializer\n\nconst { messageWithCauses, stackWithCauses, isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = messageWithCauses(err)\n _err.stack = stackWithCauses(err)\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errSerializer(err))\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n // We append cause messages and stacks to _err, therefore skipping causes here\n if (key !== 'cause' && !Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n","'use strict'\n\nmodule.exports = errWithCauseSerializer\n\nconst { isErrorLike } = require('./err-helpers')\nconst { pinoErrProto, pinoErrorSymbols } = require('./err-proto')\nconst { seen } = pinoErrorSymbols\n\nconst { toString } = Object.prototype\n\nfunction errWithCauseSerializer (err) {\n if (!isErrorLike(err)) {\n return err\n }\n\n err[seen] = undefined // tag to prevent re-looking at this\n const _err = Object.create(pinoErrProto)\n _err.type = toString.call(err.constructor) === '[object Function]'\n ? err.constructor.name\n : err.name\n _err.message = err.message\n _err.stack = err.stack\n\n if (Array.isArray(err.errors)) {\n _err.aggregateErrors = err.errors.map(err => errWithCauseSerializer(err))\n }\n\n if (isErrorLike(err.cause) && !Object.prototype.hasOwnProperty.call(err.cause, seen)) {\n _err.cause = errWithCauseSerializer(err.cause)\n }\n\n for (const key in err) {\n if (_err[key] === undefined) {\n const val = err[key]\n if (isErrorLike(val)) {\n if (!Object.prototype.hasOwnProperty.call(val, seen)) {\n _err[key] = errWithCauseSerializer(val)\n }\n } else {\n _err[key] = val\n }\n }\n }\n\n delete err[seen] // clean up tag in case err is serialized again later\n _err.raw = err\n return _err\n}\n","'use strict'\n\nmodule.exports = {\n mapHttpRequest,\n reqSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-req-ref')\nconst pinoReqProto = Object.create({}, {\n id: {\n enumerable: true,\n writable: true,\n value: ''\n },\n method: {\n enumerable: true,\n writable: true,\n value: ''\n },\n url: {\n enumerable: true,\n writable: true,\n value: ''\n },\n query: {\n enumerable: true,\n writable: true,\n value: ''\n },\n params: {\n enumerable: true,\n writable: true,\n value: ''\n },\n headers: {\n enumerable: true,\n writable: true,\n value: {}\n },\n remoteAddress: {\n enumerable: true,\n writable: true,\n value: ''\n },\n remotePort: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoReqProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction reqSerializer (req) {\n // req.info is for hapi compat.\n const connection = req.info || req.socket\n const _req = Object.create(pinoReqProto)\n _req.id = (typeof req.id === 'function' ? req.id() : (req.id || (req.info ? req.info.id : undefined)))\n _req.method = req.method\n // req.originalUrl is for expressjs compat.\n if (req.originalUrl) {\n _req.url = req.originalUrl\n } else {\n const path = req.path\n // path for safe hapi compat.\n _req.url = typeof path === 'string' ? path : (req.url ? req.url.path || req.url : undefined)\n }\n\n if (req.query) {\n _req.query = req.query\n }\n\n if (req.params) {\n _req.params = req.params\n }\n\n _req.headers = req.headers\n _req.remoteAddress = connection && connection.remoteAddress\n _req.remotePort = connection && connection.remotePort\n // req.raw is for hapi compat/equivalence\n _req.raw = req.raw || req\n return _req\n}\n\nfunction mapHttpRequest (req) {\n return {\n req: reqSerializer(req)\n }\n}\n","'use strict'\n\nmodule.exports = {\n mapHttpResponse,\n resSerializer\n}\n\nconst rawSymbol = Symbol('pino-raw-res-ref')\nconst pinoResProto = Object.create({}, {\n statusCode: {\n enumerable: true,\n writable: true,\n value: 0\n },\n headers: {\n enumerable: true,\n writable: true,\n value: ''\n },\n raw: {\n enumerable: false,\n get: function () {\n return this[rawSymbol]\n },\n set: function (val) {\n this[rawSymbol] = val\n }\n }\n})\nObject.defineProperty(pinoResProto, rawSymbol, {\n writable: true,\n value: {}\n})\n\nfunction resSerializer (res) {\n const _res = Object.create(pinoResProto)\n _res.statusCode = res.headersSent ? res.statusCode : null\n _res.headers = res.getHeaders ? res.getHeaders() : res._headers\n _res.raw = res\n return _res\n}\n\nfunction mapHttpResponse (res) {\n return {\n res: resSerializer(res)\n }\n}\n","'use strict'\n\nconst errSerializer = require('./lib/err')\nconst errWithCauseSerializer = require('./lib/err-with-cause')\nconst reqSerializers = require('./lib/req')\nconst resSerializers = require('./lib/res')\n\nmodule.exports = {\n err: errSerializer,\n errWithCause: errWithCauseSerializer,\n mapHttpRequest: reqSerializers.mapHttpRequest,\n mapHttpResponse: resSerializers.mapHttpResponse,\n req: reqSerializers.reqSerializer,\n res: resSerializers.resSerializer,\n\n wrapErrorSerializer: function wrapErrorSerializer (customSerializer) {\n if (customSerializer === errSerializer) return customSerializer\n return function wrapErrSerializer (err) {\n return customSerializer(errSerializer(err))\n }\n },\n\n wrapRequestSerializer: function wrapRequestSerializer (customSerializer) {\n if (customSerializer === reqSerializers.reqSerializer) return customSerializer\n return function wrappedReqSerializer (req) {\n return customSerializer(reqSerializers.reqSerializer(req))\n }\n },\n\n wrapResponseSerializer: function wrapResponseSerializer (customSerializer) {\n if (customSerializer === resSerializers.resSerializer) return customSerializer\n return function wrappedResSerializer (res) {\n return customSerializer(resSerializers.resSerializer(res))\n }\n }\n}\n","'use strict'\n\nfunction noOpPrepareStackTrace (_, stack) {\n return stack\n}\n\nmodule.exports = function getCallers () {\n const originalPrepare = Error.prepareStackTrace\n Error.prepareStackTrace = noOpPrepareStackTrace\n const stack = new Error().stack\n Error.prepareStackTrace = originalPrepare\n\n if (!Array.isArray(stack)) {\n return undefined\n }\n\n const entries = stack.slice(2)\n\n const fileNames = []\n\n for (const entry of entries) {\n if (!entry) {\n continue\n }\n\n fileNames.push(entry.getFileName())\n }\n\n return fileNames\n}\n","'use strict'\n\nmodule.exports = validator\n\nfunction validator (opts = {}) {\n const {\n ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings',\n ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})`\n } = opts\n\n return function validate ({ paths }) {\n paths.forEach((s) => {\n if (typeof s !== 'string') {\n throw Error(ERR_PATHS_MUST_BE_STRINGS())\n }\n try {\n if (/〇/.test(s)) throw Error()\n const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\\*/, '〇').replace(/\\.\\*/g, '.〇').replace(/\\[\\*\\]/g, '[〇]')\n if (/\\n|\\r|;/.test(expr)) throw Error()\n if (/\\/\\*/.test(expr)) throw Error()\n /* eslint-disable-next-line */\n Function(`\n 'use strict'\n const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });\n const 〇 = null;\n o${expr}\n if ([o${expr}].length !== 1) throw Error()`)()\n } catch (e) {\n throw Error(ERR_INVALID_PATH(s))\n }\n })\n }\n}\n","'use strict'\n\nmodule.exports = /[^.[\\]]+|\\[((?:.)*?)\\]/g\n\n/*\nRegular expression explanation:\n\nAlt 1: /[^.[\\]]+/ - Match one or more characters that are *not* a dot (.)\n opening square bracket ([) or closing square bracket (])\n\nAlt 2: /\\[((?:.)*?)\\]/ - If the char IS dot or square bracket, then create a capture\n group (which will be capture group $1) that matches anything\n within square brackets. Expansion is lazy so it will\n stop matching as soon as the first closing bracket is met `]`\n (rather than continuing to match until the final closing bracket).\n*/\n","'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = parse\n\nfunction parse ({ paths }) {\n const wildcards = []\n var wcLen = 0\n const secret = paths.reduce(function (o, strPath, ix) {\n var path = strPath.match(rx).map((p) => p.replace(/'|\"|`/g, ''))\n const leadingBracket = strPath[0] === '['\n path = path.map((p) => {\n if (p[0] === '[') return p.substr(1, p.length - 2)\n else return p\n })\n const star = path.indexOf('*')\n if (star > -1) {\n const before = path.slice(0, star)\n const beforeStr = before.join('.')\n const after = path.slice(star + 1, path.length)\n const nested = after.length > 0\n wcLen++\n wildcards.push({\n before,\n beforeStr,\n after,\n nested\n })\n } else {\n o[strPath] = {\n path: path,\n val: undefined,\n precensored: false,\n circle: '',\n escPath: JSON.stringify(strPath),\n leadingBracket: leadingBracket\n }\n }\n return o\n }, {})\n\n return { wildcards, wcLen, secret }\n}\n","'use strict'\n\nconst rx = require('./rx')\n\nmodule.exports = redactor\n\nfunction redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {\n /* eslint-disable-next-line */\n const redact = Function('o', `\n if (typeof o !== 'object' || o == null) {\n ${strictImpl(strict, serialize)}\n }\n const { censor, secret } = this\n const originalSecret = {}\n const secretKeys = Object.keys(secret)\n for (var i = 0; i < secretKeys.length; i++) {\n originalSecret[secretKeys[i]] = secret[secretKeys[i]]\n }\n\n ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}\n this.compileRestore()\n ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}\n this.secret = originalSecret\n ${resultTmpl(serialize)}\n `).bind(state)\n\n redact.state = state\n\n if (serialize === false) {\n redact.restore = (o) => state.restore(o)\n }\n\n return redact\n}\n\nfunction redactTmpl (secret, isCensorFct, censorFctTakesPath) {\n return Object.keys(secret).map((path) => {\n const { escPath, leadingBracket, path: arrPath } = secret[path]\n const skip = leadingBracket ? 1 : 0\n const delim = leadingBracket ? '' : '.'\n const hops = []\n var match\n while ((match = rx.exec(path)) !== null) {\n const [ , ix ] = match\n const { index, input } = match\n if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)))\n }\n var existence = hops.map((p) => `o${delim}${p}`).join(' && ')\n if (existence.length === 0) existence += `o${delim}${path} != null`\n else existence += ` && o${delim}${path} != null`\n\n const circularDetection = `\n switch (true) {\n ${hops.reverse().map((p) => `\n case o${delim}${p} === censor:\n secret[${escPath}].circle = ${JSON.stringify(p)}\n break\n `).join('\\n')}\n }\n `\n\n const censorArgs = censorFctTakesPath\n ? `val, ${JSON.stringify(arrPath)}`\n : `val`\n\n return `\n if (${existence}) {\n const val = o${delim}${path}\n if (val === censor) {\n secret[${escPath}].precensored = true\n } else {\n secret[${escPath}].val = val\n o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'}\n ${circularDetection}\n }\n }\n `\n }).join('\\n')\n}\n\nfunction dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) {\n return hasWildcards === true ? `\n {\n const { wildcards, wcLen, groupRedact, nestedRedact } = this\n for (var i = 0; i < wcLen; i++) {\n const { before, beforeStr, after, nested } = wildcards[i]\n if (nested === true) {\n secret[beforeStr] = secret[beforeStr] || []\n nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})\n } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})\n }\n }\n ` : ''\n}\n\nfunction resultTmpl (serialize) {\n return serialize === false ? `return o` : `\n var s = this.serialize(o)\n this.restore(o)\n return s\n `\n}\n\nfunction strictImpl (strict, serialize) {\n return strict === true\n ? `throw Error('fast-redact: primitives cannot be redacted')`\n : serialize === false ? `return o` : `return this.serialize(o)`\n}\n","'use strict'\n\nmodule.exports = {\n groupRedact,\n groupRestore,\n nestedRedact,\n nestedRestore\n}\n\nfunction groupRestore ({ keys, values, target }) {\n if (target == null || typeof target === 'string') return\n const length = keys.length\n for (var i = 0; i < length; i++) {\n const k = keys[i]\n target[k] = values[i]\n }\n}\n\nfunction groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null || typeof target === 'string') return { keys: null, values: null, target, flat: true }\n const keys = Object.keys(target)\n const keysLength = keys.length\n const pathLength = path.length\n const pathWithKey = censorFctTakesPath ? [...path] : undefined\n const values = new Array(keysLength)\n\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n values[i] = target[key]\n\n if (censorFctTakesPath) {\n pathWithKey[pathLength] = key\n target[key] = censor(target[key], pathWithKey)\n } else if (isCensorFct) {\n target[key] = censor(target[key])\n } else {\n target[key] = censor\n }\n }\n return { keys, values, target, flat: true }\n}\n\n/**\n * @param {RestoreInstruction[]} instructions a set of instructions for restoring values to objects\n */\nfunction nestedRestore (instructions) {\n for (let i = 0; i < instructions.length; i++) {\n const { target, path, value } = instructions[i]\n let current = target\n for (let i = path.length - 1; i > 0; i--) {\n current = current[path[i]]\n }\n current[path[0]] = value\n }\n}\n\nfunction nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {\n const target = get(o, path)\n if (target == null) return\n const keys = Object.keys(target)\n const keysLength = keys.length\n for (var i = 0; i < keysLength; i++) {\n const key = keys[i]\n specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath)\n }\n return store\n}\n\nfunction has (obj, prop) {\n return obj !== undefined && obj !== null\n ? ('hasOwn' in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop))\n : false\n}\n\nfunction specialSet (store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {\n const afterPathLen = afterPath.length\n const lastPathIndex = afterPathLen - 1\n const originalKey = k\n var i = -1\n var n\n var nv\n var ov\n var oov = null\n var wc = null\n var kIsWc\n var wcov\n var consecutive = false\n var level = 0\n // need to track depth of the `redactPath` tree\n var depth = 0\n var redactPathCurrent = tree()\n ov = n = o[k]\n if (typeof n !== 'object') return\n while (n != null && ++i < afterPathLen) {\n depth += 1\n k = afterPath[i]\n oov = ov\n if (k !== '*' && !wc && !(typeof n === 'object' && k in n)) {\n break\n }\n if (k === '*') {\n if (wc === '*') {\n consecutive = true\n }\n wc = k\n if (i !== lastPathIndex) {\n continue\n }\n }\n if (wc) {\n const wcKeys = Object.keys(n)\n for (var j = 0; j < wcKeys.length; j++) {\n const wck = wcKeys[j]\n wcov = n[wck]\n kIsWc = k === '*'\n if (consecutive) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n level = i\n ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1)\n } else {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey])\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n } else {\n redactPathCurrent = node(redactPathCurrent, wck, depth)\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey])\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n }\n wc = null\n } else {\n ov = n[k]\n redactPathCurrent = node(redactPathCurrent, k, depth)\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if ((has(n, k) && nv === ov) || (nv === undefined && censor !== undefined)) {\n // pass\n } else {\n const rv = restoreInstr(redactPathCurrent, ov, o[originalKey])\n store.push(rv)\n n[k] = nv\n }\n n = n[k]\n }\n if (typeof n !== 'object') break\n // prevent circular structure, see https://github.com/pinojs/pino/issues/1513\n if (ov === oov || typeof ov === 'undefined') {\n // pass\n }\n }\n}\n\nfunction get (o, p) {\n var i = -1\n var l = p.length\n var n = o\n while (n != null && ++i < l) {\n n = n[p[i]]\n }\n return n\n}\n\nfunction iterateNthLevel (wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {\n if (level === 0) {\n if (kIsWc || (typeof wcov === 'object' && wcov !== null && k in wcov)) {\n if (kIsWc) {\n ov = wcov\n } else {\n ov = wcov[k]\n }\n nv = (i !== lastPathIndex)\n ? ov\n : (isCensorFct\n ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov))\n : censor)\n if (kIsWc) {\n const rv = restoreInstr(redactPathCurrent, ov, parent)\n store.push(rv)\n n[wck] = nv\n } else {\n if (wcov[k] === nv) {\n // pass\n } else if ((nv === undefined && censor !== undefined) || (has(wcov, k) && nv === ov)) {\n // pass\n } else {\n const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent)\n store.push(rv)\n wcov[k] = nv\n }\n }\n }\n }\n for (const key in wcov) {\n if (typeof wcov[key] === 'object') {\n redactPathCurrent = node(redactPathCurrent, key, depth)\n iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1)\n }\n }\n}\n\n/**\n * @typedef {object} TreeNode\n * @prop {TreeNode} [parent] reference to the parent of this node in the tree, or `null` if there is no parent\n * @prop {string} key the key that this node represents (key here being part of the path being redacted\n * @prop {TreeNode[]} children the child nodes of this node\n * @prop {number} depth the depth of this node in the tree\n */\n\n/**\n * instantiate a new, empty tree\n * @returns {TreeNode}\n */\nfunction tree () {\n return { parent: null, key: null, children: [], depth: 0 }\n}\n\n/**\n * creates a new node in the tree, attaching it as a child of the provided parent node\n * if the specified depth matches the parent depth, adds the new node as a _sibling_ of the parent instead\n * @param {TreeNode} parent the parent node to add a new node to (if the parent depth matches the provided `depth` value, will instead add as a sibling of this\n * @param {string} key the key that the new node represents (key here being part of the path being redacted)\n * @param {number} depth the depth of the new node in the tree - used to determing whether to add the new node as a child or sibling of the provided `parent` node\n * @returns {TreeNode} a reference to the newly created node in the tree\n */\nfunction node (parent, key, depth) {\n if (parent.depth === depth) {\n return node(parent.parent, key, depth)\n }\n\n var child = {\n parent,\n key,\n depth,\n children: []\n }\n\n parent.children.push(child)\n\n return child\n}\n\n/**\n * @typedef {object} RestoreInstruction\n * @prop {string[]} path a reverse-order path that can be used to find the correct insertion point to restore a `value` for the given `parent` object\n * @prop {*} value the value to restore\n * @prop {object} target the object to restore the `value` in\n */\n\n/**\n * create a restore instruction for the given redactPath node\n * generates a path in reverse order by walking up the redactPath tree\n * @param {TreeNode} node a tree node that should be at the bottom of the redact path (i.e. have no children) - this will be used to walk up the redact path tree to construct the path needed to restore\n * @param {*} value the value to restore\n * @param {object} target a reference to the parent object to apply the restore instruction to\n * @returns {RestoreInstruction} an instruction used to restore a nested value for a specific object\n */\nfunction restoreInstr (node, value, target) {\n let current = node\n const path = []\n do {\n path.push(current.key)\n current = current.parent\n } while (current.parent != null)\n\n return { path, value, target }\n}\n","'use strict'\n\nconst { groupRestore, nestedRestore } = require('./modifiers')\n\nmodule.exports = restorer\n\nfunction restorer () {\n return function compileRestore () {\n if (this.restore) {\n this.restore.state.secret = this.secret\n return\n }\n const { secret, wcLen } = this\n const paths = Object.keys(secret)\n const resetters = resetTmpl(secret, paths)\n const hasWildcards = wcLen > 0\n const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret }\n /* eslint-disable-next-line */\n this.restore = Function(\n 'o',\n restoreTmpl(resetters, paths, hasWildcards)\n ).bind(state)\n this.restore.state = state\n }\n}\n\n/**\n * Mutates the original object to be censored by restoring its original values\n * prior to censoring.\n *\n * @param {object} secret Compiled object describing which target fields should\n * be censored and the field states.\n * @param {string[]} paths The list of paths to censor as provided at\n * initialization time.\n *\n * @returns {string} String of JavaScript to be used by `Function()`. The\n * string compiles to the function that does the work in the description.\n */\nfunction resetTmpl (secret, paths) {\n return paths.map((path) => {\n const { circle, escPath, leadingBracket } = secret[path]\n const delim = leadingBracket ? '' : '.'\n const reset = circle\n ? `o.${circle} = secret[${escPath}].val`\n : `o${delim}${path} = secret[${escPath}].val`\n const clear = `secret[${escPath}].val = undefined`\n return `\n if (secret[${escPath}].val !== undefined) {\n try { ${reset} } catch (e) {}\n ${clear}\n }\n `\n }).join('')\n}\n\n/**\n * Creates the body of the restore function\n *\n * Restoration of the redacted object happens\n * backwards, in reverse order of redactions,\n * so that repeated redactions on the same object\n * property can be eventually rolled back to the\n * original value.\n *\n * This way dynamic redactions are restored first,\n * starting from the last one working backwards and\n * followed by the static ones.\n *\n * @returns {string} the body of the restore function\n */\nfunction restoreTmpl (resetters, paths, hasWildcards) {\n const dynamicReset = hasWildcards === true ? `\n const keys = Object.keys(secret)\n const len = keys.length\n for (var i = len - 1; i >= ${paths.length}; i--) {\n const k = keys[i]\n const o = secret[k]\n if (o) {\n if (o.flat === true) this.groupRestore(o)\n else this.nestedRestore(o)\n secret[k] = null\n }\n }\n ` : ''\n\n return `\n const secret = this.secret\n ${dynamicReset}\n ${resetters}\n return o\n `\n}\n","'use strict'\n\nmodule.exports = state\n\nfunction state (o) {\n const {\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n } = o\n const builder = [{ secret, censor, compileRestore }]\n if (serialize !== false) builder.push({ serialize })\n if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen })\n return Object.assign(...builder)\n}\n","'use strict'\n\nconst validator = require('./lib/validator')\nconst parse = require('./lib/parse')\nconst redactor = require('./lib/redactor')\nconst restorer = require('./lib/restorer')\nconst { groupRedact, nestedRedact } = require('./lib/modifiers')\nconst state = require('./lib/state')\nconst rx = require('./lib/rx')\nconst validate = validator()\nconst noop = (o) => o\nnoop.restore = noop\n\nconst DEFAULT_CENSOR = '[REDACTED]'\nfastRedact.rx = rx\nfastRedact.validator = validator\n\nmodule.exports = fastRedact\n\nfunction fastRedact (opts = {}) {\n const paths = Array.from(new Set(opts.paths || []))\n const serialize = 'serialize' in opts ? (\n opts.serialize === false ? opts.serialize\n : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify)\n ) : JSON.stringify\n const remove = opts.remove\n if (remove === true && serialize !== JSON.stringify) {\n throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify')\n }\n const censor = remove === true\n ? undefined\n : 'censor' in opts ? opts.censor : DEFAULT_CENSOR\n\n const isCensorFct = typeof censor === 'function'\n const censorFctTakesPath = isCensorFct && censor.length > 1\n\n if (paths.length === 0) return serialize || noop\n\n validate({ paths, serialize, censor })\n\n const { wildcards, wcLen, secret } = parse({ paths, censor })\n\n const compileRestore = restorer()\n const strict = 'strict' in opts ? opts.strict : true\n\n return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({\n secret,\n censor,\n compileRestore,\n serialize,\n groupRedact,\n nestedRedact,\n wildcards,\n wcLen\n }))\n}\n","'use strict'\n\nconst setLevelSym = Symbol('pino.setLevel')\nconst getLevelSym = Symbol('pino.getLevel')\nconst levelValSym = Symbol('pino.levelVal')\nconst levelCompSym = Symbol('pino.levelComp')\nconst useLevelLabelsSym = Symbol('pino.useLevelLabels')\nconst useOnlyCustomLevelsSym = Symbol('pino.useOnlyCustomLevels')\nconst mixinSym = Symbol('pino.mixin')\n\nconst lsCacheSym = Symbol('pino.lsCache')\nconst chindingsSym = Symbol('pino.chindings')\n\nconst asJsonSym = Symbol('pino.asJson')\nconst writeSym = Symbol('pino.write')\nconst redactFmtSym = Symbol('pino.redactFmt')\n\nconst timeSym = Symbol('pino.time')\nconst timeSliceIndexSym = Symbol('pino.timeSliceIndex')\nconst streamSym = Symbol('pino.stream')\nconst stringifySym = Symbol('pino.stringify')\nconst stringifySafeSym = Symbol('pino.stringifySafe')\nconst stringifiersSym = Symbol('pino.stringifiers')\nconst endSym = Symbol('pino.end')\nconst formatOptsSym = Symbol('pino.formatOpts')\nconst messageKeySym = Symbol('pino.messageKey')\nconst errorKeySym = Symbol('pino.errorKey')\nconst nestedKeySym = Symbol('pino.nestedKey')\nconst nestedKeyStrSym = Symbol('pino.nestedKeyStr')\nconst mixinMergeStrategySym = Symbol('pino.mixinMergeStrategy')\nconst msgPrefixSym = Symbol('pino.msgPrefix')\n\nconst wildcardFirstSym = Symbol('pino.wildcardFirst')\n\n// public symbols, no need to use the same pino\n// version for these\nconst serializersSym = Symbol.for('pino.serializers')\nconst formattersSym = Symbol.for('pino.formatters')\nconst hooksSym = Symbol.for('pino.hooks')\nconst needsMetadataGsym = Symbol.for('pino.metadata')\n\nmodule.exports = {\n setLevelSym,\n getLevelSym,\n levelValSym,\n levelCompSym,\n useLevelLabelsSym,\n mixinSym,\n lsCacheSym,\n chindingsSym,\n asJsonSym,\n writeSym,\n serializersSym,\n redactFmtSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n wildcardFirstSym,\n needsMetadataGsym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n}\n","'use strict'\n\nconst fastRedact = require('fast-redact')\nconst { redactFmtSym, wildcardFirstSym } = require('./symbols')\nconst { rx, validator } = fastRedact\n\nconst validate = validator({\n ERR_PATHS_MUST_BE_STRINGS: () => 'pino – redacted paths must be strings',\n ERR_INVALID_PATH: (s) => `pino – redact paths array contains an invalid path (${s})`\n})\n\nconst CENSOR = '[Redacted]'\nconst strict = false // TODO should this be configurable?\n\nfunction redaction (opts, serialize) {\n const { paths, censor } = handle(opts)\n\n const shape = paths.reduce((o, str) => {\n rx.lastIndex = 0\n const first = rx.exec(str)\n const next = rx.exec(str)\n\n // ns is the top-level path segment, brackets + quoting removed.\n let ns = first[1] !== undefined\n ? first[1].replace(/^(?:\"|'|`)(.*)(?:\"|'|`)$/, '$1')\n : first[0]\n\n if (ns === '*') {\n ns = wildcardFirstSym\n }\n\n // top level key:\n if (next === null) {\n o[ns] = null\n return o\n }\n\n // path with at least two segments:\n // if ns is already redacted at the top level, ignore lower level redactions\n if (o[ns] === null) {\n return o\n }\n\n const { index } = next\n const nextPath = `${str.substr(index, str.length - 1)}`\n\n o[ns] = o[ns] || []\n\n // shape is a mix of paths beginning with literal values and wildcard\n // paths [ \"a.b.c\", \"*.b.z\" ] should reduce to a shape of\n // { \"a\": [ \"b.c\", \"b.z\" ], *: [ \"b.z\" ] }\n // note: \"b.z\" is in both \"a\" and * arrays because \"a\" matches the wildcard.\n // (* entry has wildcardFirstSym as key)\n if (ns !== wildcardFirstSym && o[ns].length === 0) {\n // first time ns's get all '*' redactions so far\n o[ns].push(...(o[wildcardFirstSym] || []))\n }\n\n if (ns === wildcardFirstSym) {\n // new * path gets added to all previously registered literal ns's.\n Object.keys(o).forEach(function (k) {\n if (o[k]) {\n o[k].push(nextPath)\n }\n })\n }\n\n o[ns].push(nextPath)\n return o\n }, {})\n\n // the redactor assigned to the format symbol key\n // provides top level redaction for instances where\n // an object is interpolated into the msg string\n const result = {\n [redactFmtSym]: fastRedact({ paths, censor, serialize, strict })\n }\n\n const topCensor = (...args) => {\n return typeof censor === 'function' ? serialize(censor(...args)) : serialize(censor)\n }\n\n return [...Object.keys(shape), ...Object.getOwnPropertySymbols(shape)].reduce((o, k) => {\n // top level key:\n if (shape[k] === null) {\n o[k] = (value) => topCensor(value, [k])\n } else {\n const wrappedCensor = typeof censor === 'function'\n ? (value, path) => {\n return censor(value, [k, ...path])\n }\n : censor\n o[k] = fastRedact({\n paths: shape[k],\n censor: wrappedCensor,\n serialize,\n strict\n })\n }\n return o\n }, result)\n}\n\nfunction handle (opts) {\n if (Array.isArray(opts)) {\n opts = { paths: opts, censor: CENSOR }\n validate(opts)\n return opts\n }\n let { paths, censor = CENSOR, remove } = opts\n if (Array.isArray(paths) === false) { throw Error('pino – redact must contain an array of strings') }\n if (remove === true) censor = undefined\n validate({ paths, censor })\n\n return { paths, censor }\n}\n\nmodule.exports = redaction\n","'use strict'\n\nconst nullTime = () => ''\n\nconst epochTime = () => `,\"time\":${Date.now()}`\n\nconst unixTime = () => `,\"time\":${Math.round(Date.now() / 1000.0)}`\n\nconst isoTime = () => `,\"time\":\"${new Date(Date.now()).toISOString()}\"` // using Date.now() for testability\n\nmodule.exports = { nullTime, epochTime, unixTime, isoTime }\n","'use strict'\nfunction tryStringify (o) {\n try { return JSON.stringify(o) } catch(e) { return '\"[Circular]\"' }\n}\n\nmodule.exports = format\n\nfunction format(f, args, opts) {\n var ss = (opts && opts.stringify) || tryStringify\n var offset = 1\n if (typeof f === 'object' && f !== null) {\n var len = args.length + offset\n if (len === 1) return f\n var objects = new Array(len)\n objects[0] = ss(f)\n for (var index = 1; index < len; index++) {\n objects[index] = ss(args[index])\n }\n return objects.join(' ')\n }\n if (typeof f !== 'string') {\n return f\n }\n var argLen = args.length\n if (argLen === 0) return f\n var str = ''\n var a = 1 - offset\n var lastPos = -1\n var flen = (f && f.length) || 0\n for (var i = 0; i < flen;) {\n if (f.charCodeAt(i) === 37 && i + 1 < flen) {\n lastPos = lastPos > -1 ? lastPos : 0\n switch (f.charCodeAt(i + 1)) {\n case 100: // 'd'\n case 102: // 'f'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Number(args[a])\n lastPos = i + 2\n i++\n break\n case 105: // 'i'\n if (a >= argLen)\n break\n if (args[a] == null) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += Math.floor(Number(args[a]))\n lastPos = i + 2\n i++\n break\n case 79: // 'O'\n case 111: // 'o'\n case 106: // 'j'\n if (a >= argLen)\n break\n if (args[a] === undefined) break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n var type = typeof args[a]\n if (type === 'string') {\n str += '\\'' + args[a] + '\\''\n lastPos = i + 2\n i++\n break\n }\n if (type === 'function') {\n str += args[a].name || '<anonymous>'\n lastPos = i + 2\n i++\n break\n }\n str += ss(args[a])\n lastPos = i + 2\n i++\n break\n case 115: // 's'\n if (a >= argLen)\n break\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += String(args[a])\n lastPos = i + 2\n i++\n break\n case 37: // '%'\n if (lastPos < i)\n str += f.slice(lastPos, i)\n str += '%'\n lastPos = i + 2\n i++\n a--\n break\n }\n ++a\n }\n ++i\n }\n if (lastPos === -1)\n return f\n else if (lastPos < flen) {\n str += f.slice(lastPos)\n }\n\n return str\n}\n","'use strict'\n\n/* global SharedArrayBuffer, Atomics */\n\nif (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {\n const nil = new Int32Array(new SharedArrayBuffer(4))\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n\n Atomics.wait(nil, 0, 0, Number(ms))\n }\n module.exports = sleep\n} else {\n\n function sleep (ms) {\n // also filters out NaN, non-number types, including empty strings, but allows bigints\n const valid = ms > 0 && ms < Infinity \n if (valid === false) {\n if (typeof ms !== 'number' && typeof ms !== 'bigint') {\n throw TypeError('sleep: ms must be a number')\n }\n throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity')\n }\n const target = Date.now() + Number(ms)\n while (target > Date.now()){}\n }\n\n module.exports = sleep\n\n}\n","'use strict'\n\nconst fs = require('fs')\nconst EventEmitter = require('events')\nconst inherits = require('util').inherits\nconst path = require('path')\nconst sleep = require('atomic-sleep')\nconst assert = require('assert')\n\nconst BUSY_WRITE_TIMEOUT = 100\nconst kEmptyBuffer = Buffer.allocUnsafe(0)\n\n// 16 KB. Don't write more than docker buffer size.\n// https://github.com/moby/moby/blob/513ec73831269947d38a644c278ce3cac36783b2/daemon/logger/copier.go#L13\nconst MAX_WRITE = 16 * 1024\n\nconst kContentModeBuffer = 'buffer'\nconst kContentModeUtf8 = 'utf8'\n\nconst [major, minor] = (process.versions.node || '0.0').split('.').map(Number)\nconst kCopyBuffer = major >= 22 && minor >= 7\n\nfunction openFile (file, sonic) {\n sonic._opening = true\n sonic._writing = true\n sonic._asyncDrainScheduled = false\n\n // NOTE: 'error' and 'ready' events emitted below only relevant when sonic.sync===false\n // for sync mode, there is no way to add a listener that will receive these\n\n function fileOpened (err, fd) {\n if (err) {\n sonic._reopening = false\n sonic._writing = false\n sonic._opening = false\n\n if (sonic.sync) {\n process.nextTick(() => {\n if (sonic.listenerCount('error') > 0) {\n sonic.emit('error', err)\n }\n })\n } else {\n sonic.emit('error', err)\n }\n return\n }\n\n const reopening = sonic._reopening\n\n sonic.fd = fd\n sonic.file = file\n sonic._reopening = false\n sonic._opening = false\n sonic._writing = false\n\n if (sonic.sync) {\n process.nextTick(() => sonic.emit('ready'))\n } else {\n sonic.emit('ready')\n }\n\n if (sonic.destroyed) {\n return\n }\n\n // start\n if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {\n sonic._actualWrite()\n } else if (reopening) {\n process.nextTick(() => sonic.emit('drain'))\n }\n }\n\n const flags = sonic.append ? 'a' : 'w'\n const mode = sonic.mode\n\n if (sonic.sync) {\n try {\n if (sonic.mkdir) fs.mkdirSync(path.dirname(file), { recursive: true })\n const fd = fs.openSync(file, flags, mode)\n fileOpened(null, fd)\n } catch (err) {\n fileOpened(err)\n throw err\n }\n } else if (sonic.mkdir) {\n fs.mkdir(path.dirname(file), { recursive: true }, (err) => {\n if (err) return fileOpened(err)\n fs.open(file, flags, mode, fileOpened)\n })\n } else {\n fs.open(file, flags, mode, fileOpened)\n }\n}\n\nfunction SonicBoom (opts) {\n if (!(this instanceof SonicBoom)) {\n return new SonicBoom(opts)\n }\n\n let { fd, dest, minLength, maxLength, maxWrite, periodicFlush, sync, append = true, mkdir, retryEAGAIN, fsync, contentMode, mode } = opts || {}\n\n fd = fd || dest\n\n this._len = 0\n this.fd = -1\n this._bufs = []\n this._lens = []\n this._writing = false\n this._ending = false\n this._reopening = false\n this._asyncDrainScheduled = false\n this._flushPending = false\n this._hwm = Math.max(minLength || 0, 16387)\n this.file = null\n this.destroyed = false\n this.minLength = minLength || 0\n this.maxLength = maxLength || 0\n this.maxWrite = maxWrite || MAX_WRITE\n this._periodicFlush = periodicFlush || 0\n this._periodicFlushTimer = undefined\n this.sync = sync || false\n this.writable = true\n this._fsync = fsync || false\n this.append = append || false\n this.mode = mode\n this.retryEAGAIN = retryEAGAIN || (() => true)\n this.mkdir = mkdir || false\n\n let fsWriteSync\n let fsWrite\n if (contentMode === kContentModeBuffer) {\n this._writingBuf = kEmptyBuffer\n this.write = writeBuffer\n this.flush = flushBuffer\n this.flushSync = flushBufferSync\n this._actualWrite = actualWriteBuffer\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf)\n fsWrite = () => fs.write(this.fd, this._writingBuf, this.release)\n } else if (contentMode === undefined || contentMode === kContentModeUtf8) {\n this._writingBuf = ''\n this.write = write\n this.flush = flush\n this.flushSync = flushSync\n this._actualWrite = actualWrite\n fsWriteSync = () => fs.writeSync(this.fd, this._writingBuf, 'utf8')\n fsWrite = () => fs.write(this.fd, this._writingBuf, 'utf8', this.release)\n } else {\n throw new Error(`SonicBoom supports \"${kContentModeUtf8}\" and \"${kContentModeBuffer}\", but passed ${contentMode}`)\n }\n\n if (typeof fd === 'number') {\n this.fd = fd\n process.nextTick(() => this.emit('ready'))\n } else if (typeof fd === 'string') {\n openFile(fd, this)\n } else {\n throw new Error('SonicBoom supports only file descriptors and files')\n }\n if (this.minLength >= this.maxWrite) {\n throw new Error(`minLength should be smaller than maxWrite (${this.maxWrite})`)\n }\n\n this.release = (err, n) => {\n if (err) {\n if ((err.code === 'EAGAIN' || err.code === 'EBUSY') && this.retryEAGAIN(err, this._writingBuf.length, this._len - this._writingBuf.length)) {\n if (this.sync) {\n // This error code should not happen in sync mode, because it is\n // not using the underlining operating system asynchronous functions.\n // However it happens, and so we handle it.\n // Ref: https://github.com/pinojs/pino/issues/783\n try {\n sleep(BUSY_WRITE_TIMEOUT)\n this.release(undefined, 0)\n } catch (err) {\n this.release(err)\n }\n } else {\n // Let's give the destination some time to process the chunk.\n setTimeout(fsWrite, BUSY_WRITE_TIMEOUT)\n }\n } else {\n this._writing = false\n\n this.emit('error', err)\n }\n return\n }\n\n this.emit('write', n)\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n\n if (this._writingBuf.length) {\n if (!this.sync) {\n fsWrite()\n return\n }\n\n try {\n do {\n const n = fsWriteSync()\n const releasedBufObj = releaseWritingBuf(this._writingBuf, this._len, n)\n this._len = releasedBufObj.len\n this._writingBuf = releasedBufObj.writingBuf\n } while (this._writingBuf.length)\n } catch (err) {\n this.release(err)\n return\n }\n }\n\n if (this._fsync) {\n fs.fsyncSync(this.fd)\n }\n\n const len = this._len\n if (this._reopening) {\n this._writing = false\n this._reopening = false\n this.reopen()\n } else if (len > this.minLength) {\n this._actualWrite()\n } else if (this._ending) {\n if (len > 0) {\n this._actualWrite()\n } else {\n this._writing = false\n actualClose(this)\n }\n } else {\n this._writing = false\n if (this.sync) {\n if (!this._asyncDrainScheduled) {\n this._asyncDrainScheduled = true\n process.nextTick(emitDrain, this)\n }\n } else {\n this.emit('drain')\n }\n }\n }\n\n this.on('newListener', function (name) {\n if (name === 'drain') {\n this._asyncDrainScheduled = false\n }\n })\n\n if (this._periodicFlush !== 0) {\n this._periodicFlushTimer = setInterval(() => this.flush(null), this._periodicFlush)\n this._periodicFlushTimer.unref()\n }\n}\n\n/**\n * Release the writingBuf after fs.write n bytes data\n * @param {string | Buffer} writingBuf - currently writing buffer, usually be instance._writingBuf.\n * @param {number} len - currently buffer length, usually be instance._len.\n * @param {number} n - number of bytes fs already written\n * @returns {{writingBuf: string | Buffer, len: number}} released writingBuf and length\n */\nfunction releaseWritingBuf (writingBuf, len, n) {\n // if Buffer.byteLength is equal to n, that means writingBuf contains no multi-byte character\n if (typeof writingBuf === 'string' && Buffer.byteLength(writingBuf) !== n) {\n // Since the fs.write callback parameter `n` means how many bytes the passed of string\n // We calculate the original string length for avoiding the multi-byte character issue\n n = Buffer.from(writingBuf).subarray(0, n).toString().length\n }\n len = Math.max(len - n, 0)\n writingBuf = writingBuf.slice(n)\n return { writingBuf, len }\n}\n\nfunction emitDrain (sonic) {\n const hasListeners = sonic.listenerCount('drain') > 0\n if (!hasListeners) return\n sonic._asyncDrainScheduled = false\n sonic.emit('drain')\n}\n\ninherits(SonicBoom, EventEmitter)\n\nfunction mergeBuf (bufs, len) {\n if (bufs.length === 0) {\n return kEmptyBuffer\n }\n\n if (bufs.length === 1) {\n return bufs[0]\n }\n\n return Buffer.concat(bufs, len)\n}\n\nfunction write (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n bufs[bufs.length - 1].length + data.length > this.maxWrite\n ) {\n bufs.push('' + data)\n } else {\n bufs[bufs.length - 1] += data\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction writeBuffer (data) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n const len = this._len + data.length\n const bufs = this._bufs\n const lens = this._lens\n\n if (this.maxLength && len > this.maxLength) {\n this.emit('drop', data)\n return this._len < this._hwm\n }\n\n if (\n bufs.length === 0 ||\n lens[lens.length - 1] + data.length > this.maxWrite\n ) {\n bufs.push([data])\n lens.push(data.length)\n } else {\n bufs[bufs.length - 1].push(data)\n lens[lens.length - 1] += data.length\n }\n\n this._len = len\n\n if (!this._writing && this._len >= this.minLength) {\n this._actualWrite()\n }\n\n return this._len < this._hwm\n}\n\nfunction callFlushCallbackOnDrain (cb) {\n this._flushPending = true\n const onDrain = () => {\n // only if _fsync is false to avoid double fsync\n if (!this._fsync) {\n try {\n fs.fsync(this.fd, (err) => {\n this._flushPending = false\n cb(err)\n })\n } catch (err) {\n cb(err)\n }\n } else {\n this._flushPending = false\n cb()\n }\n this.off('error', onError)\n }\n const onError = (err) => {\n this._flushPending = false\n cb(err)\n this.off('drain', onDrain)\n }\n\n this.once('drain', onDrain)\n this.once('error', onError)\n}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push('')\n }\n\n this._actualWrite()\n}\n\nfunction flushBuffer (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw new Error('flush cb must be a function')\n }\n\n if (this.destroyed) {\n const error = new Error('SonicBoom destroyed')\n if (cb) {\n cb(error)\n return\n }\n\n throw error\n }\n\n if (this.minLength <= 0) {\n cb?.()\n return\n }\n\n if (cb) {\n callFlushCallbackOnDrain.call(this, cb)\n }\n\n if (this._writing) {\n return\n }\n\n if (this._bufs.length === 0) {\n this._bufs.push([])\n this._lens.push(0)\n }\n\n this._actualWrite()\n}\n\nSonicBoom.prototype.reopen = function (file) {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.reopen(file)\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n if (!this.file) {\n throw new Error('Unable to reopen a file descriptor, you must pass a file to SonicBoom')\n }\n\n if (file) {\n this.file = file\n }\n this._reopening = true\n\n if (this._writing) {\n return\n }\n\n const fd = this.fd\n this.once('ready', () => {\n if (fd !== this.fd) {\n fs.close(fd, (err) => {\n if (err) {\n return this.emit('error', err)\n }\n })\n }\n })\n\n openFile(this.file, this)\n}\n\nSonicBoom.prototype.end = function () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this._opening) {\n this.once('ready', () => {\n this.end()\n })\n return\n }\n\n if (this._ending) {\n return\n }\n\n this._ending = true\n\n if (this._writing) {\n return\n }\n\n if (this._len > 0 && this.fd >= 0) {\n this._actualWrite()\n } else {\n actualClose(this)\n }\n}\n\nfunction flushSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift(this._writingBuf)\n this._writingBuf = ''\n }\n\n let buf = ''\n while (this._bufs.length || buf) {\n if (buf.length <= 0) {\n buf = this._bufs[0]\n }\n try {\n const n = fs.writeSync(this.fd, buf, 'utf8')\n const releasedBufObj = releaseWritingBuf(buf, this._len, n)\n buf = releasedBufObj.writingBuf\n this._len = releasedBufObj.len\n if (buf.length <= 0) {\n this._bufs.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n\n try {\n fs.fsyncSync(this.fd)\n } catch {\n // Skip the error. The fd might not support fsync.\n }\n}\n\nfunction flushBufferSync () {\n if (this.destroyed) {\n throw new Error('SonicBoom destroyed')\n }\n\n if (this.fd < 0) {\n throw new Error('sonic boom is not ready yet')\n }\n\n if (!this._writing && this._writingBuf.length > 0) {\n this._bufs.unshift([this._writingBuf])\n this._writingBuf = kEmptyBuffer\n }\n\n let buf = kEmptyBuffer\n while (this._bufs.length || buf.length) {\n if (buf.length <= 0) {\n buf = mergeBuf(this._bufs[0], this._lens[0])\n }\n try {\n const n = fs.writeSync(this.fd, buf)\n buf = buf.subarray(n)\n this._len = Math.max(this._len - n, 0)\n if (buf.length <= 0) {\n this._bufs.shift()\n this._lens.shift()\n }\n } catch (err) {\n const shouldRetry = err.code === 'EAGAIN' || err.code === 'EBUSY'\n if (shouldRetry && !this.retryEAGAIN(err, buf.length, this._len - buf.length)) {\n throw err\n }\n\n sleep(BUSY_WRITE_TIMEOUT)\n }\n }\n}\n\nSonicBoom.prototype.destroy = function () {\n if (this.destroyed) {\n return\n }\n actualClose(this)\n}\n\nfunction actualWrite () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf || this._bufs.shift() || ''\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf, 'utf8')\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n fs.write(this.fd, this._writingBuf, 'utf8', release)\n }\n}\n\nfunction actualWriteBuffer () {\n const release = this.release\n this._writing = true\n this._writingBuf = this._writingBuf.length ? this._writingBuf : mergeBuf(this._bufs.shift(), this._lens.shift())\n\n if (this.sync) {\n try {\n const written = fs.writeSync(this.fd, this._writingBuf)\n release(null, written)\n } catch (err) {\n release(err)\n }\n } else {\n // fs.write will need to copy string to buffer anyway so\n // we do it here to avoid the overhead of calculating the buffer size\n // in releaseWritingBuf.\n if (kCopyBuffer) {\n this._writingBuf = Buffer.from(this._writingBuf)\n }\n fs.write(this.fd, this._writingBuf, release)\n }\n}\n\nfunction actualClose (sonic) {\n if (sonic.fd === -1) {\n sonic.once('ready', actualClose.bind(null, sonic))\n return\n }\n\n if (sonic._periodicFlushTimer !== undefined) {\n clearInterval(sonic._periodicFlushTimer)\n }\n\n sonic.destroyed = true\n sonic._bufs = []\n sonic._lens = []\n\n assert(typeof sonic.fd === 'number', `sonic.fd must be a number, got ${typeof sonic.fd}`)\n try {\n fs.fsync(sonic.fd, closeWrapped)\n } catch {\n }\n\n function closeWrapped () {\n // We skip errors in fsync\n\n if (sonic.fd !== 1 && sonic.fd !== 2) {\n fs.close(sonic.fd, done)\n } else {\n done()\n }\n }\n\n function done (err) {\n if (err) {\n sonic.emit('error', err)\n return\n }\n\n if (sonic._ending && !sonic._writing) {\n sonic.emit('finish')\n }\n sonic.emit('close')\n }\n}\n\n/**\n * These export configurations enable JS and TS developers\n * to consumer SonicBoom in whatever way best suits their needs.\n * Some examples of supported import syntax includes:\n * - `const SonicBoom = require('SonicBoom')`\n * - `const { SonicBoom } = require('SonicBoom')`\n * - `import * as SonicBoom from 'SonicBoom'`\n * - `import { SonicBoom } from 'SonicBoom'`\n * - `import SonicBoom from 'SonicBoom'`\n */\nSonicBoom.SonicBoom = SonicBoom\nSonicBoom.default = SonicBoom\nmodule.exports = SonicBoom\n","'use strict'\n\nconst refs = {\n exit: [],\n beforeExit: []\n}\nconst functions = {\n exit: onExit,\n beforeExit: onBeforeExit\n}\n\nlet registry\n\nfunction ensureRegistry () {\n if (registry === undefined) {\n registry = new FinalizationRegistry(clear)\n }\n}\n\nfunction install (event) {\n if (refs[event].length > 0) {\n return\n }\n\n process.on(event, functions[event])\n}\n\nfunction uninstall (event) {\n if (refs[event].length > 0) {\n return\n }\n process.removeListener(event, functions[event])\n if (refs.exit.length === 0 && refs.beforeExit.length === 0) {\n registry = undefined\n }\n}\n\nfunction onExit () {\n callRefs('exit')\n}\n\nfunction onBeforeExit () {\n callRefs('beforeExit')\n}\n\nfunction callRefs (event) {\n for (const ref of refs[event]) {\n const obj = ref.deref()\n const fn = ref.fn\n\n // This should always happen, however GC is\n // undeterministic so it might not happen.\n /* istanbul ignore else */\n if (obj !== undefined) {\n fn(obj, event)\n }\n }\n refs[event] = []\n}\n\nfunction clear (ref) {\n for (const event of ['exit', 'beforeExit']) {\n const index = refs[event].indexOf(ref)\n refs[event].splice(index, index + 1)\n uninstall(event)\n }\n}\n\nfunction _register (event, obj, fn) {\n if (obj === undefined) {\n throw new Error('the object can\\'t be undefined')\n }\n install(event)\n const ref = new WeakRef(obj)\n ref.fn = fn\n\n ensureRegistry()\n registry.register(obj, ref)\n refs[event].push(ref)\n}\n\nfunction register (obj, fn) {\n _register('exit', obj, fn)\n}\n\nfunction registerBeforeExit (obj, fn) {\n _register('beforeExit', obj, fn)\n}\n\nfunction unregister (obj) {\n if (registry === undefined) {\n return\n }\n registry.unregister(obj)\n for (const event of ['exit', 'beforeExit']) {\n refs[event] = refs[event].filter((ref) => {\n const _obj = ref.deref()\n return _obj && _obj !== obj\n })\n uninstall(event)\n }\n}\n\nmodule.exports = {\n register,\n registerBeforeExit,\n unregister\n}\n","{\n \"name\": \"thread-stream\",\n \"version\": \"3.1.0\",\n \"description\": \"A streaming way to send data to a Node.js Worker Thread\",\n \"main\": \"index.js\",\n \"types\": \"index.d.ts\",\n \"dependencies\": {\n \"real-require\": \"^0.2.0\"\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.1.0\",\n \"@types/tap\": \"^15.0.0\",\n \"@yao-pkg/pkg\": \"^5.11.5\",\n \"desm\": \"^1.3.0\",\n \"fastbench\": \"^1.0.1\",\n \"husky\": \"^9.0.6\",\n \"pino-elasticsearch\": \"^8.0.0\",\n \"sonic-boom\": \"^4.0.1\",\n \"standard\": \"^17.0.0\",\n \"tap\": \"^16.2.0\",\n \"ts-node\": \"^10.8.0\",\n \"typescript\": \"^5.3.2\",\n \"why-is-node-running\": \"^2.2.2\"\n },\n \"scripts\": {\n \"build\": \"tsc --noEmit\",\n \"test\": \"standard && npm run build && npm run transpile && tap \\\"test/**/*.test.*js\\\" && tap --ts test/*.test.*ts\",\n \"test:ci\": \"standard && npm run transpile && npm run test:ci:js && npm run test:ci:ts\",\n \"test:ci:js\": \"tap --no-check-coverage --timeout=120 --coverage-report=lcovonly \\\"test/**/*.test.*js\\\"\",\n \"test:ci:ts\": \"tap --ts --no-check-coverage --coverage-report=lcovonly \\\"test/**/*.test.*ts\\\"\",\n \"test:yarn\": \"npm run transpile && tap \\\"test/**/*.test.js\\\" --no-check-coverage\",\n \"transpile\": \"sh ./test/ts/transpile.sh\",\n \"prepare\": \"husky install\"\n },\n \"standard\": {\n \"ignore\": [\n \"test/ts/**/*\",\n \"test/syntax-error.mjs\"\n ]\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/mcollina/thread-stream.git\"\n },\n \"keywords\": [\n \"worker\",\n \"thread\",\n \"threads\",\n \"stream\"\n ],\n \"author\": \"Matteo Collina <hello@matteocollina.com>\",\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/mcollina/thread-stream/issues\"\n },\n \"homepage\": \"https://github.com/mcollina/thread-stream#readme\"\n}\n","'use strict'\n\nconst MAX_TIMEOUT = 1000\n\nfunction wait (state, index, expected, timeout, done) {\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current === expected) {\n done(null, 'ok')\n return\n }\n let prior = current\n const check = (backoff) => {\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n prior = current\n current = Atomics.load(state, index)\n if (current === prior) {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n } else {\n if (current === expected) done(null, 'ok')\n else done(null, 'not-equal')\n }\n }, backoff)\n }\n }\n check(1)\n}\n\n// let waitDiffCount = 0\nfunction waitDiff (state, index, expected, timeout, done) {\n // const id = waitDiffCount++\n // process._rawDebug(`>>> waitDiff ${id}`)\n const max = Date.now() + timeout\n let current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n return\n }\n const check = (backoff) => {\n // process._rawDebug(`${id} ${index} current ${current} expected ${expected}`)\n // process._rawDebug('' + backoff)\n if (Date.now() > max) {\n done(null, 'timed-out')\n } else {\n setTimeout(() => {\n current = Atomics.load(state, index)\n if (current !== expected) {\n done(null, 'ok')\n } else {\n check(backoff >= MAX_TIMEOUT ? MAX_TIMEOUT : backoff * 2)\n }\n }, backoff)\n }\n }\n check(1)\n}\n\nmodule.exports = { wait, waitDiff }\n","'use strict'\n\nconst WRITE_INDEX = 4\nconst READ_INDEX = 8\n\nmodule.exports = {\n WRITE_INDEX,\n READ_INDEX\n}\n","'use strict'\n\nconst { version } = require('./package.json')\nconst { EventEmitter } = require('events')\nconst { Worker } = require('worker_threads')\nconst { join } = require('path')\nconst { pathToFileURL } = require('url')\nconst { wait } = require('./lib/wait')\nconst {\n WRITE_INDEX,\n READ_INDEX\n} = require('./lib/indexes')\nconst buffer = require('buffer')\nconst assert = require('assert')\n\nconst kImpl = Symbol('kImpl')\n\n// V8 limit for string size\nconst MAX_STRING = buffer.constants.MAX_STRING_LENGTH\n\nclass FakeWeakRef {\n constructor (value) {\n this._value = value\n }\n\n deref () {\n return this._value\n }\n}\n\nclass FakeFinalizationRegistry {\n register () {}\n\n unregister () {}\n}\n\n// Currently using FinalizationRegistry with code coverage breaks the world\n// Ref: https://github.com/nodejs/node/issues/49344\nconst FinalizationRegistry = process.env.NODE_V8_COVERAGE ? FakeFinalizationRegistry : global.FinalizationRegistry || FakeFinalizationRegistry\nconst WeakRef = process.env.NODE_V8_COVERAGE ? FakeWeakRef : global.WeakRef || FakeWeakRef\n\nconst registry = new FinalizationRegistry((worker) => {\n if (worker.exited) {\n return\n }\n worker.terminate()\n})\n\nfunction createWorker (stream, opts) {\n const { filename, workerData } = opts\n\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n const toExecute = bundlerOverrides['thread-stream-worker'] || join(__dirname, 'lib', 'worker.js')\n\n const worker = new Worker(toExecute, {\n ...opts.workerOpts,\n trackUnmanagedFds: false,\n workerData: {\n filename: filename.indexOf('file://') === 0\n ? filename\n : pathToFileURL(filename).href,\n dataBuf: stream[kImpl].dataBuf,\n stateBuf: stream[kImpl].stateBuf,\n workerData: {\n $context: {\n threadStreamVersion: version\n },\n ...workerData\n }\n }\n })\n\n // We keep a strong reference for now,\n // we need to start writing first\n worker.stream = new FakeWeakRef(stream)\n\n worker.on('message', onWorkerMessage)\n worker.on('exit', onWorkerExit)\n registry.register(stream, worker)\n\n return worker\n}\n\nfunction drain (stream) {\n assert(!stream[kImpl].sync)\n if (stream[kImpl].needDrain) {\n stream[kImpl].needDrain = false\n stream.emit('drain')\n }\n}\n\nfunction nextFlush (stream) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n\n if (leftover > 0) {\n if (stream[kImpl].buf.length === 0) {\n stream[kImpl].flushing = false\n\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n\n return\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, nextFlush.bind(null, stream))\n } else {\n // multi-byte utf-8\n stream.flush(() => {\n // err is already handled in flush()\n if (stream.destroyed) {\n return\n }\n\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].data.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, nextFlush.bind(null, stream))\n })\n }\n } else if (leftover === 0) {\n if (writeIndex === 0 && stream[kImpl].buf.length === 0) {\n // we had a flushSync in the meanwhile\n return\n }\n stream.flush(() => {\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n nextFlush(stream)\n })\n } else {\n // This should never happen\n destroy(stream, new Error('overwritten'))\n }\n}\n\nfunction onWorkerMessage (msg) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n this.exited = true\n // Terminate the worker.\n this.terminate()\n return\n }\n\n switch (msg.code) {\n case 'READY':\n // Replace the FakeWeakRef with a\n // proper one.\n this.stream = new WeakRef(stream)\n\n stream.flush(() => {\n stream[kImpl].ready = true\n stream.emit('ready')\n })\n break\n case 'ERROR':\n destroy(stream, msg.err)\n break\n case 'EVENT':\n if (Array.isArray(msg.args)) {\n stream.emit(msg.name, ...msg.args)\n } else {\n stream.emit(msg.name, msg.args)\n }\n break\n case 'WARNING':\n process.emitWarning(msg.err)\n break\n default:\n destroy(stream, new Error('this should not happen: ' + msg.code))\n }\n}\n\nfunction onWorkerExit (code) {\n const stream = this.stream.deref()\n if (stream === undefined) {\n // Nothing to do, the worker already exit\n return\n }\n registry.unregister(stream)\n stream.worker.exited = true\n stream.worker.off('exit', onWorkerExit)\n destroy(stream, code !== 0 ? new Error('the worker thread exited') : null)\n}\n\nclass ThreadStream extends EventEmitter {\n constructor (opts = {}) {\n super()\n\n if (opts.bufferSize < 4) {\n throw new Error('bufferSize must at least fit a 4-byte utf-8 char')\n }\n\n this[kImpl] = {}\n this[kImpl].stateBuf = new SharedArrayBuffer(128)\n this[kImpl].state = new Int32Array(this[kImpl].stateBuf)\n this[kImpl].dataBuf = new SharedArrayBuffer(opts.bufferSize || 4 * 1024 * 1024)\n this[kImpl].data = Buffer.from(this[kImpl].dataBuf)\n this[kImpl].sync = opts.sync || false\n this[kImpl].ending = false\n this[kImpl].ended = false\n this[kImpl].needDrain = false\n this[kImpl].destroyed = false\n this[kImpl].flushing = false\n this[kImpl].ready = false\n this[kImpl].finished = false\n this[kImpl].errored = null\n this[kImpl].closed = false\n this[kImpl].buf = ''\n\n // TODO (fix): Make private?\n this.worker = createWorker(this, opts) // TODO (fix): make private\n this.on('message', (message, transferList) => {\n this.worker.postMessage(message, transferList)\n })\n }\n\n write (data) {\n if (this[kImpl].destroyed) {\n error(this, new Error('the worker has exited'))\n return false\n }\n\n if (this[kImpl].ending) {\n error(this, new Error('the worker is ending'))\n return false\n }\n\n if (this[kImpl].flushing && this[kImpl].buf.length + data.length >= MAX_STRING) {\n try {\n writeSync(this)\n this[kImpl].flushing = true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n this[kImpl].buf += data\n\n if (this[kImpl].sync) {\n try {\n writeSync(this)\n return true\n } catch (err) {\n destroy(this, err)\n return false\n }\n }\n\n if (!this[kImpl].flushing) {\n this[kImpl].flushing = true\n setImmediate(nextFlush, this)\n }\n\n this[kImpl].needDrain = this[kImpl].data.length - this[kImpl].buf.length - Atomics.load(this[kImpl].state, WRITE_INDEX) <= 0\n return !this[kImpl].needDrain\n }\n\n end () {\n if (this[kImpl].destroyed) {\n return\n }\n\n this[kImpl].ending = true\n end(this)\n }\n\n flush (cb) {\n if (this[kImpl].destroyed) {\n if (typeof cb === 'function') {\n process.nextTick(cb, new Error('the worker has exited'))\n }\n return\n }\n\n // TODO write all .buf\n const writeIndex = Atomics.load(this[kImpl].state, WRITE_INDEX)\n // process._rawDebug(`(flush) readIndex (${Atomics.load(this.state, READ_INDEX)}) writeIndex (${Atomics.load(this.state, WRITE_INDEX)})`)\n wait(this[kImpl].state, READ_INDEX, writeIndex, Infinity, (err, res) => {\n if (err) {\n destroy(this, err)\n process.nextTick(cb, err)\n return\n }\n if (res === 'not-equal') {\n // TODO handle deadlock\n this.flush(cb)\n return\n }\n process.nextTick(cb)\n })\n }\n\n flushSync () {\n if (this[kImpl].destroyed) {\n return\n }\n\n writeSync(this)\n flushSync(this)\n }\n\n unref () {\n this.worker.unref()\n }\n\n ref () {\n this.worker.ref()\n }\n\n get ready () {\n return this[kImpl].ready\n }\n\n get destroyed () {\n return this[kImpl].destroyed\n }\n\n get closed () {\n return this[kImpl].closed\n }\n\n get writable () {\n return !this[kImpl].destroyed && !this[kImpl].ending\n }\n\n get writableEnded () {\n return this[kImpl].ending\n }\n\n get writableFinished () {\n return this[kImpl].finished\n }\n\n get writableNeedDrain () {\n return this[kImpl].needDrain\n }\n\n get writableObjectMode () {\n return false\n }\n\n get writableErrored () {\n return this[kImpl].errored\n }\n}\n\nfunction error (stream, err) {\n setImmediate(() => {\n stream.emit('error', err)\n })\n}\n\nfunction destroy (stream, err) {\n if (stream[kImpl].destroyed) {\n return\n }\n stream[kImpl].destroyed = true\n\n if (err) {\n stream[kImpl].errored = err\n error(stream, err)\n }\n\n if (!stream.worker.exited) {\n stream.worker.terminate()\n .catch(() => {})\n .then(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n } else {\n setImmediate(() => {\n stream[kImpl].closed = true\n stream.emit('close')\n })\n }\n}\n\nfunction write (stream, data, cb) {\n // data is smaller than the shared buffer length\n const current = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n const length = Buffer.byteLength(data)\n stream[kImpl].data.write(data, current)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, current + length)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n cb()\n return true\n}\n\nfunction end (stream) {\n if (stream[kImpl].ended || !stream[kImpl].ending || stream[kImpl].flushing) {\n return\n }\n stream[kImpl].ended = true\n\n try {\n stream.flushSync()\n\n let readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n // process._rawDebug('writing index')\n Atomics.store(stream[kImpl].state, WRITE_INDEX, -1)\n // process._rawDebug(`(end) readIndex (${Atomics.load(stream.state, READ_INDEX)}) writeIndex (${Atomics.load(stream.state, WRITE_INDEX)})`)\n Atomics.notify(stream[kImpl].state, WRITE_INDEX)\n\n // Wait for the process to complete\n let spins = 0\n while (readIndex !== -1) {\n // process._rawDebug(`read = ${read}`)\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n destroy(stream, new Error('end() failed'))\n return\n }\n\n if (++spins === 10) {\n destroy(stream, new Error('end() took too long (10s)'))\n return\n }\n }\n\n process.nextTick(() => {\n stream[kImpl].finished = true\n stream.emit('finish')\n })\n } catch (err) {\n destroy(stream, err)\n }\n // process._rawDebug('end finished...')\n}\n\nfunction writeSync (stream) {\n const cb = () => {\n if (stream[kImpl].ending) {\n end(stream)\n } else if (stream[kImpl].needDrain) {\n process.nextTick(drain, stream)\n }\n }\n stream[kImpl].flushing = false\n\n while (stream[kImpl].buf.length !== 0) {\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n let leftover = stream[kImpl].data.length - writeIndex\n if (leftover === 0) {\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n continue\n } else if (leftover < 0) {\n // stream should never happen\n throw new Error('overwritten')\n }\n\n let toWrite = stream[kImpl].buf.slice(0, leftover)\n let toWriteBytes = Buffer.byteLength(toWrite)\n if (toWriteBytes <= leftover) {\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n // process._rawDebug('writing ' + toWrite.length)\n write(stream, toWrite, cb)\n } else {\n // multi-byte utf-8\n flushSync(stream)\n Atomics.store(stream[kImpl].state, READ_INDEX, 0)\n Atomics.store(stream[kImpl].state, WRITE_INDEX, 0)\n\n // Find a toWrite length that fits the buffer\n // it must exists as the buffer is at least 4 bytes length\n // and the max utf-8 length for a char is 4 bytes.\n while (toWriteBytes > stream[kImpl].buf.length) {\n leftover = leftover / 2\n toWrite = stream[kImpl].buf.slice(0, leftover)\n toWriteBytes = Buffer.byteLength(toWrite)\n }\n stream[kImpl].buf = stream[kImpl].buf.slice(leftover)\n write(stream, toWrite, cb)\n }\n }\n}\n\nfunction flushSync (stream) {\n if (stream[kImpl].flushing) {\n throw new Error('unable to flush while flushing')\n }\n\n // process._rawDebug('flushSync started')\n\n const writeIndex = Atomics.load(stream[kImpl].state, WRITE_INDEX)\n\n let spins = 0\n\n // TODO handle deadlock\n while (true) {\n const readIndex = Atomics.load(stream[kImpl].state, READ_INDEX)\n\n if (readIndex === -2) {\n throw Error('_flushSync failed')\n }\n\n // process._rawDebug(`(flushSync) readIndex (${readIndex}) writeIndex (${writeIndex})`)\n if (readIndex !== writeIndex) {\n // TODO stream timeouts for some reason.\n Atomics.wait(stream[kImpl].state, READ_INDEX, readIndex, 1000)\n } else {\n break\n }\n\n if (++spins === 10) {\n throw new Error('_flushSync took too long (10s)')\n }\n }\n // process._rawDebug('flushSync finished')\n}\n\nmodule.exports = ThreadStream\n","'use strict'\n\nconst { createRequire } = require('module')\nconst getCallers = require('./caller')\nconst { join, isAbsolute, sep } = require('node:path')\nconst sleep = require('atomic-sleep')\nconst onExit = require('on-exit-leak-free')\nconst ThreadStream = require('thread-stream')\n\nfunction setupOnExit (stream) {\n // This is leak free, it does not leave event handlers\n onExit.register(stream, autoEnd)\n onExit.registerBeforeExit(stream, flush)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n}\n\nfunction buildStream (filename, workerData, workerOpts, sync) {\n const stream = new ThreadStream({\n filename,\n workerData,\n workerOpts,\n sync\n })\n\n stream.on('ready', onReady)\n stream.on('close', function () {\n process.removeListener('exit', onExit)\n })\n\n process.on('exit', onExit)\n\n function onReady () {\n process.removeListener('exit', onExit)\n stream.unref()\n\n if (workerOpts.autoEnd !== false) {\n setupOnExit(stream)\n }\n }\n\n function onExit () {\n /* istanbul ignore next */\n if (stream.closed) {\n return\n }\n stream.flushSync()\n // Apparently there is a very sporadic race condition\n // that in certain OS would prevent the messages to be flushed\n // because the thread might not have been created still.\n // Unfortunately we need to sleep(100) in this case.\n sleep(100)\n stream.end()\n }\n\n return stream\n}\n\nfunction autoEnd (stream) {\n stream.ref()\n stream.flushSync()\n stream.end()\n stream.once('close', function () {\n stream.unref()\n })\n}\n\nfunction flush (stream) {\n stream.flushSync()\n}\n\nfunction transport (fullOptions) {\n const { pipeline, targets, levels, dedupe, worker = {}, caller = getCallers(), sync = false } = fullOptions\n\n const options = {\n ...fullOptions.options\n }\n\n // Backwards compatibility\n const callers = typeof caller === 'string' ? [caller] : caller\n\n // This will be eventually modified by bundlers\n const bundlerOverrides = '__bundlerPathsOverrides' in globalThis ? globalThis.__bundlerPathsOverrides : {}\n\n let target = fullOptions.target\n\n if (target && targets) {\n throw new Error('only one of target or targets can be specified')\n }\n\n if (targets) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.targets = targets.filter(dest => dest.target).map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })\n options.pipelines = targets.filter(dest => dest.pipeline).map((dest) => {\n return dest.pipeline.map((t) => {\n return {\n ...t,\n level: dest.level, // duplicate the pipeline `level` property defined in the upper level\n target: fixTarget(t.target)\n }\n })\n })\n } else if (pipeline) {\n target = bundlerOverrides['pino-worker'] || join(__dirname, 'worker.js')\n options.pipelines = [pipeline.map((dest) => {\n return {\n ...dest,\n target: fixTarget(dest.target)\n }\n })]\n }\n\n if (levels) {\n options.levels = levels\n }\n\n if (dedupe) {\n options.dedupe = dedupe\n }\n\n options.pinoWillSendConfig = true\n\n return buildStream(fixTarget(target), options, worker, sync)\n\n function fixTarget (origin) {\n origin = bundlerOverrides[origin] || origin\n\n if (isAbsolute(origin) || origin.indexOf('file://') === 0) {\n return origin\n }\n\n if (origin === 'pino/file') {\n return join(__dirname, '..', 'file.js')\n }\n\n let fixTarget\n\n for (const filePath of callers) {\n try {\n const context = filePath === 'node:repl'\n ? process.cwd() + sep\n : filePath\n\n fixTarget = createRequire(context).resolve(origin)\n break\n } catch (err) {\n // Silent catch\n continue\n }\n }\n\n if (!fixTarget) {\n throw new Error(`unable to determine transport target for \"${origin}\"`)\n }\n\n return fixTarget\n }\n}\n\nmodule.exports = transport\n","'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst format = require('quick-format-unescaped')\nconst { mapHttpRequest, mapHttpResponse } = require('pino-std-serializers')\nconst SonicBoom = require('sonic-boom')\nconst onExit = require('on-exit-leak-free')\nconst {\n lsCacheSym,\n chindingsSym,\n writeSym,\n serializersSym,\n formatOptsSym,\n endSym,\n stringifiersSym,\n stringifySym,\n stringifySafeSym,\n wildcardFirstSym,\n nestedKeySym,\n formattersSym,\n messageKeySym,\n errorKeySym,\n nestedKeyStrSym,\n msgPrefixSym\n} = require('./symbols')\nconst { isMainThread } = require('worker_threads')\nconst transport = require('./transport')\n\nfunction noop () {\n}\n\nfunction genLog (level, hook) {\n if (!hook) return LOG\n\n return function hookWrappedLog (...args) {\n hook.call(this, args, LOG, level)\n }\n\n function LOG (o, ...n) {\n if (typeof o === 'object') {\n let msg = o\n if (o !== null) {\n if (o.method && o.headers && o.socket) {\n o = mapHttpRequest(o)\n } else if (typeof o.setHeader === 'function') {\n o = mapHttpResponse(o)\n }\n }\n let formatParams\n if (msg === null && n.length === 0) {\n formatParams = [null]\n } else {\n msg = n.shift()\n formatParams = n\n }\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](o, format(msg, formatParams, this[formatOptsSym]), level)\n } else {\n let msg = o === undefined ? n.shift() : o\n\n // We do not use a coercive check for `msg` as it is\n // measurably slower than the explicit checks.\n if (typeof this[msgPrefixSym] === 'string' && msg !== undefined && msg !== null) {\n msg = this[msgPrefixSym] + msg\n }\n this[writeSym](null, format(msg, n, this[formatOptsSym]), level)\n }\n }\n}\n\n// magically escape strings for json\n// relying on their charCodeAt\n// everything below 32 needs JSON.stringify()\n// 34 and 92 happens all the time, so we\n// have a fast case for them\nfunction asString (str) {\n let result = ''\n let last = 0\n let found = false\n let point = 255\n const l = str.length\n if (l > 100) {\n return JSON.stringify(str)\n }\n for (var i = 0; i < l && point >= 32; i++) {\n point = str.charCodeAt(i)\n if (point === 34 || point === 92) {\n result += str.slice(last, i) + '\\\\'\n last = i\n found = true\n }\n }\n if (!found) {\n result = str\n } else {\n result += str.slice(last)\n }\n return point < 32 ? JSON.stringify(str) : '\"' + result + '\"'\n}\n\nfunction asJson (obj, msg, num, time) {\n const stringify = this[stringifySym]\n const stringifySafe = this[stringifySafeSym]\n const stringifiers = this[stringifiersSym]\n const end = this[endSym]\n const chindings = this[chindingsSym]\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const messageKey = this[messageKeySym]\n const errorKey = this[errorKeySym]\n let data = this[lsCacheSym][num] + time\n\n // we need the child bindings added to the output first so instance logged\n // objects can take precedence when JSON.parse-ing the resulting log line\n data = data + chindings\n\n let value\n if (formatters.log) {\n obj = formatters.log(obj)\n }\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n let propStr = ''\n for (const key in obj) {\n value = obj[key]\n if (Object.prototype.hasOwnProperty.call(obj, key) && value !== undefined) {\n if (serializers[key]) {\n value = serializers[key](value)\n } else if (key === errorKey && serializers.err) {\n value = serializers.err(value)\n }\n\n const stringifier = stringifiers[key] || wildcardStringifier\n\n switch (typeof value) {\n case 'undefined':\n case 'function':\n continue\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n break\n case 'string':\n value = (stringifier || asString)(value)\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n }\n if (value === undefined) continue\n const strKey = asString(key)\n propStr += ',' + strKey + ':' + value\n }\n }\n\n let msgStr = ''\n if (msg !== undefined) {\n value = serializers[messageKey] ? serializers[messageKey](msg) : msg\n const stringifier = stringifiers[messageKey] || wildcardStringifier\n\n switch (typeof value) {\n case 'function':\n break\n case 'number':\n /* eslint no-fallthrough: \"off\" */\n if (Number.isFinite(value) === false) {\n value = null\n }\n // this case explicitly falls through to the next one\n case 'boolean':\n if (stringifier) value = stringifier(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n case 'string':\n value = (stringifier || asString)(value)\n msgStr = ',\"' + messageKey + '\":' + value\n break\n default:\n value = (stringifier || stringify)(value, stringifySafe)\n msgStr = ',\"' + messageKey + '\":' + value\n }\n }\n\n if (this[nestedKeySym] && propStr) {\n // place all the obj properties under the specified key\n // the nested key is already formatted from the constructor\n return data + this[nestedKeyStrSym] + propStr.slice(1) + '}' + msgStr + end\n } else {\n return data + propStr + msgStr + end\n }\n}\n\nfunction asChindings (instance, bindings) {\n let value\n let data = instance[chindingsSym]\n const stringify = instance[stringifySym]\n const stringifySafe = instance[stringifySafeSym]\n const stringifiers = instance[stringifiersSym]\n const wildcardStringifier = stringifiers[wildcardFirstSym]\n const serializers = instance[serializersSym]\n const formatter = instance[formattersSym].bindings\n bindings = formatter(bindings)\n\n for (const key in bindings) {\n value = bindings[key]\n const valid = key !== 'level' &&\n key !== 'serializers' &&\n key !== 'formatters' &&\n key !== 'customLevels' &&\n bindings.hasOwnProperty(key) &&\n value !== undefined\n if (valid === true) {\n value = serializers[key] ? serializers[key](value) : value\n value = (stringifiers[key] || wildcardStringifier || stringify)(value, stringifySafe)\n if (value === undefined) continue\n data += ',\"' + key + '\":' + value\n }\n }\n return data\n}\n\nfunction hasBeenTampered (stream) {\n return stream.write !== stream.constructor.prototype.write\n}\n\nfunction buildSafeSonicBoom (opts) {\n const stream = new SonicBoom(opts)\n stream.on('error', filterBrokenPipe)\n // If we are sync: false, we must flush on exit\n if (!opts.sync && isMainThread) {\n onExit.register(stream, autoEnd)\n\n stream.on('close', function () {\n onExit.unregister(stream)\n })\n }\n return stream\n\n function filterBrokenPipe (err) {\n // Impossible to replicate across all operating systems\n /* istanbul ignore next */\n if (err.code === 'EPIPE') {\n // If we get EPIPE, we should stop logging here\n // however we have no control to the consumer of\n // SonicBoom, so we just overwrite the write method\n stream.write = noop\n stream.end = noop\n stream.flushSync = noop\n stream.destroy = noop\n return\n }\n stream.removeListener('error', filterBrokenPipe)\n stream.emit('error', err)\n }\n}\n\nfunction autoEnd (stream, eventName) {\n // This check is needed only on some platforms\n /* istanbul ignore next */\n if (stream.destroyed) {\n return\n }\n\n if (eventName === 'beforeExit') {\n // We still have an event loop, let's use it\n stream.flush()\n stream.on('drain', function () {\n stream.end()\n })\n } else {\n // For some reason istanbul is not detecting this, but it's there\n /* istanbul ignore next */\n // We do not have an event loop, so flush synchronously\n stream.flushSync()\n }\n}\n\nfunction createArgsNormalizer (defaultOptions) {\n return function normalizeArgs (instance, caller, opts = {}, stream) {\n // support stream as a string\n if (typeof opts === 'string') {\n stream = buildSafeSonicBoom({ dest: opts })\n opts = {}\n } else if (typeof stream === 'string') {\n if (opts && opts.transport) {\n throw Error('only one of option.transport or stream can be specified')\n }\n stream = buildSafeSonicBoom({ dest: stream })\n } else if (opts instanceof SonicBoom || opts.writable || opts._writableState) {\n stream = opts\n opts = {}\n } else if (opts.transport) {\n if (opts.transport instanceof SonicBoom || opts.transport.writable || opts.transport._writableState) {\n throw Error('option.transport do not allow stream, please pass to option directly. e.g. pino(transport)')\n }\n if (opts.transport.targets && opts.transport.targets.length && opts.formatters && typeof opts.formatters.level === 'function') {\n throw Error('option.transport.targets do not allow custom level formatters')\n }\n\n let customLevels\n if (opts.customLevels) {\n customLevels = opts.useOnlyCustomLevels ? opts.customLevels : Object.assign({}, opts.levels, opts.customLevels)\n }\n stream = transport({ caller, ...opts.transport, levels: customLevels })\n }\n opts = Object.assign({}, defaultOptions, opts)\n opts.serializers = Object.assign({}, defaultOptions.serializers, opts.serializers)\n opts.formatters = Object.assign({}, defaultOptions.formatters, opts.formatters)\n\n if (opts.prettyPrint) {\n throw new Error('prettyPrint option is no longer supported, see the pino-pretty package (https://github.com/pinojs/pino-pretty)')\n }\n\n const { enabled, onChild } = opts\n if (enabled === false) opts.level = 'silent'\n if (!onChild) opts.onChild = noop\n if (!stream) {\n if (!hasBeenTampered(process.stdout)) {\n // If process.stdout.fd is undefined, it means that we are running\n // in a worker thread. Let's assume we are logging to file descriptor 1.\n stream = buildSafeSonicBoom({ fd: process.stdout.fd || 1 })\n } else {\n stream = process.stdout\n }\n }\n return { opts, stream }\n }\n}\n\nfunction stringify (obj, stringifySafeFn) {\n try {\n return JSON.stringify(obj)\n } catch (_) {\n try {\n const stringify = stringifySafeFn || this[stringifySafeSym]\n return stringify(obj)\n } catch (_) {\n return '\"[unable to serialize, circular reference is too complex to analyze]\"'\n }\n }\n}\n\nfunction buildFormatters (level, bindings, log) {\n return {\n level,\n bindings,\n log\n }\n}\n\n/**\n * Convert a string integer file descriptor to a proper native integer\n * file descriptor.\n *\n * @param {string} destination The file descriptor string to attempt to convert.\n *\n * @returns {Number}\n */\nfunction normalizeDestFileDescriptor (destination) {\n const fd = Number(destination)\n if (typeof destination === 'string' && Number.isFinite(fd)) {\n return fd\n }\n // destination could be undefined if we are in a worker\n if (destination === undefined) {\n // This is stdout in UNIX systems\n return 1\n }\n return destination\n}\n\nmodule.exports = {\n noop,\n buildSafeSonicBoom,\n asChindings,\n asJson,\n genLog,\n createArgsNormalizer,\n stringify,\n buildFormatters,\n normalizeDestFileDescriptor\n}\n","/**\n * Represents default log level values\n *\n * @enum {number}\n */\nconst DEFAULT_LEVELS = {\n trace: 10,\n debug: 20,\n info: 30,\n warn: 40,\n error: 50,\n fatal: 60\n}\n\n/**\n * Represents sort order direction: `ascending` or `descending`\n *\n * @enum {string}\n */\nconst SORTING_ORDER = {\n ASC: 'ASC',\n DESC: 'DESC'\n}\n\nmodule.exports = {\n DEFAULT_LEVELS,\n SORTING_ORDER\n}\n","'use strict'\n/* eslint no-prototype-builtins: 0 */\nconst {\n lsCacheSym,\n levelValSym,\n useOnlyCustomLevelsSym,\n streamSym,\n formattersSym,\n hooksSym,\n levelCompSym\n} = require('./symbols')\nconst { noop, genLog } = require('./tools')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./constants')\n\nconst levelMethods = {\n fatal: (hook) => {\n const logFatal = genLog(DEFAULT_LEVELS.fatal, hook)\n return function (...args) {\n const stream = this[streamSym]\n logFatal.call(this, ...args)\n if (typeof stream.flushSync === 'function') {\n try {\n stream.flushSync()\n } catch (e) {\n // https://github.com/pinojs/pino/pull/740#discussion_r346788313\n }\n }\n }\n },\n error: (hook) => genLog(DEFAULT_LEVELS.error, hook),\n warn: (hook) => genLog(DEFAULT_LEVELS.warn, hook),\n info: (hook) => genLog(DEFAULT_LEVELS.info, hook),\n debug: (hook) => genLog(DEFAULT_LEVELS.debug, hook),\n trace: (hook) => genLog(DEFAULT_LEVELS.trace, hook)\n}\n\nconst nums = Object.keys(DEFAULT_LEVELS).reduce((o, k) => {\n o[DEFAULT_LEVELS[k]] = k\n return o\n}, {})\n\nconst initialLsCache = Object.keys(nums).reduce((o, k) => {\n o[k] = '{\"level\":' + Number(k)\n return o\n}, {})\n\nfunction genLsCache (instance) {\n const formatter = instance[formattersSym].level\n const { labels } = instance.levels\n const cache = {}\n for (const label in labels) {\n const level = formatter(labels[label], Number(label))\n cache[label] = JSON.stringify(level).slice(0, -1)\n }\n instance[lsCacheSym] = cache\n return instance\n}\n\nfunction isStandardLevel (level, useOnlyCustomLevels) {\n if (useOnlyCustomLevels) {\n return false\n }\n\n switch (level) {\n case 'fatal':\n case 'error':\n case 'warn':\n case 'info':\n case 'debug':\n case 'trace':\n return true\n default:\n return false\n }\n}\n\nfunction setLevel (level) {\n const { labels, values } = this.levels\n if (typeof level === 'number') {\n if (labels[level] === undefined) throw Error('unknown level value' + level)\n level = labels[level]\n }\n if (values[level] === undefined) throw Error('unknown level ' + level)\n const preLevelVal = this[levelValSym]\n const levelVal = this[levelValSym] = values[level]\n const useOnlyCustomLevelsVal = this[useOnlyCustomLevelsSym]\n const levelComparison = this[levelCompSym]\n const hook = this[hooksSym].logMethod\n\n for (const key in values) {\n if (levelComparison(values[key], levelVal) === false) {\n this[key] = noop\n continue\n }\n this[key] = isStandardLevel(key, useOnlyCustomLevelsVal) ? levelMethods[key](hook) : genLog(values[key], hook)\n }\n\n this.emit(\n 'level-change',\n level,\n levelVal,\n labels[preLevelVal],\n preLevelVal,\n this\n )\n}\n\nfunction getLevel (level) {\n const { levels, levelVal } = this\n // protection against potential loss of Pino scope from serializers (edge case with circular refs - https://github.com/pinojs/pino/issues/833)\n return (levels && levels.labels) ? levels.labels[levelVal] : ''\n}\n\nfunction isLevelEnabled (logLevel) {\n const { values } = this.levels\n const logLevelVal = values[logLevel]\n return logLevelVal !== undefined && this[levelCompSym](logLevelVal, this[levelValSym])\n}\n\n/**\n * Determine if the given `current` level is enabled by comparing it\n * against the current threshold (`expected`).\n *\n * @param {SORTING_ORDER} direction comparison direction \"ASC\" or \"DESC\"\n * @param {number} current current log level number representation\n * @param {number} expected threshold value to compare with\n * @returns {boolean}\n */\nfunction compareLevel (direction, current, expected) {\n if (direction === SORTING_ORDER.DESC) {\n return current <= expected\n }\n\n return current >= expected\n}\n\n/**\n * Create a level comparison function based on `levelComparison`\n * it could a default function which compares levels either in \"ascending\" or \"descending\" order or custom comparison function\n *\n * @param {SORTING_ORDER | Function} levelComparison sort levels order direction or custom comparison function\n * @returns Function\n */\nfunction genLevelComparison (levelComparison) {\n if (typeof levelComparison === 'string') {\n return compareLevel.bind(null, levelComparison)\n }\n\n return levelComparison\n}\n\nfunction mappings (customLevels = null, useOnlyCustomLevels = false) {\n const customNums = customLevels\n /* eslint-disable */\n ? Object.keys(customLevels).reduce((o, k) => {\n o[customLevels[k]] = k\n return o\n }, {})\n : null\n /* eslint-enable */\n\n const labels = Object.assign(\n Object.create(Object.prototype, { Infinity: { value: 'silent' } }),\n useOnlyCustomLevels ? null : nums,\n customNums\n )\n const values = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n return { labels, values }\n}\n\nfunction assertDefaultLevelFound (defaultLevel, customLevels, useOnlyCustomLevels) {\n if (typeof defaultLevel === 'number') {\n const values = [].concat(\n Object.keys(customLevels || {}).map(key => customLevels[key]),\n useOnlyCustomLevels ? [] : Object.keys(nums).map(level => +level),\n Infinity\n )\n if (!values.includes(defaultLevel)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n return\n }\n\n const labels = Object.assign(\n Object.create(Object.prototype, { silent: { value: Infinity } }),\n useOnlyCustomLevels ? null : DEFAULT_LEVELS,\n customLevels\n )\n if (!(defaultLevel in labels)) {\n throw Error(`default level:${defaultLevel} must be included in custom levels`)\n }\n}\n\nfunction assertNoLevelCollisions (levels, customLevels) {\n const { labels, values } = levels\n for (const k in customLevels) {\n if (k in values) {\n throw Error('levels cannot be overridden')\n }\n if (customLevels[k] in labels) {\n throw Error('pre-existing level values cannot be used for new levels')\n }\n }\n}\n\n/**\n * Validates whether `levelComparison` is correct\n *\n * @throws Error\n * @param {SORTING_ORDER | Function} levelComparison - value to validate\n * @returns\n */\nfunction assertLevelComparison (levelComparison) {\n if (typeof levelComparison === 'function') {\n return\n }\n\n if (typeof levelComparison === 'string' && Object.values(SORTING_ORDER).includes(levelComparison)) {\n return\n }\n\n throw new Error('Levels comparison should be one of \"ASC\", \"DESC\" or \"function\" type')\n}\n\nmodule.exports = {\n initialLsCache,\n genLsCache,\n levelMethods,\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n assertNoLevelCollisions,\n assertDefaultLevelFound,\n genLevelComparison,\n assertLevelComparison\n}\n","'use strict'\n\nmodule.exports = { version: '9.9.0' }\n","'use strict'\n\n/* eslint no-prototype-builtins: 0 */\n\nconst { EventEmitter } = require('node:events')\nconst {\n lsCacheSym,\n levelValSym,\n setLevelSym,\n getLevelSym,\n chindingsSym,\n parsedChindingsSym,\n mixinSym,\n asJsonSym,\n writeSym,\n mixinMergeStrategySym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n serializersSym,\n formattersSym,\n errorKeySym,\n messageKeySym,\n useOnlyCustomLevelsSym,\n needsMetadataGsym,\n redactFmtSym,\n stringifySym,\n formatOptsSym,\n stringifiersSym,\n msgPrefixSym,\n hooksSym\n} = require('./symbols')\nconst {\n getLevel,\n setLevel,\n isLevelEnabled,\n mappings,\n initialLsCache,\n genLsCache,\n assertNoLevelCollisions\n} = require('./levels')\nconst {\n asChindings,\n asJson,\n buildFormatters,\n stringify\n} = require('./tools')\nconst {\n version\n} = require('./meta')\nconst redaction = require('./redaction')\n\n// note: use of class is satirical\n// https://github.com/pinojs/pino/pull/433#pullrequestreview-127703127\nconst constructor = class Pino {}\nconst prototype = {\n constructor,\n child,\n bindings,\n setBindings,\n flush,\n isLevelEnabled,\n version,\n get level () { return this[getLevelSym]() },\n set level (lvl) { this[setLevelSym](lvl) },\n get levelVal () { return this[levelValSym] },\n set levelVal (n) { throw Error('levelVal is read-only') },\n get msgPrefix () { return this[msgPrefixSym] },\n [lsCacheSym]: initialLsCache,\n [writeSym]: write,\n [asJsonSym]: asJson,\n [getLevelSym]: getLevel,\n [setLevelSym]: setLevel\n}\n\nObject.setPrototypeOf(prototype, EventEmitter.prototype)\n\n// exporting and consuming the prototype object using factory pattern fixes scoping issues with getters when serializing\nmodule.exports = function () {\n return Object.create(prototype)\n}\n\nconst resetChildingsFormatter = bindings => bindings\nfunction child (bindings, options) {\n if (!bindings) {\n throw Error('missing bindings for child Pino')\n }\n options = options || {} // default options to empty object\n const serializers = this[serializersSym]\n const formatters = this[formattersSym]\n const instance = Object.create(this)\n\n if (options.hasOwnProperty('serializers') === true) {\n instance[serializersSym] = Object.create(null)\n\n for (const k in serializers) {\n instance[serializersSym][k] = serializers[k]\n }\n const parentSymbols = Object.getOwnPropertySymbols(serializers)\n /* eslint no-var: off */\n for (var i = 0; i < parentSymbols.length; i++) {\n const ks = parentSymbols[i]\n instance[serializersSym][ks] = serializers[ks]\n }\n\n for (const bk in options.serializers) {\n instance[serializersSym][bk] = options.serializers[bk]\n }\n const bindingsSymbols = Object.getOwnPropertySymbols(options.serializers)\n for (var bi = 0; bi < bindingsSymbols.length; bi++) {\n const bks = bindingsSymbols[bi]\n instance[serializersSym][bks] = options.serializers[bks]\n }\n } else instance[serializersSym] = serializers\n if (options.hasOwnProperty('formatters')) {\n const { level, bindings: chindings, log } = options.formatters\n instance[formattersSym] = buildFormatters(\n level || formatters.level,\n chindings || resetChildingsFormatter,\n log || formatters.log\n )\n } else {\n instance[formattersSym] = buildFormatters(\n formatters.level,\n resetChildingsFormatter,\n formatters.log\n )\n }\n if (options.hasOwnProperty('customLevels') === true) {\n assertNoLevelCollisions(this.levels, options.customLevels)\n instance.levels = mappings(options.customLevels, instance[useOnlyCustomLevelsSym])\n genLsCache(instance)\n }\n\n // redact must place before asChindings and only replace if exist\n if ((typeof options.redact === 'object' && options.redact !== null) || Array.isArray(options.redact)) {\n instance.redact = options.redact // replace redact directly\n const stringifiers = redaction(instance.redact, stringify)\n const formatOpts = { stringify: stringifiers[redactFmtSym] }\n instance[stringifySym] = stringify\n instance[stringifiersSym] = stringifiers\n instance[formatOptsSym] = formatOpts\n }\n\n if (typeof options.msgPrefix === 'string') {\n instance[msgPrefixSym] = (this[msgPrefixSym] || '') + options.msgPrefix\n }\n\n instance[chindingsSym] = asChindings(instance, bindings)\n const childLevel = options.level || this.level\n instance[setLevelSym](childLevel)\n this.onChild(instance)\n return instance\n}\n\nfunction bindings () {\n const chindings = this[chindingsSym]\n const chindingsJson = `{${chindings.substr(1)}}` // at least contains ,\"pid\":7068,\"hostname\":\"myMac\"\n const bindingsFromJson = JSON.parse(chindingsJson)\n delete bindingsFromJson.pid\n delete bindingsFromJson.hostname\n return bindingsFromJson\n}\n\nfunction setBindings (newBindings) {\n const chindings = asChindings(this, newBindings)\n this[chindingsSym] = chindings\n delete this[parsedChindingsSym]\n}\n\n/**\n * Default strategy for creating `mergeObject` from arguments and the result from `mixin()`.\n * Fields from `mergeObject` have higher priority in this strategy.\n *\n * @param {Object} mergeObject The object a user has supplied to the logging function.\n * @param {Object} mixinObject The result of the `mixin` method.\n * @return {Object}\n */\nfunction defaultMixinMergeStrategy (mergeObject, mixinObject) {\n return Object.assign(mixinObject, mergeObject)\n}\n\nfunction write (_obj, msg, num) {\n const t = this[timeSym]()\n const mixin = this[mixinSym]\n const errorKey = this[errorKeySym]\n const messageKey = this[messageKeySym]\n const mixinMergeStrategy = this[mixinMergeStrategySym] || defaultMixinMergeStrategy\n let obj\n const streamWriteHook = this[hooksSym].streamWrite\n\n if (_obj === undefined || _obj === null) {\n obj = {}\n } else if (_obj instanceof Error) {\n obj = { [errorKey]: _obj }\n if (msg === undefined) {\n msg = _obj.message\n }\n } else {\n obj = _obj\n if (msg === undefined && _obj[messageKey] === undefined && _obj[errorKey]) {\n msg = _obj[errorKey].message\n }\n }\n\n if (mixin) {\n obj = mixinMergeStrategy(obj, mixin(obj, num, this))\n }\n\n const s = this[asJsonSym](obj, msg, num, t)\n\n const stream = this[streamSym]\n if (stream[needsMetadataGsym] === true) {\n stream.lastLevel = num\n stream.lastObj = obj\n stream.lastMsg = msg\n stream.lastTime = t.slice(this[timeSliceIndexSym])\n stream.lastLogger = this // for child loggers\n }\n stream.write(streamWriteHook ? streamWriteHook(s) : s)\n}\n\nfunction noop () {}\n\nfunction flush (cb) {\n if (cb != null && typeof cb !== 'function') {\n throw Error('callback must be a function')\n }\n\n const stream = this[streamSym]\n\n if (typeof stream.flush === 'function') {\n stream.flush(cb || noop)\n } else if (cb) cb()\n}\n","'use strict'\n\nconst { hasOwnProperty } = Object.prototype\n\nconst stringify = configure()\n\n// @ts-expect-error\nstringify.configure = configure\n// @ts-expect-error\nstringify.stringify = stringify\n\n// @ts-expect-error\nstringify.default = stringify\n\n// @ts-expect-error used for named export\nexports.stringify = stringify\n// @ts-expect-error used for named export\nexports.configure = configure\n\nmodule.exports = stringify\n\n// eslint-disable-next-line no-control-regex\nconst strEscapeSequencesRegExp = /[\\u0000-\\u001f\\u0022\\u005c\\ud800-\\udfff]/\n\n// Escape C0 control characters, double quotes, the backslash and every code\n// unit with a numeric value in the inclusive range 0xD800 to 0xDFFF.\nfunction strEscape (str) {\n // Some magic numbers that worked out fine while benchmarking with v8 8.0\n if (str.length < 5000 && !strEscapeSequencesRegExp.test(str)) {\n return `\"${str}\"`\n }\n return JSON.stringify(str)\n}\n\nfunction sort (array, comparator) {\n // Insertion sort is very efficient for small input sizes, but it has a bad\n // worst case complexity. Thus, use native array sort for bigger values.\n if (array.length > 2e2 || comparator) {\n return array.sort(comparator)\n }\n for (let i = 1; i < array.length; i++) {\n const currentValue = array[i]\n let position = i\n while (position !== 0 && array[position - 1] > currentValue) {\n array[position] = array[position - 1]\n position--\n }\n array[position] = currentValue\n }\n return array\n}\n\nconst typedArrayPrototypeGetSymbolToStringTag =\n Object.getOwnPropertyDescriptor(\n Object.getPrototypeOf(\n Object.getPrototypeOf(\n new Int8Array()\n )\n ),\n Symbol.toStringTag\n ).get\n\nfunction isTypedArrayWithEntries (value) {\n return typedArrayPrototypeGetSymbolToStringTag.call(value) !== undefined && value.length !== 0\n}\n\nfunction stringifyTypedArray (array, separator, maximumBreadth) {\n if (array.length < maximumBreadth) {\n maximumBreadth = array.length\n }\n const whitespace = separator === ',' ? '' : ' '\n let res = `\"0\":${whitespace}${array[0]}`\n for (let i = 1; i < maximumBreadth; i++) {\n res += `${separator}\"${i}\":${whitespace}${array[i]}`\n }\n return res\n}\n\nfunction getCircularValueOption (options) {\n if (hasOwnProperty.call(options, 'circularValue')) {\n const circularValue = options.circularValue\n if (typeof circularValue === 'string') {\n return `\"${circularValue}\"`\n }\n if (circularValue == null) {\n return circularValue\n }\n if (circularValue === Error || circularValue === TypeError) {\n return {\n toString () {\n throw new TypeError('Converting circular structure to JSON')\n }\n }\n }\n throw new TypeError('The \"circularValue\" argument must be of type string or the value null or undefined')\n }\n return '\"[Circular]\"'\n}\n\nfunction getDeterministicOption (options) {\n let value\n if (hasOwnProperty.call(options, 'deterministic')) {\n value = options.deterministic\n if (typeof value !== 'boolean' && typeof value !== 'function') {\n throw new TypeError('The \"deterministic\" argument must be of type boolean or comparator function')\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getBooleanOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'boolean') {\n throw new TypeError(`The \"${key}\" argument must be of type boolean`)\n }\n }\n return value === undefined ? true : value\n}\n\nfunction getPositiveIntegerOption (options, key) {\n let value\n if (hasOwnProperty.call(options, key)) {\n value = options[key]\n if (typeof value !== 'number') {\n throw new TypeError(`The \"${key}\" argument must be of type number`)\n }\n if (!Number.isInteger(value)) {\n throw new TypeError(`The \"${key}\" argument must be an integer`)\n }\n if (value < 1) {\n throw new RangeError(`The \"${key}\" argument must be >= 1`)\n }\n }\n return value === undefined ? Infinity : value\n}\n\nfunction getItemCount (number) {\n if (number === 1) {\n return '1 item'\n }\n return `${number} items`\n}\n\nfunction getUniqueReplacerSet (replacerArray) {\n const replacerSet = new Set()\n for (const value of replacerArray) {\n if (typeof value === 'string' || typeof value === 'number') {\n replacerSet.add(String(value))\n }\n }\n return replacerSet\n}\n\nfunction getStrictOption (options) {\n if (hasOwnProperty.call(options, 'strict')) {\n const value = options.strict\n if (typeof value !== 'boolean') {\n throw new TypeError('The \"strict\" argument must be of type boolean')\n }\n if (value) {\n return (value) => {\n let message = `Object can not safely be stringified. Received type ${typeof value}`\n if (typeof value !== 'function') message += ` (${value.toString()})`\n throw new Error(message)\n }\n }\n }\n}\n\nfunction configure (options) {\n options = { ...options }\n const fail = getStrictOption(options)\n if (fail) {\n if (options.bigint === undefined) {\n options.bigint = false\n }\n if (!('circularValue' in options)) {\n options.circularValue = Error\n }\n }\n const circularValue = getCircularValueOption(options)\n const bigint = getBooleanOption(options, 'bigint')\n const deterministic = getDeterministicOption(options)\n const comparator = typeof deterministic === 'function' ? deterministic : undefined\n const maximumDepth = getPositiveIntegerOption(options, 'maximumDepth')\n const maximumBreadth = getPositiveIntegerOption(options, 'maximumBreadth')\n\n function stringifyFnReplacer (key, parent, stack, replacer, spacer, indentation) {\n let value = parent[key]\n\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n value = replacer.call(parent, key, value)\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n let join = ','\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let whitespace = ''\n let separator = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (deterministic && !isTypedArrayWithEntries(value)) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyFnReplacer(key, value, stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":${whitespace}\"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyArrayReplacer (key, value, stack, replacer, spacer, indentation) {\n if (typeof value === 'object' && value !== null && typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n }\n\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n const originalIndentation = indentation\n let res = ''\n let join = ','\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n if (spacer !== '') {\n indentation += spacer\n res += `\\n${indentation}`\n join = `,\\n${indentation}`\n }\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n if (spacer !== '') {\n res += `\\n${originalIndentation}`\n }\n stack.pop()\n return `[${res}]`\n }\n stack.push(value)\n let whitespace = ''\n if (spacer !== '') {\n indentation += spacer\n join = `,\\n${indentation}`\n whitespace = ' '\n }\n let separator = ''\n for (const key of replacer) {\n const tmp = stringifyArrayReplacer(key, value[key], stack, replacer, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${whitespace}${tmp}`\n separator = join\n }\n }\n if (spacer !== '' && separator.length > 1) {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifyIndent (key, value, stack, spacer, indentation) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again.\n if (typeof value !== 'object') {\n return stringifyIndent(key, value, stack, spacer, indentation)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n const originalIndentation = indentation\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n indentation += spacer\n let res = `\\n${indentation}`\n const join = `,\\n${indentation}`\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n res += join\n }\n const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `${join}\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n res += `\\n${originalIndentation}`\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n indentation += spacer\n const join = `,\\n${indentation}`\n let res = ''\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, join, maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = join\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifyIndent(key, value[key], stack, spacer, indentation)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}: ${tmp}`\n separator = join\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\": \"${getItemCount(removedKeys)} not stringified\"`\n separator = join\n }\n if (separator !== '') {\n res = `\\n${indentation}${res}\\n${originalIndentation}`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringifySimple (key, value, stack) {\n switch (typeof value) {\n case 'string':\n return strEscape(value)\n case 'object': {\n if (value === null) {\n return 'null'\n }\n if (typeof value.toJSON === 'function') {\n value = value.toJSON(key)\n // Prevent calling `toJSON` again\n if (typeof value !== 'object') {\n return stringifySimple(key, value, stack)\n }\n if (value === null) {\n return 'null'\n }\n }\n if (stack.indexOf(value) !== -1) {\n return circularValue\n }\n\n let res = ''\n\n const hasLength = value.length !== undefined\n if (hasLength && Array.isArray(value)) {\n if (value.length === 0) {\n return '[]'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Array]\"'\n }\n stack.push(value)\n const maximumValuesToStringify = Math.min(value.length, maximumBreadth)\n let i = 0\n for (; i < maximumValuesToStringify - 1; i++) {\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n res += ','\n }\n const tmp = stringifySimple(String(i), value[i], stack)\n res += tmp !== undefined ? tmp : 'null'\n if (value.length - 1 > maximumBreadth) {\n const removedKeys = value.length - maximumBreadth - 1\n res += `,\"... ${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `[${res}]`\n }\n\n let keys = Object.keys(value)\n const keyLength = keys.length\n if (keyLength === 0) {\n return '{}'\n }\n if (maximumDepth < stack.length + 1) {\n return '\"[Object]\"'\n }\n let separator = ''\n let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth)\n if (hasLength && isTypedArrayWithEntries(value)) {\n res += stringifyTypedArray(value, ',', maximumBreadth)\n keys = keys.slice(value.length)\n maximumPropertiesToStringify -= value.length\n separator = ','\n }\n if (deterministic) {\n keys = sort(keys, comparator)\n }\n stack.push(value)\n for (let i = 0; i < maximumPropertiesToStringify; i++) {\n const key = keys[i]\n const tmp = stringifySimple(key, value[key], stack)\n if (tmp !== undefined) {\n res += `${separator}${strEscape(key)}:${tmp}`\n separator = ','\n }\n }\n if (keyLength > maximumBreadth) {\n const removedKeys = keyLength - maximumBreadth\n res += `${separator}\"...\":\"${getItemCount(removedKeys)} not stringified\"`\n }\n stack.pop()\n return `{${res}}`\n }\n case 'number':\n return isFinite(value) ? String(value) : fail ? fail(value) : 'null'\n case 'boolean':\n return value === true ? 'true' : 'false'\n case 'undefined':\n return undefined\n case 'bigint':\n if (bigint) {\n return String(value)\n }\n // fallthrough\n default:\n return fail ? fail(value) : undefined\n }\n }\n\n function stringify (value, replacer, space) {\n if (arguments.length > 1) {\n let spacer = ''\n if (typeof space === 'number') {\n spacer = ' '.repeat(Math.min(space, 10))\n } else if (typeof space === 'string') {\n spacer = space.slice(0, 10)\n }\n if (replacer != null) {\n if (typeof replacer === 'function') {\n return stringifyFnReplacer('', { '': value }, [], replacer, spacer, '')\n }\n if (Array.isArray(replacer)) {\n return stringifyArrayReplacer('', value, [], getUniqueReplacerSet(replacer), spacer, '')\n }\n }\n if (spacer.length !== 0) {\n return stringifyIndent('', value, [], spacer, '')\n }\n }\n return stringifySimple('', value, [])\n }\n\n return stringify\n}\n","'use strict'\n\nconst metadata = Symbol.for('pino.metadata')\nconst { DEFAULT_LEVELS } = require('./constants')\n\nconst DEFAULT_INFO_LEVEL = DEFAULT_LEVELS.info\n\nfunction multistream (streamsArray, opts) {\n streamsArray = streamsArray || []\n opts = opts || { dedupe: false }\n\n const streamLevels = Object.create(DEFAULT_LEVELS)\n streamLevels.silent = Infinity\n if (opts.levels && typeof opts.levels === 'object') {\n Object.keys(opts.levels).forEach(i => {\n streamLevels[i] = opts.levels[i]\n })\n }\n\n const res = {\n write,\n add,\n remove,\n emit,\n flushSync,\n end,\n minLevel: 0,\n lastId: 0,\n streams: [],\n clone,\n [metadata]: true,\n streamLevels\n }\n\n if (Array.isArray(streamsArray)) {\n streamsArray.forEach(add, res)\n } else {\n add.call(res, streamsArray)\n }\n\n // clean this object up\n // or it will stay allocated forever\n // as it is closed on the following closures\n streamsArray = null\n\n return res\n\n // we can exit early because the streams are ordered by level\n function write (data) {\n let dest\n const level = this.lastLevel\n const { streams } = this\n // for handling situation when several streams has the same level\n let recordedLevel = 0\n let stream\n\n // if dedupe set to true we send logs to the stream with the highest level\n // therefore, we have to change sorting order\n for (let i = initLoopVar(streams.length, opts.dedupe); checkLoopVar(i, streams.length, opts.dedupe); i = adjustLoopVar(i, opts.dedupe)) {\n dest = streams[i]\n if (dest.level <= level) {\n if (recordedLevel !== 0 && recordedLevel !== dest.level) {\n break\n }\n stream = dest.stream\n if (stream[metadata]) {\n const { lastTime, lastMsg, lastObj, lastLogger } = this\n stream.lastLevel = level\n stream.lastTime = lastTime\n stream.lastMsg = lastMsg\n stream.lastObj = lastObj\n stream.lastLogger = lastLogger\n }\n stream.write(data)\n if (opts.dedupe) {\n recordedLevel = dest.level\n }\n } else if (!opts.dedupe) {\n break\n }\n }\n }\n\n function emit (...args) {\n for (const { stream } of this.streams) {\n if (typeof stream.emit === 'function') {\n stream.emit(...args)\n }\n }\n }\n\n function flushSync () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n }\n }\n\n function add (dest) {\n if (!dest) {\n return res\n }\n\n // Check that dest implements either StreamEntry or DestinationStream\n const isStream = typeof dest.write === 'function' || dest.stream\n const stream_ = dest.write ? dest : dest.stream\n // This is necessary to provide a meaningful error message, otherwise it throws somewhere inside write()\n if (!isStream) {\n throw Error('stream object needs to implement either StreamEntry or DestinationStream interface')\n }\n\n const { streams, streamLevels } = this\n\n let level\n if (typeof dest.levelVal === 'number') {\n level = dest.levelVal\n } else if (typeof dest.level === 'string') {\n level = streamLevels[dest.level]\n } else if (typeof dest.level === 'number') {\n level = dest.level\n } else {\n level = DEFAULT_INFO_LEVEL\n }\n\n const dest_ = {\n stream: stream_,\n level,\n levelVal: undefined,\n id: ++res.lastId\n }\n\n streams.unshift(dest_)\n streams.sort(compareByLevel)\n\n this.minLevel = streams[0].level\n\n return res\n }\n\n function remove (id) {\n const { streams } = this\n const index = streams.findIndex(s => s.id === id)\n\n if (index >= 0) {\n streams.splice(index, 1)\n streams.sort(compareByLevel)\n this.minLevel = streams.length > 0 ? streams[0].level : -1\n }\n\n return res\n }\n\n function end () {\n for (const { stream } of this.streams) {\n if (typeof stream.flushSync === 'function') {\n stream.flushSync()\n }\n stream.end()\n }\n }\n\n function clone (level) {\n const streams = new Array(this.streams.length)\n\n for (let i = 0; i < streams.length; i++) {\n streams[i] = {\n level,\n stream: this.streams[i].stream\n }\n }\n\n return {\n write,\n add,\n remove,\n minLevel: level,\n streams,\n clone,\n emit,\n flushSync,\n [metadata]: true\n }\n }\n}\n\nfunction compareByLevel (a, b) {\n return a.level - b.level\n}\n\nfunction initLoopVar (length, dedupe) {\n return dedupe ? length - 1 : 0\n}\n\nfunction adjustLoopVar (i, dedupe) {\n return dedupe ? i - 1 : i + 1\n}\n\nfunction checkLoopVar (i, length, dedupe) {\n return dedupe ? i >= 0 : i < length\n}\n\nmodule.exports = multistream\n","'use strict'\n\nconst os = require('node:os')\nconst stdSerializers = require('pino-std-serializers')\nconst caller = require('./lib/caller')\nconst redaction = require('./lib/redaction')\nconst time = require('./lib/time')\nconst proto = require('./lib/proto')\nconst symbols = require('./lib/symbols')\nconst { configure } = require('safe-stable-stringify')\nconst { assertDefaultLevelFound, mappings, genLsCache, genLevelComparison, assertLevelComparison } = require('./lib/levels')\nconst { DEFAULT_LEVELS, SORTING_ORDER } = require('./lib/constants')\nconst {\n createArgsNormalizer,\n asChindings,\n buildSafeSonicBoom,\n buildFormatters,\n stringify,\n normalizeDestFileDescriptor,\n noop\n} = require('./lib/tools')\nconst { version } = require('./lib/meta')\nconst {\n chindingsSym,\n redactFmtSym,\n serializersSym,\n timeSym,\n timeSliceIndexSym,\n streamSym,\n stringifySym,\n stringifySafeSym,\n stringifiersSym,\n setLevelSym,\n endSym,\n formatOptsSym,\n messageKeySym,\n errorKeySym,\n nestedKeySym,\n mixinSym,\n levelCompSym,\n useOnlyCustomLevelsSym,\n formattersSym,\n hooksSym,\n nestedKeyStrSym,\n mixinMergeStrategySym,\n msgPrefixSym\n} = symbols\nconst { epochTime, nullTime } = time\nconst { pid } = process\nconst hostname = os.hostname()\nconst defaultErrorSerializer = stdSerializers.err\nconst defaultOptions = {\n level: 'info',\n levelComparison: SORTING_ORDER.ASC,\n levels: DEFAULT_LEVELS,\n messageKey: 'msg',\n errorKey: 'err',\n nestedKey: null,\n enabled: true,\n base: { pid, hostname },\n serializers: Object.assign(Object.create(null), {\n err: defaultErrorSerializer\n }),\n formatters: Object.assign(Object.create(null), {\n bindings (bindings) {\n return bindings\n },\n level (label, number) {\n return { level: number }\n }\n }),\n hooks: {\n logMethod: undefined,\n streamWrite: undefined\n },\n timestamp: epochTime,\n name: undefined,\n redact: null,\n customLevels: null,\n useOnlyCustomLevels: false,\n depthLimit: 5,\n edgeLimit: 100\n}\n\nconst normalize = createArgsNormalizer(defaultOptions)\n\nconst serializers = Object.assign(Object.create(null), stdSerializers)\n\nfunction pino (...args) {\n const instance = {}\n const { opts, stream } = normalize(instance, caller(), ...args)\n\n if (opts.level && typeof opts.level === 'string' && DEFAULT_LEVELS[opts.level.toLowerCase()] !== undefined) opts.level = opts.level.toLowerCase()\n\n const {\n redact,\n crlf,\n serializers,\n timestamp,\n messageKey,\n errorKey,\n nestedKey,\n base,\n name,\n level,\n customLevels,\n levelComparison,\n mixin,\n mixinMergeStrategy,\n useOnlyCustomLevels,\n formatters,\n hooks,\n depthLimit,\n edgeLimit,\n onChild,\n msgPrefix\n } = opts\n\n const stringifySafe = configure({\n maximumDepth: depthLimit,\n maximumBreadth: edgeLimit\n })\n\n const allFormatters = buildFormatters(\n formatters.level,\n formatters.bindings,\n formatters.log\n )\n\n const stringifyFn = stringify.bind({\n [stringifySafeSym]: stringifySafe\n })\n const stringifiers = redact ? redaction(redact, stringifyFn) : {}\n const formatOpts = redact\n ? { stringify: stringifiers[redactFmtSym] }\n : { stringify: stringifyFn }\n const end = '}' + (crlf ? '\\r\\n' : '\\n')\n const coreChindings = asChindings.bind(null, {\n [chindingsSym]: '',\n [serializersSym]: serializers,\n [stringifiersSym]: stringifiers,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [formattersSym]: allFormatters\n })\n\n let chindings = ''\n if (base !== null) {\n if (name === undefined) {\n chindings = coreChindings(base)\n } else {\n chindings = coreChindings(Object.assign({}, base, { name }))\n }\n }\n\n const time = (timestamp instanceof Function)\n ? timestamp\n : (timestamp ? epochTime : nullTime)\n const timeSliceIndex = time().indexOf(':') + 1\n\n if (useOnlyCustomLevels && !customLevels) throw Error('customLevels is required if useOnlyCustomLevels is set true')\n if (mixin && typeof mixin !== 'function') throw Error(`Unknown mixin type \"${typeof mixin}\" - expected \"function\"`)\n if (msgPrefix && typeof msgPrefix !== 'string') throw Error(`Unknown msgPrefix type \"${typeof msgPrefix}\" - expected \"string\"`)\n\n assertDefaultLevelFound(level, customLevels, useOnlyCustomLevels)\n const levels = mappings(customLevels, useOnlyCustomLevels)\n\n if (typeof stream.emit === 'function') {\n stream.emit('message', { code: 'PINO_CONFIG', config: { levels, messageKey, errorKey } })\n }\n\n assertLevelComparison(levelComparison)\n const levelCompFunc = genLevelComparison(levelComparison)\n\n Object.assign(instance, {\n levels,\n [levelCompSym]: levelCompFunc,\n [useOnlyCustomLevelsSym]: useOnlyCustomLevels,\n [streamSym]: stream,\n [timeSym]: time,\n [timeSliceIndexSym]: timeSliceIndex,\n [stringifySym]: stringify,\n [stringifySafeSym]: stringifySafe,\n [stringifiersSym]: stringifiers,\n [endSym]: end,\n [formatOptsSym]: formatOpts,\n [messageKeySym]: messageKey,\n [errorKeySym]: errorKey,\n [nestedKeySym]: nestedKey,\n // protect against injection\n [nestedKeyStrSym]: nestedKey ? `,${JSON.stringify(nestedKey)}:{` : '',\n [serializersSym]: serializers,\n [mixinSym]: mixin,\n [mixinMergeStrategySym]: mixinMergeStrategy,\n [chindingsSym]: chindings,\n [formattersSym]: allFormatters,\n [hooksSym]: hooks,\n silent: noop,\n onChild,\n [msgPrefixSym]: msgPrefix\n })\n\n Object.setPrototypeOf(instance, proto())\n\n genLsCache(instance)\n\n instance[setLevelSym](level)\n\n return instance\n}\n\nmodule.exports = pino\n\nmodule.exports.destination = (dest = process.stdout.fd) => {\n if (typeof dest === 'object') {\n dest.dest = normalizeDestFileDescriptor(dest.dest || process.stdout.fd)\n return buildSafeSonicBoom(dest)\n } else {\n return buildSafeSonicBoom({ dest: normalizeDestFileDescriptor(dest), minLength: 0 })\n }\n}\n\nmodule.exports.transport = require('./lib/transport')\nmodule.exports.multistream = require('./lib/multistream')\n\nmodule.exports.levels = mappings()\nmodule.exports.stdSerializers = serializers\nmodule.exports.stdTimeFunctions = Object.assign({}, time)\nmodule.exports.symbols = symbols\nmodule.exports.version = version\n\n// Enables default and name export with TypeScript and Babel\nmodule.exports.default = pino\nmodule.exports.pino = pino\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { formatMessage, removeKeys } from \"./utils.js\";\n\nconst MAX_BUFFER_SIZE = 1000;\n\nconst originalStreamSym = Symbol.for(\"apitally.originalStream\");\nconst logLevelMap: Record<number, string> = {\n 10: \"trace\",\n 20: \"debug\",\n 30: \"info\",\n 40: \"warn\",\n 50: \"error\",\n 60: \"fatal\",\n};\n\nexport async function patchPinoLogger(\n logger: any,\n logsContext: AsyncLocalStorage<LogRecord[]>,\n) {\n try {\n const pino = await import(\"pino\");\n if (!(pino.default.symbols.streamSym in logger)) {\n return;\n }\n if (!(originalStreamSym in logger)) {\n logger[originalStreamSym] = logger[pino.default.symbols.streamSym];\n }\n\n const originalStream = logger[originalStreamSym];\n if (originalStream) {\n const messageKey = logger[pino.default.symbols.messageKeySym];\n const captureStream = new ApitallyLogCaptureStream(\n logsContext,\n messageKey,\n );\n logger[pino.default.symbols.streamSym] = pino.default.multistream(\n [\n { level: 0, stream: originalStream },\n { level: 0, stream: captureStream },\n ],\n {\n levels: logger.levels,\n },\n );\n }\n } catch {\n // pino is not installed, silently ignore\n }\n}\n\nfunction filterLogs(obj: any, messageKey: string) {\n return obj[messageKey] !== \"request completed\";\n}\n\nclass ApitallyLogCaptureStream {\n private logsContext: AsyncLocalStorage<LogRecord[]>;\n private messageKey: string;\n\n constructor(logsContext: AsyncLocalStorage<LogRecord[]>, messageKey: string) {\n this.logsContext = logsContext;\n this.messageKey = messageKey;\n }\n\n write(msg: string): void {\n const logs = this.logsContext.getStore();\n if (!logs || !msg || logs.length >= MAX_BUFFER_SIZE) {\n return;\n }\n\n let obj: any;\n try {\n obj = JSON.parse(msg);\n } catch (e) {\n return;\n }\n if (\n obj === null ||\n typeof obj !== \"object\" ||\n !filterLogs(obj, this.messageKey)\n ) {\n return;\n }\n\n try {\n const message = obj[this.messageKey];\n const rest = removeKeys(obj, [\n \"hostname\",\n \"level\",\n this.messageKey,\n \"pid\",\n \"time\",\n \"reqId\",\n \"req\",\n \"res\",\n ]);\n const formattedMessage = formatMessage(message, rest);\n if (formattedMessage) {\n logs.push({\n timestamp: this.convertTime(obj.time),\n level: logLevelMap[obj.level] || \"info\",\n message: formattedMessage,\n });\n }\n } catch (e) {\n // ignore\n }\n }\n\n private convertTime(time: any): number {\n if (typeof time === \"number\" && !isNaN(time)) {\n return time / 1000; // Convert milliseconds to seconds\n }\n return Date.now() / 1000; // Fallback to current time\n }\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { formatMessage, removeKeys } from \"./utils.js\";\n\nconst MAX_BUFFER_SIZE = 1000;\n\nlet isPatched = false;\nlet globalLogsContext: AsyncLocalStorage<LogRecord[]>;\n\nexport async function patchWinston(\n logsContext: AsyncLocalStorage<LogRecord[]>,\n) {\n globalLogsContext = logsContext;\n\n if (isPatched) {\n return;\n }\n\n try {\n // @ts-expect-error - file is not typed\n const loggerModule = await import(\"winston/lib/winston/logger.js\");\n if (loggerModule.default?.prototype?.write) {\n const originalWrite = loggerModule.default.prototype.write;\n loggerModule.default.prototype.write = function (info: any) {\n captureLog(info);\n return originalWrite.call(this, info);\n };\n }\n } catch {\n // winston is not installed, silently ignore\n }\n\n isPatched = true;\n}\n\nfunction captureLog(info: any) {\n const logs = globalLogsContext?.getStore();\n if (!logs || !info || logs.length >= MAX_BUFFER_SIZE) {\n return;\n }\n\n try {\n const rest = removeKeys(info, [\"timestamp\", \"level\", \"message\", \"splat\"]);\n const formattedMessage = formatMessage(info.message, rest);\n if (formattedMessage) {\n logs.push({\n timestamp: parseTimestamp(info.timestamp),\n level: info.level || \"info\",\n message: formattedMessage.trim(),\n });\n }\n } catch (e) {\n // ignore\n }\n}\n\nfunction parseTimestamp(timestamp: any) {\n if (timestamp) {\n const ts = new Date(timestamp).getTime();\n if (!isNaN(ts)) {\n return ts / 1000;\n }\n }\n return Date.now() / 1000;\n}\n","export { patchConsole } from \"./console.js\";\nexport { patchNestLogger } from \"./nestjs.js\";\nexport { patchPinoLogger } from \"./pino.js\";\nexport { patchWinston } from \"./winston.js\";\n","// Adapted from https://github.com/AlbertoFdzM/express-list-endpoints/blob/305535d43008b46f34e18b01947762e039af6d2d/src/index.js\n// and also incorporated https://github.com/AlbertoFdzM/express-list-endpoints/pull/96\n// and https://github.com/labithiotis/express-list-routes/blob/5432c83a67c2788c56a1cdfc067ec809961c0c05/index.js\n\n/**\n * @typedef {Object} Route\n * @property {Object} methods\n * @property {string | string[]} path\n * @property {any[]} stack\n *\n * @typedef {Object} Endpoint\n * @property {string} path Path name\n * @property {string[]} methods Methods handled\n * @property {string[]} middlewares Mounted middlewares\n */\n\nconst regExpToParseExpressPathRegExp =\n /^\\/\\^\\\\?\\/?(?:(:?[\\w\\\\.-]*(?:\\\\\\/:?[\\w\\\\.-]*)*)|(\\(\\?:\\\\?\\/?\\([^)]+\\)\\)))\\\\\\/.*/;\nconst regExpToReplaceExpressPathRegExpParams = /\\(\\?:\\\\?\\/?\\([^)]+\\)\\)/;\nconst regexpExpressParamRegexp = /\\(\\?:\\\\?\\\\?\\/?\\([^)]+\\)\\)/g;\nconst regexpExpressPathParamRegexp = /(:[^)]+)\\([^)]+\\)/g;\n\nconst EXPRESS_ROOT_PATH_REGEXP_VALUE = \"/^\\\\/?(?=\\\\/|$)/i\";\nconst STACK_ITEM_VALID_NAMES = [\"router\", \"bound dispatch\", \"mounted_app\"];\n\n/**\n * Detects Express version and returns router information\n * @param {import('express').Express | import('express').Router | any} app\n * @returns {{stack: any[] | null, version: 'v4' | 'v5'}}\n */\nexport const getRouterInfo = function (app) {\n if (app.stack) {\n // Express 4 router\n return { stack: app.stack, version: \"v4\" };\n } else if (app._router?.stack) {\n // Express 4\n return { stack: app._router.stack, version: \"v4\" };\n } else if (app.router?.stack) {\n // Express 5\n return { stack: app.router.stack, version: \"v5\" };\n }\n return { stack: null, version: \"v4\" };\n};\n\n/**\n * Returns all the verbs detected for the passed route\n * @param {Route} route\n */\nconst getRouteMethods = function (route) {\n let methods = Object.keys(route.methods);\n\n methods = methods.filter((method) => method !== \"_all\");\n methods = methods.map((method) => method.toUpperCase());\n\n return methods;\n};\n\n/**\n * Returns the names (or anonymous) of all the middlewares attached to the\n * passed route\n * @param {Route} route\n * @returns {string[]}\n */\nconst getRouteMiddlewares = function (route) {\n return route.stack.map((item) => {\n return item.handle.name || \"anonymous\";\n });\n};\n\n/**\n * Returns true if found regexp related with express params\n * @param {string} expressPathRegExp\n * @returns {boolean}\n */\nconst hasParams = function (expressPathRegExp) {\n return regexpExpressParamRegexp.test(expressPathRegExp);\n};\n\n/**\n * @param {Route} route Express route object to be parsed\n * @param {string} basePath The basePath the route is on\n * @return {Endpoint[]} Endpoints info\n */\nconst parseExpressRoute = function (route, basePath) {\n const paths = [];\n\n if (Array.isArray(route.path)) {\n paths.push(...route.path);\n } else {\n paths.push(route.path);\n }\n\n /** @type {Endpoint[]} */\n const endpoints = paths.map((path) => {\n const completePath =\n basePath && path === \"/\" ? basePath : `${basePath}${path}`;\n\n /** @type {Endpoint} */\n const endpoint = {\n path: completePath.replace(regexpExpressPathParamRegexp, \"$1\"),\n methods: getRouteMethods(route),\n middlewares: getRouteMiddlewares(route),\n };\n\n return endpoint;\n });\n\n return endpoints;\n};\n\n/**\n * @param {RegExp} expressPathRegExp\n * @param {any[]} keys\n * @returns {string}\n */\nexport const parseExpressPathRegExp = function (expressPathRegExp, keys) {\n let parsedRegExp = expressPathRegExp.toString();\n let expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);\n let paramIndex = 0;\n\n while (hasParams(parsedRegExp)) {\n const paramName = keys[paramIndex].name;\n const paramId = `:${paramName}`;\n\n parsedRegExp = parsedRegExp.replace(\n regExpToReplaceExpressPathRegExpParams,\n (str) => {\n // Express >= 4.20.0 uses a different RegExp for parameters: it\n // captures the slash as part of the parameter. We need to check\n // for this case and add the slash to the value that will replace\n // the parameter in the path.\n if (str.startsWith(\"(?:\\\\/\")) {\n return `\\\\/${paramId}`;\n }\n\n return paramId;\n },\n );\n\n paramIndex++;\n }\n\n if (parsedRegExp !== expressPathRegExp.toString()) {\n expressPathRegExpExec = regExpToParseExpressPathRegExp.exec(parsedRegExp);\n }\n\n return expressPathRegExpExec[1].replace(/\\\\\\//g, \"/\");\n};\n\n/**\n * @param {string} expressPath\n * @param {Object.<string, string>} params\n * @returns {string}\n */\nexport const parseExpressPath = function (expressPath, params) {\n let result = expressPath;\n for (const [paramName, paramValue] of Object.entries(params)) {\n result = result.replace(paramValue, `:${paramName}`);\n }\n return result;\n};\n\n/**\n * @param {import('express').Express | import('express').Router | any} app\n * @param {string} [basePath]\n * @param {Endpoint[]} [endpoints]\n * @returns {Endpoint[]}\n */\nconst parseEndpoints = function (app, basePath, endpoints) {\n const routerInfo = getRouterInfo(app);\n const stack = routerInfo.stack;\n const version = routerInfo.version;\n\n endpoints = endpoints || [];\n basePath = basePath || \"\";\n\n if (!stack) {\n if (endpoints.length) {\n endpoints = addEndpoints(endpoints, [\n {\n path: basePath,\n methods: [],\n middlewares: [],\n },\n ]);\n }\n } else {\n endpoints = parseStack(stack, basePath, endpoints, version);\n }\n\n return endpoints;\n};\n\n/**\n * Ensures the path of the new endpoints isn't yet in the array.\n * If the path is already in the array merges the endpoints with the existing\n * one, if not, it adds them to the array.\n *\n * @param {Endpoint[]} currentEndpoints Array of current endpoints\n * @param {Endpoint[]} endpointsToAdd New endpoints to be added to the array\n * @returns {Endpoint[]} Updated endpoints array\n */\nconst addEndpoints = function (currentEndpoints, endpointsToAdd) {\n endpointsToAdd.forEach((newEndpoint) => {\n const existingEndpoint = currentEndpoints.find(\n (endpoint) => endpoint.path === newEndpoint.path,\n );\n\n if (existingEndpoint !== undefined) {\n const newMethods = newEndpoint.methods.filter(\n (method) => !existingEndpoint.methods.includes(method),\n );\n\n existingEndpoint.methods = existingEndpoint.methods.concat(newMethods);\n } else {\n currentEndpoints.push(newEndpoint);\n }\n });\n\n return currentEndpoints;\n};\n\n/**\n * @param {any[]} stack\n * @param {string} basePath\n * @param {Endpoint[]} endpoints\n * @param {'v4' | 'v5'} [version]\n * @returns {Endpoint[]}\n */\nconst parseStack = function (stack, basePath, endpoints, version) {\n stack.forEach((stackItem) => {\n if (stackItem.route) {\n const newEndpoints = parseExpressRoute(stackItem.route, basePath);\n\n endpoints = addEndpoints(endpoints, newEndpoints);\n } else if (STACK_ITEM_VALID_NAMES.includes(stackItem.name)) {\n let newBasePath = basePath;\n\n if (version === \"v4\") {\n const isExpressPathRegExp = regExpToParseExpressPathRegExp.test(\n stackItem.regexp,\n );\n if (isExpressPathRegExp) {\n const parsedPath = parseExpressPathRegExp(\n stackItem.regexp,\n stackItem.keys,\n );\n newBasePath += `/${parsedPath}`;\n } else if (\n !stackItem.path &&\n stackItem.regexp &&\n stackItem.regexp.toString() !== EXPRESS_ROOT_PATH_REGEXP_VALUE\n ) {\n const regExpPath = `RegExp(${stackItem.regexp})`;\n newBasePath += `/${regExpPath}`;\n }\n } else if (version === \"v5\") {\n if (!stackItem.path) {\n return;\n } else if (stackItem.path !== \"/\") {\n newBasePath += stackItem.path.startsWith(\"/\")\n ? stackItem.path\n : `/${stackItem.path}`;\n }\n }\n\n endpoints = parseEndpoints(stackItem.handle, newBasePath, endpoints);\n }\n });\n\n return endpoints;\n};\n\nexport const getEndpoints = function (app, basePath) {\n const endpoints = parseEndpoints(app);\n const standardHttpMethods = [\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\"];\n return endpoints.flatMap((route) =>\n route.methods\n .filter((method) => standardHttpMethods.includes(method.toUpperCase()))\n .map((method) => ({\n method,\n path: (basePath + route.path).replace(/\\/\\//g, \"/\"),\n })),\n );\n};\n","import type { Express, NextFunction, Request, Response, Router } from \"express\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { performance } from \"node:perf_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { parseContentLength } from \"../common/headers.js\";\nimport { getPackageVersion } from \"../common/packageVersions.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertBody, convertHeaders } from \"../common/requestLogger.js\";\nimport {\n ApitallyConfig,\n ApitallyConsumer,\n StartupData,\n ValidationError,\n} from \"../common/types.js\";\nimport {\n patchConsole,\n patchNestLogger,\n patchPinoLogger,\n patchWinston,\n} from \"../loggers/index.js\";\nimport {\n getEndpoints,\n getRouterInfo,\n parseExpressPath,\n parseExpressPathRegExp,\n} from \"./utils.js\";\n\ndeclare module \"express\" {\n interface Request {\n apitallyConsumer?: ApitallyConsumer | string | null;\n consumerIdentifier?: ApitallyConsumer | string | null; // For backwards compatibility\n }\n}\n\nexport function useApitally(\n app: Express | Router,\n config: ApitallyConfig & { basePath?: string },\n) {\n const client = new ApitallyClient(config);\n const middleware = getMiddleware(app, client);\n app.use(middleware);\n\n const setStartupData = (attempt: number = 1) => {\n const appInfo = getAppInfo(app, config.basePath, config.appVersion);\n if (appInfo.paths.length > 0 || attempt >= 10) {\n client.setStartupData(appInfo);\n } else {\n setTimeout(() => setStartupData(attempt + 1), 500);\n }\n };\n setTimeout(() => setStartupData(), 500);\n}\n\nfunction getMiddleware(app: Express | Router, client: ApitallyClient) {\n let errorHandlerConfigured = false;\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n patchNestLogger(logsContext);\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n if (!client.isEnabled() || req.method.toUpperCase() === \"OPTIONS\") {\n next();\n return;\n }\n\n if (!errorHandlerConfigured) {\n // Add error handling middleware to the bottom of the stack when handling the first request\n app.use((err: Error, req: Request, res: Response, next: NextFunction) => {\n res.locals.serverError = err;\n next(err);\n });\n errorHandlerConfigured = true;\n }\n\n if (client.requestLogger.config.captureLogs && \"log\" in req) {\n await patchPinoLogger((req as any).log, logsContext);\n }\n\n logsContext.run([], () => {\n try {\n const startTime = performance.now();\n const originalSend = res.send;\n res.send = (body) => {\n const contentType = res.get(\"content-type\");\n if (client.requestLogger.isSupportedContentType(contentType)) {\n res.locals.body = body;\n }\n return originalSend.call(res, body);\n };\n\n res.once(\"finish\", () => {\n try {\n const responseTime = performance.now() - startTime;\n const path = getRoutePath(req);\n const consumer = getConsumer(req);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n\n const requestSize = parseContentLength(req.get(\"content-length\"));\n const responseSize = parseContentLength(res.get(\"content-length\"));\n\n if (path) {\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: req.method,\n path,\n statusCode: res.statusCode,\n responseTime: responseTime,\n requestSize,\n responseSize,\n });\n\n if (\n (res.statusCode === 400 || res.statusCode === 422) &&\n res.locals.body\n ) {\n let jsonBody: any;\n try {\n jsonBody = JSON.parse(res.locals.body);\n } catch {\n // Ignore\n }\n if (jsonBody) {\n const validationErrors: ValidationError[] = [];\n if (validationErrors.length === 0) {\n validationErrors.push(\n ...extractExpressValidatorErrors(jsonBody),\n );\n }\n if (validationErrors.length === 0) {\n validationErrors.push(...extractCelebrateErrors(jsonBody));\n }\n if (validationErrors.length === 0) {\n validationErrors.push(\n ...extractNestValidationErrors(jsonBody),\n );\n }\n validationErrors.forEach((error) => {\n client.validationErrorCounter.addValidationError({\n consumer: consumer?.identifier,\n method: req.method,\n path,\n ...error,\n });\n });\n }\n }\n\n if (res.statusCode === 500 && res.locals.serverError) {\n const serverError = res.locals.serverError as Error;\n client.serverErrorCounter.addServerError({\n consumer: consumer?.identifier,\n method: req.method,\n path,\n type: serverError.name,\n msg: serverError.message,\n traceback: serverError.stack || \"\",\n });\n }\n }\n\n if (client.requestLogger.enabled) {\n const logs = logsContext.getStore();\n client.requestLogger.logRequest(\n {\n timestamp: Date.now() / 1000,\n method: req.method,\n path,\n url: `${req.protocol}://${req.host}${req.originalUrl}`,\n headers: convertHeaders(req.headers),\n size: requestSize,\n consumer: consumer?.identifier,\n body: convertBody(req.body, req.get(\"content-type\")),\n },\n {\n statusCode: res.statusCode,\n responseTime: responseTime / 1000,\n headers: convertHeaders(res.getHeaders()),\n size: responseSize,\n body: convertBody(res.locals.body, res.get(\"content-type\")),\n },\n res.locals.serverError,\n logs,\n );\n }\n } catch (error) {\n client.logger.error(\n \"Error while logging request in Apitally middleware.\",\n { request: req, response: res, error },\n );\n }\n });\n } catch (error) {\n client.logger.error(\"Error in Apitally middleware.\", {\n request: req,\n response: res,\n error,\n });\n } finally {\n next();\n }\n });\n };\n}\n\nfunction getRoutePath(req: Request) {\n if (!req.route) {\n return;\n }\n if (req.baseUrl) {\n const routerInfo = getRouterInfo(req.app);\n if (routerInfo.stack) {\n const routerPath = getRouterPath(routerInfo.stack, req.baseUrl);\n return req.route.path === \"/\" ? routerPath : routerPath + req.route.path;\n }\n }\n return req.route.path;\n}\n\nfunction getRouterPath(stack: any[], baseUrl: string) {\n const routerPaths: string[] = [];\n while (stack && stack.length > 0) {\n const routerLayer = stack.find(\n (layer) =>\n layer.name === \"router\" &&\n layer.path &&\n (baseUrl.startsWith(layer.path) || layer.regexp?.test(baseUrl)),\n );\n if (routerLayer) {\n if (\n routerLayer.regexp &&\n routerLayer.keys &&\n routerLayer.keys.length > 0\n ) {\n const parsedPath = parseExpressPathRegExp(\n routerLayer.regexp,\n routerLayer.keys,\n );\n routerPaths.push(\"/\" + parsedPath);\n } else if (\n routerLayer.params &&\n Object.keys(routerLayer.params).length > 0\n ) {\n const parsedPath = parseExpressPath(\n routerLayer.path,\n routerLayer.params,\n );\n routerPaths.push(parsedPath);\n } else {\n routerPaths.push(routerLayer.path);\n }\n stack = routerLayer.handle?.stack;\n baseUrl = baseUrl.slice(routerLayer.path.length);\n } else {\n break;\n }\n }\n return routerPaths.filter((path) => path !== \"/\").join(\"\");\n}\n\nexport function setConsumer(\n req: Request,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n req.apitallyConsumer = consumer || undefined;\n}\n\nfunction getConsumer(req: Request) {\n if (req.apitallyConsumer) {\n return consumerFromStringOrObject(req.apitallyConsumer);\n } else if (req.consumerIdentifier) {\n // For backwards compatibility\n process.emitWarning(\n \"The consumerIdentifier property on the request object is deprecated. Use apitallyConsumer instead.\",\n \"DeprecationWarning\",\n );\n return consumerFromStringOrObject(req.consumerIdentifier);\n }\n return null;\n}\n\nfunction extractExpressValidatorErrors(responseBody: any) {\n try {\n const errors: ValidationError[] = [];\n if (\n responseBody &&\n responseBody.errors &&\n Array.isArray(responseBody.errors)\n ) {\n responseBody.errors.forEach((error: any) => {\n if (error.location && error.path && error.msg && error.type) {\n errors.push({\n loc: `${error.location}.${error.path}`,\n msg: error.msg,\n type: error.type,\n });\n }\n });\n }\n return errors;\n } catch (error) {\n return [];\n }\n}\n\nfunction extractCelebrateErrors(responseBody: any) {\n try {\n const errors: ValidationError[] = [];\n if (responseBody && responseBody.validation) {\n Object.values(responseBody.validation).forEach((error: any) => {\n if (\n error.source &&\n error.keys &&\n Array.isArray(error.keys) &&\n error.message\n ) {\n error.keys.forEach((key: string) => {\n errors.push({\n loc: `${error.source}.${key}`,\n msg: subsetJoiMessage(error.message, key),\n type: \"\",\n });\n });\n }\n });\n }\n return errors;\n } catch (error) {\n return [];\n }\n}\n\nfunction extractNestValidationErrors(responseBody: any) {\n try {\n const errors: ValidationError[] = [];\n if (responseBody && Array.isArray(responseBody.message)) {\n responseBody.message.forEach((message: any) => {\n errors.push({\n loc: \"\",\n msg: message,\n type: \"\",\n });\n });\n }\n return errors;\n } catch (error) {\n return [];\n }\n}\n\nfunction subsetJoiMessage(message: string, key: string) {\n const messageWithKey = message\n .split(\". \")\n .find((message) => message.includes(`\"${key}\"`));\n return messageWithKey ? messageWithKey : message;\n}\n\nfunction getAppInfo(\n app: Express | Router,\n basePath?: string,\n appVersion?: string,\n): StartupData {\n const versions: Array<[string, string]> = [\n [\"nodejs\", process.version.replace(/^v/, \"\")],\n ];\n const expressVersion = getPackageVersion(\"express\");\n const nestjsVersion = getPackageVersion(\"@nestjs/core\");\n const apitallyVersion = getPackageVersion(\"../..\");\n if (expressVersion) {\n versions.push([\"express\", expressVersion]);\n }\n if (nestjsVersion) {\n versions.push([\"nestjs\", nestjsVersion]);\n }\n if (apitallyVersion) {\n versions.push([\"apitally\", apitallyVersion]);\n }\n if (appVersion) {\n versions.push([\"app\", appVersion]);\n }\n return {\n paths: getEndpoints(app, basePath || \"\"),\n versions: Object.fromEntries(versions),\n client: \"js:express\",\n };\n}\n","export type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { setConsumer, useApitally } from \"./middleware.js\";\n","import type {\n FastifyError,\n FastifyPluginAsync,\n FastifyReply,\n FastifyRequest,\n} from \"fastify\";\nimport fp from \"fastify-plugin\";\nimport { AsyncLocalStorage, AsyncResource } from \"node:async_hooks\";\n\nimport { ApitallyClient } from \"../common/client.js\";\nimport { consumerFromStringOrObject } from \"../common/consumerRegistry.js\";\nimport { parseContentLength } from \"../common/headers.js\";\nimport { getPackageVersion } from \"../common/packageVersions.js\";\nimport type { LogRecord } from \"../common/requestLogger.js\";\nimport { convertBody, convertHeaders } from \"../common/requestLogger.js\";\nimport {\n ApitallyConfig,\n ApitallyConsumer,\n PathInfo,\n ValidationError,\n} from \"../common/types.js\";\nimport {\n patchConsole,\n patchNestLogger,\n patchPinoLogger,\n patchWinston,\n} from \"../loggers/index.js\";\n\nconst LOGS_SYMBOL = Symbol(\"apitally.logs\");\nconst ASYNC_RESOURCE_SYMBOL = Symbol(\"apitally.logsContextAsyncResource\");\n\ndeclare module \"fastify\" {\n interface FastifyReply {\n payload: any;\n serverError?: FastifyError;\n }\n\n interface FastifyRequest {\n apitallyConsumer?: ApitallyConsumer | string | null;\n consumerIdentifier?: ApitallyConsumer | string | null; // For backwards compatibility\n\n [LOGS_SYMBOL]?: LogRecord[];\n [ASYNC_RESOURCE_SYMBOL]?: AsyncResource;\n }\n}\n\nconst apitallyPlugin: FastifyPluginAsync<ApitallyConfig> = async (\n fastify,\n config,\n) => {\n const client = new ApitallyClient(config);\n const routes: PathInfo[] = [];\n const logsContext = new AsyncLocalStorage<LogRecord[]>();\n\n if (client.requestLogger.config.captureLogs) {\n patchConsole(logsContext);\n patchWinston(logsContext);\n patchPinoLogger(fastify.log, logsContext);\n patchNestLogger(logsContext);\n }\n\n fastify.decorateRequest(\"apitallyConsumer\", null);\n fastify.decorateRequest(\"consumerIdentifier\", null); // For backwards compatibility\n fastify.decorateReply(\"payload\", null);\n\n fastify.addHook(\"onRoute\", (routeOptions) => {\n const methods = Array.isArray(routeOptions.method)\n ? routeOptions.method\n : [routeOptions.method];\n methods.forEach((method) => {\n if (![\"HEAD\", \"OPTIONS\"].includes(method.toUpperCase())) {\n routes.push({\n method: method.toUpperCase(),\n path: routeOptions.url,\n });\n }\n });\n });\n\n fastify.addHook(\"onReady\", () => {\n client.setStartupData(getAppInfo(routes, config.appVersion));\n });\n\n fastify.addHook(\"onClose\", async () => {\n await client.handleShutdown();\n });\n\n // Establish logs context for each request\n fastify.addHook(\"onRequest\", (request, reply, done) => {\n if (client.isEnabled()) {\n const logs: LogRecord[] = [];\n request[LOGS_SYMBOL] = logs;\n logsContext.run(logs, () => {\n const asyncResource = new AsyncResource(\"ApitallyLogsContext\");\n request[ASYNC_RESOURCE_SYMBOL] = asyncResource;\n asyncResource.runInAsyncScope(done, request.raw);\n });\n } else {\n done();\n }\n });\n\n // Restore async context for later hooks and route handlers\n fastify.addHook(\"preValidation\", (request, reply, done) => {\n if (client.isEnabled() && request[ASYNC_RESOURCE_SYMBOL]) {\n const asyncResource = request[ASYNC_RESOURCE_SYMBOL];\n asyncResource.runInAsyncScope(done, request.raw);\n } else {\n done();\n }\n });\n\n fastify.addHook(\"onSend\", (request, reply, payload: any, done) => {\n const contentType = reply.getHeader(\"content-type\") as string | undefined;\n if (client.requestLogger.isSupportedContentType(contentType)) {\n reply.payload = payload;\n }\n done();\n });\n\n fastify.addHook(\"onError\", (request, reply, error, done) => {\n if (!error.statusCode || error.statusCode === 500) {\n reply.serverError = error;\n }\n done();\n });\n\n fastify.addHook(\"onResponse\", (request, reply, done) => {\n if (client.isEnabled() && request.method.toUpperCase() !== \"OPTIONS\") {\n // Get path from routeOptions if available (from v4), otherwise fallback to deprecated routerPath\n const consumer = getConsumer(request);\n const path =\n \"routeOptions\" in request\n ? (request as any).routeOptions.url\n : (request as any).routerPath;\n const requestSize = parseContentLength(request.headers[\"content-length\"]);\n const responseSize = parseContentLength(\n reply.getHeader(\"content-length\"),\n );\n const responseTime = getResponseTime(reply);\n client.consumerRegistry.addOrUpdateConsumer(consumer);\n client.requestCounter.addRequest({\n consumer: consumer?.identifier,\n method: request.method,\n path,\n statusCode: reply.statusCode,\n responseTime,\n requestSize,\n responseSize,\n });\n\n if (\n (reply.statusCode === 400 || reply.statusCode === 422) &&\n reply.payload\n ) {\n try {\n const parsedPayload = JSON.parse(reply.payload);\n const validationErrors: ValidationError[] = [];\n\n if (\n (!parsedPayload.code ||\n parsedPayload.code === \"FST_ERR_VALIDATION\") &&\n typeof parsedPayload.message === \"string\"\n ) {\n validationErrors.push(...extractAjvErrors(parsedPayload.message));\n } else if (Array.isArray(parsedPayload.message)) {\n validationErrors.push(\n ...extractNestValidationErrors(parsedPayload.message),\n );\n }\n\n validationErrors.forEach((error) => {\n client.validationErrorCounter.addValidationError({\n consumer: consumer?.identifier,\n method: request.method,\n path: path,\n ...error,\n });\n });\n } catch (error) {} // eslint-disable-line no-empty\n }\n\n if (reply.statusCode === 500 && reply.serverError) {\n client.serverErrorCounter.addServerError({\n consumer: consumer?.identifier,\n method: request.method,\n path: path,\n type: reply.serverError.name,\n msg: reply.serverError.message,\n traceback: reply.serverError.stack || \"\",\n });\n }\n\n if (client.requestLogger.enabled) {\n const logs = request[LOGS_SYMBOL];\n client.requestLogger.logRequest(\n {\n timestamp: Date.now() / 1000,\n method: request.method,\n path,\n url: `${request.protocol}://${request.host ?? request.hostname}${request.originalUrl ?? request.url}`,\n headers: convertHeaders(request.headers),\n size: requestSize,\n consumer: consumer?.identifier,\n body: convertBody(request.body, request.headers[\"content-type\"]),\n },\n {\n statusCode: reply.statusCode,\n responseTime: responseTime / 1000,\n headers: convertHeaders(reply.getHeaders()),\n size: responseSize,\n body: convertBody(\n reply.payload,\n reply.getHeader(\"content-type\")?.toString(),\n ),\n },\n reply.serverError,\n logs,\n );\n }\n }\n\n done();\n });\n};\n\nfunction getAppInfo(routes: PathInfo[], appVersion?: string) {\n const versions = [[\"nodejs\", process.version.replace(/^v/, \"\")]];\n const fastifyVersion = getPackageVersion(\"fastify\");\n const pinoVersion = getPackageVersion(\"pino\");\n const nestjsVersion = getPackageVersion(\"@nestjs/core\");\n const apitallyVersion = getPackageVersion(\"../..\");\n if (fastifyVersion) {\n versions.push([\"fastify\", fastifyVersion]);\n }\n if (pinoVersion) {\n versions.push([\"pino\", pinoVersion]);\n }\n if (nestjsVersion) {\n versions.push([\"nestjs\", nestjsVersion]);\n }\n if (apitallyVersion) {\n versions.push([\"apitally\", apitallyVersion]);\n }\n if (appVersion) {\n versions.push([\"app\", appVersion]);\n }\n return {\n paths: routes,\n versions: Object.fromEntries(versions),\n client: \"js:fastify\",\n };\n}\n\nexport function setConsumer(\n request: FastifyRequest,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n request.apitallyConsumer = consumer || undefined;\n}\n\nfunction getConsumer(request: FastifyRequest) {\n if (request.apitallyConsumer) {\n return consumerFromStringOrObject(request.apitallyConsumer);\n } else if (request.consumerIdentifier) {\n // For backwards compatibility\n process.emitWarning(\n \"The consumerIdentifier property on the request object is deprecated. Use apitallyConsumer instead.\",\n \"DeprecationWarning\",\n );\n return consumerFromStringOrObject(request.consumerIdentifier);\n }\n return null;\n}\n\nfunction getResponseTime(reply: FastifyReply) {\n if (reply.elapsedTime !== undefined) {\n return reply.elapsedTime;\n } else if ((reply as any).getResponseTime !== undefined) {\n return (reply as any).getResponseTime();\n }\n return 0;\n}\n\nfunction extractAjvErrors(message: string): ValidationError[] {\n try {\n const regex =\n /(?<=^|, )((?:headers|params|query|querystring|body)[/.][^ ]+)(?= )/g;\n const matches: { match: string; index: number }[] = [];\n let match: RegExpExecArray | null;\n while ((match = regex.exec(message)) !== null) {\n matches.push({ match: match[0], index: match.index });\n }\n\n return matches.map((m, i) => {\n const endIndex =\n i + 1 < matches.length ? matches[i + 1].index - 2 : message.length;\n const matchSplit = m.match.split(/[/.]/);\n if (matchSplit[0] === \"querystring\") {\n matchSplit[0] = \"query\";\n }\n return {\n loc: matchSplit.join(\".\"),\n msg: message.substring(m.index, endIndex),\n type: \"\",\n };\n });\n } catch (error) {\n return [];\n }\n}\n\nfunction extractNestValidationErrors(message: any[]): ValidationError[] {\n try {\n return message\n .filter((msg: any) => typeof msg === \"string\")\n .map((msg: any) => ({\n loc: \"\",\n msg,\n type: \"\",\n }));\n } catch (error) {\n return [];\n }\n}\n\nexport { apitallyPlugin };\n\nexport default fp(apitallyPlugin, {\n name: \"apitally\",\n});\n","export type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport { default as apitallyPlugin, setConsumer } from \"./plugin.js\";\n","import {\n CallHandler,\n ExecutionContext,\n INestApplication,\n Injectable,\n NestInterceptor,\n} from \"@nestjs/common\";\nimport { catchError, throwError } from \"rxjs\";\n\nimport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\nexport type { ApitallyConfig, ApitallyConsumer } from \"../common/types.js\";\n\nlet setConsumerFn:\n | ((\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n ) => void)\n | null = null;\n\nexport async function useApitally(\n app: INestApplication,\n config: ApitallyConfig,\n) {\n const httpAdapter = app.getHttpAdapter();\n const instance = httpAdapter.getInstance();\n const platform = httpAdapter.constructor.name\n .toLowerCase()\n .includes(\"fastify\")\n ? \"fastify\"\n : \"express\";\n\n if (platform === \"express\") {\n const { useApitally, setConsumer } = await import(\"../express/index.js\");\n setConsumerFn = setConsumer;\n useApitally(instance, config);\n } else if (platform === \"fastify\") {\n const { apitallyPlugin, setConsumer } = await import(\"../fastify/index.js\");\n setConsumerFn = setConsumer;\n await instance.register(apitallyPlugin, config);\n }\n\n app.useGlobalInterceptors(new ApitallyInterceptor(platform));\n}\n\nexport function setConsumer(\n request: any,\n consumer: ApitallyConsumer | string | null | undefined,\n) {\n if (setConsumerFn) {\n setConsumerFn(request, consumer);\n }\n}\n\n@Injectable()\nclass ApitallyInterceptor implements NestInterceptor {\n constructor(private readonly platform: \"express\" | \"fastify\") {}\n\n intercept(context: ExecutionContext, next: CallHandler) {\n return next.handle().pipe(\n catchError((exception) => {\n if (context.getType() === \"http\") {\n const ctx = context.switchToHttp();\n const res = ctx.getResponse();\n\n if (this.platform === \"express\" && res.locals) {\n res.locals.serverError = exception;\n } else if (\n this.platform === \"fastify\" &&\n (!exception.statusCode || exception.statusCode === 500)\n ) {\n res.serverError = exception;\n }\n }\n return throwError(() => exception);\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;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EJ;AACF,GAvBMV,OAAAA,KAAAA,wBADNG;;;;;;;;","names":["exports","exports","exports","exports","Subscription","_a","exports","exports","exports","exports","exports","exports","_a","exports","Subscriber","exports","ConsumerObserver","SafeSubscriber","exports","exports","exports","Observable","_a","exports","exports","exports","OperatorSubscriber","err","_a","exports","ConnectableObservable","exports","exports","exports","exports","exports","Subject","_a","exports","AnonymousSubject","BehaviorSubject","_a","exports","exports","ReplaySubject","_a","exports","AsyncSubject","_a","exports","Action","exports","exports","AsyncAction","_a","exports","exports","setImmediate","exports","AsapAction","_a","exports","Scheduler","exports","AsyncScheduler","exports","AsapScheduler","exports","exports","exports","QueueAction","exports","QueueScheduler","exports","exports","AnimationFrameAction","_a","exports","AnimationFrameScheduler","exports","exports","VirtualTimeScheduler","_a","exports","VirtualAction","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","_a","exports","exports","process","exports","exports","exports","exports","exports","exports","_a","exports","exports","exports","exports","exports","exports","throwError","exports","NotificationKind","exports","Notification","_a","exports","exports","exports","exports","exports","exports","exports","exports","exports","_a","exports","exports","_i","exports","exports","exports","exports","exports","_a","exports","i","exports","exports","exports","exports","exports","exports","DEFAULT_CONFIG","_a","exports","_a","sourceIndex","exports","_a","exports","exports","_a","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","i","exports","exports","sourceIndex","exports","exports","exports","exports","exports","exports","_a","exports","exports","exports","catchError","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","DEFAULT_CONFIG","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","_a","exports","exports","_a","exports","exports","exports","exports","exports","exports","_a","exports","_a","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","exports","_a","exports","_a","exports","exports","exports","TimeInterval","exports","exports","exports","exports","_a","exports","exports","exports","i","exports","exports","exports","exports","exports","consumerFromStringOrObject","ConsumerRegistry","consumer","_a","String","trim","substring","identifier","name","group","consumers","updated","Map","Set","addOrUpdateConsumer","existing","get","set","add","getAndResetUpdatedConsumers","data","forEach","push","clear","getLogger","createLogger","level","process","env","APITALLY_DEBUG","format","combine","colorize","timestamp","printf","info","message","transports","Console","isValidClientId","clientId","regexExp","test","isValidEnv","env","RequestCounter","requestCounts","requestSizeSums","responseSizeSums","responseTimes","requestSizes","responseSizes","Map","getKey","requestInfo","consumer","method","toUpperCase","path","statusCode","join","addRequest","key","set","get","has","responseTimeMap","responseTimeMsBin","Math","floor","responseTime","requestSize","undefined","Number","requestSizeMap","requestSizeKbBin","responseSize","responseSizeMap","responseSizeKbBin","getAndResetRequests","data","forEach","count","statusCodeStr","split","push","status_code","parseInt","request_count","request_size_sum","response_size_sum","response_times","Object","fromEntries","request_sizes","response_sizes","clear","getSentryEventId","sentry","lastEventId","undefined","e","truncateExceptionMessage","msg","length","MAX_MSG_LENGTH","suffix","cutoff","substring","truncateExceptionStackTrace","stack","MAX_STACKTRACE_LENGTH","lines","trim","split","truncatedLines","line","push","join","ServerErrorCounter","errorCounts","errorDetails","sentryEventIds","Map","addServerError","serverError","key","getKey","has","set","get","sentryEventId","getSentryEventId","getAndResetServerErrors","data","forEach","count","consumer","method","path","type","traceback","sentry_event_id","error_count","clear","hashInput","toUpperCase","createHash","update","digest","import_node_crypto","TempGzipFile","uuid","filePath","gzip","writeStream","readyPromise","closedPromise","randomUUID","join","tmpdir","createWriteStream","Promise","resolve","reject","once","createGzip","pipe","size","bytesWritten","writeLine","data","write","Buffer","concat","from","error","getContent","readFile","close","end","delete","unlink","convertHeaders","headers","Headers","Array","from","entries","Object","flatMap","key","value","undefined","isArray","map","v","toString","convertBody","body","contentType","startsWith","isValidJsonString","Buffer","JSON","stringify","error","parse","matchPatterns","patterns","some","pattern","test","skipEmptyValues","data","fromEntries","filter","_","Number","isNaN","isBuffer","length","truncateLogMessage","msg","MAX_LOG_MSG_LENGTH","suffix","slice","checkWritableFs","testPath","join","tmpdir","randomUUID","writeFileSync","unlinkSync","import_node_buffer","import_node_crypto","import_node_fs","import_node_os","import_node_path","MAX_BODY_SIZE","MAX_FILE_SIZE","MAX_FILES","MAX_PENDING_WRITES","BODY_TOO_LARGE","BODY_MASKED","MASKED","ALLOWED_CONTENT_TYPES","EXCLUDE_PATH_PATTERNS","EXCLUDE_USER_AGENT_PATTERNS","MASK_QUERY_PARAM_PATTERNS","MASK_HEADER_PATTERNS","MASK_BODY_FIELD_PATTERNS","DEFAULT_CONFIG","RequestLogger","enabled","logQueryParams","logRequestHeaders","logRequestBody","logResponseHeaders","logResponseBody","logException","captureLogs","maskQueryParams","maskHeaders","maskBodyFields","excludePaths","config","suspendUntil","pendingWrites","currentFile","files","maintainIntervalId","lock","AsyncLock","setInterval","maintain","maxBodySize","shouldExcludePath","urlPath","shouldExcludeUserAgent","userAgent","shouldMaskQueryParam","name","shouldMaskHeader","shouldMaskBodyField","hasSupportedContentType","_a","find","k","toLowerCase","isSupportedContentType","hasJsonContentType","t","search","params","URLSearchParams","set","maskBody","result","item","applyMasking","maskRequestBodyCallback","request","maskedBody","maskResponseBodyCallback","response","bodyData","hasJsonContent","parsedBody","url","URL","logRequest","logs","path","pathname","excludeCallback","size","uuid","exception","type","message","truncateExceptionMessage","stacktrace","truncateExceptionStackTrace","stack","sentryEventId","getSentryEventId","log","timestamp","logger","level","push","shift","writeToFile","acquire","TempGzipFile","finalItem","forEach","toJSON","writeLine","getFile","retryFileLater","file","unshift","rotateFile","close","delete","Date","now","clear","clearInterval","import_node_crypto","ValidationErrorCounter","errorCounts","errorDetails","Map","addValidationError","validationError","key","getKey","has","set","get","getAndResetValidationErrors","data","forEach","count","push","consumer","method","path","loc","split","filter","Boolean","msg","type","error_count","clear","hashInput","toUpperCase","trim","join","createHash","update","digest","import_node_crypto","SYNC_INTERVAL","INITIAL_SYNC_INTERVAL","INITIAL_SYNC_INTERVAL_DURATION","MAX_QUEUE_TIME","HTTPError","ApitallyClient","Error","response","reason","status","clientId","env","instanceUuid","syncDataQueue","syncIntervalId","startupData","startupDataSent","enabled","requestCounter","requestLogger","validationErrorCounter","serverErrorCounter","consumerRegistry","logger","requestLogging","requestLoggingConfig","instance","isValidClientId","isValidEnv","console","warn","randomUUID","RequestCounter","RequestLogger","ValidationErrorCounter","ServerErrorCounter","ConsumerRegistry","getLogger","startSync","handleShutdown","bind","getInstance","isEnabled","shutdown","stopSync","sendSyncData","sendLogData","close","undefined","getHubUrlPrefix","baseURL","process","APITALLY_HUB_BASE_URL","version","sendData","url","payload","fetchWithRetry","fetchRetry","fetch","retries","retryDelay","retryOn","method","body","JSON","stringify","headers","ok","sync","setInterval","setTimeout","clearInterval","promises","push","sendStartupData","Promise","all","error","setStartupData","data","debug","instance_uuid","message_uuid","handled","handleHubError","message","newPayload","timestamp","Date","now","requests","getAndResetRequests","validation_errors","getAndResetValidationErrors","server_errors","getAndResetServerErrors","consumers","getAndResetUpdatedConsumers","i","length","shift","randomDelay","rotateFile","logFile","getFile","uuid","getContent","has","retryAfter","parseInt","get","suspendUntil","clear","delete","retryFileLater","delay","Math","random","resolve","parseContentLength","contentLength","undefined","parsed","parseInt","isNaN","Array","isArray","getPackageVersion","name","packageJsonPath","require","version","error","_require","createRequire","url","patchConsole","logsContext","globalLogsContext","isPatched","logMethods","forEach","method","originalMethod","console","args","captureLog","apply","level","logs","getStore","length","MAX_BUFFER_SIZE","push","timestamp","Date","now","logger","message","format","formatMessage","message","args","map","formatArg","filter","arg","join","removeKeys","obj","keys","Object","fromEntries","entries","key","includes","trim","Error","format","undefined","isEmptyObject","JSON","stringify","getPrototypeOf","prototype","length","import_node_util","patchNestLogger","logsContext","globalLogsContext","isPatched","Logger","logMethods","forEach","method","originalMethod","message","args","captureLog","apply","prototype","context","level","logs","getStore","length","MAX_BUFFER_SIZE","push","timestamp","Date","now","logger","formatMessage","slice","exports","module","isErrorLike","err","message","getErrorCause","cause","causeResult","undefined","_stackWithCauses","seen","stack","has","add","stackWithCauses","Set","_messageWithCauses","skip","skipIfVErrorStyleCause","messageWithCauses","exports","module","seen","Symbol","rawSymbol","pinoErrProto","Object","create","type","enumerable","writable","value","undefined","message","stack","aggregateErrors","raw","get","set","val","defineProperty","pinoErrorSymbols","exports","module","errSerializer","messageWithCauses","stackWithCauses","isErrorLike","require","pinoErrProto","pinoErrorSymbols","seen","toString","Object","prototype","err","undefined","_err","create","type","call","name","message","stack","Array","isArray","errors","aggregateErrors","map","key","val","hasOwnProperty","raw","exports","module","errWithCauseSerializer","isErrorLike","require","pinoErrProto","pinoErrorSymbols","seen","toString","Object","prototype","err","undefined","_err","create","type","call","name","message","stack","Array","isArray","errors","aggregateErrors","map","cause","hasOwnProperty","key","val","raw","exports","module","mapHttpRequest","reqSerializer","rawSymbol","Symbol","pinoReqProto","Object","create","id","enumerable","writable","value","method","url","query","params","headers","remoteAddress","remotePort","raw","get","set","val","defineProperty","req","connection","info","socket","_req","undefined","originalUrl","path","exports","module","mapHttpResponse","resSerializer","rawSymbol","Symbol","pinoResProto","Object","create","statusCode","enumerable","writable","value","headers","raw","get","set","val","defineProperty","res","_res","headersSent","getHeaders","_headers","exports","module","errSerializer","require","errWithCauseSerializer","reqSerializers","resSerializers","err","errWithCause","mapHttpRequest","mapHttpResponse","req","reqSerializer","res","resSerializer","wrapErrorSerializer","customSerializer","wrapErrSerializer","wrapRequestSerializer","wrappedReqSerializer","wrapResponseSerializer","wrappedResSerializer","exports","module","noOpPrepareStackTrace","_","stack","getCallers","originalPrepare","Error","prepareStackTrace","Array","isArray","undefined","entries","slice","fileNames","entry","push","getFileName","exports","module","validator","opts","ERR_PATHS_MUST_BE_STRINGS","ERR_INVALID_PATH","s","validate","paths","forEach","Error","test","expr","replace","Function","e","exports","module","exports","module","rx","require","parse","paths","wildcards","wcLen","secret","reduce","o","strPath","ix","path","match","map","p","replace","leadingBracket","substr","length","star","indexOf","before","slice","beforeStr","join","after","nested","push","val","undefined","precensored","circle","escPath","JSON","stringify","exports","module","rx","require","redactor","secret","serialize","wcLen","strict","isCensorFct","censorFctTakesPath","state","redact","Function","strictImpl","redactTmpl","dynamicRedactTmpl","resultTmpl","bind","restore","o","Object","keys","map","path","escPath","leadingBracket","arrPath","skip","delim","hops","match","exec","ix","index","input","push","substring","existence","p","join","length","circularDetection","reverse","JSON","stringify","censorArgs","hasWildcards","exports","module","groupRedact","groupRestore","nestedRedact","nestedRestore","keys","values","target","length","i","k","o","path","censor","isCensorFct","censorFctTakesPath","get","flat","Object","keysLength","pathLength","pathWithKey","undefined","Array","key","instructions","value","current","store","ns","specialSet","has","obj","prop","hasOwn","prototype","hasOwnProperty","call","afterPath","afterPathLen","lastPathIndex","originalKey","n","nv","ov","oov","wc","kIsWc","wcov","consecutive","level","depth","redactPathCurrent","tree","wcKeys","j","wck","node","iterateNthLevel","rv","restoreInstr","push","p","l","parent","children","child","exports","module","groupRestore","nestedRestore","require","restorer","compileRestore","restore","state","secret","wcLen","paths","Object","keys","resetters","resetTmpl","hasWildcards","Function","restoreTmpl","bind","map","path","circle","escPath","leadingBracket","delim","reset","clear","join","dynamicReset","length","exports","module","state","o","secret","censor","compileRestore","serialize","groupRedact","nestedRedact","wildcards","wcLen","builder","push","Object","assign","exports","module","validator","require","parse","redactor","restorer","groupRedact","nestedRedact","state","rx","validate","noop","o","restore","DEFAULT_CENSOR","fastRedact","opts","paths","Array","from","Set","serialize","JSON","stringify","remove","Error","censor","undefined","isCensorFct","censorFctTakesPath","length","wildcards","wcLen","secret","compileRestore","strict","exports","module","setLevelSym","Symbol","getLevelSym","levelValSym","levelCompSym","useLevelLabelsSym","useOnlyCustomLevelsSym","mixinSym","lsCacheSym","chindingsSym","asJsonSym","writeSym","redactFmtSym","timeSym","timeSliceIndexSym","streamSym","stringifySym","stringifySafeSym","stringifiersSym","endSym","formatOptsSym","messageKeySym","errorKeySym","nestedKeySym","nestedKeyStrSym","mixinMergeStrategySym","msgPrefixSym","wildcardFirstSym","serializersSym","for","formattersSym","hooksSym","needsMetadataGsym","exports","module","fastRedact","require","redactFmtSym","wildcardFirstSym","rx","validator","validate","ERR_PATHS_MUST_BE_STRINGS","ERR_INVALID_PATH","s","CENSOR","strict","redaction","opts","serialize","paths","censor","handle","shape","reduce","o","str","lastIndex","first","exec","next","ns","undefined","replace","index","nextPath","substr","length","push","Object","keys","forEach","k","result","topCensor","args","getOwnPropertySymbols","value","wrappedCensor","path","Array","isArray","remove","Error","exports","module","nullTime","epochTime","Date","now","unixTime","Math","round","isoTime","toISOString","exports","module","tryStringify","o","JSON","stringify","e","format","f","args","opts","ss","offset","len","length","objects","Array","index","join","argLen","str","a","lastPos","flen","i","charCodeAt","slice","Number","Math","floor","undefined","type","name","String","exports","module","SharedArrayBuffer","Atomics","sleep","ms","valid","Infinity","TypeError","RangeError","wait","nil","Number","Int32Array","target","Date","now","exports","module","fs","require","EventEmitter","inherits","path","sleep","assert","BUSY_WRITE_TIMEOUT","kEmptyBuffer","Buffer","allocUnsafe","MAX_WRITE","kContentModeBuffer","kContentModeUtf8","major","minor","process","versions","node","split","map","Number","kCopyBuffer","openFile","file","sonic","_opening","_writing","_asyncDrainScheduled","fileOpened","err","fd","_reopening","sync","nextTick","listenerCount","emit","reopening","destroyed","_len","minLength","_flushPending","_actualWrite","flags","append","mode","mkdir","mkdirSync","dirname","recursive","openSync","open","SonicBoom","opts","dest","maxLength","maxWrite","periodicFlush","retryEAGAIN","fsync","contentMode","_bufs","_lens","_ending","_hwm","Math","max","_periodicFlush","_periodicFlushTimer","undefined","writable","_fsync","fsWriteSync","fsWrite","_writingBuf","write","writeBuffer","flush","flushBuffer","flushSync","flushBufferSync","actualWriteBuffer","writeSync","release","actualWrite","Error","n","code","length","setTimeout","releasedBufObj","releaseWritingBuf","len","writingBuf","fsyncSync","reopen","actualClose","emitDrain","on","name","setInterval","unref","byteLength","from","subarray","toString","slice","hasListeners","mergeBuf","bufs","concat","data","push","lens","callFlushCallbackOnDrain","cb","onDrain","off","onError","once","error","call","prototype","close","end","unshift","buf","shift","shouldRetry","destroy","written","bind","clearInterval","closeWrapped","done","default","exports","module","refs","exit","beforeExit","functions","onExit","onBeforeExit","registry","ensureRegistry","undefined","FinalizationRegistry","clear","install","event","length","process","on","uninstall","removeListener","callRefs","ref","obj","deref","fn","index","indexOf","splice","_register","Error","WeakRef","register","push","registerBeforeExit","unregister","filter","_obj","exports","module","exports","module","MAX_TIMEOUT","wait","state","index","expected","timeout","done","max","Date","now","current","Atomics","load","prior","check","backoff","setTimeout","waitDiff","exports","module","WRITE_INDEX","READ_INDEX","exports","module","version","require","EventEmitter","Worker","join","pathToFileURL","wait","WRITE_INDEX","READ_INDEX","buffer","assert","kImpl","Symbol","MAX_STRING","constants","MAX_STRING_LENGTH","_a","FakeWeakRef","value","_value","deref","FakeFinalizationRegistry","register","unregister","FinalizationRegistry","process","env","NODE_V8_COVERAGE","global","WeakRef","registry","worker","exited","terminate","createWorker","stream","opts","filename","workerData","bundlerOverrides","globalThis","__bundlerPathsOverrides","toExecute","__dirname","workerOpts","trackUnmanagedFds","indexOf","href","dataBuf","stateBuf","$context","threadStreamVersion","on","onWorkerMessage","onWorkerExit","drain","sync","needDrain","emit","nextFlush","writeIndex","Atomics","load","state","leftover","data","length","buf","flushing","ending","end","nextTick","toWrite","slice","toWriteBytes","Buffer","byteLength","write","bind","flush","destroyed","store","destroy","Error","msg","undefined","code","ready","err","Array","isArray","args","name","emitWarning","off","ThreadStream","bufferSize","SharedArrayBuffer","Int32Array","from","ended","finished","errored","closed","message","transferList","postMessage","error","writeSync","setImmediate","cb","Infinity","res","flushSync","unref","ref","writable","writableEnded","writableFinished","writableNeedDrain","writableObjectMode","writableErrored","catch","then","current","notify","readIndex","spins","exports","module","createRequire","require","getCallers","join","isAbsolute","sep","sleep","onExit","ThreadStream","setupOnExit","stream","register","autoEnd","registerBeforeExit","flush","on","unregister","buildStream","filename","workerData","workerOpts","sync","onReady","process","removeListener","unref","closed","flushSync","end","ref","once","transport","fullOptions","pipeline","targets","levels","dedupe","worker","caller","options","callers","bundlerOverrides","globalThis","__bundlerPathsOverrides","target","Error","__dirname","filter","dest","map","fixTarget","pipelines","t","level","pinoWillSendConfig","origin","indexOf","filePath","context","cwd","resolve","err","exports","module","format","require","mapHttpRequest","mapHttpResponse","SonicBoom","onExit","lsCacheSym","chindingsSym","writeSym","serializersSym","formatOptsSym","endSym","stringifiersSym","stringifySym","stringifySafeSym","wildcardFirstSym","nestedKeySym","formattersSym","messageKeySym","errorKeySym","nestedKeyStrSym","msgPrefixSym","isMainThread","transport","noop","genLog","level","hook","LOG","hookWrappedLog","args","call","o","n","msg","method","headers","socket","setHeader","formatParams","length","shift","undefined","asString","str","result","last","found","point","l","JSON","stringify","i","charCodeAt","slice","asJson","obj","num","time","stringifySafe","stringifiers","end","chindings","serializers","formatters","messageKey","errorKey","data","value","log","wildcardStringifier","propStr","key","Object","prototype","hasOwnProperty","err","stringifier","Number","isFinite","strKey","msgStr","asChindings","instance","bindings","formatter","valid","hasBeenTampered","stream","write","buildSafeSonicBoom","opts","on","filterBrokenPipe","sync","register","autoEnd","unregister","code","flushSync","destroy","removeListener","emit","eventName","destroyed","flush","createArgsNormalizer","defaultOptions","normalizeArgs","caller","dest","Error","writable","_writableState","targets","customLevels","useOnlyCustomLevels","assign","levels","prettyPrint","enabled","onChild","process","stdout","fd","stringifySafeFn","_","buildFormatters","normalizeDestFileDescriptor","destination","exports","module","DEFAULT_LEVELS","trace","debug","info","warn","error","fatal","SORTING_ORDER","ASC","DESC","exports","module","lsCacheSym","levelValSym","useOnlyCustomLevelsSym","streamSym","formattersSym","hooksSym","levelCompSym","require","noop","genLog","DEFAULT_LEVELS","SORTING_ORDER","levelMethods","fatal","hook","logFatal","args","stream","call","flushSync","e","error","warn","info","debug","trace","nums","Object","keys","reduce","o","k","initialLsCache","Number","genLsCache","instance","formatter","level","labels","levels","cache","label","JSON","stringify","slice","isStandardLevel","useOnlyCustomLevels","setLevel","values","undefined","Error","preLevelVal","levelVal","useOnlyCustomLevelsVal","levelComparison","logMethod","key","emit","getLevel","isLevelEnabled","logLevel","logLevelVal","compareLevel","direction","current","expected","DESC","genLevelComparison","bind","mappings","customLevels","customNums","assign","create","prototype","Infinity","value","silent","assertDefaultLevelFound","defaultLevel","concat","map","includes","assertNoLevelCollisions","assertLevelComparison","exports","module","version","exports","module","EventEmitter","require","lsCacheSym","levelValSym","setLevelSym","getLevelSym","chindingsSym","parsedChindingsSym","mixinSym","asJsonSym","writeSym","mixinMergeStrategySym","timeSym","timeSliceIndexSym","streamSym","serializersSym","formattersSym","errorKeySym","messageKeySym","useOnlyCustomLevelsSym","needsMetadataGsym","redactFmtSym","stringifySym","formatOptsSym","stringifiersSym","msgPrefixSym","hooksSym","getLevel","setLevel","isLevelEnabled","mappings","initialLsCache","genLsCache","assertNoLevelCollisions","asChindings","asJson","buildFormatters","stringify","version","redaction","_a","constructor","Pino","prototype","child","bindings","setBindings","flush","level","lvl","levelVal","n","Error","msgPrefix","write","Object","setPrototypeOf","create","resetChildingsFormatter","options","serializers","formatters","instance","hasOwnProperty","k","parentSymbols","getOwnPropertySymbols","i","length","ks","bk","bindingsSymbols","bi","bks","chindings","log","levels","customLevels","redact","Array","isArray","stringifiers","formatOpts","childLevel","onChild","chindingsJson","substr","bindingsFromJson","JSON","parse","pid","hostname","newBindings","defaultMixinMergeStrategy","mergeObject","mixinObject","assign","_obj","msg","num","t","mixin","errorKey","messageKey","mixinMergeStrategy","obj","streamWriteHook","streamWrite","undefined","message","s","stream","lastLevel","lastObj","lastMsg","lastTime","slice","lastLogger","noop","cb","exports","module","hasOwnProperty","Object","prototype","stringify","configure","default","strEscapeSequencesRegExp","strEscape","str","length","test","JSON","sort","array","comparator","i","currentValue","position","typedArrayPrototypeGetSymbolToStringTag","getOwnPropertyDescriptor","getPrototypeOf","Int8Array","Symbol","toStringTag","get","isTypedArrayWithEntries","value","call","undefined","stringifyTypedArray","separator","maximumBreadth","whitespace","res","getCircularValueOption","options","circularValue","Error","TypeError","toString","getDeterministicOption","deterministic","getBooleanOption","key","getPositiveIntegerOption","Number","isInteger","RangeError","Infinity","getItemCount","number","getUniqueReplacerSet","replacerArray","replacerSet","Set","add","String","getStrictOption","strict","message","fail","bigint","maximumDepth","stringifyFnReplacer","parent","stack","replacer","spacer","indentation","toJSON","indexOf","join","originalIndentation","Array","isArray","push","maximumValuesToStringify","Math","min","tmp","removedKeys","pop","keys","keyLength","maximumPropertiesToStringify","isFinite","stringifyArrayReplacer","stringifyIndent","slice","stringifySimple","hasLength","space","arguments","repeat","exports","module","metadata","Symbol","for","DEFAULT_LEVELS","require","DEFAULT_INFO_LEVEL","info","multistream","streamsArray","opts","dedupe","streamLevels","Object","create","silent","Infinity","levels","keys","forEach","i","res","write","add","remove","emit","flushSync","end","minLevel","lastId","streams","clone","Array","isArray","call","data","dest","level","lastLevel","recordedLevel","stream","initLoopVar","length","checkLoopVar","adjustLoopVar","lastTime","lastMsg","lastObj","lastLogger","args","isStream","stream_","Error","levelVal","dest_","undefined","id","unshift","sort","compareByLevel","index","findIndex","s","splice","a","b","exports","module","os","require","stdSerializers","caller","redaction","time","proto","symbols","configure","assertDefaultLevelFound","mappings","genLsCache","genLevelComparison","assertLevelComparison","DEFAULT_LEVELS","SORTING_ORDER","createArgsNormalizer","asChindings","buildSafeSonicBoom","buildFormatters","stringify","normalizeDestFileDescriptor","noop","version","chindingsSym","redactFmtSym","serializersSym","timeSym","timeSliceIndexSym","streamSym","stringifySym","stringifySafeSym","stringifiersSym","setLevelSym","endSym","formatOptsSym","messageKeySym","errorKeySym","nestedKeySym","mixinSym","levelCompSym","useOnlyCustomLevelsSym","formattersSym","hooksSym","nestedKeyStrSym","mixinMergeStrategySym","msgPrefixSym","epochTime","nullTime","pid","process","hostname","defaultErrorSerializer","err","defaultOptions","level","levelComparison","ASC","levels","messageKey","errorKey","nestedKey","enabled","base","serializers","Object","assign","create","formatters","bindings","label","number","hooks","logMethod","undefined","streamWrite","timestamp","name","redact","customLevels","useOnlyCustomLevels","depthLimit","edgeLimit","normalize","pino","args","instance","opts","stream","toLowerCase","crlf","mixin","mixinMergeStrategy","onChild","msgPrefix","stringifySafe","maximumDepth","maximumBreadth","allFormatters","log","stringifyFn","bind","stringifiers","formatOpts","end","coreChindings","chindings","Function","timeSliceIndex","indexOf","Error","emit","code","config","levelCompFunc","JSON","silent","setPrototypeOf","destination","dest","stdout","fd","minLength","transport","multistream","stdTimeFunctions","default","patchPinoLogger","logger","logsContext","pino","default","symbols","streamSym","originalStreamSym","originalStream","messageKey","messageKeySym","captureStream","ApitallyLogCaptureStream","multistream","level","stream","levels","filterLogs","obj","MAX_BUFFER_SIZE","logLevelMap","_a","Symbol","for","write","msg","logs","getStore","length","JSON","parse","e","message","rest","removeKeys","formattedMessage","formatMessage","push","timestamp","convertTime","time","isNaN","Date","now","patchWinston","logsContext","_a","globalLogsContext","isPatched","loggerModule","default","prototype","write","originalWrite","info","captureLog","call","logs","getStore","length","MAX_BUFFER_SIZE","rest","removeKeys","formattedMessage","formatMessage","message","push","timestamp","parseTimestamp","level","trim","e","ts","Date","getTime","isNaN","now","regExpToParseExpressPathRegExp","regExpToReplaceExpressPathRegExpParams","regexpExpressParamRegexp","regexpExpressPathParamRegexp","EXPRESS_ROOT_PATH_REGEXP_VALUE","STACK_ITEM_VALID_NAMES","getRouterInfo","getRouteMethods","getRouteMiddlewares","hasParams","parseExpressRoute","parseExpressPathRegExp","parseExpressPath","parseEndpoints","addEndpoints","parseStack","getEndpoints","init_utils","app","_a","stack","version","_router","router","route","methods","Object","keys","filter","method","map","toUpperCase","item","handle","name","expressPathRegExp","test","basePath","paths","Array","isArray","path","push","endpoints","completePath","endpoint","replace","middlewares","parsedRegExp","toString","expressPathRegExpExec","exec","paramIndex","paramName","paramId","str","startsWith","expressPath","params","result","paramValue","entries","routerInfo","length","currentEndpoints","endpointsToAdd","forEach","newEndpoint","existingEndpoint","find","undefined","newMethods","includes","concat","stackItem","newEndpoints","newBasePath","isExpressPathRegExp","regexp","parsedPath","regExpPath","standardHttpMethods","flatMap","useApitally","app","config","client","ApitallyClient","middleware","getMiddleware","use","setStartupData","attempt","appInfo","getAppInfo","basePath","appVersion","paths","length","setTimeout","errorHandlerConfigured","logsContext","AsyncLocalStorage","requestLogger","captureLogs","patchConsole","patchWinston","patchNestLogger","req","res","next","isEnabled","method","toUpperCase","err","locals","serverError","patchPinoLogger","log","run","startTime","performance","now","originalSend","send","body","contentType","get","isSupportedContentType","call","once","responseTime","path","getRoutePath","consumer","getConsumer","consumerRegistry","addOrUpdateConsumer","requestSize","parseContentLength","responseSize","requestCounter","addRequest","identifier","statusCode","jsonBody","JSON","parse","validationErrors","push","extractExpressValidatorErrors","extractCelebrateErrors","extractNestValidationErrors","forEach","error","validationErrorCounter","addValidationError","serverErrorCounter","addServerError","type","name","msg","message","traceback","stack","enabled","logs","getStore","logRequest","timestamp","Date","url","protocol","host","originalUrl","headers","convertHeaders","size","convertBody","getHeaders","logger","request","response","route","baseUrl","routerInfo","getRouterInfo","routerPath","getRouterPath","_a","routerPaths","routerLayer","find","layer","startsWith","regexp","test","keys","parsedPath","parseExpressPathRegExp","params","Object","parseExpressPath","handle","slice","filter","join","setConsumer","apitallyConsumer","undefined","consumerFromStringOrObject","consumerIdentifier","process","emitWarning","responseBody","errors","Array","isArray","location","loc","validation","values","source","key","subsetJoiMessage","messageWithKey","split","includes","versions","version","replace","expressVersion","getPackageVersion","nestjsVersion","apitallyVersion","getEndpoints","fromEntries","init_utils","getAppInfo","routes","appVersion","versions","process","version","replace","fastifyVersion","getPackageVersion","pinoVersion","nestjsVersion","apitallyVersion","push","paths","Object","fromEntries","client","setConsumer","request","consumer","apitallyConsumer","undefined","getConsumer","consumerFromStringOrObject","consumerIdentifier","emitWarning","getResponseTime","reply","elapsedTime","extractAjvErrors","message","regex","matches","match","exec","index","map","m","i","endIndex","length","matchSplit","split","loc","join","msg","substring","type","error","extractNestValidationErrors","filter","import_node_async_hooks","LOGS_SYMBOL","ASYNC_RESOURCE_SYMBOL","apitallyPlugin","Symbol","fastify","config","ApitallyClient","logsContext","AsyncLocalStorage","requestLogger","captureLogs","patchConsole","patchWinston","patchPinoLogger","log","patchNestLogger","decorateRequest","decorateReply","addHook","routeOptions","methods","Array","isArray","method","forEach","includes","toUpperCase","path","url","setStartupData","handleShutdown","done","isEnabled","logs","run","asyncResource","AsyncResource","runInAsyncScope","raw","payload","contentType","getHeader","isSupportedContentType","statusCode","serverError","_a","routerPath","requestSize","parseContentLength","headers","responseSize","responseTime","consumerRegistry","addOrUpdateConsumer","requestCounter","addRequest","identifier","parsedPayload","JSON","parse","validationErrors","code","validationErrorCounter","addValidationError","serverErrorCounter","addServerError","name","traceback","stack","enabled","logRequest","timestamp","Date","now","protocol","host","hostname","originalUrl","convertHeaders","size","body","convertBody","getHeaders","toString","fp","setConsumer","setConsumerFn","useApitally","app","config","httpAdapter","getHttpAdapter","instance","getInstance","platform","name","toLowerCase","includes","setConsumer","apitallyPlugin","register","useGlobalInterceptors","ApitallyInterceptor","request","consumer","_a","intercept","context","next","handle","pipe","catchError","exception","getType","ctx","switchToHttp","res","getResponse","locals","serverError","statusCode","throwError"]}