This commit is contained in:
2025-03-18 16:37:12 +02:00
commit 91c2721fe6
4862 changed files with 405393 additions and 0 deletions

5
node_modules/rxjs/src/Rx.global.js generated vendored Normal file
View File

@@ -0,0 +1,5 @@
(function (root, factory) {
root.Rx = factory();
})(window || global || this, function () {
return require('../dist/package/Rx');
});

4
node_modules/rxjs/src/ajax/index.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export { ajax } from '../internal/ajax/ajax';
export { AjaxError, AjaxTimeoutError } from '../internal/ajax/errors';
export { AjaxResponse } from '../internal/ajax/AjaxResponse';
export { AjaxRequest, AjaxConfig, AjaxDirection } from '../internal/ajax/types';

1
node_modules/rxjs/src/fetch/index.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export { fromFetch } from '../internal/observable/dom/fetch';

209
node_modules/rxjs/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,209 @@
//////////////////////////////////////////////////////////
// Here we need to reference our other deep imports
// so VS code will figure out where they are
// see conversation here:
// https://github.com/microsoft/TypeScript/issues/43034
//////////////////////////////////////////////////////////
// tslint:disable: no-reference
// It's tempting to add references to all of the deep-import locations, but
// adding references to those that require DOM types breaks Node projects.
/// <reference path="./operators/index.ts" />
/// <reference path="./testing/index.ts" />
// tslint:enable: no-reference
/* Observable */
export { Observable } from './internal/Observable';
export { ConnectableObservable } from './internal/observable/ConnectableObservable';
export { GroupedObservable } from './internal/operators/groupBy';
export { Operator } from './internal/Operator';
export { observable } from './internal/symbol/observable';
export { animationFrames } from './internal/observable/dom/animationFrames';
/* Subjects */
export { Subject } from './internal/Subject';
export { BehaviorSubject } from './internal/BehaviorSubject';
export { ReplaySubject } from './internal/ReplaySubject';
export { AsyncSubject } from './internal/AsyncSubject';
/* Schedulers */
export { asap, asapScheduler } from './internal/scheduler/asap';
export { async, asyncScheduler } from './internal/scheduler/async';
export { queue, queueScheduler } from './internal/scheduler/queue';
export { animationFrame, animationFrameScheduler } from './internal/scheduler/animationFrame';
export { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/VirtualTimeScheduler';
export { Scheduler } from './internal/Scheduler';
/* Subscription */
export { Subscription } from './internal/Subscription';
export { Subscriber } from './internal/Subscriber';
/* Notification */
export { Notification, NotificationKind } from './internal/Notification';
/* Utils */
export { pipe } from './internal/util/pipe';
export { noop } from './internal/util/noop';
export { identity } from './internal/util/identity';
export { isObservable } from './internal/util/isObservable';
/* Promise Conversion */
export { lastValueFrom } from './internal/lastValueFrom';
export { firstValueFrom } from './internal/firstValueFrom';
/* Error types */
export { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';
export { EmptyError } from './internal/util/EmptyError';
export { NotFoundError } from './internal/util/NotFoundError';
export { ObjectUnsubscribedError } from './internal/util/ObjectUnsubscribedError';
export { SequenceError } from './internal/util/SequenceError';
export { TimeoutError } from './internal/operators/timeout';
export { UnsubscriptionError } from './internal/util/UnsubscriptionError';
/* Static observable creation exports */
export { bindCallback } from './internal/observable/bindCallback';
export { bindNodeCallback } from './internal/observable/bindNodeCallback';
export { combineLatest } from './internal/observable/combineLatest';
export { concat } from './internal/observable/concat';
export { connectable } from './internal/observable/connectable';
export { defer } from './internal/observable/defer';
export { empty } from './internal/observable/empty';
export { forkJoin } from './internal/observable/forkJoin';
export { from } from './internal/observable/from';
export { fromEvent } from './internal/observable/fromEvent';
export { fromEventPattern } from './internal/observable/fromEventPattern';
export { generate } from './internal/observable/generate';
export { iif } from './internal/observable/iif';
export { interval } from './internal/observable/interval';
export { merge } from './internal/observable/merge';
export { never } from './internal/observable/never';
export { of } from './internal/observable/of';
export { onErrorResumeNext } from './internal/observable/onErrorResumeNext';
export { pairs } from './internal/observable/pairs';
export { partition } from './internal/observable/partition';
export { race } from './internal/observable/race';
export { range } from './internal/observable/range';
export { throwError } from './internal/observable/throwError';
export { timer } from './internal/observable/timer';
export { using } from './internal/observable/using';
export { zip } from './internal/observable/zip';
export { scheduled } from './internal/scheduled/scheduled';
/* Constants */
export { EMPTY } from './internal/observable/empty';
export { NEVER } from './internal/observable/never';
/* Types */
export * from './internal/types';
/* Config */
export { config, GlobalConfig } from './internal/config';
/* Operators */
export { audit } from './internal/operators/audit';
export { auditTime } from './internal/operators/auditTime';
export { buffer } from './internal/operators/buffer';
export { bufferCount } from './internal/operators/bufferCount';
export { bufferTime } from './internal/operators/bufferTime';
export { bufferToggle } from './internal/operators/bufferToggle';
export { bufferWhen } from './internal/operators/bufferWhen';
export { catchError } from './internal/operators/catchError';
export { combineAll } from './internal/operators/combineAll';
export { combineLatestAll } from './internal/operators/combineLatestAll';
export { combineLatestWith } from './internal/operators/combineLatestWith';
export { concatAll } from './internal/operators/concatAll';
export { concatMap } from './internal/operators/concatMap';
export { concatMapTo } from './internal/operators/concatMapTo';
export { concatWith } from './internal/operators/concatWith';
export { connect, ConnectConfig } from './internal/operators/connect';
export { count } from './internal/operators/count';
export { debounce } from './internal/operators/debounce';
export { debounceTime } from './internal/operators/debounceTime';
export { defaultIfEmpty } from './internal/operators/defaultIfEmpty';
export { delay } from './internal/operators/delay';
export { delayWhen } from './internal/operators/delayWhen';
export { dematerialize } from './internal/operators/dematerialize';
export { distinct } from './internal/operators/distinct';
export { distinctUntilChanged } from './internal/operators/distinctUntilChanged';
export { distinctUntilKeyChanged } from './internal/operators/distinctUntilKeyChanged';
export { elementAt } from './internal/operators/elementAt';
export { endWith } from './internal/operators/endWith';
export { every } from './internal/operators/every';
export { exhaust } from './internal/operators/exhaust';
export { exhaustAll } from './internal/operators/exhaustAll';
export { exhaustMap } from './internal/operators/exhaustMap';
export { expand } from './internal/operators/expand';
export { filter } from './internal/operators/filter';
export { finalize } from './internal/operators/finalize';
export { find } from './internal/operators/find';
export { findIndex } from './internal/operators/findIndex';
export { first } from './internal/operators/first';
export { groupBy, BasicGroupByOptions, GroupByOptionsWithElement } from './internal/operators/groupBy';
export { ignoreElements } from './internal/operators/ignoreElements';
export { isEmpty } from './internal/operators/isEmpty';
export { last } from './internal/operators/last';
export { map } from './internal/operators/map';
export { mapTo } from './internal/operators/mapTo';
export { materialize } from './internal/operators/materialize';
export { max } from './internal/operators/max';
export { mergeAll } from './internal/operators/mergeAll';
export { flatMap } from './internal/operators/flatMap';
export { mergeMap } from './internal/operators/mergeMap';
export { mergeMapTo } from './internal/operators/mergeMapTo';
export { mergeScan } from './internal/operators/mergeScan';
export { mergeWith } from './internal/operators/mergeWith';
export { min } from './internal/operators/min';
export { multicast } from './internal/operators/multicast';
export { observeOn } from './internal/operators/observeOn';
export { onErrorResumeNextWith } from './internal/operators/onErrorResumeNextWith';
export { pairwise } from './internal/operators/pairwise';
export { pluck } from './internal/operators/pluck';
export { publish } from './internal/operators/publish';
export { publishBehavior } from './internal/operators/publishBehavior';
export { publishLast } from './internal/operators/publishLast';
export { publishReplay } from './internal/operators/publishReplay';
export { raceWith } from './internal/operators/raceWith';
export { reduce } from './internal/operators/reduce';
export { repeat, RepeatConfig } from './internal/operators/repeat';
export { repeatWhen } from './internal/operators/repeatWhen';
export { retry, RetryConfig } from './internal/operators/retry';
export { retryWhen } from './internal/operators/retryWhen';
export { refCount } from './internal/operators/refCount';
export { sample } from './internal/operators/sample';
export { sampleTime } from './internal/operators/sampleTime';
export { scan } from './internal/operators/scan';
export { sequenceEqual } from './internal/operators/sequenceEqual';
export { share, ShareConfig } from './internal/operators/share';
export { shareReplay, ShareReplayConfig } from './internal/operators/shareReplay';
export { single } from './internal/operators/single';
export { skip } from './internal/operators/skip';
export { skipLast } from './internal/operators/skipLast';
export { skipUntil } from './internal/operators/skipUntil';
export { skipWhile } from './internal/operators/skipWhile';
export { startWith } from './internal/operators/startWith';
export { subscribeOn } from './internal/operators/subscribeOn';
export { switchAll } from './internal/operators/switchAll';
export { switchMap } from './internal/operators/switchMap';
export { switchMapTo } from './internal/operators/switchMapTo';
export { switchScan } from './internal/operators/switchScan';
export { take } from './internal/operators/take';
export { takeLast } from './internal/operators/takeLast';
export { takeUntil } from './internal/operators/takeUntil';
export { takeWhile } from './internal/operators/takeWhile';
export { tap, TapObserver } from './internal/operators/tap';
export { throttle, ThrottleConfig } from './internal/operators/throttle';
export { throttleTime } from './internal/operators/throttleTime';
export { throwIfEmpty } from './internal/operators/throwIfEmpty';
export { timeInterval } from './internal/operators/timeInterval';
export { timeout, TimeoutConfig, TimeoutInfo } from './internal/operators/timeout';
export { timeoutWith } from './internal/operators/timeoutWith';
export { timestamp } from './internal/operators/timestamp';
export { toArray } from './internal/operators/toArray';
export { window } from './internal/operators/window';
export { windowCount } from './internal/operators/windowCount';
export { windowTime } from './internal/operators/windowTime';
export { windowToggle } from './internal/operators/windowToggle';
export { windowWhen } from './internal/operators/windowWhen';
export { withLatestFrom } from './internal/operators/withLatestFrom';
export { zipAll } from './internal/operators/zipAll';
export { zipWith } from './internal/operators/zipWith';

14
node_modules/rxjs/src/internal/AnyCatcher.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
/*
* Note that we cannot apply the `internal` tag here because the declaration
* needs to survive the `stripInternal` option. Otherwise, `AnyCatcher` will
* be `any` in the `.d.ts` files.
*/
declare const anyCatcherSymbol: unique symbol;
/**
* This is just a type that we're using to identify `any` being passed to
* function overloads. This is used because of situations like {@link forkJoin},
* where it could return an `Observable<T[]>` or an `Observable<{ [key: K]: T }>`,
* so `forkJoin(any)` would mean we need to return `Observable<unknown>`.
*/
export type AnyCatcher = typeof anyCatcherSymbol;

39
node_modules/rxjs/src/internal/AsyncSubject.ts generated vendored Normal file
View File

@@ -0,0 +1,39 @@
import { Subject } from './Subject';
import { Subscriber } from './Subscriber';
/**
* A variant of Subject that only emits a value when it completes. It will emit
* its latest value to all its observers on completion.
*/
export class AsyncSubject<T> extends Subject<T> {
private _value: T | null = null;
private _hasValue = false;
private _isComplete = false;
/** @internal */
protected _checkFinalizedStatuses(subscriber: Subscriber<T>) {
const { hasError, _hasValue, _value, thrownError, isStopped, _isComplete } = this;
if (hasError) {
subscriber.error(thrownError);
} else if (isStopped || _isComplete) {
_hasValue && subscriber.next(_value!);
subscriber.complete();
}
}
next(value: T): void {
if (!this.isStopped) {
this._value = value;
this._hasValue = true;
}
}
complete(): void {
const { _hasValue, _value, _isComplete } = this;
if (!_isComplete) {
this._isComplete = true;
_hasValue && super.next(_value!);
super.complete();
}
}
}

37
node_modules/rxjs/src/internal/BehaviorSubject.ts generated vendored Normal file
View File

@@ -0,0 +1,37 @@
import { Subject } from './Subject';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
/**
* A variant of Subject that requires an initial value and emits its current
* value whenever it is subscribed to.
*/
export class BehaviorSubject<T> extends Subject<T> {
constructor(private _value: T) {
super();
}
get value(): T {
return this.getValue();
}
/** @internal */
protected _subscribe(subscriber: Subscriber<T>): Subscription {
const subscription = super._subscribe(subscriber);
!subscription.closed && subscriber.next(this._value);
return subscription;
}
getValue(): T {
const { hasError, thrownError, _value } = this;
if (hasError) {
throw thrownError;
}
this._throwIfClosed();
return _value;
}
next(value: T): void {
super.next((this._value = value));
}
}

238
node_modules/rxjs/src/internal/Notification.ts generated vendored Normal file
View File

@@ -0,0 +1,238 @@
import { PartialObserver, ObservableNotification, CompleteNotification, NextNotification, ErrorNotification } from './types';
import { Observable } from './Observable';
import { EMPTY } from './observable/empty';
import { of } from './observable/of';
import { throwError } from './observable/throwError';
import { isFunction } from './util/isFunction';
// TODO: When this enum is removed, replace it with a type alias. See #4556.
/**
* @deprecated Use a string literal instead. `NotificationKind` will be replaced with a type alias in v8.
* It will not be replaced with a const enum as those are not compatible with isolated modules.
*/
export enum NotificationKind {
NEXT = 'N',
ERROR = 'E',
COMPLETE = 'C',
}
/**
* Represents a push-based event or value that an {@link Observable} can emit.
* This class is particularly useful for operators that manage notifications,
* like {@link materialize}, {@link dematerialize}, {@link observeOn}, and
* others. Besides wrapping the actual delivered value, it also annotates it
* with metadata of, for instance, what type of push message it is (`next`,
* `error`, or `complete`).
*
* @see {@link materialize}
* @see {@link dematerialize}
* @see {@link observeOn}
* @deprecated It is NOT recommended to create instances of `Notification` directly.
* Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.
* For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.
* Will be removed in v8.
*/
export class Notification<T> {
/**
* A value signifying that the notification will "next" if observed. In truth,
* This is really synonymous with just checking `kind === "N"`.
* @deprecated Will be removed in v8. Instead, just check to see if the value of `kind` is `"N"`.
*/
readonly hasValue: boolean;
/**
* Creates a "Next" notification object.
* @param kind Always `'N'`
* @param value The value to notify with if observed.
* @deprecated Internal implementation detail. Use {@link Notification#createNext createNext} instead.
*/
constructor(kind: 'N', value?: T);
/**
* Creates an "Error" notification object.
* @param kind Always `'E'`
* @param value Always `undefined`
* @param error The error to notify with if observed.
* @deprecated Internal implementation detail. Use {@link Notification#createError createError} instead.
*/
constructor(kind: 'E', value: undefined, error: any);
/**
* Creates a "completion" notification object.
* @param kind Always `'C'`
* @deprecated Internal implementation detail. Use {@link Notification#createComplete createComplete} instead.
*/
constructor(kind: 'C');
constructor(public readonly kind: 'N' | 'E' | 'C', public readonly value?: T, public readonly error?: any) {
this.hasValue = kind === 'N';
}
/**
* Executes the appropriate handler on a passed `observer` given the `kind` of notification.
* If the handler is missing it will do nothing. Even if the notification is an error, if
* there is no error handler on the observer, an error will not be thrown, it will noop.
* @param observer The observer to notify.
*/
observe(observer: PartialObserver<T>): void {
return observeNotification(this as ObservableNotification<T>, observer);
}
/**
* Executes a notification on the appropriate handler from a list provided.
* If a handler is missing for the kind of notification, nothing is called
* and no error is thrown, it will be a noop.
* @param next A next handler
* @param error An error handler
* @param complete A complete handler
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
do(next: (value: T) => void, error: (err: any) => void, complete: () => void): void;
/**
* Executes a notification on the appropriate handler from a list provided.
* If a handler is missing for the kind of notification, nothing is called
* and no error is thrown, it will be a noop.
* @param next A next handler
* @param error An error handler
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
do(next: (value: T) => void, error: (err: any) => void): void;
/**
* Executes the next handler if the Notification is of `kind` `"N"`. Otherwise
* this will not error, and it will be a noop.
* @param next The next handler
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
do(next: (value: T) => void): void;
do(nextHandler: (value: T) => void, errorHandler?: (err: any) => void, completeHandler?: () => void): void {
const { kind, value, error } = this;
return kind === 'N' ? nextHandler?.(value!) : kind === 'E' ? errorHandler?.(error) : completeHandler?.();
}
/**
* Executes a notification on the appropriate handler from a list provided.
* If a handler is missing for the kind of notification, nothing is called
* and no error is thrown, it will be a noop.
* @param next A next handler
* @param error An error handler
* @param complete A complete handler
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
accept(next: (value: T) => void, error: (err: any) => void, complete: () => void): void;
/**
* Executes a notification on the appropriate handler from a list provided.
* If a handler is missing for the kind of notification, nothing is called
* and no error is thrown, it will be a noop.
* @param next A next handler
* @param error An error handler
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
accept(next: (value: T) => void, error: (err: any) => void): void;
/**
* Executes the next handler if the Notification is of `kind` `"N"`. Otherwise
* this will not error, and it will be a noop.
* @param next The next handler
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
accept(next: (value: T) => void): void;
/**
* Executes the appropriate handler on a passed `observer` given the `kind` of notification.
* If the handler is missing it will do nothing. Even if the notification is an error, if
* there is no error handler on the observer, an error will not be thrown, it will noop.
* @param observer The observer to notify.
* @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.
*/
accept(observer: PartialObserver<T>): void;
accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {
return isFunction((nextOrObserver as any)?.next)
? this.observe(nextOrObserver as PartialObserver<T>)
: this.do(nextOrObserver as (value: T) => void, error as any, complete as any);
}
/**
* Returns a simple Observable that just delivers the notification represented
* by this Notification instance.
*
* @deprecated Will be removed in v8. To convert a `Notification` to an {@link Observable},
* use {@link of} and {@link dematerialize}: `of(notification).pipe(dematerialize())`.
*/
toObservable(): Observable<T> {
const { kind, value, error } = this;
// Select the observable to return by `kind`
const result =
kind === 'N'
? // Next kind. Return an observable of that value.
of(value!)
: //
kind === 'E'
? // Error kind. Return an observable that emits the error.
throwError(() => error)
: //
kind === 'C'
? // Completion kind. Kind is "C", return an observable that just completes.
EMPTY
: // Unknown kind, return falsy, so we error below.
0;
if (!result) {
// TODO: consider removing this check. The only way to cause this would be to
// use the Notification constructor directly in a way that is not type-safe.
// and direct use of the Notification constructor is deprecated.
throw new TypeError(`Unexpected notification kind ${kind}`);
}
return result;
}
private static completeNotification = new Notification('C') as Notification<never> & CompleteNotification;
/**
* A shortcut to create a Notification instance of the type `next` from a
* given value.
* @param value The `next` value.
* @return The "next" Notification representing the argument.
* @deprecated It is NOT recommended to create instances of `Notification` directly.
* Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.
* For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.
* Will be removed in v8.
*/
static createNext<T>(value: T) {
return new Notification('N', value) as Notification<T> & NextNotification<T>;
}
/**
* A shortcut to create a Notification instance of the type `error` from a
* given error.
* @param err The `error` error.
* @return The "error" Notification representing the argument.
* @deprecated It is NOT recommended to create instances of `Notification` directly.
* Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.
* For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.
* Will be removed in v8.
*/
static createError(err?: any) {
return new Notification('E', undefined, err) as Notification<never> & ErrorNotification;
}
/**
* A shortcut to create a Notification instance of the type `complete`.
* @return The valueless "complete" Notification.
* @deprecated It is NOT recommended to create instances of `Notification` directly.
* Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.
* For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.
* Will be removed in v8.
*/
static createComplete(): Notification<never> & CompleteNotification {
return Notification.completeNotification;
}
}
/**
* Executes the appropriate handler on a passed `observer` given the `kind` of notification.
* If the handler is missing it will do nothing. Even if the notification is an error, if
* there is no error handler on the observer, an error will not be thrown, it will noop.
* @param notification The notification object to observe.
* @param observer The observer to notify.
*/
export function observeNotification<T>(notification: ObservableNotification<T>, observer: PartialObserver<T>) {
const { kind, value, error } = notification as any;
if (typeof kind !== 'string') {
throw new TypeError('Invalid notification, missing "kind"');
}
kind === 'N' ? observer.next?.(value!) : kind === 'E' ? observer.error?.(error) : observer.complete?.();
}

View File

@@ -0,0 +1,40 @@
import { CompleteNotification, NextNotification, ErrorNotification } from './types';
/**
* A completion object optimized for memory use and created to be the
* same "shape" as other notifications in v8.
* @internal
*/
export const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();
/**
* Internal use only. Creates an optimized error notification that is the same "shape"
* as other notifications.
* @internal
*/
export function errorNotification(error: any): ErrorNotification {
return createNotification('E', undefined, error) as any;
}
/**
* Internal use only. Creates an optimized next notification that is the same "shape"
* as other notifications.
* @internal
*/
export function nextNotification<T>(value: T) {
return createNotification('N', value, undefined) as NextNotification<T>;
}
/**
* Ensures that all notifications created internally have the same "shape" in v8.
*
* TODO: This is only exported to support a crazy legacy test in `groupBy`.
* @internal
*/
export function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {
return {
kind,
value,
error,
};
}

487
node_modules/rxjs/src/internal/Observable.ts generated vendored Normal file
View File

@@ -0,0 +1,487 @@
import { Operator } from './Operator';
import { SafeSubscriber, Subscriber } from './Subscriber';
import { isSubscription, Subscription } from './Subscription';
import { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';
import { observable as Symbol_observable } from './symbol/observable';
import { pipeFromArray } from './util/pipe';
import { config } from './config';
import { isFunction } from './util/isFunction';
import { errorContext } from './util/errorContext';
/**
* A representation of any set of values over any amount of time. This is the most basic building block
* of RxJS.
*/
export class Observable<T> implements Subscribable<T> {
/**
* @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
*/
source: Observable<any> | undefined;
/**
* @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
*/
operator: Operator<any, T> | undefined;
/**
* @param subscribe The function that is called when the Observable is
* initially subscribed to. This function is given a Subscriber, to which new values
* can be `next`ed, or an `error` method can be called to raise an error, or
* `complete` can be called to notify of a successful completion.
*/
constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {
if (subscribe) {
this._subscribe = subscribe;
}
}
// HACK: Since TypeScript inherits static properties too, we have to
// fight against TypeScript here so Subject can have a different static create signature
/**
* Creates a new Observable by calling the Observable constructor
* @param subscribe the subscriber function to be passed to the Observable constructor
* @return A new observable.
* @deprecated Use `new Observable()` instead. Will be removed in v8.
*/
static create: (...args: any[]) => any = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {
return new Observable<T>(subscribe);
};
/**
* Creates a new Observable, with this Observable instance as the source, and the passed
* operator defined as the new observable's operator.
* @param operator the operator defining the operation to take on the observable
* @return A new observable with the Operator applied.
* @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
* If you have implemented an operator using `lift`, it is recommended that you create an
* operator by simply returning `new Observable()` directly. See "Creating new operators from
* scratch" section here: https://rxjs.dev/guide/operators
*/
lift<R>(operator?: Operator<T, R>): Observable<R> {
const observable = new Observable<R>();
observable.source = this;
observable.operator = operator;
return observable;
}
subscribe(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;
/** @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 */
subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): Subscription;
/**
* Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.
*
* <span class="informal">Use it when you have all these Observables, but still nothing is happening.</span>
*
* `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It
* might be for example a function that you passed to Observable's constructor, but most of the time it is
* a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means
* that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often
* the thought.
*
* Apart from starting the execution of an Observable, this method allows you to listen for values
* that an Observable emits, as well as for when it completes or errors. You can achieve this in two
* of the following ways.
*
* The first way is creating an object that implements {@link Observer} interface. It should have methods
* defined by that interface, but note that it should be just a regular JavaScript object, which you can create
* yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular, do
* not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also
* that your object does not have to implement all methods. If you find yourself creating a method that doesn't
* do anything, you can simply omit it. Note however, if the `error` method is not provided and an error happens,
* it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,
* use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or
* `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide
* an `error` method to avoid missing thrown errors.
*
* The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.
* This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent
* of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of an Observer,
* if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,
* since `subscribe` recognizes these functions by where they were placed in function call. When it comes
* to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.
*
* You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events
* and you also handled emissions internally by using operators (e.g. using `tap`).
*
* Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.
* This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean
* up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback
* provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.
*
* Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.
* It is an Observable itself that decides when these functions will be called. For example {@link of}
* by default emits all its values synchronously. Always check documentation for how given Observable
* will behave when subscribed and if its default behavior can be modified with a `scheduler`.
*
* #### Examples
*
* Subscribe with an {@link guide/observer Observer}
*
* ```ts
* import { of } from 'rxjs';
*
* const sumObserver = {
* sum: 0,
* next(value) {
* console.log('Adding: ' + value);
* this.sum = this.sum + value;
* },
* error() {
* // We actually could just remove this method,
* // since we do not really care about errors right now.
* },
* complete() {
* console.log('Sum equals: ' + this.sum);
* }
* };
*
* of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.
* .subscribe(sumObserver);
*
* // Logs:
* // 'Adding: 1'
* // 'Adding: 2'
* // 'Adding: 3'
* // 'Sum equals: 6'
* ```
*
* Subscribe with functions ({@link deprecations/subscribe-arguments deprecated})
*
* ```ts
* import { of } from 'rxjs'
*
* let sum = 0;
*
* of(1, 2, 3).subscribe(
* value => {
* console.log('Adding: ' + value);
* sum = sum + value;
* },
* undefined,
* () => console.log('Sum equals: ' + sum)
* );
*
* // Logs:
* // 'Adding: 1'
* // 'Adding: 2'
* // 'Adding: 3'
* // 'Sum equals: 6'
* ```
*
* Cancel a subscription
*
* ```ts
* import { interval } from 'rxjs';
*
* const subscription = interval(1000).subscribe({
* next(num) {
* console.log(num)
* },
* complete() {
* // Will not be called, even when cancelling subscription.
* console.log('completed!');
* }
* });
*
* setTimeout(() => {
* subscription.unsubscribe();
* console.log('unsubscribed!');
* }, 2500);
*
* // Logs:
* // 0 after 1s
* // 1 after 2s
* // 'unsubscribed!' after 2.5s
* ```
*
* @param observerOrNext Either an {@link Observer} with some or all callback methods,
* or the `next` handler that is called for each value emitted from the subscribed Observable.
* @param error A handler for a terminal event resulting from an error. If no error handler is provided,
* the error will be thrown asynchronously as unhandled.
* @param complete A handler for a terminal event resulting from successful completion.
* @return A subscription reference to the registered handlers.
*/
subscribe(
observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,
error?: ((error: any) => void) | null,
complete?: (() => void) | null
): Subscription {
const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
errorContext(() => {
const { operator, source } = this;
subscriber.add(
operator
? // We're dealing with a subscription in the
// operator chain to one of our lifted operators.
operator.call(subscriber, source)
: source
? // If `source` has a value, but `operator` does not, something that
// had intimate knowledge of our API, like our `Subject`, must have
// set it. We're going to just call `_subscribe` directly.
this._subscribe(subscriber)
: // In all other cases, we're likely wrapping a user-provided initializer
// function, so we need to catch errors and handle them appropriately.
this._trySubscribe(subscriber)
);
});
return subscriber;
}
/** @internal */
protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {
try {
return this._subscribe(sink);
} catch (err) {
// We don't need to return anything in this case,
// because it's just going to try to `add()` to a subscription
// above.
sink.error(err);
}
}
/**
* Used as a NON-CANCELLABLE means of subscribing to an observable, for use with
* APIs that expect promises, like `async/await`. You cannot unsubscribe from this.
*
* **WARNING**: Only use this with observables you *know* will complete. If the source
* observable does not complete, you will end up with a promise that is hung up, and
* potentially all of the state of an async function hanging out in memory. To avoid
* this situation, look into adding something like {@link timeout}, {@link take},
* {@link takeWhile}, or {@link takeUntil} amongst others.
*
* #### Example
*
* ```ts
* import { interval, take } from 'rxjs';
*
* const source$ = interval(1000).pipe(take(4));
*
* async function getTotal() {
* let total = 0;
*
* await source$.forEach(value => {
* total += value;
* console.log('observable -> ' + value);
* });
*
* return total;
* }
*
* getTotal().then(
* total => console.log('Total: ' + total)
* );
*
* // Expected:
* // 'observable -> 0'
* // 'observable -> 1'
* // 'observable -> 2'
* // 'observable -> 3'
* // 'Total: 6'
* ```
*
* @param next A handler for each value emitted by the observable.
* @return A promise that either resolves on observable completion or
* rejects with the handled error.
*/
forEach(next: (value: T) => void): Promise<void>;
/**
* @param next a handler for each value emitted by the observable
* @param promiseCtor a constructor function used to instantiate the Promise
* @return a promise that either resolves on observable completion or
* rejects with the handled error
* @deprecated Passing a Promise constructor will no longer be available
* in upcoming versions of RxJS. This is because it adds weight to the library, for very
* little benefit. If you need this functionality, it is recommended that you either
* polyfill Promise, or you create an adapter to convert the returned native promise
* to whatever promise implementation you wanted. Will be removed in v8.
*/
forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise<void>;
forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor<void>((resolve, reject) => {
const subscriber = new SafeSubscriber<T>({
next: (value) => {
try {
next(value);
} catch (err) {
reject(err);
subscriber.unsubscribe();
}
},
error: reject,
complete: resolve,
});
this.subscribe(subscriber);
}) as Promise<void>;
}
/** @internal */
protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {
return this.source?.subscribe(subscriber);
}
/**
* An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable
* @return This instance of the observable.
*/
[Symbol_observable]() {
return this;
}
/* tslint:disable:max-line-length */
pipe(): Observable<T>;
pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;
pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;
pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;
pipe<A, B, C, D>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>
): Observable<D>;
pipe<A, B, C, D, E>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>,
op5: OperatorFunction<D, E>
): Observable<E>;
pipe<A, B, C, D, E, F>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>,
op5: OperatorFunction<D, E>,
op6: OperatorFunction<E, F>
): Observable<F>;
pipe<A, B, C, D, E, F, G>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>,
op5: OperatorFunction<D, E>,
op6: OperatorFunction<E, F>,
op7: OperatorFunction<F, G>
): Observable<G>;
pipe<A, B, C, D, E, F, G, H>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>,
op5: OperatorFunction<D, E>,
op6: OperatorFunction<E, F>,
op7: OperatorFunction<F, G>,
op8: OperatorFunction<G, H>
): Observable<H>;
pipe<A, B, C, D, E, F, G, H, I>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>,
op5: OperatorFunction<D, E>,
op6: OperatorFunction<E, F>,
op7: OperatorFunction<F, G>,
op8: OperatorFunction<G, H>,
op9: OperatorFunction<H, I>
): Observable<I>;
pipe<A, B, C, D, E, F, G, H, I>(
op1: OperatorFunction<T, A>,
op2: OperatorFunction<A, B>,
op3: OperatorFunction<B, C>,
op4: OperatorFunction<C, D>,
op5: OperatorFunction<D, E>,
op6: OperatorFunction<E, F>,
op7: OperatorFunction<F, G>,
op8: OperatorFunction<G, H>,
op9: OperatorFunction<H, I>,
...operations: OperatorFunction<any, any>[]
): Observable<unknown>;
/* tslint:enable:max-line-length */
/**
* Used to stitch together functional operators into a chain.
*
* ## Example
*
* ```ts
* import { interval, filter, map, scan } from 'rxjs';
*
* interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x));
* ```
*
* @return The Observable result of all the operators having been called
* in the order they were passed in.
*/
pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {
return pipeFromArray(operations)(this);
}
/* tslint:disable:max-line-length */
/** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
toPromise(): Promise<T | undefined>;
/** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
toPromise(PromiseCtor: typeof Promise): Promise<T | undefined>;
/** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */
toPromise(PromiseCtor: PromiseConstructorLike): Promise<T | undefined>;
/* tslint:enable:max-line-length */
/**
* Subscribe to this Observable and get a Promise resolving on
* `complete` with the last emission (if any).
*
* **WARNING**: Only use this with observables you *know* will complete. If the source
* observable does not complete, you will end up with a promise that is hung up, and
* potentially all of the state of an async function hanging out in memory. To avoid
* this situation, look into adding something like {@link timeout}, {@link take},
* {@link takeWhile}, or {@link takeUntil} amongst others.
*
* @param [promiseCtor] a constructor function used to instantiate
* the Promise
* @return A Promise that resolves with the last value emit, or
* rejects on an error. If there were no emissions, Promise
* resolves with undefined.
* @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise
*/
toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor((resolve, reject) => {
let value: T | undefined;
this.subscribe(
(x: T) => (value = x),
(err: any) => reject(err),
() => resolve(value)
);
}) as Promise<T | undefined>;
}
}
/**
* Decides between a passed promise constructor from consuming code,
* A default configured promise constructor, and the native promise
* constructor and returns it. If nothing can be found, it will throw
* an error.
* @param promiseCtor The optional promise constructor to passed by consuming code
*/
function getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {
return promiseCtor ?? config.Promise ?? Promise;
}
function isObserver<T>(value: any): value is Observer<T> {
return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
}
function isSubscriber<T>(value: any): value is Subscriber<T> {
return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
}

9
node_modules/rxjs/src/internal/Operator.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { Subscriber } from './Subscriber';
import { TeardownLogic } from './types';
/***
* @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
*/
export interface Operator<T, R> {
call(subscriber: Subscriber<R>, source: any): TeardownLogic;
}

110
node_modules/rxjs/src/internal/ReplaySubject.ts generated vendored Normal file
View File

@@ -0,0 +1,110 @@
import { Subject } from './Subject';
import { TimestampProvider } from './types';
import { Subscriber } from './Subscriber';
import { Subscription } from './Subscription';
import { dateTimestampProvider } from './scheduler/dateTimestampProvider';
/**
* A variant of {@link Subject} that "replays" old values to new subscribers by emitting them when they first subscribe.
*
* `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,
* `ReplaySubject` "observes" values by having them passed to its `next` method. When it observes a value, it will store that
* value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.
*
* When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in
* a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will
* error if it has observed an error.
*
* There are two main configuration items to be concerned with:
*
* 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.
* 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.
*
* Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values
* are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.
*
* ### Differences with BehaviorSubject
*
* `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:
*
* 1. `BehaviorSubject` comes "primed" with a single value upon construction.
* 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.
*
* @see {@link Subject}
* @see {@link BehaviorSubject}
* @see {@link shareReplay}
*/
export class ReplaySubject<T> extends Subject<T> {
private _buffer: (T | number)[] = [];
private _infiniteTimeWindow = true;
/**
* @param _bufferSize The size of the buffer to replay on subscription
* @param _windowTime The amount of time the buffered items will stay buffered
* @param _timestampProvider An object with a `now()` method that provides the current timestamp. This is used to
* calculate the amount of time something has been buffered.
*/
constructor(
private _bufferSize = Infinity,
private _windowTime = Infinity,
private _timestampProvider: TimestampProvider = dateTimestampProvider
) {
super();
this._infiniteTimeWindow = _windowTime === Infinity;
this._bufferSize = Math.max(1, _bufferSize);
this._windowTime = Math.max(1, _windowTime);
}
next(value: T): void {
const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;
if (!isStopped) {
_buffer.push(value);
!_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
}
this._trimBuffer();
super.next(value);
}
/** @internal */
protected _subscribe(subscriber: Subscriber<T>): Subscription {
this._throwIfClosed();
this._trimBuffer();
const subscription = this._innerSubscribe(subscriber);
const { _infiniteTimeWindow, _buffer } = this;
// We use a copy here, so reentrant code does not mutate our array while we're
// emitting it to a new subscriber.
const copy = _buffer.slice();
for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
subscriber.next(copy[i] as T);
}
this._checkFinalizedStatuses(subscriber);
return subscription;
}
private _trimBuffer() {
const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;
// If we don't have an infinite buffer size, and we're over the length,
// use splice to truncate the old buffer values off. Note that we have to
// double the size for instances where we're not using an infinite time window
// because we're storing the values and the timestamps in the same array.
const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
_bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
// Now, if we're not in an infinite time window, remove all values where the time is
// older than what is allowed.
if (!_infiniteTimeWindow) {
const now = _timestampProvider.now();
let last = 0;
// Search the array for the first timestamp that isn't expired and
// truncate the buffer up to that point.
for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {
last = i;
}
last && _buffer.splice(0, last + 1);
}
}
}

60
node_modules/rxjs/src/internal/Scheduler.ts generated vendored Normal file
View File

@@ -0,0 +1,60 @@
import { Action } from './scheduler/Action';
import { Subscription } from './Subscription';
import { SchedulerLike, SchedulerAction } from './types';
import { dateTimestampProvider } from './scheduler/dateTimestampProvider';
/**
* An execution context and a data structure to order tasks and schedule their
* execution. Provides a notion of (potentially virtual) time, through the
* `now()` getter method.
*
* Each unit of work in a Scheduler is called an `Action`.
*
* ```ts
* class Scheduler {
* now(): number;
* schedule(work, delay?, state?): Subscription;
* }
* ```
*
* @deprecated Scheduler is an internal implementation detail of RxJS, and
* should not be used directly. Rather, create your own class and implement
* {@link SchedulerLike}. Will be made internal in v8.
*/
export class Scheduler implements SchedulerLike {
public static now: () => number = dateTimestampProvider.now;
constructor(private schedulerActionCtor: typeof Action, now: () => number = Scheduler.now) {
this.now = now;
}
/**
* A getter method that returns a number representing the current time
* (at the time this function was called) according to the scheduler's own
* internal clock.
* @return A number that represents the current time. May or may not
* have a relation to wall-clock time. May or may not refer to a time unit
* (e.g. milliseconds).
*/
public now: () => number;
/**
* Schedules a function, `work`, for execution. May happen at some point in
* the future, according to the `delay` parameter, if specified. May be passed
* some context object, `state`, which will be passed to the `work` function.
*
* The given arguments will be processed an stored as an Action object in a
* queue of actions.
*
* @param work A function representing a task, or some unit of work to be
* executed by the Scheduler.
* @param delay Time to wait before executing the work, where the time unit is
* implicit and defined by the Scheduler itself.
* @param state Some contextual data that the `work` function uses when called
* by the Scheduler.
* @return A subscription in order to be able to unsubscribe the scheduled work.
*/
public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {
return new this.schedulerActionCtor<T>(this, work).schedule(state, delay);
}
}

185
node_modules/rxjs/src/internal/Subject.ts generated vendored Normal file
View File

@@ -0,0 +1,185 @@
import { Operator } from './Operator';
import { Observable } from './Observable';
import { Subscriber } from './Subscriber';
import { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';
import { Observer, SubscriptionLike, TeardownLogic } from './types';
import { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';
import { arrRemove } from './util/arrRemove';
import { errorContext } from './util/errorContext';
/**
* A Subject is a special type of Observable that allows values to be
* multicasted to many Observers. Subjects are like EventEmitters.
*
* Every Subject is an Observable and an Observer. You can subscribe to a
* Subject, and you can call next to feed values as well as error and complete.
*/
export class Subject<T> extends Observable<T> implements SubscriptionLike {
closed = false;
private currentObservers: Observer<T>[] | null = null;
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
observers: Observer<T>[] = [];
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
isStopped = false;
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
hasError = false;
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
thrownError: any = null;
/**
* Creates a "subject" by basically gluing an observer to an observable.
*
* @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.
*/
static create: (...args: any[]) => any = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {
return new AnonymousSubject<T>(destination, source);
};
constructor() {
// NOTE: This must be here to obscure Observable's constructor.
super();
}
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
lift<R>(operator: Operator<T, R>): Observable<R> {
const subject = new AnonymousSubject(this, this);
subject.operator = operator as any;
return subject as any;
}
/** @internal */
protected _throwIfClosed() {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
}
next(value: T) {
errorContext(() => {
this._throwIfClosed();
if (!this.isStopped) {
if (!this.currentObservers) {
this.currentObservers = Array.from(this.observers);
}
for (const observer of this.currentObservers) {
observer.next(value);
}
}
});
}
error(err: any) {
errorContext(() => {
this._throwIfClosed();
if (!this.isStopped) {
this.hasError = this.isStopped = true;
this.thrownError = err;
const { observers } = this;
while (observers.length) {
observers.shift()!.error(err);
}
}
});
}
complete() {
errorContext(() => {
this._throwIfClosed();
if (!this.isStopped) {
this.isStopped = true;
const { observers } = this;
while (observers.length) {
observers.shift()!.complete();
}
}
});
}
unsubscribe() {
this.isStopped = this.closed = true;
this.observers = this.currentObservers = null!;
}
get observed() {
return this.observers?.length > 0;
}
/** @internal */
protected _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {
this._throwIfClosed();
return super._trySubscribe(subscriber);
}
/** @internal */
protected _subscribe(subscriber: Subscriber<T>): Subscription {
this._throwIfClosed();
this._checkFinalizedStatuses(subscriber);
return this._innerSubscribe(subscriber);
}
/** @internal */
protected _innerSubscribe(subscriber: Subscriber<any>) {
const { hasError, isStopped, observers } = this;
if (hasError || isStopped) {
return EMPTY_SUBSCRIPTION;
}
this.currentObservers = null;
observers.push(subscriber);
return new Subscription(() => {
this.currentObservers = null;
arrRemove(observers, subscriber);
});
}
/** @internal */
protected _checkFinalizedStatuses(subscriber: Subscriber<any>) {
const { hasError, thrownError, isStopped } = this;
if (hasError) {
subscriber.error(thrownError);
} else if (isStopped) {
subscriber.complete();
}
}
/**
* Creates a new Observable with this Subject as the source. You can do this
* to create custom Observer-side logic of the Subject and conceal it from
* code that uses the Observable.
* @return Observable that this Subject casts to.
*/
asObservable(): Observable<T> {
const observable: any = new Observable<T>();
observable.source = this;
return observable;
}
}
export class AnonymousSubject<T> extends Subject<T> {
constructor(
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
public destination?: Observer<T>,
source?: Observable<T>
) {
super();
this.source = source;
}
next(value: T) {
this.destination?.next?.(value);
}
error(err: any) {
this.destination?.error?.(err);
}
complete() {
this.destination?.complete?.();
}
/** @internal */
protected _subscribe(subscriber: Subscriber<T>): Subscription {
return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;
}
}

270
node_modules/rxjs/src/internal/Subscriber.ts generated vendored Normal file
View File

@@ -0,0 +1,270 @@
import { isFunction } from './util/isFunction';
import { Observer, ObservableNotification } from './types';
import { isSubscription, Subscription } from './Subscription';
import { config } from './config';
import { reportUnhandledError } from './util/reportUnhandledError';
import { noop } from './util/noop';
import { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';
import { timeoutProvider } from './scheduler/timeoutProvider';
import { captureError } from './util/errorContext';
/**
* Implements the {@link Observer} interface and extends the
* {@link Subscription} class. While the {@link Observer} is the public API for
* consuming the values of an {@link Observable}, all Observers get converted to
* a Subscriber, in order to provide Subscription-like capabilities such as
* `unsubscribe`. Subscriber is a common type in RxJS, and crucial for
* implementing operators, but it is rarely used as a public API.
*/
export class Subscriber<T> extends Subscription implements Observer<T> {
/**
* A static factory for a Subscriber, given a (potentially partial) definition
* of an Observer.
* @param next The `next` callback of an Observer.
* @param error The `error` callback of an
* Observer.
* @param complete The `complete` callback of an
* Observer.
* @return A Subscriber wrapping the (partially defined)
* Observer represented by the given arguments.
* @deprecated Do not use. Will be removed in v8. There is no replacement for this
* method, and there is no reason to be creating instances of `Subscriber` directly.
* If you have a specific use case, please file an issue.
*/
static create<T>(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber<T> {
return new SafeSubscriber(next, error, complete);
}
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
protected isStopped: boolean = false;
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
protected destination: Subscriber<any> | Observer<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)
/**
* @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.
* There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.
*/
constructor(destination?: Subscriber<any> | Observer<any>) {
super();
if (destination) {
this.destination = destination;
// Automatically chain subscriptions together here.
// if destination is a Subscription, then it is a Subscriber.
if (isSubscription(destination)) {
destination.add(this);
}
} else {
this.destination = EMPTY_OBSERVER;
}
}
/**
* The {@link Observer} callback to receive notifications of type `next` from
* the Observable, with a value. The Observable may call this method 0 or more
* times.
* @param value The `next` value.
*/
next(value: T): void {
if (this.isStopped) {
handleStoppedNotification(nextNotification(value), this);
} else {
this._next(value!);
}
}
/**
* The {@link Observer} callback to receive notifications of type `error` from
* the Observable, with an attached `Error`. Notifies the Observer that
* the Observable has experienced an error condition.
* @param err The `error` exception.
*/
error(err?: any): void {
if (this.isStopped) {
handleStoppedNotification(errorNotification(err), this);
} else {
this.isStopped = true;
this._error(err);
}
}
/**
* The {@link Observer} callback to receive a valueless notification of type
* `complete` from the Observable. Notifies the Observer that the Observable
* has finished sending push-based notifications.
*/
complete(): void {
if (this.isStopped) {
handleStoppedNotification(COMPLETE_NOTIFICATION, this);
} else {
this.isStopped = true;
this._complete();
}
}
unsubscribe(): void {
if (!this.closed) {
this.isStopped = true;
super.unsubscribe();
this.destination = null!;
}
}
protected _next(value: T): void {
this.destination.next(value);
}
protected _error(err: any): void {
try {
this.destination.error(err);
} finally {
this.unsubscribe();
}
}
protected _complete(): void {
try {
this.destination.complete();
} finally {
this.unsubscribe();
}
}
}
/**
* This bind is captured here because we want to be able to have
* compatibility with monoid libraries that tend to use a method named
* `bind`. In particular, a library called Monio requires this.
*/
const _bind = Function.prototype.bind;
function bind<Fn extends (...args: any[]) => any>(fn: Fn, thisArg: any): Fn {
return _bind.call(fn, thisArg);
}
/**
* Internal optimization only, DO NOT EXPOSE.
* @internal
*/
class ConsumerObserver<T> implements Observer<T> {
constructor(private partialObserver: Partial<Observer<T>>) {}
next(value: T): void {
const { partialObserver } = this;
if (partialObserver.next) {
try {
partialObserver.next(value);
} catch (error) {
handleUnhandledError(error);
}
}
}
error(err: any): void {
const { partialObserver } = this;
if (partialObserver.error) {
try {
partialObserver.error(err);
} catch (error) {
handleUnhandledError(error);
}
} else {
handleUnhandledError(err);
}
}
complete(): void {
const { partialObserver } = this;
if (partialObserver.complete) {
try {
partialObserver.complete();
} catch (error) {
handleUnhandledError(error);
}
}
}
}
export class SafeSubscriber<T> extends Subscriber<T> {
constructor(
observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,
error?: ((e?: any) => void) | null,
complete?: (() => void) | null
) {
super();
let partialObserver: Partial<Observer<T>>;
if (isFunction(observerOrNext) || !observerOrNext) {
// The first argument is a function, not an observer. The next
// two arguments *could* be observers, or they could be empty.
partialObserver = {
next: (observerOrNext ?? undefined) as ((value: T) => void) | undefined,
error: error ?? undefined,
complete: complete ?? undefined,
};
} else {
// The first argument is a partial observer.
let context: any;
if (this && config.useDeprecatedNextContext) {
// This is a deprecated path that made `this.unsubscribe()` available in
// next handler functions passed to subscribe. This only exists behind a flag
// now, as it is *very* slow.
context = Object.create(observerOrNext);
context.unsubscribe = () => this.unsubscribe();
partialObserver = {
next: observerOrNext.next && bind(observerOrNext.next, context),
error: observerOrNext.error && bind(observerOrNext.error, context),
complete: observerOrNext.complete && bind(observerOrNext.complete, context),
};
} else {
// The "normal" path. Just use the partial observer directly.
partialObserver = observerOrNext;
}
}
// Wrap the partial observer to ensure it's a full observer, and
// make sure proper error handling is accounted for.
this.destination = new ConsumerObserver(partialObserver);
}
}
function handleUnhandledError(error: any) {
if (config.useDeprecatedSynchronousErrorHandling) {
captureError(error);
} else {
// Ideal path, we report this as an unhandled error,
// which is thrown on a new call stack.
reportUnhandledError(error);
}
}
/**
* An error handler used when no error handler was supplied
* to the SafeSubscriber -- meaning no error handler was supplied
* do the `subscribe` call on our observable.
* @param err The error to handle
*/
function defaultErrorHandler(err: any) {
throw err;
}
/**
* A handler for notifications that cannot be sent to a stopped subscriber.
* @param notification The notification being sent.
* @param subscriber The stopped subscriber.
*/
function handleStoppedNotification(notification: ObservableNotification<any>, subscriber: Subscriber<any>) {
const { onStoppedNotification } = config;
onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));
}
/**
* The observer used as a stub for subscriptions where the user did not
* pass any arguments to `subscribe`. Comes with the default error handling
* behavior.
*/
export const EMPTY_OBSERVER: Readonly<Observer<any>> & { closed: true } = {
closed: true,
next: noop,
error: defaultErrorHandler,
complete: noop,
};

212
node_modules/rxjs/src/internal/Subscription.ts generated vendored Normal file
View File

@@ -0,0 +1,212 @@
import { isFunction } from './util/isFunction';
import { UnsubscriptionError } from './util/UnsubscriptionError';
import { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';
import { arrRemove } from './util/arrRemove';
/**
* Represents a disposable resource, such as the execution of an Observable. A
* Subscription has one important method, `unsubscribe`, that takes no argument
* and just disposes the resource held by the subscription.
*
* Additionally, subscriptions may be grouped together through the `add()`
* method, which will attach a child Subscription to the current Subscription.
* When a Subscription is unsubscribed, all its children (and its grandchildren)
* will be unsubscribed as well.
*/
export class Subscription implements SubscriptionLike {
public static EMPTY = (() => {
const empty = new Subscription();
empty.closed = true;
return empty;
})();
/**
* A flag to indicate whether this Subscription has already been unsubscribed.
*/
public closed = false;
private _parentage: Subscription[] | Subscription | null = null;
/**
* The list of registered finalizers to execute upon unsubscription. Adding and removing from this
* list occurs in the {@link #add} and {@link #remove} methods.
*/
private _finalizers: Exclude<TeardownLogic, void>[] | null = null;
/**
* @param initialTeardown A function executed first as part of the finalization
* process that is kicked off when {@link #unsubscribe} is called.
*/
constructor(private initialTeardown?: () => void) {}
/**
* Disposes the resources held by the subscription. May, for instance, cancel
* an ongoing Observable execution or cancel any other type of work that
* started when the Subscription was created.
*/
unsubscribe(): void {
let errors: any[] | undefined;
if (!this.closed) {
this.closed = true;
// Remove this from it's parents.
const { _parentage } = this;
if (_parentage) {
this._parentage = null;
if (Array.isArray(_parentage)) {
for (const parent of _parentage) {
parent.remove(this);
}
} else {
_parentage.remove(this);
}
}
const { initialTeardown: initialFinalizer } = this;
if (isFunction(initialFinalizer)) {
try {
initialFinalizer();
} catch (e) {
errors = e instanceof UnsubscriptionError ? e.errors : [e];
}
}
const { _finalizers } = this;
if (_finalizers) {
this._finalizers = null;
for (const finalizer of _finalizers) {
try {
execFinalizer(finalizer);
} catch (err) {
errors = errors ?? [];
if (err instanceof UnsubscriptionError) {
errors = [...errors, ...err.errors];
} else {
errors.push(err);
}
}
}
}
if (errors) {
throw new UnsubscriptionError(errors);
}
}
}
/**
* Adds a finalizer to this subscription, so that finalization will be unsubscribed/called
* when this subscription is unsubscribed. If this subscription is already {@link #closed},
* because it has already been unsubscribed, then whatever finalizer is passed to it
* will automatically be executed (unless the finalizer itself is also a closed subscription).
*
* Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed
* subscription to a any subscription will result in no operation. (A noop).
*
* Adding a subscription to itself, or adding `null` or `undefined` will not perform any
* operation at all. (A noop).
*
* `Subscription` instances that are added to this instance will automatically remove themselves
* if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove
* will need to be removed manually with {@link #remove}
*
* @param teardown The finalization logic to add to this subscription.
*/
add(teardown: TeardownLogic): void {
// Only add the finalizer if it's not undefined
// and don't add a subscription to itself.
if (teardown && teardown !== this) {
if (this.closed) {
// If this subscription is already closed,
// execute whatever finalizer is handed to it automatically.
execFinalizer(teardown);
} else {
if (teardown instanceof Subscription) {
// We don't add closed subscriptions, and we don't add the same subscription
// twice. Subscription unsubscribe is idempotent.
if (teardown.closed || teardown._hasParent(this)) {
return;
}
teardown._addParent(this);
}
(this._finalizers = this._finalizers ?? []).push(teardown);
}
}
}
/**
* Checks to see if a this subscription already has a particular parent.
* This will signal that this subscription has already been added to the parent in question.
* @param parent the parent to check for
*/
private _hasParent(parent: Subscription) {
const { _parentage } = this;
return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
}
/**
* Adds a parent to this subscription so it can be removed from the parent if it
* unsubscribes on it's own.
*
* NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.
* @param parent The parent subscription to add
*/
private _addParent(parent: Subscription) {
const { _parentage } = this;
this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
}
/**
* Called on a child when it is removed via {@link #remove}.
* @param parent The parent to remove
*/
private _removeParent(parent: Subscription) {
const { _parentage } = this;
if (_parentage === parent) {
this._parentage = null;
} else if (Array.isArray(_parentage)) {
arrRemove(_parentage, parent);
}
}
/**
* Removes a finalizer from this subscription that was previously added with the {@link #add} method.
*
* Note that `Subscription` instances, when unsubscribed, will automatically remove themselves
* from every other `Subscription` they have been added to. This means that using the `remove` method
* is not a common thing and should be used thoughtfully.
*
* If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance
* more than once, you will need to call `remove` the same number of times to remove all instances.
*
* All finalizer instances are removed to free up memory upon unsubscription.
*
* @param teardown The finalizer to remove from this subscription
*/
remove(teardown: Exclude<TeardownLogic, void>): void {
const { _finalizers } = this;
_finalizers && arrRemove(_finalizers, teardown);
if (teardown instanceof Subscription) {
teardown._removeParent(this);
}
}
}
export const EMPTY_SUBSCRIPTION = Subscription.EMPTY;
export function isSubscription(value: any): value is Subscription {
return (
value instanceof Subscription ||
(value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))
);
}
function execFinalizer(finalizer: Unsubscribable | (() => void)) {
if (isFunction(finalizer)) {
finalizer();
} else {
finalizer.unsubscribe();
}
}

124
node_modules/rxjs/src/internal/ajax/AjaxResponse.ts generated vendored Normal file
View File

@@ -0,0 +1,124 @@
import { AjaxRequest, AjaxResponseType } from './types';
import { getXHRResponse } from './getXHRResponse';
/**
* A normalized response from an AJAX request. To get the data from the response,
* you will want to read the `response` property.
*
* - DO NOT create instances of this class directly.
* - DO NOT subclass this class.
*
* It is advised not to hold this object in memory, as it has a reference to
* the original XHR used to make the request, as well as properties containing
* request and response data.
*
* @see {@link ajax}
* @see {@link AjaxConfig}
*/
export class AjaxResponse<T> {
/** The HTTP status code */
readonly status: number;
/**
* The response data, if any. Note that this will automatically be converted to the proper type
*/
readonly response: T;
/**
* The responseType set on the request. (For example: `""`, `"arraybuffer"`, `"blob"`, `"document"`, `"json"`, or `"text"`)
* @deprecated There isn't much reason to examine this. It's the same responseType set (or defaulted) on the ajax config.
* If you really need to examine this value, you can check it on the `request` or the `xhr`. Will be removed in v8.
*/
readonly responseType: XMLHttpRequestResponseType;
/**
* The total number of bytes loaded so far. To be used with {@link total} while
* calculating progress. (You will want to set {@link includeDownloadProgress} or
* {@link includeDownloadProgress})
*/
readonly loaded: number;
/**
* The total number of bytes to be loaded. To be used with {@link loaded} while
* calculating progress. (You will want to set {@link includeDownloadProgress} or
* {@link includeDownloadProgress})
*/
readonly total: number;
/**
* A dictionary of the response headers.
*/
readonly responseHeaders: Record<string, string>;
/**
* A normalized response from an AJAX request. To get the data from the response,
* you will want to read the `response` property.
*
* - DO NOT create instances of this class directly.
* - DO NOT subclass this class.
*
* @param originalEvent The original event object from the XHR `onload` event.
* @param xhr The `XMLHttpRequest` object used to make the request. This is useful for examining status code, etc.
* @param request The request settings used to make the HTTP request.
* @param type The type of the event emitted by the {@link ajax} Observable
*/
constructor(
/**
* The original event object from the raw XHR event.
*/
public readonly originalEvent: ProgressEvent,
/**
* The XMLHttpRequest object used to make the request.
* NOTE: It is advised not to hold this in memory, as it will retain references to all of it's event handlers
* and many other things related to the request.
*/
public readonly xhr: XMLHttpRequest,
/**
* The request parameters used to make the HTTP request.
*/
public readonly request: AjaxRequest,
/**
* The event type. This can be used to discern between different events
* if you're using progress events with {@link includeDownloadProgress} or
* {@link includeUploadProgress} settings in {@link AjaxConfig}.
*
* The event type consists of two parts: the {@link AjaxDirection} and the
* the event type. Merged with `_`, they form the `type` string. The
* direction can be an `upload` or a `download` direction, while an event can
* be `loadstart`, `progress` or `load`.
*
* `download_load` is the type of event when download has finished and the
* response is available.
*/
public readonly type: AjaxResponseType = 'download_load'
) {
const { status, responseType } = xhr;
this.status = status ?? 0;
this.responseType = responseType ?? '';
// Parse the response headers in advance for the user. There's really
// not a great way to get all of them. So we need to parse the header string
// we get back. It comes in a simple enough format:
//
// header-name: value here
// content-type: application/json
// other-header-here: some, other, values, or, whatever
const allHeaders = xhr.getAllResponseHeaders();
this.responseHeaders = allHeaders
? // Split the header text into lines
allHeaders.split('\n').reduce((headers: Record<string, string>, line) => {
// Split the lines on the first ": " as
// "key: value". Note that the value could
// technically have a ": " in it.
const index = line.indexOf(': ');
headers[line.slice(0, index)] = line.slice(index + 2);
return headers;
}, {})
: {};
this.response = getXHRResponse(xhr);
const { loaded, total } = originalEvent;
this.loaded = loaded;
this.total = total;
}
}

622
node_modules/rxjs/src/internal/ajax/ajax.ts generated vendored Normal file
View File

@@ -0,0 +1,622 @@
import { map } from '../operators/map';
import { Observable } from '../Observable';
import { AjaxConfig, AjaxRequest, AjaxDirection, ProgressEventType } from './types';
import { AjaxResponse } from './AjaxResponse';
import { AjaxTimeoutError, AjaxError } from './errors';
export interface AjaxCreationMethod {
/**
* Creates an observable that will perform an AJAX request using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default.
*
* This is the most configurable option, and the basis for all other AJAX calls in the library.
*
* ## Example
*
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError, of } from 'rxjs';
*
* const obs$ = ajax({
* method: 'GET',
* url: 'https://api.github.com/users?per_page=5',
* responseType: 'json'
* }).pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
* ```
*/
<T>(config: AjaxConfig): Observable<AjaxResponse<T>>;
/**
* Perform an HTTP GET using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope. Defaults to a `responseType` of `"json"`.
*
* ## Example
*
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError, of } from 'rxjs';
*
* const obs$ = ajax('https://api.github.com/users?per_page=5').pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
* ```
*/
<T>(url: string): Observable<AjaxResponse<T>>;
/**
* Performs an HTTP GET using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default, and a `responseType` of `"json"`.
*
* @param url The URL to get the resource from
* @param headers Optional headers. Case-Insensitive.
*/
get<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
/**
* Performs an HTTP POST using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default, and a `responseType` of `"json"`.
*
* Before sending the value passed to the `body` argument, it is automatically serialized
* based on the specified `responseType`. By default, a JavaScript object will be serialized
* to JSON. A `responseType` of `application/x-www-form-urlencoded` will flatten any provided
* dictionary object to a url-encoded string.
*
* @param url The URL to get the resource from
* @param body The content to send. The body is automatically serialized.
* @param headers Optional headers. Case-Insensitive.
*/
post<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
/**
* Performs an HTTP PUT using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default, and a `responseType` of `"json"`.
*
* Before sending the value passed to the `body` argument, it is automatically serialized
* based on the specified `responseType`. By default, a JavaScript object will be serialized
* to JSON. A `responseType` of `application/x-www-form-urlencoded` will flatten any provided
* dictionary object to a url-encoded string.
*
* @param url The URL to get the resource from
* @param body The content to send. The body is automatically serialized.
* @param headers Optional headers. Case-Insensitive.
*/
put<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
/**
* Performs an HTTP PATCH using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default, and a `responseType` of `"json"`.
*
* Before sending the value passed to the `body` argument, it is automatically serialized
* based on the specified `responseType`. By default, a JavaScript object will be serialized
* to JSON. A `responseType` of `application/x-www-form-urlencoded` will flatten any provided
* dictionary object to a url-encoded string.
*
* @param url The URL to get the resource from
* @param body The content to send. The body is automatically serialized.
* @param headers Optional headers. Case-Insensitive.
*/
patch<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
/**
* Performs an HTTP DELETE using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default, and a `responseType` of `"json"`.
*
* @param url The URL to get the resource from
* @param headers Optional headers. Case-Insensitive.
*/
delete<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
/**
* Performs an HTTP GET using the
* [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
* global scope by default, and returns the hydrated JavaScript object from the
* response.
*
* @param url The URL to get the resource from
* @param headers Optional headers. Case-Insensitive.
*/
getJSON<T>(url: string, headers?: Record<string, string>): Observable<T>;
}
function ajaxGet<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
return ajax({ method: 'GET', url, headers });
}
function ajaxPost<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
return ajax({ method: 'POST', url, body, headers });
}
function ajaxDelete<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
return ajax({ method: 'DELETE', url, headers });
}
function ajaxPut<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
return ajax({ method: 'PUT', url, body, headers });
}
function ajaxPatch<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
return ajax({ method: 'PATCH', url, body, headers });
}
const mapResponse = map((x: AjaxResponse<any>) => x.response);
function ajaxGetJSON<T>(url: string, headers?: Record<string, string>): Observable<T> {
return mapResponse(
ajax<T>({
method: 'GET',
url,
headers,
})
);
}
/**
* There is an ajax operator on the Rx object.
*
* It creates an observable for an Ajax request with either a request object with
* url, headers, etc or a string for a URL.
*
* ## Examples
*
* Using `ajax()` to fetch the response object that is being returned from API
*
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError, of } from 'rxjs';
*
* const obs$ = ajax('https://api.github.com/users?per_page=5').pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* obs$.subscribe({
* next: value => console.log(value),
* error: err => console.log(err)
* });
* ```
*
* Using `ajax.getJSON()` to fetch data from API
*
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError, of } from 'rxjs';
*
* const obs$ = ajax.getJSON('https://api.github.com/users?per_page=5').pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* obs$.subscribe({
* next: value => console.log(value),
* error: err => console.log(err)
* });
* ```
*
* Using `ajax()` with object as argument and method POST with a two seconds delay
*
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError, of } from 'rxjs';
*
* const users = ajax({
* url: 'https://httpbin.org/delay/2',
* method: 'POST',
* headers: {
* 'Content-Type': 'application/json',
* 'rxjs-custom-header': 'Rxjs'
* },
* body: {
* rxjs: 'Hello World!'
* }
* }).pipe(
* map(response => console.log('response: ', response)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* users.subscribe({
* next: value => console.log(value),
* error: err => console.log(err)
* });
* ```
*
* Using `ajax()` to fetch. An error object that is being returned from the request
*
* ```ts
* import { ajax } from 'rxjs/ajax';
* import { map, catchError, of } from 'rxjs';
*
* const obs$ = ajax('https://api.github.com/404').pipe(
* map(userResponse => console.log('users: ', userResponse)),
* catchError(error => {
* console.log('error: ', error);
* return of(error);
* })
* );
*
* obs$.subscribe({
* next: value => console.log(value),
* error: err => console.log(err)
* });
* ```
*/
export const ajax: AjaxCreationMethod = (() => {
const create = <T>(urlOrConfig: string | AjaxConfig) => {
const config: AjaxConfig =
typeof urlOrConfig === 'string'
? {
url: urlOrConfig,
}
: urlOrConfig;
return fromAjax<T>(config);
};
create.get = ajaxGet;
create.post = ajaxPost;
create.delete = ajaxDelete;
create.put = ajaxPut;
create.patch = ajaxPatch;
create.getJSON = ajaxGetJSON;
return create;
})();
const UPLOAD = 'upload';
const DOWNLOAD = 'download';
const LOADSTART = 'loadstart';
const PROGRESS = 'progress';
const LOAD = 'load';
export function fromAjax<T>(init: AjaxConfig): Observable<AjaxResponse<T>> {
return new Observable((destination) => {
const config = {
// Defaults
async: true,
crossDomain: false,
withCredentials: false,
method: 'GET',
timeout: 0,
responseType: 'json' as XMLHttpRequestResponseType,
...init,
};
const { queryParams, body: configuredBody, headers: configuredHeaders } = config;
let url = config.url;
if (!url) {
throw new TypeError('url is required');
}
if (queryParams) {
let searchParams: URLSearchParams;
if (url.includes('?')) {
// If the user has passed a URL with a querystring already in it,
// we need to combine them. So we're going to split it. There
// should only be one `?` in a valid URL.
const parts = url.split('?');
if (2 < parts.length) {
throw new TypeError('invalid url');
}
// Add the passed queryParams to the params already in the url provided.
searchParams = new URLSearchParams(parts[1]);
// queryParams is converted to any because the runtime is *much* more permissive than
// the types are.
new URLSearchParams(queryParams as any).forEach((value, key) => searchParams.set(key, value));
// We have to do string concatenation here, because `new URL(url)` does
// not like relative URLs like `/this` without a base url, which we can't
// specify, nor can we assume `location` will exist, because of node.
url = parts[0] + '?' + searchParams;
} else {
// There is no preexisting querystring, so we can just use URLSearchParams
// to convert the passed queryParams into the proper format and encodings.
// queryParams is converted to any because the runtime is *much* more permissive than
// the types are.
searchParams = new URLSearchParams(queryParams as any);
url = url + '?' + searchParams;
}
}
// Normalize the headers. We're going to make them all lowercase, since
// Headers are case insensitive by design. This makes it easier to verify
// that we aren't setting or sending duplicates.
const headers: Record<string, any> = {};
if (configuredHeaders) {
for (const key in configuredHeaders) {
if (configuredHeaders.hasOwnProperty(key)) {
headers[key.toLowerCase()] = configuredHeaders[key];
}
}
}
const crossDomain = config.crossDomain;
// Set the x-requested-with header. This is a non-standard header that has
// come to be a de facto standard for HTTP requests sent by libraries and frameworks
// using XHR. However, we DO NOT want to set this if it is a CORS request. This is
// because sometimes this header can cause issues with CORS. To be clear,
// None of this is necessary, it's only being set because it's "the thing libraries do"
// Starting back as far as JQuery, and continuing with other libraries such as Angular 1,
// Axios, et al.
if (!crossDomain && !('x-requested-with' in headers)) {
headers['x-requested-with'] = 'XMLHttpRequest';
}
// Allow users to provide their XSRF cookie name and the name of a custom header to use to
// send the cookie.
const { withCredentials, xsrfCookieName, xsrfHeaderName } = config;
if ((withCredentials || !crossDomain) && xsrfCookieName && xsrfHeaderName) {
const xsrfCookie = document?.cookie.match(new RegExp(`(^|;\\s*)(${xsrfCookieName})=([^;]*)`))?.pop() ?? '';
if (xsrfCookie) {
headers[xsrfHeaderName] = xsrfCookie;
}
}
// Examine the body and determine whether or not to serialize it
// and set the content-type in `headers`, if we're able.
const body = extractContentTypeAndMaybeSerializeBody(configuredBody, headers);
// The final request settings.
const _request: Readonly<AjaxRequest> = {
...config,
// Set values we ensured above
url,
headers,
body,
};
let xhr: XMLHttpRequest;
// Create our XHR so we can get started.
xhr = init.createXHR ? init.createXHR() : new XMLHttpRequest();
{
///////////////////////////////////////////////////
// set up the events before open XHR
// https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
// You need to add the event listeners before calling open() on the request.
// Otherwise the progress events will not fire.
///////////////////////////////////////////////////
const { progressSubscriber, includeDownloadProgress = false, includeUploadProgress = false } = init;
/**
* Wires up an event handler that will emit an error when fired. Used
* for timeout and abort events.
* @param type The type of event we're treating as an error
* @param errorFactory A function that creates the type of error to emit.
*/
const addErrorEvent = (type: string, errorFactory: () => any) => {
xhr.addEventListener(type, () => {
const error = errorFactory();
progressSubscriber?.error?.(error);
destination.error(error);
});
};
// If the request times out, handle errors appropriately.
addErrorEvent('timeout', () => new AjaxTimeoutError(xhr, _request));
// If the request aborts (due to a network disconnection or the like), handle
// it as an error.
addErrorEvent('abort', () => new AjaxError('aborted', xhr, _request));
/**
* Creates a response object to emit to the consumer.
* @param direction the direction related to the event. Prefixes the event `type` in the
* `AjaxResponse` object with "upload_" for events related to uploading and "download_"
* for events related to downloading.
* @param event the actual event object.
*/
const createResponse = (direction: AjaxDirection, event: ProgressEvent) =>
new AjaxResponse<T>(event, xhr, _request, `${direction}_${event.type as ProgressEventType}` as const);
/**
* Wires up an event handler that emits a Response object to the consumer, used for
* all events that emit responses, loadstart, progress, and load.
* Note that download load handling is a bit different below, because it has
* more logic it needs to run.
* @param target The target, either the XHR itself or the Upload object.
* @param type The type of event to wire up
* @param direction The "direction", used to prefix the response object that is
* emitted to the consumer. (e.g. "upload_" or "download_")
*/
const addProgressEvent = (target: any, type: string, direction: AjaxDirection) => {
target.addEventListener(type, (event: ProgressEvent) => {
destination.next(createResponse(direction, event));
});
};
if (includeUploadProgress) {
[LOADSTART, PROGRESS, LOAD].forEach((type) => addProgressEvent(xhr.upload, type, UPLOAD));
}
if (progressSubscriber) {
[LOADSTART, PROGRESS].forEach((type) => xhr.upload.addEventListener(type, (e: any) => progressSubscriber?.next?.(e)));
}
if (includeDownloadProgress) {
[LOADSTART, PROGRESS].forEach((type) => addProgressEvent(xhr, type, DOWNLOAD));
}
const emitError = (status?: number) => {
const msg = 'ajax error' + (status ? ' ' + status : '');
destination.error(new AjaxError(msg, xhr, _request));
};
xhr.addEventListener('error', (e) => {
progressSubscriber?.error?.(e);
emitError();
});
xhr.addEventListener(LOAD, (event) => {
const { status } = xhr;
// 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
if (status < 400) {
progressSubscriber?.complete?.();
let response: AjaxResponse<T>;
try {
// This can throw in IE, because we end up needing to do a JSON.parse
// of the response in some cases to produce object we'd expect from
// modern browsers.
response = createResponse(DOWNLOAD, event);
} catch (err) {
destination.error(err);
return;
}
destination.next(response);
destination.complete();
} else {
progressSubscriber?.error?.(event);
emitError(status);
}
});
}
const { user, method, async } = _request;
// open XHR
if (user) {
xhr.open(method, url, async, user, _request.password);
} else {
xhr.open(method, url, async);
}
// timeout, responseType and withCredentials can be set once the XHR is open
if (async) {
xhr.timeout = _request.timeout;
xhr.responseType = _request.responseType;
}
if ('withCredentials' in xhr) {
xhr.withCredentials = _request.withCredentials;
}
// set headers
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
xhr.setRequestHeader(key, headers[key]);
}
}
// finally send the request
if (body) {
xhr.send(body);
} else {
xhr.send();
}
return () => {
if (xhr && xhr.readyState !== 4 /*XHR done*/) {
xhr.abort();
}
};
});
}
/**
* Examines the body to determine if we need to serialize it for them or not.
* If the body is a type that XHR handles natively, we just allow it through,
* otherwise, if the body is something that *we* can serialize for the user,
* we will serialize it, and attempt to set the `content-type` header, if it's
* not already set.
* @param body The body passed in by the user
* @param headers The normalized headers
*/
function extractContentTypeAndMaybeSerializeBody(body: any, headers: Record<string, string>) {
if (
!body ||
typeof body === 'string' ||
isFormData(body) ||
isURLSearchParams(body) ||
isArrayBuffer(body) ||
isFile(body) ||
isBlob(body) ||
isReadableStream(body)
) {
// The XHR instance itself can handle serializing these, and set the content-type for us
// so we don't need to do that. https://xhr.spec.whatwg.org/#the-send()-method
return body;
}
if (isArrayBufferView(body)) {
// This is a typed array (e.g. Float32Array or Uint8Array), or a DataView.
// XHR can handle this one too: https://fetch.spec.whatwg.org/#concept-bodyinit-extract
return body.buffer;
}
if (typeof body === 'object') {
// If we have made it here, this is an object, probably a POJO, and we'll try
// to serialize it for them. If this doesn't work, it will throw, obviously, which
// is okay. The workaround for users would be to manually set the body to their own
// serialized string (accounting for circular references or whatever), then set
// the content-type manually as well.
headers['content-type'] = headers['content-type'] ?? 'application/json;charset=utf-8';
return JSON.stringify(body);
}
// If we've gotten past everything above, this is something we don't quite know how to
// handle. Throw an error. This will be caught and emitted from the observable.
throw new TypeError('Unknown body type');
}
const _toString = Object.prototype.toString;
function toStringCheck(obj: any, name: string): boolean {
return _toString.call(obj) === `[object ${name}]`;
}
function isArrayBuffer(body: any): body is ArrayBuffer {
return toStringCheck(body, 'ArrayBuffer');
}
function isFile(body: any): body is File {
return toStringCheck(body, 'File');
}
function isBlob(body: any): body is Blob {
return toStringCheck(body, 'Blob');
}
function isArrayBufferView(body: any): body is ArrayBufferView {
return typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(body);
}
function isFormData(body: any): body is FormData {
return typeof FormData !== 'undefined' && body instanceof FormData;
}
function isURLSearchParams(body: any): body is URLSearchParams {
return typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams;
}
function isReadableStream(body: any): body is ReadableStream {
return typeof ReadableStream !== 'undefined' && body instanceof ReadableStream;
}

102
node_modules/rxjs/src/internal/ajax/errors.ts generated vendored Normal file
View File

@@ -0,0 +1,102 @@
import { AjaxRequest } from './types';
import { getXHRResponse } from './getXHRResponse';
import { createErrorClass } from '../util/createErrorClass';
/**
* A normalized AJAX error.
*
* @see {@link ajax}
*/
export interface AjaxError extends Error {
/**
* The XHR instance associated with the error.
*/
xhr: XMLHttpRequest;
/**
* The AjaxRequest associated with the error.
*/
request: AjaxRequest;
/**
* The HTTP status code, if the request has completed. If not,
* it is set to `0`.
*/
status: number;
/**
* The responseType (e.g. 'json', 'arraybuffer', or 'xml').
*/
responseType: XMLHttpRequestResponseType;
/**
* The response data.
*/
response: any;
}
export interface AjaxErrorCtor {
/**
* @deprecated Internal implementation detail. Do not construct error instances.
* Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269
*/
new (message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError;
}
/**
* Thrown when an error occurs during an AJAX request.
* This is only exported because it is useful for checking to see if an error
* is an `instanceof AjaxError`. DO NOT create new instances of `AjaxError` with
* the constructor.
*
* @see {@link ajax}
*/
export const AjaxError: AjaxErrorCtor = createErrorClass(
(_super) =>
function AjaxErrorImpl(this: any, message: string, xhr: XMLHttpRequest, request: AjaxRequest) {
this.message = message;
this.name = 'AjaxError';
this.xhr = xhr;
this.request = request;
this.status = xhr.status;
this.responseType = xhr.responseType;
let response: any;
try {
// This can throw in IE, because we have to do a JSON.parse of
// the response in some cases to get the expected response property.
response = getXHRResponse(xhr);
} catch (err) {
response = xhr.responseText;
}
this.response = response;
}
);
export interface AjaxTimeoutError extends AjaxError {}
export interface AjaxTimeoutErrorCtor {
/**
* @deprecated Internal implementation detail. Do not construct error instances.
* Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269
*/
new (xhr: XMLHttpRequest, request: AjaxRequest): AjaxTimeoutError;
}
/**
* Thrown when an AJAX request times out. Not to be confused with {@link TimeoutError}.
*
* This is exported only because it is useful for checking to see if errors are an
* `instanceof AjaxTimeoutError`. DO NOT use the constructor to create an instance of
* this type.
*
* @see {@link ajax}
*/
export const AjaxTimeoutError: AjaxTimeoutErrorCtor = (() => {
function AjaxTimeoutErrorImpl(this: any, xhr: XMLHttpRequest, request: AjaxRequest) {
AjaxError.call(this, 'ajax timeout', xhr, request);
this.name = 'AjaxTimeoutError';
return this;
}
AjaxTimeoutErrorImpl.prototype = Object.create(AjaxError.prototype);
return AjaxTimeoutErrorImpl;
})() as any;

37
node_modules/rxjs/src/internal/ajax/getXHRResponse.ts generated vendored Normal file
View File

@@ -0,0 +1,37 @@
/**
* Gets what should be in the `response` property of the XHR. However,
* since we still support the final versions of IE, we need to do a little
* checking here to make sure that we get the right thing back. Consequently,
* we need to do a JSON.parse() in here, which *could* throw if the response
* isn't valid JSON.
*
* This is used both in creating an AjaxResponse, and in creating certain errors
* that we throw, so we can give the user whatever was in the response property.
*
* @param xhr The XHR to examine the response of
*/
export function getXHRResponse(xhr: XMLHttpRequest) {
switch (xhr.responseType) {
case 'json': {
if ('response' in xhr) {
return xhr.response;
} else {
// IE
const ieXHR: any = xhr;
return JSON.parse(ieXHR.responseText);
}
}
case 'document':
return xhr.responseXML;
case 'text':
default: {
if ('response' in xhr) {
return xhr.response;
} else {
// IE
const ieXHR: any = xhr;
return ieXHR.responseText;
}
}
}
}

235
node_modules/rxjs/src/internal/ajax/types.ts generated vendored Normal file
View File

@@ -0,0 +1,235 @@
import { PartialObserver } from '../types';
/**
* Valid Ajax direction types. Prefixes the event `type` in the
* {@link AjaxResponse} object with "upload_" for events related
* to uploading and "download_" for events related to downloading.
*/
export type AjaxDirection = 'upload' | 'download';
export type ProgressEventType = 'loadstart' | 'progress' | 'load';
export type AjaxResponseType = `${AjaxDirection}_${ProgressEventType}`;
/**
* The object containing values RxJS used to make the HTTP request.
*
* This is provided in {@link AjaxError} instances as the `request`
* object.
*/
export interface AjaxRequest {
/**
* The URL requested.
*/
url: string;
/**
* The body to send over the HTTP request.
*/
body?: any;
/**
* The HTTP method used to make the HTTP request.
*/
method: string;
/**
* Whether or not the request was made asynchronously.
*/
async: boolean;
/**
* The headers sent over the HTTP request.
*/
headers: Readonly<Record<string, any>>;
/**
* The timeout value used for the HTTP request.
* Note: this is only honored if the request is asynchronous (`async` is `true`).
*/
timeout: number;
/**
* The user credentials user name sent with the HTTP request.
*/
user?: string;
/**
* The user credentials password sent with the HTTP request.
*/
password?: string;
/**
* Whether or not the request was a CORS request.
*/
crossDomain: boolean;
/**
* Whether or not a CORS request was sent with credentials.
* If `false`, will also ignore cookies in the CORS response.
*/
withCredentials: boolean;
/**
* The [`responseType`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType) set before sending the request.
*/
responseType: XMLHttpRequestResponseType;
}
/**
* Configuration for the {@link ajax} creation function.
*/
export interface AjaxConfig {
/** The address of the resource to request via HTTP. */
url: string;
/**
* The body of the HTTP request to send.
*
* This is serialized, by default, based off of the value of the `"content-type"` header.
* For example, if the `"content-type"` is `"application/json"`, the body will be serialized
* as JSON. If the `"content-type"` is `"application/x-www-form-urlencoded"`, whatever object passed
* to the body will be serialized as URL, using key-value pairs based off of the keys and values of the object.
* In all other cases, the body will be passed directly.
*/
body?: any;
/**
* Whether or not to send the request asynchronously. Defaults to `true`.
* If set to `false`, this will block the thread until the AJAX request responds.
*/
async?: boolean;
/**
* The HTTP Method to use for the request. Defaults to "GET".
*/
method?: string;
/**
* The HTTP headers to apply.
*
* Note that, by default, RxJS will add the following headers under certain conditions:
*
* 1. If the `"content-type"` header is **NOT** set, and the `body` is [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData),
* a `"content-type"` of `"application/x-www-form-urlencoded; charset=UTF-8"` will be set automatically.
* 2. If the `"x-requested-with"` header is **NOT** set, and the `crossDomain` configuration property is **NOT** explicitly set to `true`,
* (meaning it is not a CORS request), a `"x-requested-with"` header with a value of `"XMLHttpRequest"` will be set automatically.
* This header is generally meaningless, and is set by libraries and frameworks using `XMLHttpRequest` to make HTTP requests.
*/
headers?: Readonly<Record<string, any>>;
/**
* The time to wait before causing the underlying XMLHttpRequest to timeout. This is only honored if the
* `async` configuration setting is unset or set to `true`. Defaults to `0`, which is idiomatic for "never timeout".
*/
timeout?: number;
/** The user credentials user name to send with the HTTP request */
user?: string;
/** The user credentials password to send with the HTTP request*/
password?: string;
/**
* Whether or not to send the HTTP request as a CORS request.
* Defaults to `false`.
*
* @deprecated Will be removed in version 8. Cross domain requests and what creates a cross
* domain request, are dictated by the browser, and a boolean that forces it to be cross domain
* does not make sense. If you need to force cross domain, make sure you're making a secure request,
* then add a custom header to the request or use `withCredentials`. For more information on what
* triggers a cross domain request, see the [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials).
* In particular, the section on [Simple Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests) is useful
* for understanding when CORS will not be used.
*/
crossDomain?: boolean;
/**
* To send user credentials in a CORS request, set to `true`. To exclude user credentials from
* a CORS request, _OR_ when cookies are to be ignored by the CORS response, set to `false`.
*
* Defaults to `false`.
*/
withCredentials?: boolean;
/**
* The name of your site's XSRF cookie.
*/
xsrfCookieName?: string;
/**
* The name of a custom header that you can use to send your XSRF cookie.
*/
xsrfHeaderName?: string;
/**
* Can be set to change the response type.
* Valid values are `"arraybuffer"`, `"blob"`, `"document"`, `"json"`, and `"text"`.
* Note that the type of `"document"` (such as an XML document) is ignored if the global context is
* not `Window`.
*
* Defaults to `"json"`.
*/
responseType?: XMLHttpRequestResponseType;
/**
* An optional factory used to create the XMLHttpRequest object used to make the AJAX request.
* This is useful in environments that lack `XMLHttpRequest`, or in situations where you
* wish to override the default `XMLHttpRequest` for some reason.
*
* If not provided, the `XMLHttpRequest` in global scope will be used.
*
* NOTE: This AJAX implementation relies on the built-in serialization and setting
* of Content-Type headers that is provided by standards-compliant XMLHttpRequest implementations,
* be sure any implementation you use meets that standard.
*/
createXHR?: () => XMLHttpRequest;
/**
* An observer for watching the upload progress of an HTTP request. Will
* emit progress events, and completes on the final upload load event, will error for
* any XHR error or timeout.
*
* This will **not** error for errored status codes. Rather, it will always _complete_ when
* the HTTP response comes back.
*
* @deprecated If you're looking for progress events, use {@link includeDownloadProgress} and
* {@link includeUploadProgress} instead. Will be removed in v8.
*/
progressSubscriber?: PartialObserver<ProgressEvent>;
/**
* If `true`, will emit all download progress and load complete events as {@link AjaxResponse}
* from the observable. The final download event will also be emitted as a {@link AjaxResponse}.
*
* If both this and {@link includeUploadProgress} are `false`, then only the {@link AjaxResponse} will
* be emitted from the resulting observable.
*/
includeDownloadProgress?: boolean;
/**
* If `true`, will emit all upload progress and load complete events as {@link AjaxResponse}
* from the observable. The final download event will also be emitted as a {@link AjaxResponse}.
*
* If both this and {@link includeDownloadProgress} are `false`, then only the {@link AjaxResponse} will
* be emitted from the resulting observable.
*/
includeUploadProgress?: boolean;
/**
* Query string parameters to add to the URL in the request.
* <em>This will require a polyfill for `URL` and `URLSearchParams` in Internet Explorer!</em>
*
* Accepts either a query string, a `URLSearchParams` object, a dictionary of key/value pairs, or an
* array of key/value entry tuples. (Essentially, it takes anything that `new URLSearchParams` would normally take).
*
* If, for some reason you have a query string in the `url` argument, this will append to the query string in the url,
* but it will also overwrite the value of any keys that are an exact match. In other words, a url of `/test?a=1&b=2`,
* with queryParams of `{ b: 5, c: 6 }` will result in a url of roughly `/test?a=1&b=5&c=6`.
*/
queryParams?:
| string
| URLSearchParams
| Record<string, string | number | boolean | string[] | number[] | boolean[]>
| [string, string | number | boolean | string[] | number[] | boolean[]][];
}

84
node_modules/rxjs/src/internal/config.ts generated vendored Normal file
View File

@@ -0,0 +1,84 @@
import { Subscriber } from './Subscriber';
import { ObservableNotification } from './types';
/**
* The {@link GlobalConfig} object for RxJS. It is used to configure things
* like how to react on unhandled errors.
*/
export const config: GlobalConfig = {
onUnhandledError: null,
onStoppedNotification: null,
Promise: undefined,
useDeprecatedSynchronousErrorHandling: false,
useDeprecatedNextContext: false,
};
/**
* The global configuration object for RxJS, used to configure things
* like how to react on unhandled errors. Accessible via {@link config}
* object.
*/
export interface GlobalConfig {
/**
* A registration point for unhandled errors from RxJS. These are errors that
* cannot were not handled by consuming code in the usual subscription path. For
* example, if you have this configured, and you subscribe to an observable without
* providing an error handler, errors from that subscription will end up here. This
* will _always_ be called asynchronously on another job in the runtime. This is because
* we do not want errors thrown in this user-configured handler to interfere with the
* behavior of the library.
*/
onUnhandledError: ((err: any) => void) | null;
/**
* A registration point for notifications that cannot be sent to subscribers because they
* have completed, errored or have been explicitly unsubscribed. By default, next, complete
* and error notifications sent to stopped subscribers are noops. However, sometimes callers
* might want a different behavior. For example, with sources that attempt to report errors
* to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.
* This will _always_ be called asynchronously on another job in the runtime. This is because
* we do not want errors thrown in this user-configured handler to interfere with the
* behavior of the library.
*/
onStoppedNotification: ((notification: ObservableNotification<any>, subscriber: Subscriber<any>) => void) | null;
/**
* The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}
* methods.
*
* @deprecated As of version 8, RxJS will no longer support this sort of injection of a
* Promise constructor. If you need a Promise implementation other than native promises,
* please polyfill/patch Promise as you see appropriate. Will be removed in v8.
*/
Promise?: PromiseConstructorLike;
/**
* If true, turns on synchronous error rethrowing, which is a deprecated behavior
* in v6 and higher. This behavior enables bad patterns like wrapping a subscribe
* call in a try/catch block. It also enables producer interference, a nasty bug
* where a multicast can be broken for all observers by a downstream consumer with
* an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME
* FOR MIGRATION REASONS.
*
* @deprecated As of version 8, RxJS will no longer support synchronous throwing
* of unhandled errors. All errors will be thrown on a separate call stack to prevent bad
* behaviors described above. Will be removed in v8.
*/
useDeprecatedSynchronousErrorHandling: boolean;
/**
* If true, enables an as-of-yet undocumented feature from v5: The ability to access
* `unsubscribe()` via `this` context in `next` functions created in observers passed
* to `subscribe`.
*
* This is being removed because the performance was severely problematic, and it could also cause
* issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have
* their `this` context overwritten.
*
* @deprecated As of version 8, RxJS will no longer support altering the
* context of next functions provided as part of an observer to Subscribe. Instead,
* you will have access to a subscription or a signal or token that will allow you to do things like
* unsubscribe and test closed status. Will be removed in v8.
*/
useDeprecatedNextContext: boolean;
}

75
node_modules/rxjs/src/internal/firstValueFrom.ts generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import { Observable } from './Observable';
import { EmptyError } from './util/EmptyError';
import { SafeSubscriber } from './Subscriber';
export interface FirstValueFromConfig<T> {
defaultValue: T;
}
export function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;
export function firstValueFrom<T>(source: Observable<T>): Promise<T>;
/**
* Converts an observable to a promise by subscribing to the observable,
* and returning a promise that will resolve as soon as the first value
* arrives from the observable. The subscription will then be closed.
*
* If the observable stream completes before any values were emitted, the
* returned promise will reject with {@link EmptyError} or will resolve
* with the default value if a default was specified.
*
* If the observable stream emits an error, the returned promise will reject
* with that error.
*
* **WARNING**: Only use this with observables you *know* will emit at least one value,
* *OR* complete. If the source observable does not emit one value or complete, you will
* end up with a promise that is hung up, and potentially all of the state of an
* async function hanging out in memory. To avoid this situation, look into adding
* something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}
* amongst others.
*
* ## Example
*
* Wait for the first value from a stream and emit it from a promise in
* an async function
*
* ```ts
* import { interval, firstValueFrom } from 'rxjs';
*
* async function execute() {
* const source$ = interval(2000);
* const firstNumber = await firstValueFrom(source$);
* console.log(`The first number is ${ firstNumber }`);
* }
*
* execute();
*
* // Expected output:
* // 'The first number is 0'
* ```
*
* @see {@link lastValueFrom}
*
* @param source the observable to convert to a promise
* @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
*/
export function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {
const hasConfig = typeof config === 'object';
return new Promise<T | D>((resolve, reject) => {
const subscriber = new SafeSubscriber<T>({
next: (value) => {
resolve(value);
subscriber.unsubscribe();
},
error: reject,
complete: () => {
if (hasConfig) {
resolve(config!.defaultValue);
} else {
reject(new EmptyError());
}
},
});
source.subscribe(subscriber);
});
}

76
node_modules/rxjs/src/internal/lastValueFrom.ts generated vendored Normal file
View File

@@ -0,0 +1,76 @@
import { Observable } from './Observable';
import { EmptyError } from './util/EmptyError';
export interface LastValueFromConfig<T> {
defaultValue: T;
}
export function lastValueFrom<T, D>(source: Observable<T>, config: LastValueFromConfig<D>): Promise<T | D>;
export function lastValueFrom<T>(source: Observable<T>): Promise<T>;
/**
* Converts an observable to a promise by subscribing to the observable,
* waiting for it to complete, and resolving the returned promise with the
* last value from the observed stream.
*
* If the observable stream completes before any values were emitted, the
* returned promise will reject with {@link EmptyError} or will resolve
* with the default value if a default was specified.
*
* If the observable stream emits an error, the returned promise will reject
* with that error.
*
* **WARNING**: Only use this with observables you *know* will complete. If the source
* observable does not complete, you will end up with a promise that is hung up, and
* potentially all of the state of an async function hanging out in memory. To avoid
* this situation, look into adding something like {@link timeout}, {@link take},
* {@link takeWhile}, or {@link takeUntil} amongst others.
*
* ## Example
*
* Wait for the last value from a stream and emit it from a promise in
* an async function
*
* ```ts
* import { interval, take, lastValueFrom } from 'rxjs';
*
* async function execute() {
* const source$ = interval(2000).pipe(take(10));
* const finalNumber = await lastValueFrom(source$);
* console.log(`The final number is ${ finalNumber }`);
* }
*
* execute();
*
* // Expected output:
* // 'The final number is 9'
* ```
*
* @see {@link firstValueFrom}
*
* @param source the observable to convert to a promise
* @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value
*/
export function lastValueFrom<T, D>(source: Observable<T>, config?: LastValueFromConfig<D>): Promise<T | D> {
const hasConfig = typeof config === 'object';
return new Promise<T | D>((resolve, reject) => {
let _hasValue = false;
let _value: T;
source.subscribe({
next: (value) => {
_value = value;
_hasValue = true;
},
error: reject,
complete: () => {
if (_hasValue) {
resolve(_value);
} else if (hasConfig) {
resolve(config!.defaultValue);
} else {
reject(new EmptyError());
}
},
});
});
}

View File

@@ -0,0 +1,104 @@
import { Subject } from '../Subject';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription } from '../Subscription';
import { refCount as higherOrderRefCount } from '../operators/refCount';
import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
import { hasLift } from '../util/lift';
/**
* @class ConnectableObservable<T>
* @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.
* If you are using the `refCount` method of `ConnectableObservable`, use the {@link share} operator
* instead.
* Details: https://rxjs.dev/deprecations/multicasting
*/
export class ConnectableObservable<T> extends Observable<T> {
protected _subject: Subject<T> | null = null;
protected _refCount: number = 0;
protected _connection: Subscription | null = null;
/**
* @param source The source observable
* @param subjectFactory The factory that creates the subject used internally.
* @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.
* `new ConnectableObservable(source, factory)` is equivalent to
* `connectable(source, { connector: factory })`.
* When the `refCount()` method is needed, the {@link share} operator should be used instead:
* `new ConnectableObservable(source, factory).refCount()` is equivalent to
* `source.pipe(share({ connector: factory }))`.
* Details: https://rxjs.dev/deprecations/multicasting
*/
constructor(public source: Observable<T>, protected subjectFactory: () => Subject<T>) {
super();
// If we have lift, monkey patch that here. This is done so custom observable
// types will compose through multicast. Otherwise the resulting observable would
// simply be an instance of `ConnectableObservable`.
if (hasLift(source)) {
this.lift = source.lift;
}
}
/** @internal */
protected _subscribe(subscriber: Subscriber<T>) {
return this.getSubject().subscribe(subscriber);
}
protected getSubject(): Subject<T> {
const subject = this._subject;
if (!subject || subject.isStopped) {
this._subject = this.subjectFactory();
}
return this._subject!;
}
protected _teardown() {
this._refCount = 0;
const { _connection } = this;
this._subject = this._connection = null;
_connection?.unsubscribe();
}
/**
* @deprecated {@link ConnectableObservable} will be removed in v8. Use {@link connectable} instead.
* Details: https://rxjs.dev/deprecations/multicasting
*/
connect(): Subscription {
let connection = this._connection;
if (!connection) {
connection = this._connection = new Subscription();
const subject = this.getSubject();
connection.add(
this.source.subscribe(
createOperatorSubscriber(
subject as any,
undefined,
() => {
this._teardown();
subject.complete();
},
(err) => {
this._teardown();
subject.error(err);
},
() => this._teardown()
)
)
);
if (connection.closed) {
this._connection = null;
connection = Subscription.EMPTY;
}
}
return connection;
}
/**
* @deprecated {@link ConnectableObservable} will be removed in v8. Use the {@link share} operator instead.
* Details: https://rxjs.dev/deprecations/multicasting
*/
refCount(): Observable<T> {
return higherOrderRefCount()(this) as Observable<T>;
}
}

View File

@@ -0,0 +1,149 @@
/* @prettier */
import { SchedulerLike } from '../types';
import { Observable } from '../Observable';
import { bindCallbackInternals } from './bindCallbackInternals';
export function bindCallback(
callbackFunc: (...args: any[]) => void,
resultSelector: (...args: any[]) => any,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<any>;
// 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
export function bindCallback<A extends readonly unknown[], R extends readonly unknown[]>(
callbackFunc: (...args: [...A, (...res: R) => void]) => void,
schedulerLike?: SchedulerLike
): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;
/**
* Converts a callback API to a function that returns an Observable.
*
* <span class="informal">Give it a function `f` of type `f(x, callback)` and
* it will return a function `g` that when called as `g(x)` will output an
* Observable.</span>
*
* `bindCallback` is not an operator because its input and output are not
* Observables. The input is a function `func` with some parameters. The
* last parameter must be a callback function that `func` calls when it is
* done.
*
* The output of `bindCallback` is a function that takes the same parameters
* as `func`, except the last one (the callback). When the output function
* is called with arguments it will return an Observable. If function `func`
* calls its callback with one argument, the Observable will emit that value.
* If on the other hand the callback is called with multiple values the resulting
* Observable will emit an array with said values as arguments.
*
* It is **very important** to remember that input function `func` is not called
* when the output function is, but rather when the Observable returned by the output
* function is subscribed. This means if `func` makes an AJAX request, that request
* will be made every time someone subscribes to the resulting Observable, but not before.
*
* The last optional parameter - `scheduler` - can be used to control when the call
* to `func` happens after someone subscribes to Observable, as well as when results
* passed to callback will be emitted. By default, the subscription to an Observable calls `func`
* synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`,
* just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler
* and call `subscribe` on the output Observable, all function calls that are currently executing
* will end before `func` is invoked.
*
* By default, results passed to the callback are emitted immediately after `func` invokes the callback.
* In particular, if the callback is called synchronously, then the subscription of the resulting Observable
* will call the `next` function synchronously as well. If you want to defer that call,
* you may use {@link asyncScheduler} just as before. This means that by using `Scheduler.async` you can
* ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.
*
* Note that the Observable created by the output function will always emit a single value
* and then complete immediately. If `func` calls the callback multiple times, values from subsequent
* calls will not appear in the stream. If you need to listen for multiple calls,
* you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.
*
* If `func` depends on some context (`this` property) and is not already bound, the context of `func`
* will be the context that the output function has at call time. In particular, if `func`
* is called as a method of some object and if `func` is not already bound, in order to preserve the context
* it is recommended that the context of the output function is set to that object as well.
*
* If the input function calls its callback in the "node style" (i.e. first argument to callback is
* optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}
* provides convenient error handling and probably is a better choice.
* `bindCallback` will treat such functions the same as any other and error parameters
* (whether passed or not) will always be interpreted as regular callback argument.
*
* ## Examples
*
* Convert jQuery's getJSON to an Observable API
*
* ```ts
* import { bindCallback } from 'rxjs';
* import * as jQuery from 'jquery';
*
* // Suppose we have jQuery.getJSON('/my/url', callback)
* const getJSONAsObservable = bindCallback(jQuery.getJSON);
* const result = getJSONAsObservable('/my/url');
* result.subscribe(x => console.log(x), e => console.error(e));
* ```
*
* Receive an array of arguments passed to a callback
*
* ```ts
* import { bindCallback } from 'rxjs';
*
* const someFunction = (n, s, cb) => {
* cb(n, s, { someProperty: 'someValue' });
* };
*
* const boundSomeFunction = bindCallback(someFunction);
* boundSomeFunction(5, 'some string').subscribe((values) => {
* console.log(values); // [5, 'some string', {someProperty: 'someValue'}]
* });
* ```
*
* Compare behaviour with and without `asyncScheduler`
*
* ```ts
* import { bindCallback, asyncScheduler } from 'rxjs';
*
* function iCallMyCallbackSynchronously(cb) {
* cb();
* }
*
* const boundSyncFn = bindCallback(iCallMyCallbackSynchronously);
* const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, asyncScheduler);
*
* boundSyncFn().subscribe(() => console.log('I was sync!'));
* boundAsyncFn().subscribe(() => console.log('I was async!'));
* console.log('This happened...');
*
* // Logs:
* // I was sync!
* // This happened...
* // I was async!
* ```
*
* Use `bindCallback` on an object method
*
* ```ts
* import { bindCallback } from 'rxjs';
*
* const boundMethod = bindCallback(someObject.methodWithCallback);
* boundMethod
* .call(someObject) // make sure methodWithCallback has access to someObject
* .subscribe(subscriber);
* ```
*
* @see {@link bindNodeCallback}
* @see {@link from}
*
* @param callbackFunc A function with a callback as the last parameter.
* @param resultSelector A mapping function used to transform callback events.
* @param scheduler The scheduler on which to schedule the callbacks.
* @return A function which returns the Observable that delivers the same
* values the callback would deliver.
*/
export function bindCallback(
callbackFunc: (...args: [...any[], (...res: any) => void]) => void,
resultSelector?: ((...args: any[]) => any) | SchedulerLike,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<unknown> {
return bindCallbackInternals(false, callbackFunc, resultSelector, scheduler);
}

View File

@@ -0,0 +1,119 @@
import { SchedulerLike } from '../types';
import { isScheduler } from '../util/isScheduler';
import { Observable } from '../Observable';
import { subscribeOn } from '../operators/subscribeOn';
import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
import { observeOn } from '../operators/observeOn';
import { AsyncSubject } from '../AsyncSubject';
export function bindCallbackInternals(
isNodeStyle: boolean,
callbackFunc: any,
resultSelector?: any,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<unknown> {
if (resultSelector) {
if (isScheduler(resultSelector)) {
scheduler = resultSelector;
} else {
// The user provided a result selector.
return function (this: any, ...args: any[]) {
return (bindCallbackInternals(isNodeStyle, callbackFunc, scheduler) as any)
.apply(this, args)
.pipe(mapOneOrManyArgs(resultSelector as any));
};
}
}
// If a scheduler was passed, use our `subscribeOn` and `observeOn` operators
// to compose that behavior for the user.
if (scheduler) {
return function (this: any, ...args: any[]) {
return (bindCallbackInternals(isNodeStyle, callbackFunc) as any)
.apply(this, args)
.pipe(subscribeOn(scheduler!), observeOn(scheduler!));
};
}
return function (this: any, ...args: any[]): Observable<any> {
// We're using AsyncSubject, because it emits when it completes,
// and it will play the value to all late-arriving subscribers.
const subject = new AsyncSubject<any>();
// If this is true, then we haven't called our function yet.
let uninitialized = true;
return new Observable((subscriber) => {
// Add our subscriber to the subject.
const subs = subject.subscribe(subscriber);
if (uninitialized) {
uninitialized = false;
// We're going to execute the bound function
// This bit is to signal that we are hitting the callback asynchronously.
// Because we don't have any anti-"Zalgo" guarantees with whatever
// function we are handed, we use this bit to figure out whether or not
// we are getting hit in a callback synchronously during our call.
let isAsync = false;
// This is used to signal that the callback completed synchronously.
let isComplete = false;
// Call our function that has a callback. If at any time during this
// call, an error is thrown, it will be caught by the Observable
// subscription process and sent to the consumer.
callbackFunc.apply(
// Pass the appropriate `this` context.
this,
[
// Pass the arguments.
...args,
// And our callback handler.
(...results: any[]) => {
if (isNodeStyle) {
// If this is a node callback, shift the first value off of the
// results and check it, as it is the error argument. By shifting,
// we leave only the argument(s) we want to pass to the consumer.
const err = results.shift();
if (err != null) {
subject.error(err);
// If we've errored, we can stop processing this function
// as there's nothing else to do. Just return to escape.
return;
}
}
// If we have one argument, notify the consumer
// of it as a single value, otherwise, if there's more than one, pass
// them as an array. Note that if there are no arguments, `undefined`
// will be emitted.
subject.next(1 < results.length ? results : results[0]);
// Flip this flag, so we know we can complete it in the synchronous
// case below.
isComplete = true;
// If we're not asynchronous, we need to defer the `complete` call
// until after the call to the function is over. This is because an
// error could be thrown in the function after it calls our callback,
// and if that is the case, if we complete here, we are unable to notify
// the consumer than an error occurred.
if (isAsync) {
subject.complete();
}
},
]
);
// If we flipped `isComplete` during the call, we resolved synchronously,
// notify complete, because we skipped it in the callback to wait
// to make sure there were no errors during the call.
if (isComplete) {
subject.complete();
}
// We're no longer synchronous. If the callback is called at this point
// we can notify complete on the spot.
isAsync = true;
}
// Return the subscription from adding our subscriber to the subject.
return subs;
});
};
}

View File

@@ -0,0 +1,131 @@
/* @prettier */
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { bindCallbackInternals } from './bindCallbackInternals';
export function bindNodeCallback(
callbackFunc: (...args: any[]) => void,
resultSelector: (...args: any[]) => any,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<any>;
// 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
export function bindNodeCallback<A extends readonly unknown[], R extends readonly unknown[]>(
callbackFunc: (...args: [...A, (err: any, ...res: R) => void]) => void,
schedulerLike?: SchedulerLike
): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;
/**
* Converts a Node.js-style callback API to a function that returns an
* Observable.
*
* <span class="informal">It's just like {@link bindCallback}, but the
* callback is expected to be of type `callback(error, result)`.</span>
*
* `bindNodeCallback` is not an operator because its input and output are not
* Observables. The input is a function `func` with some parameters, but the
* last parameter must be a callback function that `func` calls when it is
* done. The callback function is expected to follow Node.js conventions,
* where the first argument to the callback is an error object, signaling
* whether call was successful. If that object is passed to callback, it means
* something went wrong.
*
* The output of `bindNodeCallback` is a function that takes the same
* parameters as `func`, except the last one (the callback). When the output
* function is called with arguments, it will return an Observable.
* If `func` calls its callback with error parameter present, Observable will
* error with that value as well. If error parameter is not passed, Observable will emit
* second parameter. If there are more parameters (third and so on),
* Observable will emit an array with all arguments, except first error argument.
*
* Note that `func` will not be called at the same time output function is,
* but rather whenever resulting Observable is subscribed. By default call to
* `func` will happen synchronously after subscription, but that can be changed
* with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}
* can also control when values from callback will be emitted by Observable.
* To find out more, check out documentation for {@link bindCallback}, where
* {@link SchedulerLike} works exactly the same.
*
* As in {@link bindCallback}, context (`this` property) of input function will be set to context
* of returned function, when it is called.
*
* After Observable emits value, it will complete immediately. This means
* even if `func` calls callback again, values from second and consecutive
* calls will never appear on the stream. If you need to handle functions
* that call callbacks multiple times, check out {@link fromEvent} or
* {@link fromEventPattern} instead.
*
* Note that `bindNodeCallback` can be used in non-Node.js environments as well.
* "Node.js-style" callbacks are just a convention, so if you write for
* browsers or any other environment and API you use implements that callback style,
* `bindNodeCallback` can be safely used on that API functions as well.
*
* Remember that Error object passed to callback does not have to be an instance
* of JavaScript built-in `Error` object. In fact, it does not even have to an object.
* Error parameter of callback function is interpreted as "present", when value
* of that parameter is truthy. It could be, for example, non-zero number, non-empty
* string or boolean `true`. In all of these cases resulting Observable would error
* with that value. This means usually regular style callbacks will fail very often when
* `bindNodeCallback` is used. If your Observable errors much more often then you
* would expect, check if callback really is called in Node.js-style and, if not,
* switch to {@link bindCallback} instead.
*
* Note that even if error parameter is technically present in callback, but its value
* is falsy, it still won't appear in array emitted by Observable.
*
* ## Examples
*
* Read a file from the filesystem and get the data as an Observable
*
* ```ts
* import * as fs from 'fs';
* const readFileAsObservable = bindNodeCallback(fs.readFile);
* const result = readFileAsObservable('./roadNames.txt', 'utf8');
* result.subscribe(x => console.log(x), e => console.error(e));
* ```
*
* Use on function calling callback with multiple arguments
*
* ```ts
* someFunction((err, a, b) => {
* console.log(err); // null
* console.log(a); // 5
* console.log(b); // "some string"
* });
* const boundSomeFunction = bindNodeCallback(someFunction);
* boundSomeFunction()
* .subscribe(value => {
* console.log(value); // [5, "some string"]
* });
* ```
*
* Use on function calling callback in regular style
*
* ```ts
* someFunction(a => {
* console.log(a); // 5
* });
* const boundSomeFunction = bindNodeCallback(someFunction);
* boundSomeFunction()
* .subscribe(
* value => {} // never gets called
* err => console.log(err) // 5
* );
* ```
*
* @see {@link bindCallback}
* @see {@link from}
*
* @param callbackFunc Function with a Node.js-style callback as the last parameter.
* @param resultSelector A mapping function used to transform callback events.
* @param scheduler The scheduler on which to schedule the callbacks.
* @return A function which returns the Observable that delivers the same values the
* Node.js callback would deliver.
*/
export function bindNodeCallback(
callbackFunc: (...args: [...any[], (err: any, ...res: any) => void]) => void,
resultSelector?: ((...args: any[]) => any) | SchedulerLike,
scheduler?: SchedulerLike
): (...args: any[]) => Observable<any> {
return bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);
}

View File

@@ -0,0 +1,300 @@
import { Observable } from '../Observable';
import { ObservableInput, SchedulerLike, ObservedValueOf, ObservableInputTuple } from '../types';
import { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';
import { Subscriber } from '../Subscriber';
import { from } from './from';
import { identity } from '../util/identity';
import { Subscription } from '../Subscription';
import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
import { popResultSelector, popScheduler } from '../util/args';
import { createObject } from '../util/createObject';
import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
import { AnyCatcher } from '../AnyCatcher';
import { executeSchedule } from '../util/executeSchedule';
// combineLatest(any)
// We put this first because we need to catch cases where the user has supplied
// _exactly `any`_ as the argument. Since `any` literally matches _anything_,
// we don't want it to randomly hit one of the other type signatures below,
// as we have no idea at build-time what type we should be returning when given an any.
/**
* You have passed `any` here, we can't figure out if it is
* an array or an object, so you're getting `unknown`. Use better types.
* @param arg Something typed as `any`
*/
export function combineLatest<T extends AnyCatcher>(arg: T): Observable<unknown>;
// combineLatest([a, b, c])
export function combineLatest(sources: []): Observable<never>;
export function combineLatest<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function combineLatest<A extends readonly unknown[], R>(
sources: readonly [...ObservableInputTuple<A>],
resultSelector: (...values: A) => R,
scheduler: SchedulerLike
): Observable<R>;
export function combineLatest<A extends readonly unknown[], R>(
sources: readonly [...ObservableInputTuple<A>],
resultSelector: (...values: A) => R
): Observable<R>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function combineLatest<A extends readonly unknown[]>(
sources: readonly [...ObservableInputTuple<A>],
scheduler: SchedulerLike
): Observable<A>;
// combineLatest(a, b, c)
/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
export function combineLatest<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function combineLatest<A extends readonly unknown[], R>(
...sourcesAndResultSelectorAndScheduler: [...ObservableInputTuple<A>, (...values: A) => R, SchedulerLike]
): Observable<R>;
/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
export function combineLatest<A extends readonly unknown[], R>(
...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]
): Observable<R>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function combineLatest<A extends readonly unknown[]>(
...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]
): Observable<A>;
// combineLatest({a, b, c})
export function combineLatest(sourcesObject: { [K in any]: never }): Observable<never>;
export function combineLatest<T extends Record<string, ObservableInput<any>>>(
sourcesObject: T
): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;
/**
* Combines multiple Observables to create an Observable whose values are
* calculated from the latest values of each of its input Observables.
*
* <span class="informal">Whenever any input Observable emits a value, it
* computes a formula using the latest values from all the inputs, then emits
* the output of that formula.</span>
*
* ![](combineLatest.png)
*
* `combineLatest` combines the values from all the Observables passed in the
* observables array. This is done by subscribing to each Observable in order and,
* whenever any Observable emits, collecting an array of the most recent
* values from each Observable. So if you pass `n` Observables to this operator,
* the returned Observable will always emit an array of `n` values, in an order
* corresponding to the order of the passed Observables (the value from the first Observable
* will be at index 0 of the array and so on).
*
* Static version of `combineLatest` accepts an array of Observables. Note that an array of
* Observables is a good choice, if you don't know beforehand how many Observables
* you will combine. Passing an empty array will result in an Observable that
* completes immediately.
*
* To ensure the output array always has the same length, `combineLatest` will
* actually wait for all input Observables to emit at least once,
* before it starts emitting results. This means if some Observable emits
* values before other Observables started emitting, all these values but the last
* will be lost. On the other hand, if some Observable does not emit a value but
* completes, resulting Observable will complete at the same moment without
* emitting anything, since it will now be impossible to include a value from the
* completed Observable in the resulting array. Also, if some input Observable does
* not emit any value and never completes, `combineLatest` will also never emit
* and never complete, since, again, it will wait for all streams to emit some
* value.
*
* If at least one Observable was passed to `combineLatest` and all passed Observables
* emitted something, the resulting Observable will complete when all combined
* streams complete. So even if some Observable completes, the result of
* `combineLatest` will still emit values when other Observables do. In case
* of a completed Observable, its value from now on will always be the last
* emitted value. On the other hand, if any Observable errors, `combineLatest`
* will error immediately as well, and all other Observables will be unsubscribed.
*
* ## Examples
*
* Combine two timer Observables
*
* ```ts
* import { timer, combineLatest } from 'rxjs';
*
* const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now
* const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now
* const combinedTimers = combineLatest([firstTimer, secondTimer]);
* combinedTimers.subscribe(value => console.log(value));
* // Logs
* // [0, 0] after 0.5s
* // [1, 0] after 1s
* // [1, 1] after 1.5s
* // [2, 1] after 2s
* ```
*
* Combine a dictionary of Observables
*
* ```ts
* import { of, delay, startWith, combineLatest } from 'rxjs';
*
* const observables = {
* a: of(1).pipe(delay(1000), startWith(0)),
* b: of(5).pipe(delay(5000), startWith(0)),
* c: of(10).pipe(delay(10000), startWith(0))
* };
* const combined = combineLatest(observables);
* combined.subscribe(value => console.log(value));
* // Logs
* // { a: 0, b: 0, c: 0 } immediately
* // { a: 1, b: 0, c: 0 } after 1s
* // { a: 1, b: 5, c: 0 } after 5s
* // { a: 1, b: 5, c: 10 } after 10s
* ```
*
* Combine an array of Observables
*
* ```ts
* import { of, delay, startWith, combineLatest } from 'rxjs';
*
* const observables = [1, 5, 10].map(
* n => of(n).pipe(
* delay(n * 1000), // emit 0 and then emit n after n seconds
* startWith(0)
* )
* );
* const combined = combineLatest(observables);
* combined.subscribe(value => console.log(value));
* // Logs
* // [0, 0, 0] immediately
* // [1, 0, 0] after 1s
* // [1, 5, 0] after 5s
* // [1, 5, 10] after 10s
* ```
*
* Use map operator to dynamically calculate the Body-Mass Index
*
* ```ts
* import { of, combineLatest, map } from 'rxjs';
*
* const weight = of(70, 72, 76, 79, 75);
* const height = of(1.76, 1.77, 1.78);
* const bmi = combineLatest([weight, height]).pipe(
* map(([w, h]) => w / (h * h)),
* );
* bmi.subscribe(x => console.log('BMI is ' + x));
*
* // With output to console:
* // BMI is 24.212293388429753
* // BMI is 23.93948099205209
* // BMI is 23.671253629592222
* ```
*
* @see {@link combineLatestAll}
* @see {@link merge}
* @see {@link withLatestFrom}
*
* @param args Any number of `ObservableInput`s provided either as an array or as an object
* to combine with each other. If the last parameter is the function, it will be used to project the
* values from the combined latest values into a new value on the output Observable.
* @return An Observable of projected values from the most recent values from each `ObservableInput`,
* or an array of the most recent values from each `ObservableInput`.
*/
export function combineLatest<O extends ObservableInput<any>, R>(...args: any[]): Observable<R> | Observable<ObservedValueOf<O>[]> {
const scheduler = popScheduler(args);
const resultSelector = popResultSelector(args);
const { args: observables, keys } = argsArgArrayOrObject(args);
if (observables.length === 0) {
// If no observables are passed, or someone has passed an empty array
// of observables, or even an empty object POJO, we need to just
// complete (EMPTY), but we have to honor the scheduler provided if any.
return from([], scheduler as any);
}
const result = new Observable<ObservedValueOf<O>[]>(
combineLatestInit(
observables as ObservableInput<ObservedValueOf<O>>[],
scheduler,
keys
? // A handler for scrubbing the array of args into a dictionary.
(values) => createObject(keys, values)
: // A passthrough to just return the array
identity
)
);
return resultSelector ? (result.pipe(mapOneOrManyArgs(resultSelector)) as Observable<R>) : result;
}
export function combineLatestInit(
observables: ObservableInput<any>[],
scheduler?: SchedulerLike,
valueTransform: (values: any[]) => any = identity
) {
return (subscriber: Subscriber<any>) => {
// The outer subscription. We're capturing this in a function
// because we may have to schedule it.
maybeSchedule(
scheduler,
() => {
const { length } = observables;
// A store for the values each observable has emitted so far. We match observable to value on index.
const values = new Array(length);
// The number of currently active subscriptions, as they complete, we decrement this number to see if
// we are all done combining values, so we can complete the result.
let active = length;
// The number of inner sources that still haven't emitted the first value
// We need to track this because all sources need to emit one value in order
// to start emitting values.
let remainingFirstValues = length;
// The loop to kick off subscription. We're keying everything on index `i` to relate the observables passed
// in to the slot in the output array or the key in the array of keys in the output dictionary.
for (let i = 0; i < length; i++) {
maybeSchedule(
scheduler,
() => {
const source = from(observables[i], scheduler as any);
let hasFirstValue = false;
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
// When we get a value, record it in our set of values.
values[i] = value;
if (!hasFirstValue) {
// If this is our first value, record that.
hasFirstValue = true;
remainingFirstValues--;
}
if (!remainingFirstValues) {
// We're not waiting for any more
// first values, so we can emit!
subscriber.next(valueTransform(values.slice()));
}
},
() => {
if (!--active) {
// We only complete the result if we have no more active
// inner observables.
subscriber.complete();
}
}
)
);
},
subscriber
);
}
},
subscriber
);
};
}
/**
* A small utility to handle the couple of locations where we want to schedule if a scheduler was provided,
* but we don't if there was no scheduler.
*/
function maybeSchedule(scheduler: SchedulerLike | undefined, execute: () => void, subscription: Subscription) {
if (scheduler) {
executeSchedule(subscription, scheduler, execute);
} else {
execute();
}
}

115
node_modules/rxjs/src/internal/observable/concat.ts generated vendored Normal file
View File

@@ -0,0 +1,115 @@
import { Observable } from '../Observable';
import { ObservableInputTuple, SchedulerLike } from '../types';
import { concatAll } from '../operators/concatAll';
import { popScheduler } from '../util/args';
import { from } from './from';
export function concat<T extends readonly unknown[]>(...inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;
export function concat<T extends readonly unknown[]>(
...inputsAndScheduler: [...ObservableInputTuple<T>, SchedulerLike]
): Observable<T[number]>;
/**
* Creates an output Observable which sequentially emits all values from the first given
* Observable and then moves on to the next.
*
* <span class="informal">Concatenates multiple Observables together by
* sequentially emitting their values, one Observable after the other.</span>
*
* ![](concat.png)
*
* `concat` joins multiple Observables together, by subscribing to them one at a time and
* merging their results into the output Observable. You can pass either an array of
* Observables, or put them directly as arguments. Passing an empty array will result
* in Observable that completes immediately.
*
* `concat` will subscribe to first input Observable and emit all its values, without
* changing or affecting them in any way. When that Observable completes, it will
* subscribe to then next Observable passed and, again, emit its values. This will be
* repeated, until the operator runs out of Observables. When last input Observable completes,
* `concat` will complete as well. At any given moment only one Observable passed to operator
* emits values. If you would like to emit values from passed Observables concurrently, check out
* {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,
* `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.
*
* Note that if some input Observable never completes, `concat` will also never complete
* and Observables following the one that did not complete will never be subscribed. On the other
* hand, if some Observable simply completes immediately after it is subscribed, it will be
* invisible for `concat`, which will just move on to the next Observable.
*
* If any Observable in chain errors, instead of passing control to the next Observable,
* `concat` will error immediately as well. Observables that would be subscribed after
* the one that emitted error, never will.
*
* If you pass to `concat` the same Observable many times, its stream of values
* will be "replayed" on every subscription, which means you can repeat given Observable
* as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,
* you can always use {@link repeat}.
*
* ## Examples
*
* Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10
*
* ```ts
* import { interval, take, range, concat } from 'rxjs';
*
* const timer = interval(1000).pipe(take(4));
* const sequence = range(1, 10);
* const result = concat(timer, sequence);
* result.subscribe(x => console.log(x));
*
* // results in:
* // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10
* ```
*
* Concatenate 3 Observables
*
* ```ts
* import { interval, take, concat } from 'rxjs';
*
* const timer1 = interval(1000).pipe(take(10));
* const timer2 = interval(2000).pipe(take(6));
* const timer3 = interval(500).pipe(take(10));
*
* const result = concat(timer1, timer2, timer3);
* result.subscribe(x => console.log(x));
*
* // results in the following:
* // (Prints to console sequentially)
* // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9
* // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5
* // -500ms-> 0 -500ms-> 1 -500ms-> ... 9
* ```
*
* Concatenate the same Observable to repeat it
*
* ```ts
* import { interval, take, concat } from 'rxjs';
*
* const timer = interval(1000).pipe(take(2));
*
* concat(timer, timer) // concatenating the same Observable!
* .subscribe({
* next: value => console.log(value),
* complete: () => console.log('...and it is done!')
* });
*
* // Logs:
* // 0 after 1s
* // 1 after 2s
* // 0 after 3s
* // 1 after 4s
* // '...and it is done!' also after 4s
* ```
*
* @see {@link concatAll}
* @see {@link concatMap}
* @see {@link concatMapTo}
* @see {@link startWith}
* @see {@link endWith}
*
* @param args `ObservableInput`s to concatenate.
*/
export function concat(...args: any[]): Observable<unknown> {
return concatAll()(from(args, popScheduler(args)));
}

View File

@@ -0,0 +1,64 @@
import { Connectable, ObservableInput, SubjectLike } from '../types';
import { Subject } from '../Subject';
import { Subscription } from '../Subscription';
import { Observable } from '../Observable';
import { defer } from './defer';
export interface ConnectableConfig<T> {
/**
* A factory function used to create the Subject through which the source
* is multicast. By default this creates a {@link Subject}.
*/
connector: () => SubjectLike<T>;
/**
* If true, the resulting observable will reset internal state upon disconnection
* and return to a "cold" state. This allows the resulting observable to be
* reconnected.
* If false, upon disconnection, the connecting subject will remain the
* connecting subject, meaning the resulting observable will not go "cold" again,
* and subsequent repeats or resubscriptions will resubscribe to that same subject.
*/
resetOnDisconnect?: boolean;
}
/**
* The default configuration for `connectable`.
*/
const DEFAULT_CONFIG: ConnectableConfig<unknown> = {
connector: () => new Subject<unknown>(),
resetOnDisconnect: true,
};
/**
* Creates an observable that multicasts once `connect()` is called on it.
*
* @param source The observable source to make connectable.
* @param config The configuration object for `connectable`.
* @returns A "connectable" observable, that has a `connect()` method, that you must call to
* connect the source to all consumers through the subject provided as the connector.
*/
export function connectable<T>(source: ObservableInput<T>, config: ConnectableConfig<T> = DEFAULT_CONFIG): Connectable<T> {
// The subscription representing the connection.
let connection: Subscription | null = null;
const { connector, resetOnDisconnect = true } = config;
let subject = connector();
const result: any = new Observable<T>((subscriber) => {
return subject.subscribe(subscriber);
});
// Define the `connect` function. This is what users must call
// in order to "connect" the source to the subject that is
// multicasting it.
result.connect = () => {
if (!connection || connection.closed) {
connection = defer(() => source).subscribe(subject);
if (resetOnDisconnect) {
connection.add(() => (subject = connector()));
}
}
return connection;
};
return result;
}

56
node_modules/rxjs/src/internal/observable/defer.ts generated vendored Normal file
View File

@@ -0,0 +1,56 @@
import { Observable } from '../Observable';
import { ObservedValueOf, ObservableInput } from '../types';
import { innerFrom } from './innerFrom';
/**
* Creates an Observable that, on subscribe, calls an Observable factory to
* make an Observable for each new Observer.
*
* <span class="informal">Creates the Observable lazily, that is, only when it
* is subscribed.
* </span>
*
* ![](defer.png)
*
* `defer` allows you to create an Observable only when the Observer
* subscribes. It waits until an Observer subscribes to it, calls the given
* factory function to get an Observable -- where a factory function typically
* generates a new Observable -- and subscribes the Observer to this Observable.
* In case the factory function returns a falsy value, then EMPTY is used as
* Observable instead. Last but not least, an exception during the factory
* function call is transferred to the Observer by calling `error`.
*
* ## Example
*
* Subscribe to either an Observable of clicks or an Observable of interval, at random
*
* ```ts
* import { defer, fromEvent, interval } from 'rxjs';
*
* const clicksOrInterval = defer(() => {
* return Math.random() > 0.5
* ? fromEvent(document, 'click')
* : interval(1000);
* });
* clicksOrInterval.subscribe(x => console.log(x));
*
* // Results in the following behavior:
* // If the result of Math.random() is greater than 0.5 it will listen
* // for clicks anywhere on the "document"; when document is clicked it
* // will log a MouseEvent object to the console. If the result is less
* // than 0.5 it will emit ascending numbers, one every second(1000ms).
* ```
*
* @see {@link Observable}
*
* @param observableFactory The Observable factory function to invoke for each
* Observer that subscribes to the output Observable. May also return any
* `ObservableInput`, which will be converted on the fly to an Observable.
* @return An Observable whose Observers' subscriptions trigger an invocation of the
* given Observable factory function.
*/
export function defer<R extends ObservableInput<any>>(observableFactory: () => R): Observable<ObservedValueOf<R>> {
return new Observable<ObservedValueOf<R>>((subscriber) => {
innerFrom(observableFactory()).subscribe(subscriber);
});
}

View File

@@ -0,0 +1,397 @@
import { Subject, AnonymousSubject } from '../../Subject';
import { Subscriber } from '../../Subscriber';
import { Observable } from '../../Observable';
import { Subscription } from '../../Subscription';
import { Operator } from '../../Operator';
import { ReplaySubject } from '../../ReplaySubject';
import { Observer, NextObserver } from '../../types';
/**
* WebSocketSubjectConfig is a plain Object that allows us to make our
* webSocket configurable.
*
* <span class="informal">Provides flexibility to {@link webSocket}</span>
*
* It defines a set of properties to provide custom behavior in specific
* moments of the socket's lifecycle. When the connection opens we can
* use `openObserver`, when the connection is closed `closeObserver`, if we
* are interested in listening for data coming from server: `deserializer`,
* which allows us to customize the deserialization strategy of data before passing it
* to the socket client. By default, `deserializer` is going to apply `JSON.parse` to each message coming
* from the Server.
*
* ## Examples
*
* **deserializer**, the default for this property is `JSON.parse` but since there are just two options
* for incoming data, either be text or binary data. We can apply a custom deserialization strategy
* or just simply skip the default behaviour.
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* //Apply any transformation of your choice.
* deserializer: ({ data }) => data
* });
*
* wsSubject.subscribe(console.log);
*
* // Let's suppose we have this on the Server: ws.send('This is a msg from the server')
* //output
* //
* // This is a msg from the server
* ```
*
* **serializer** allows us to apply custom serialization strategy but for the outgoing messages.
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* // Apply any transformation of your choice.
* serializer: msg => JSON.stringify({ channel: 'webDevelopment', msg: msg })
* });
*
* wsSubject.subscribe(() => subject.next('msg to the server'));
*
* // Let's suppose we have this on the Server:
* // ws.on('message', msg => console.log);
* // ws.send('This is a msg from the server');
* // output at server side:
* //
* // {"channel":"webDevelopment","msg":"msg to the server"}
* ```
*
* **closeObserver** allows us to set a custom error when an error raises up.
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* closeObserver: {
* next() {
* const customError = { code: 6666, reason: 'Custom evil reason' }
* console.log(`code: ${ customError.code }, reason: ${ customError.reason }`);
* }
* }
* });
*
* // output
* // code: 6666, reason: Custom evil reason
* ```
*
* **openObserver**, Let's say we need to make some kind of init task before sending/receiving msgs to the
* webSocket or sending notification that the connection was successful, this is when
* openObserver is useful for.
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const wsSubject = webSocket({
* url: 'ws://localhost:8081',
* openObserver: {
* next: () => {
* console.log('Connection ok');
* }
* }
* });
*
* // output
* // Connection ok
* ```
*/
export interface WebSocketSubjectConfig<T> {
/** The url of the socket server to connect to */
url: string;
/** The protocol to use to connect */
protocol?: string | Array<string>;
/** @deprecated Will be removed in v8. Use {@link deserializer} instead. */
resultSelector?: (e: MessageEvent) => T;
/**
* A serializer used to create messages from passed values before the
* messages are sent to the server. Defaults to JSON.stringify.
*/
serializer?: (value: T) => WebSocketMessage;
/**
* A deserializer used for messages arriving on the socket from the
* server. Defaults to JSON.parse.
*/
deserializer?: (e: MessageEvent) => T;
/**
* An Observer that watches when open events occur on the underlying web socket.
*/
openObserver?: NextObserver<Event>;
/**
* An Observer that watches when close events occur on the underlying web socket
*/
closeObserver?: NextObserver<CloseEvent>;
/**
* An Observer that watches when a close is about to occur due to
* unsubscription.
*/
closingObserver?: NextObserver<void>;
/**
* A WebSocket constructor to use. This is useful for situations like using a
* WebSocket impl in Node (WebSocket is a DOM API), or for mocking a WebSocket
* for testing purposes
*/
WebSocketCtor?: { new (url: string, protocols?: string | string[]): WebSocket };
/** Sets the `binaryType` property of the underlying WebSocket. */
binaryType?: 'blob' | 'arraybuffer';
}
const DEFAULT_WEBSOCKET_CONFIG: WebSocketSubjectConfig<any> = {
url: '',
deserializer: (e: MessageEvent) => JSON.parse(e.data),
serializer: (value: any) => JSON.stringify(value),
};
const WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT =
'WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }';
export type WebSocketMessage = string | ArrayBuffer | Blob | ArrayBufferView;
export class WebSocketSubject<T> extends AnonymousSubject<T> {
// @ts-ignore: Property has no initializer and is not definitely assigned
private _config: WebSocketSubjectConfig<T>;
/** @internal */
// @ts-ignore: Property has no initializer and is not definitely assigned
_output: Subject<T>;
private _socket: WebSocket | null = null;
constructor(urlConfigOrSource: string | WebSocketSubjectConfig<T> | Observable<T>, destination?: Observer<T>) {
super();
if (urlConfigOrSource instanceof Observable) {
this.destination = destination;
this.source = urlConfigOrSource as Observable<T>;
} else {
const config = (this._config = { ...DEFAULT_WEBSOCKET_CONFIG });
this._output = new Subject<T>();
if (typeof urlConfigOrSource === 'string') {
config.url = urlConfigOrSource;
} else {
for (const key in urlConfigOrSource) {
if (urlConfigOrSource.hasOwnProperty(key)) {
(config as any)[key] = (urlConfigOrSource as any)[key];
}
}
}
if (!config.WebSocketCtor && WebSocket) {
config.WebSocketCtor = WebSocket;
} else if (!config.WebSocketCtor) {
throw new Error('no WebSocket constructor can be found');
}
this.destination = new ReplaySubject();
}
}
/** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */
lift<R>(operator: Operator<T, R>): WebSocketSubject<R> {
const sock = new WebSocketSubject<R>(this._config as WebSocketSubjectConfig<any>, this.destination as any);
sock.operator = operator;
sock.source = this;
return sock;
}
private _resetState() {
this._socket = null;
if (!this.source) {
this.destination = new ReplaySubject();
}
this._output = new Subject<T>();
}
/**
* Creates an {@link Observable}, that when subscribed to, sends a message,
* defined by the `subMsg` function, to the server over the socket to begin a
* subscription to data over that socket. Once data arrives, the
* `messageFilter` argument will be used to select the appropriate data for
* the resulting Observable. When finalization occurs, either due to
* unsubscription, completion, or error, a message defined by the `unsubMsg`
* argument will be sent to the server over the WebSocketSubject.
*
* @param subMsg A function to generate the subscription message to be sent to
* the server. This will still be processed by the serializer in the
* WebSocketSubject's config. (Which defaults to JSON serialization)
* @param unsubMsg A function to generate the unsubscription message to be
* sent to the server at finalization. This will still be processed by the
* serializer in the WebSocketSubject's config.
* @param messageFilter A predicate for selecting the appropriate messages
* from the server for the output stream.
*/
multiplex(subMsg: () => any, unsubMsg: () => any, messageFilter: (value: T) => boolean) {
const self = this;
return new Observable((observer: Observer<T>) => {
try {
self.next(subMsg());
} catch (err) {
observer.error(err);
}
const subscription = self.subscribe({
next: (x) => {
try {
if (messageFilter(x)) {
observer.next(x);
}
} catch (err) {
observer.error(err);
}
},
error: (err) => observer.error(err),
complete: () => observer.complete(),
});
return () => {
try {
self.next(unsubMsg());
} catch (err) {
observer.error(err);
}
subscription.unsubscribe();
};
});
}
private _connectSocket() {
const { WebSocketCtor, protocol, url, binaryType } = this._config;
const observer = this._output;
let socket: WebSocket | null = null;
try {
socket = protocol ? new WebSocketCtor!(url, protocol) : new WebSocketCtor!(url);
this._socket = socket;
if (binaryType) {
this._socket.binaryType = binaryType;
}
} catch (e) {
observer.error(e);
return;
}
const subscription = new Subscription(() => {
this._socket = null;
if (socket && socket.readyState === 1) {
socket.close();
}
});
socket.onopen = (evt: Event) => {
const { _socket } = this;
if (!_socket) {
socket!.close();
this._resetState();
return;
}
const { openObserver } = this._config;
if (openObserver) {
openObserver.next(evt);
}
const queue = this.destination;
this.destination = Subscriber.create<T>(
(x) => {
if (socket!.readyState === 1) {
try {
const { serializer } = this._config;
socket!.send(serializer!(x!));
} catch (e) {
this.destination!.error(e);
}
}
},
(err) => {
const { closingObserver } = this._config;
if (closingObserver) {
closingObserver.next(undefined);
}
if (err && err.code) {
socket!.close(err.code, err.reason);
} else {
observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT));
}
this._resetState();
},
() => {
const { closingObserver } = this._config;
if (closingObserver) {
closingObserver.next(undefined);
}
socket!.close();
this._resetState();
}
) as Subscriber<any>;
if (queue && queue instanceof ReplaySubject) {
subscription.add((queue as ReplaySubject<T>).subscribe(this.destination));
}
};
socket.onerror = (e: Event) => {
this._resetState();
observer.error(e);
};
socket.onclose = (e: CloseEvent) => {
if (socket === this._socket) {
this._resetState();
}
const { closeObserver } = this._config;
if (closeObserver) {
closeObserver.next(e);
}
if (e.wasClean) {
observer.complete();
} else {
observer.error(e);
}
};
socket.onmessage = (e: MessageEvent) => {
try {
const { deserializer } = this._config;
observer.next(deserializer!(e));
} catch (err) {
observer.error(err);
}
};
}
/** @internal */
protected _subscribe(subscriber: Subscriber<T>): Subscription {
const { source } = this;
if (source) {
return source.subscribe(subscriber);
}
if (!this._socket) {
this._connectSocket();
}
this._output.subscribe(subscriber);
subscriber.add(() => {
const { _socket } = this;
if (this._output.observers.length === 0) {
if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
_socket.close();
}
this._resetState();
}
});
return subscriber;
}
unsubscribe() {
const { _socket } = this;
if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
_socket.close();
}
this._resetState();
super.unsubscribe();
}
}

View File

@@ -0,0 +1,132 @@
import { Observable } from '../../Observable';
import { TimestampProvider } from '../../types';
import { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider';
import { animationFrameProvider } from '../../scheduler/animationFrameProvider';
/**
* An observable of animation frames
*
* Emits the amount of time elapsed since subscription and the timestamp on each animation frame.
* Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own.
*
* Every subscription will start a separate animation loop. Since animation frames are always scheduled
* by the browser to occur directly before a repaint, scheduling more than one animation frame synchronously
* should not be much different or have more overhead than looping over an array of events during
* a single animation frame. However, if for some reason the developer would like to ensure the
* execution of animation-related handlers are all executed during the same task by the engine,
* the `share` operator can be used.
*
* This is useful for setting up animations with RxJS.
*
* ## Examples
*
* Tweening a div to move it on the screen
*
* ```ts
* import { animationFrames, map, takeWhile, endWith } from 'rxjs';
*
* function tween(start: number, end: number, duration: number) {
* const diff = end - start;
* return animationFrames().pipe(
* // Figure out what percentage of time has passed
* map(({ elapsed }) => elapsed / duration),
* // Take the vector while less than 100%
* takeWhile(v => v < 1),
* // Finish with 100%
* endWith(1),
* // Calculate the distance traveled between start and end
* map(v => v * diff + start)
* );
* }
*
* // Setup a div for us to move around
* const div = document.createElement('div');
* document.body.appendChild(div);
* div.style.position = 'absolute';
* div.style.width = '40px';
* div.style.height = '40px';
* div.style.backgroundColor = 'lime';
* div.style.transform = 'translate3d(10px, 0, 0)';
*
* tween(10, 200, 4000).subscribe(x => {
* div.style.transform = `translate3d(${ x }px, 0, 0)`;
* });
* ```
*
* Providing a custom timestamp provider
*
* ```ts
* import { animationFrames, TimestampProvider } from 'rxjs';
*
* // A custom timestamp provider
* let now = 0;
* const customTSProvider: TimestampProvider = {
* now() { return now++; }
* };
*
* const source$ = animationFrames(customTSProvider);
*
* // Log increasing numbers 0...1...2... on every animation frame.
* source$.subscribe(({ elapsed }) => console.log(elapsed));
* ```
*
* @param timestampProvider An object with a `now` method that provides a numeric timestamp
*/
export function animationFrames(timestampProvider?: TimestampProvider) {
return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;
}
/**
* Does the work of creating the observable for `animationFrames`.
* @param timestampProvider The timestamp provider to use to create the observable
*/
function animationFramesFactory(timestampProvider?: TimestampProvider) {
return new Observable<{ timestamp: number; elapsed: number }>((subscriber) => {
// If no timestamp provider is specified, use performance.now() - as it
// will return timestamps 'compatible' with those passed to the run
// callback and won't be affected by NTP adjustments, etc.
const provider = timestampProvider || performanceTimestampProvider;
// Capture the start time upon subscription, as the run callback can remain
// queued for a considerable period of time and the elapsed time should
// represent the time elapsed since subscription - not the time since the
// first rendered animation frame.
const start = provider.now();
let id = 0;
const run = () => {
if (!subscriber.closed) {
id = animationFrameProvider.requestAnimationFrame((timestamp: DOMHighResTimeStamp | number) => {
id = 0;
// Use the provider's timestamp to calculate the elapsed time. Note that
// this means - if the caller hasn't passed a provider - that
// performance.now() will be used instead of the timestamp that was
// passed to the run callback. The reason for this is that the timestamp
// passed to the callback can be earlier than the start time, as it
// represents the time at which the browser decided it would render any
// queued frames - and that time can be earlier the captured start time.
const now = provider.now();
subscriber.next({
timestamp: timestampProvider ? now : timestamp,
elapsed: now - start,
});
run();
});
}
};
run();
return () => {
if (id) {
animationFrameProvider.cancelAnimationFrame(id);
}
};
});
}
/**
* In the common case, where the timestamp provided by the rAF API is used,
* we use this shared observable to reduce overhead.
*/
const DEFAULT_ANIMATION_FRAMES = animationFramesFactory();

180
node_modules/rxjs/src/internal/observable/dom/fetch.ts generated vendored Normal file
View File

@@ -0,0 +1,180 @@
import { createOperatorSubscriber } from '../../operators/OperatorSubscriber';
import { Observable } from '../../Observable';
import { innerFrom } from '../../observable/innerFrom';
import { ObservableInput } from '../../types';
export function fromFetch<T>(
input: string | Request,
init: RequestInit & {
selector: (response: Response) => ObservableInput<T>;
}
): Observable<T>;
export function fromFetch(input: string | Request, init?: RequestInit): Observable<Response>;
/**
* Uses [the Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to
* make an HTTP request.
*
* **WARNING** Parts of the fetch API are still experimental. `AbortController` is
* required for this implementation to work and use cancellation appropriately.
*
* Will automatically set up an internal [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController)
* in order to finalize the internal `fetch` when the subscription tears down.
*
* If a `signal` is provided via the `init` argument, it will behave like it usually does with
* `fetch`. If the provided `signal` aborts, the error that `fetch` normally rejects with
* in that scenario will be emitted as an error from the observable.
*
* ## Examples
*
* Basic use
*
* ```ts
* import { fromFetch } from 'rxjs/fetch';
* import { switchMap, of, catchError } from 'rxjs';
*
* const data$ = fromFetch('https://api.github.com/users?per_page=5').pipe(
* switchMap(response => {
* if (response.ok) {
* // OK return data
* return response.json();
* } else {
* // Server is returning a status requiring the client to try something else.
* return of({ error: true, message: `Error ${ response.status }` });
* }
* }),
* catchError(err => {
* // Network or other error, handle appropriately
* console.error(err);
* return of({ error: true, message: err.message })
* })
* );
*
* data$.subscribe({
* next: result => console.log(result),
* complete: () => console.log('done')
* });
* ```
*
* ### Use with Chunked Transfer Encoding
*
* With HTTP responses that use [chunked transfer encoding](https://tools.ietf.org/html/rfc7230#section-3.3.1),
* the promise returned by `fetch` will resolve as soon as the response's headers are
* received.
*
* That means the `fromFetch` observable will emit a `Response` - and will
* then complete - before the body is received. When one of the methods on the
* `Response` - like `text()` or `json()` - is called, the returned promise will not
* resolve until the entire body has been received. Unsubscribing from any observable
* that uses the promise as an observable input will not abort the request.
*
* To facilitate aborting the retrieval of responses that use chunked transfer encoding,
* a `selector` can be specified via the `init` parameter:
*
* ```ts
* import { of } from 'rxjs';
* import { fromFetch } from 'rxjs/fetch';
*
* const data$ = fromFetch('https://api.github.com/users?per_page=5', {
* selector: response => response.json()
* });
*
* data$.subscribe({
* next: result => console.log(result),
* complete: () => console.log('done')
* });
* ```
*
* @param input The resource you would like to fetch. Can be a url or a request object.
* @param initWithSelector A configuration object for the fetch.
* [See MDN for more details](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
* @returns An Observable, that when subscribed to, performs an HTTP request using the native `fetch`
* function. The {@link Subscription} is tied to an `AbortController` for the fetch.
*/
export function fromFetch<T>(
input: string | Request,
initWithSelector: RequestInit & {
selector?: (response: Response) => ObservableInput<T>;
} = {}
): Observable<Response | T> {
const { selector, ...init } = initWithSelector;
return new Observable<Response | T>((subscriber) => {
// Our controller for aborting this fetch.
// Any externally provided AbortSignal will have to call
// abort on this controller when signaled, because the
// signal from this controller is what is being passed to `fetch`.
const controller = new AbortController();
const { signal } = controller;
// This flag exists to make sure we don't `abort()` the fetch upon tearing down
// this observable after emitting a Response. Aborting in such circumstances
// would also abort subsequent methods - like `json()` - that could be called
// on the Response. Consider: `fromFetch().pipe(take(1), mergeMap(res => res.json()))`
let abortable = true;
// If the user provided an init configuration object,
// let's process it and chain our abort signals, if necessary.
// If a signal is provided, just have it finalized. It's a cancellation token, basically.
const { signal: outerSignal } = init;
if (outerSignal) {
if (outerSignal.aborted) {
controller.abort();
} else {
// We got an AbortSignal from the arguments passed into `fromFetch`.
// We need to wire up our AbortController to abort when this signal aborts.
const outerSignalHandler = () => {
if (!signal.aborted) {
controller.abort();
}
};
outerSignal.addEventListener('abort', outerSignalHandler);
subscriber.add(() => outerSignal.removeEventListener('abort', outerSignalHandler));
}
}
// The initialization object passed to `fetch` as the second
// argument. This ferries in important information, including our
// AbortSignal. Create a new init, so we don't accidentally mutate the
// passed init, or reassign it. This is because the init passed in
// is shared between each subscription to the result.
const perSubscriberInit: RequestInit = { ...init, signal };
const handleError = (err: any) => {
abortable = false;
subscriber.error(err);
};
fetch(input, perSubscriberInit)
.then((response) => {
if (selector) {
// If we have a selector function, use it to project our response.
// Note that any error that comes from our selector will be
// sent to the promise `catch` below and handled.
innerFrom(selector(response)).subscribe(
createOperatorSubscriber(
subscriber,
// Values are passed through to the subscriber
undefined,
// The projected response is complete.
() => {
abortable = false;
subscriber.complete();
},
handleError
)
);
} else {
abortable = false;
subscriber.next(response);
subscriber.complete();
}
})
.catch(handleError);
return () => {
if (abortable) {
controller.abort();
}
};
});
}

View File

@@ -0,0 +1,161 @@
import { WebSocketSubject, WebSocketSubjectConfig } from './WebSocketSubject';
/**
* Wrapper around the w3c-compatible WebSocket object provided by the browser.
*
* <span class="informal">{@link Subject} that communicates with a server via WebSocket</span>
*
* `webSocket` is a factory function that produces a `WebSocketSubject`,
* which can be used to make WebSocket connection with an arbitrary endpoint.
* `webSocket` accepts as an argument either a string with url of WebSocket endpoint, or an
* {@link WebSocketSubjectConfig} object for providing additional configuration, as
* well as Observers for tracking lifecycle of WebSocket connection.
*
* When `WebSocketSubject` is subscribed, it attempts to make a socket connection,
* unless there is one made already. This means that many subscribers will always listen
* on the same socket, thus saving resources. If however, two instances are made of `WebSocketSubject`,
* even if these two were provided with the same url, they will attempt to make separate
* connections. When consumer of a `WebSocketSubject` unsubscribes, socket connection is closed,
* only if there are no more subscribers still listening. If after some time a consumer starts
* subscribing again, connection is reestablished.
*
* Once connection is made, whenever a new message comes from the server, `WebSocketSubject` will emit that
* message as a value in the stream. By default, a message from the socket is parsed via `JSON.parse`. If you
* want to customize how deserialization is handled (if at all), you can provide custom `resultSelector`
* function in {@link WebSocketSubject}. When connection closes, stream will complete, provided it happened without
* any errors. If at any point (starting, maintaining or closing a connection) there is an error,
* stream will also error with whatever WebSocket API has thrown.
*
* By virtue of being a {@link Subject}, `WebSocketSubject` allows for receiving and sending messages from the server. In order
* to communicate with a connected endpoint, use `next`, `error` and `complete` methods. `next` sends a value to the server, so bear in mind
* that this value will not be serialized beforehand. Because of This, `JSON.stringify` will have to be called on a value by hand,
* before calling `next` with a result. Note also that if at the moment of nexting value
* there is no socket connection (for example no one is subscribing), those values will be buffered, and sent when connection
* is finally established. `complete` method closes socket connection. `error` does the same,
* as well as notifying the server that something went wrong via status code and string with details of what happened.
* Since status code is required in WebSocket API, `WebSocketSubject` does not allow, like regular `Subject`,
* arbitrary values being passed to the `error` method. It needs to be called with an object that has `code`
* property with status code number and optional `reason` property with string describing details
* of an error.
*
* Calling `next` does not affect subscribers of `WebSocketSubject` - they have no
* information that something was sent to the server (unless of course the server
* responds somehow to a message). On the other hand, since calling `complete` triggers
* an attempt to close socket connection. If that connection is closed without any errors, stream will
* complete, thus notifying all subscribers. And since calling `error` closes
* socket connection as well, just with a different status code for the server, if closing itself proceeds
* without errors, subscribed Observable will not error, as one might expect, but complete as usual. In both cases
* (calling `complete` or `error`), if process of closing socket connection results in some errors, *then* stream
* will error.
*
* **Multiplexing**
*
* `WebSocketSubject` has an additional operator, not found in other Subjects. It is called `multiplex` and it is
* used to simulate opening several socket connections, while in reality maintaining only one.
* For example, an application has both chat panel and real-time notifications about sport news. Since these are two distinct functions,
* it would make sense to have two separate connections for each. Perhaps there could even be two separate services with WebSocket
* endpoints, running on separate machines with only GUI combining them together. Having a socket connection
* for each functionality could become too resource expensive. It is a common pattern to have single
* WebSocket endpoint that acts as a gateway for the other services (in this case chat and sport news services).
* Even though there is a single connection in a client app, having the ability to manipulate streams as if it
* were two separate sockets is desirable. This eliminates manually registering and unregistering in a gateway for
* given service and filter out messages of interest. This is exactly what `multiplex` method is for.
*
* Method accepts three parameters. First two are functions returning subscription and unsubscription messages
* respectively. These are messages that will be sent to the server, whenever consumer of resulting Observable
* subscribes and unsubscribes. Server can use them to verify that some kind of messages should start or stop
* being forwarded to the client. In case of the above example application, after getting subscription message with proper identifier,
* gateway server can decide that it should connect to real sport news service and start forwarding messages from it.
* Note that both messages will be sent as returned by the functions, they are by default serialized using JSON.stringify, just
* as messages pushed via `next`. Also bear in mind that these messages will be sent on *every* subscription and
* unsubscription. This is potentially dangerous, because one consumer of an Observable may unsubscribe and the server
* might stop sending messages, since it got unsubscription message. This needs to be handled
* on the server or using {@link publish} on a Observable returned from 'multiplex'.
*
* Last argument to `multiplex` is a `messageFilter` function which should return a boolean. It is used to filter out messages
* sent by the server to only those that belong to simulated WebSocket stream. For example, server might mark these
* messages with some kind of string identifier on a message object and `messageFilter` would return `true`
* if there is such identifier on an object emitted by the socket. Messages which returns `false` in `messageFilter` are simply skipped,
* and are not passed down the stream.
*
* Return value of `multiplex` is an Observable with messages incoming from emulated socket connection. Note that this
* is not a `WebSocketSubject`, so calling `next` or `multiplex` again will fail. For pushing values to the
* server, use root `WebSocketSubject`.
*
* ## Examples
*
* Listening for messages from the server
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const subject = webSocket('ws://localhost:8081');
*
* subject.subscribe({
* next: msg => console.log('message received: ' + msg), // Called whenever there is a message from the server.
* error: err => console.log(err), // Called if at any point WebSocket API signals some kind of error.
* complete: () => console.log('complete') // Called when connection is closed (for whatever reason).
* });
* ```
*
* Pushing messages to the server
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const subject = webSocket('ws://localhost:8081');
*
* subject.subscribe();
* // Note that at least one consumer has to subscribe to the created subject - otherwise "nexted" values will be just buffered and not sent,
* // since no connection was established!
*
* subject.next({ message: 'some message' });
* // This will send a message to the server once a connection is made. Remember value is serialized with JSON.stringify by default!
*
* subject.complete(); // Closes the connection.
*
* subject.error({ code: 4000, reason: 'I think our app just broke!' });
* // Also closes the connection, but let's the server know that this closing is caused by some error.
* ```
*
* Multiplexing WebSocket
*
* ```ts
* import { webSocket } from 'rxjs/webSocket';
*
* const subject = webSocket('ws://localhost:8081');
*
* const observableA = subject.multiplex(
* () => ({ subscribe: 'A' }), // When server gets this message, it will start sending messages for 'A'...
* () => ({ unsubscribe: 'A' }), // ...and when gets this one, it will stop.
* message => message.type === 'A' // If the function returns `true` message is passed down the stream. Skipped if the function returns false.
* );
*
* const observableB = subject.multiplex( // And the same goes for 'B'.
* () => ({ subscribe: 'B' }),
* () => ({ unsubscribe: 'B' }),
* message => message.type === 'B'
* );
*
* const subA = observableA.subscribe(messageForA => console.log(messageForA));
* // At this moment WebSocket connection is established. Server gets '{"subscribe": "A"}' message and starts sending messages for 'A',
* // which we log here.
*
* const subB = observableB.subscribe(messageForB => console.log(messageForB));
* // Since we already have a connection, we just send '{"subscribe": "B"}' message to the server. It starts sending messages for 'B',
* // which we log here.
*
* subB.unsubscribe();
* // Message '{"unsubscribe": "B"}' is sent to the server, which stops sending 'B' messages.
*
* subA.unsubscribe();
* // Message '{"unsubscribe": "A"}' makes the server stop sending messages for 'A'. Since there is no more subscribers to root Subject,
* // socket connection closes.
* ```
*
* @param urlConfigOrSource The WebSocket endpoint as an url or an object with configuration and additional Observers.
* @return Subject which allows to both send and receive messages via WebSocket connection.
*/
export function webSocket<T>(urlConfigOrSource: string | WebSocketSubjectConfig<T>): WebSocketSubject<T> {
return new WebSocketSubject<T>(urlConfigOrSource);
}

79
node_modules/rxjs/src/internal/observable/empty.ts generated vendored Normal file
View File

@@ -0,0 +1,79 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
/**
* A simple Observable that emits no items to the Observer and immediately
* emits a complete notification.
*
* <span class="informal">Just emits 'complete', and nothing else.</span>
*
* ![](empty.png)
*
* A simple Observable that only emits the complete notification. It can be used
* for composing with other Observables, such as in a {@link mergeMap}.
*
* ## Examples
*
* Log complete notification
*
* ```ts
* import { EMPTY } from 'rxjs';
*
* EMPTY.subscribe({
* next: () => console.log('Next'),
* complete: () => console.log('Complete!')
* });
*
* // Outputs
* // Complete!
* ```
*
* Emit the number 7, then complete
*
* ```ts
* import { EMPTY, startWith } from 'rxjs';
*
* const result = EMPTY.pipe(startWith(7));
* result.subscribe(x => console.log(x));
*
* // Outputs
* // 7
* ```
*
* Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`
*
* ```ts
* import { interval, mergeMap, of, EMPTY } from 'rxjs';
*
* const interval$ = interval(1000);
* const result = interval$.pipe(
* mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following to the console:
* // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)
* // x will occur every 1000ms
* // if x % 2 is equal to 1, print a, b, c (each on its own)
* // if x % 2 is not equal to 1, nothing will be output
* ```
*
* @see {@link Observable}
* @see {@link NEVER}
* @see {@link of}
* @see {@link throwError}
*/
export const EMPTY = new Observable<never>((subscriber) => subscriber.complete());
/**
* @param scheduler A {@link SchedulerLike} to use for scheduling
* the emission of the complete notification.
* @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.
*/
export function empty(scheduler?: SchedulerLike) {
return scheduler ? emptyScheduled(scheduler) : EMPTY;
}
function emptyScheduled(scheduler: SchedulerLike) {
return new Observable<never>((subscriber) => scheduler.schedule(() => subscriber.complete()));
}

184
node_modules/rxjs/src/internal/observable/forkJoin.ts generated vendored Normal file
View File

@@ -0,0 +1,184 @@
import { Observable } from '../Observable';
import { ObservedValueOf, ObservableInputTuple, ObservableInput } from '../types';
import { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';
import { innerFrom } from './innerFrom';
import { popResultSelector } from '../util/args';
import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
import { createObject } from '../util/createObject';
import { AnyCatcher } from '../AnyCatcher';
// forkJoin(any)
// We put this first because we need to catch cases where the user has supplied
// _exactly `any`_ as the argument. Since `any` literally matches _anything_,
// we don't want it to randomly hit one of the other type signatures below,
// as we have no idea at build-time what type we should be returning when given an any.
/**
* You have passed `any` here, we can't figure out if it is
* an array or an object, so you're getting `unknown`. Use better types.
* @param arg Something typed as `any`
*/
export function forkJoin<T extends AnyCatcher>(arg: T): Observable<unknown>;
// forkJoin(null | undefined)
export function forkJoin(scheduler: null | undefined): Observable<never>;
// forkJoin([a, b, c])
export function forkJoin(sources: readonly []): Observable<never>;
export function forkJoin<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;
export function forkJoin<A extends readonly unknown[], R>(
sources: readonly [...ObservableInputTuple<A>],
resultSelector: (...values: A) => R
): Observable<R>;
// forkJoin(a, b, c)
/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
export function forkJoin<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;
/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */
export function forkJoin<A extends readonly unknown[], R>(
...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]
): Observable<R>;
// forkJoin({a, b, c})
export function forkJoin(sourcesObject: { [K in any]: never }): Observable<never>;
export function forkJoin<T extends Record<string, ObservableInput<any>>>(
sourcesObject: T
): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;
/**
* Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns
* an {@link Observable} that emits either an array of values in the exact same order as the passed array,
* or a dictionary of values in the same shape as the passed dictionary.
*
* <span class="informal">Wait for Observables to complete and then combine last values they emitted;
* complete immediately if an empty array is passed.</span>
*
* ![](forkJoin.png)
*
* `forkJoin` is an operator that takes any number of input observables which can be passed either as an array
* or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed),
* then the resulting stream will complete immediately.
*
* `forkJoin` will wait for all passed observables to emit and complete and then it will emit an array or an object with last
* values from corresponding observables.
*
* If you pass an array of `n` observables to the operator, then the resulting
* array will have `n` values, where the first value is the last one emitted by the first observable,
* second value is the last one emitted by the second observable and so on.
*
* If you pass a dictionary of observables to the operator, then the resulting
* objects will have the same keys as the dictionary passed, with their last values they have emitted
* located at the corresponding key.
*
* That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined
* values not only at the end of the lifecycle of passed observables, but also throughout it, try out {@link combineLatest}
* or {@link zip} instead.
*
* In order for the resulting array to have the same length as the number of input observables, whenever any of
* the given observables completes without emitting any value, `forkJoin` will complete at that moment as well
* and it will not emit anything either, even if it already has some last values from other observables.
* Conversely, if there is an observable that never completes, `forkJoin` will never complete either,
* unless at any point some other observable completes without emitting a value, which brings us back to
* the previous case. Overall, in order for `forkJoin` to emit a value, all given observables
* have to emit something at least once and complete.
*
* If any given observable errors at some point, `forkJoin` will error as well and immediately unsubscribe
* from the other observables.
*
* Optionally `forkJoin` accepts a `resultSelector` function, that will be called with values which normally
* would land in the emitted array. Whatever is returned by the `resultSelector`, will appear in the output
* observable instead. This means that the default `resultSelector` can be thought of as a function that takes
* all its arguments and puts them into an array. Note that the `resultSelector` will be called only
* when `forkJoin` is supposed to emit a result.
*
* ## Examples
*
* Use `forkJoin` with a dictionary of observable inputs
*
* ```ts
* import { forkJoin, of, timer } from 'rxjs';
*
* const observable = forkJoin({
* foo: of(1, 2, 3, 4),
* bar: Promise.resolve(8),
* baz: timer(4000)
* });
* observable.subscribe({
* next: value => console.log(value),
* complete: () => console.log('This is how it ends!'),
* });
*
* // Logs:
* // { foo: 4, bar: 8, baz: 0 } after 4 seconds
* // 'This is how it ends!' immediately after
* ```
*
* Use `forkJoin` with an array of observable inputs
*
* ```ts
* import { forkJoin, of, timer } from 'rxjs';
*
* const observable = forkJoin([
* of(1, 2, 3, 4),
* Promise.resolve(8),
* timer(4000)
* ]);
* observable.subscribe({
* next: value => console.log(value),
* complete: () => console.log('This is how it ends!'),
* });
*
* // Logs:
* // [4, 8, 0] after 4 seconds
* // 'This is how it ends!' immediately after
* ```
*
* @see {@link combineLatest}
* @see {@link zip}
*
* @param args Any number of `ObservableInput`s provided either as an array, as an object
* or as arguments passed directly to the operator.
* @return Observable emitting either an array of last values emitted by passed Observables
* or value from project function.
*/
export function forkJoin(...args: any[]): Observable<any> {
const resultSelector = popResultSelector(args);
const { args: sources, keys } = argsArgArrayOrObject(args);
const result = new Observable((subscriber) => {
const { length } = sources;
if (!length) {
subscriber.complete();
return;
}
const values = new Array(length);
let remainingCompletions = length;
let remainingEmissions = length;
for (let sourceIndex = 0; sourceIndex < length; sourceIndex++) {
let hasValue = false;
innerFrom(sources[sourceIndex]).subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
if (!hasValue) {
hasValue = true;
remainingEmissions--;
}
values[sourceIndex] = value;
},
() => remainingCompletions--,
undefined,
() => {
if (!remainingCompletions || !hasValue) {
if (!remainingEmissions) {
subscriber.next(keys ? createObject(keys, values) : values);
}
subscriber.complete();
}
}
)
);
}
});
return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;
}

104
node_modules/rxjs/src/internal/observable/from.ts generated vendored Normal file
View File

@@ -0,0 +1,104 @@
import { Observable } from '../Observable';
import { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';
import { scheduled } from '../scheduled/scheduled';
import { innerFrom } from './innerFrom';
export function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike | undefined): Observable<ObservedValueOf<O>>;
/**
* Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.
*
* <span class="informal">Converts almost anything to an Observable.</span>
*
* ![](from.png)
*
* `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable" target="_blank">iterable</a>
* object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated
* as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be
* converted through this operator.
*
* ## Examples
*
* Converts an array to an Observable
*
* ```ts
* import { from } from 'rxjs';
*
* const array = [10, 20, 30];
* const result = from(array);
*
* result.subscribe(x => console.log(x));
*
* // Logs:
* // 10
* // 20
* // 30
* ```
*
* Convert an infinite iterable (from a generator) to an Observable
*
* ```ts
* import { from, take } from 'rxjs';
*
* function* generateDoubles(seed) {
* let i = seed;
* while (true) {
* yield i;
* i = 2 * i; // double it
* }
* }
*
* const iterator = generateDoubles(3);
* const result = from(iterator).pipe(take(10));
*
* result.subscribe(x => console.log(x));
*
* // Logs:
* // 3
* // 6
* // 12
* // 24
* // 48
* // 96
* // 192
* // 384
* // 768
* // 1536
* ```
*
* With `asyncScheduler`
*
* ```ts
* import { from, asyncScheduler } from 'rxjs';
*
* console.log('start');
*
* const array = [10, 20, 30];
* const result = from(array, asyncScheduler);
*
* result.subscribe(x => console.log(x));
*
* console.log('end');
*
* // Logs:
* // 'start'
* // 'end'
* // 10
* // 20
* // 30
* ```
*
* @see {@link fromEvent}
* @see {@link fromEventPattern}
*
* @param input A subscription object, a Promise, an Observable-like,
* an Array, an iterable, or an array-like object to be converted.
* @param scheduler An optional {@link SchedulerLike} on which to schedule the emission of values.
* @return An Observable converted from {@link ObservableInput}.
*/
export function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {
return scheduler ? scheduled(input, scheduler) : innerFrom(input);
}

339
node_modules/rxjs/src/internal/observable/fromEvent.ts generated vendored Normal file
View File

@@ -0,0 +1,339 @@
import { innerFrom } from '../observable/innerFrom';
import { Observable } from '../Observable';
import { mergeMap } from '../operators/mergeMap';
import { isArrayLike } from '../util/isArrayLike';
import { isFunction } from '../util/isFunction';
import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
// These constants are used to create handler registry functions using array mapping below.
const nodeEventEmitterMethods = ['addListener', 'removeListener'] as const;
const eventTargetMethods = ['addEventListener', 'removeEventListener'] as const;
const jqueryMethods = ['on', 'off'] as const;
export interface NodeStyleEventEmitter {
addListener(eventName: string | symbol, handler: NodeEventHandler): this;
removeListener(eventName: string | symbol, handler: NodeEventHandler): this;
}
export type NodeEventHandler = (...args: any[]) => void;
// For APIs that implement `addListener` and `removeListener` methods that may
// not use the same arguments or return EventEmitter values
// such as React Native
export interface NodeCompatibleEventEmitter {
addListener(eventName: string, handler: NodeEventHandler): void | {};
removeListener(eventName: string, handler: NodeEventHandler): void | {};
}
// Use handler types like those in @types/jquery. See:
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/847731ba1d7fa6db6b911c0e43aa0afe596e7723/types/jquery/misc.d.ts#L6395
export interface JQueryStyleEventEmitter<TContext, T> {
on(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;
off(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;
}
export interface EventListenerObject<E> {
handleEvent(evt: E): void;
}
export interface HasEventTargetAddRemove<E> {
addEventListener(
type: string,
listener: ((evt: E) => void) | EventListenerObject<E> | null,
options?: boolean | AddEventListenerOptions
): void;
removeEventListener(
type: string,
listener: ((evt: E) => void) | EventListenerObject<E> | null,
options?: EventListenerOptions | boolean
): void;
}
export interface EventListenerOptions {
capture?: boolean;
passive?: boolean;
once?: boolean;
}
export interface AddEventListenerOptions extends EventListenerOptions {
once?: boolean;
passive?: boolean;
}
export function fromEvent<T>(target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>, eventName: string): Observable<T>;
export function fromEvent<T, R>(
target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,
eventName: string,
resultSelector: (event: T) => R
): Observable<R>;
export function fromEvent<T>(
target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,
eventName: string,
options: EventListenerOptions
): Observable<T>;
export function fromEvent<T, R>(
target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,
eventName: string,
options: EventListenerOptions,
resultSelector: (event: T) => R
): Observable<R>;
export function fromEvent(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<unknown>;
/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */
export function fromEvent<T>(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<T>;
export function fromEvent<R>(
target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>,
eventName: string,
resultSelector: (...args: any[]) => R
): Observable<R>;
export function fromEvent(
target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,
eventName: string
): Observable<unknown>;
/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */
export function fromEvent<T>(target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>, eventName: string): Observable<T>;
export function fromEvent<R>(
target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,
eventName: string,
resultSelector: (...args: any[]) => R
): Observable<R>;
export function fromEvent<T>(
target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,
eventName: string
): Observable<T>;
export function fromEvent<T, R>(
target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,
eventName: string,
resultSelector: (value: T, ...args: any[]) => R
): Observable<R>;
/**
* Creates an Observable that emits events of a specific type coming from the
* given event target.
*
* <span class="informal">Creates an Observable from DOM events, or Node.js
* EventEmitter events or others.</span>
*
* ![](fromEvent.png)
*
* `fromEvent` accepts as a first argument event target, which is an object with methods
* for registering event handler functions. As a second argument it takes string that indicates
* type of event we want to listen for. `fromEvent` supports selected types of event targets,
* which are described in detail below. If your event target does not match any of the ones listed,
* you should use {@link fromEventPattern}, which can be used on arbitrary APIs.
* When it comes to APIs supported by `fromEvent`, their methods for adding and removing event
* handler functions have different names, but they all accept a string describing event type
* and function itself, which will be called whenever said event happens.
*
* Every time resulting Observable is subscribed, event handler function will be registered
* to event target on given event type. When that event fires, value
* passed as a first argument to registered function will be emitted by output Observable.
* When Observable is unsubscribed, function will be unregistered from event target.
*
* Note that if event target calls registered function with more than one argument, second
* and following arguments will not appear in resulting stream. In order to get access to them,
* you can pass to `fromEvent` optional project function, which will be called with all arguments
* passed to event handler. Output Observable will then emit value returned by project function,
* instead of the usual value.
*
* Remember that event targets listed below are checked via duck typing. It means that
* no matter what kind of object you have and no matter what environment you work in,
* you can safely use `fromEvent` on that object if it exposes described methods (provided
* of course they behave as was described above). So for example if Node.js library exposes
* event target which has the same method names as DOM EventTarget, `fromEvent` is still
* a good choice.
*
* If the API you use is more callback then event handler oriented (subscribed
* callback function fires only once and thus there is no need to manually
* unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}
* instead.
*
* `fromEvent` supports following types of event targets:
*
* **DOM EventTarget**
*
* This is an object with `addEventListener` and `removeEventListener` methods.
*
* In the browser, `addEventListener` accepts - apart from event type string and event
* handler function arguments - optional third parameter, which is either an object or boolean,
* both used for additional configuration how and when passed function will be called. When
* `fromEvent` is used with event target of that type, you can provide this values
* as third parameter as well.
*
* **Node.js EventEmitter**
*
* An object with `addListener` and `removeListener` methods.
*
* **JQuery-style event target**
*
* An object with `on` and `off` methods
*
* **DOM NodeList**
*
* List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.
*
* Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes
* it contains and install event handler function in every of them. When returned Observable
* is unsubscribed, function will be removed from all Nodes.
*
* **DOM HtmlCollection**
*
* Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is
* installed and removed in each of elements.
*
*
* ## Examples
*
* Emit clicks happening on the DOM document
*
* ```ts
* import { fromEvent } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* clicks.subscribe(x => console.log(x));
*
* // Results in:
* // MouseEvent object logged to console every time a click
* // occurs on the document.
* ```
*
* Use `addEventListener` with capture option
*
* ```ts
* import { fromEvent } from 'rxjs';
*
* const div = document.createElement('div');
* div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
* document.body.appendChild(div);
*
* // note optional configuration parameter which will be passed to addEventListener
* const clicksInDocument = fromEvent(document, 'click', { capture: true });
* const clicksInDiv = fromEvent(div, 'click');
*
* clicksInDocument.subscribe(() => console.log('document'));
* clicksInDiv.subscribe(() => console.log('div'));
*
* // By default events bubble UP in DOM tree, so normally
* // when we would click on div in document
* // "div" would be logged first and then "document".
* // Since we specified optional `capture` option, document
* // will catch event when it goes DOWN DOM tree, so console
* // will log "document" and then "div".
* ```
*
* @see {@link bindCallback}
* @see {@link bindNodeCallback}
* @see {@link fromEventPattern}
*
* @param target The DOM EventTarget, Node.js EventEmitter, JQuery-like event target,
* NodeList or HTMLCollection to attach the event handler to.
* @param eventName The event name of interest, being emitted by the `target`.
* @param options Options to pass through to the underlying `addListener`,
* `addEventListener` or `on` functions.
* @param resultSelector A mapping function used to transform events. It takes the
* arguments from the event handler and should return a single value.
* @return An Observable emitting events registered through `target`'s
* listener handlers.
*/
export function fromEvent<T>(
target: any,
eventName: string,
options?: EventListenerOptions | ((...args: any[]) => T),
resultSelector?: (...args: any[]) => T
): Observable<T> {
if (isFunction(options)) {
resultSelector = options;
options = undefined;
}
if (resultSelector) {
return fromEvent<T>(target, eventName, options as EventListenerOptions).pipe(mapOneOrManyArgs(resultSelector));
}
// Figure out our add and remove methods. In order to do this,
// we are going to analyze the target in a preferred order, if
// the target matches a given signature, we take the two "add" and "remove"
// method names and apply them to a map to create opposite versions of the
// same function. This is because they all operate in duplicate pairs,
// `addListener(name, handler)`, `removeListener(name, handler)`, for example.
// The call only differs by method name, as to whether or not you're adding or removing.
const [add, remove] =
// If it is an EventTarget, we need to use a slightly different method than the other two patterns.
isEventTarget(target)
? eventTargetMethods.map((methodName) => (handler: any) => target[methodName](eventName, handler, options as EventListenerOptions))
: // In all other cases, the call pattern is identical with the exception of the method names.
isNodeStyleEventEmitter(target)
? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))
: isJQueryStyleEventEmitter(target)
? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))
: [];
// If add is falsy, it's because we didn't match a pattern above.
// Check to see if it is an ArrayLike, because if it is, we want to
// try to apply fromEvent to all of it's items. We do this check last,
// because there are may be some types that are both ArrayLike *and* implement
// event registry points, and we'd rather delegate to that when possible.
if (!add) {
if (isArrayLike(target)) {
return mergeMap((subTarget: any) => fromEvent(subTarget, eventName, options as EventListenerOptions))(
innerFrom(target)
) as Observable<T>;
}
}
// If add is falsy and we made it here, it's because we didn't
// match any valid target objects above.
if (!add) {
throw new TypeError('Invalid event target');
}
return new Observable<T>((subscriber) => {
// The handler we are going to register. Forwards the event object, by itself, or
// an array of arguments to the event handler, if there is more than one argument,
// to the consumer.
const handler = (...args: any[]) => subscriber.next(1 < args.length ? args : args[0]);
// Do the work of adding the handler to the target.
add(handler);
// When we finalize, we want to remove the handler and free up memory.
return () => remove!(handler);
});
}
/**
* Used to create `add` and `remove` functions to register and unregister event handlers
* from a target in the most common handler pattern, where there are only two arguments.
* (e.g. `on(name, fn)`, `off(name, fn)`, `addListener(name, fn)`, or `removeListener(name, fn)`)
* @param target The target we're calling methods on
* @param eventName The event name for the event we're creating register or unregister functions for
*/
function toCommonHandlerRegistry(target: any, eventName: string) {
return (methodName: string) => (handler: any) => target[methodName](eventName, handler);
}
/**
* Checks to see if the target implements the required node-style EventEmitter methods
* for adding and removing event handlers.
* @param target the object to check
*/
function isNodeStyleEventEmitter(target: any): target is NodeStyleEventEmitter {
return isFunction(target.addListener) && isFunction(target.removeListener);
}
/**
* Checks to see if the target implements the required jQuery-style EventEmitter methods
* for adding and removing event handlers.
* @param target the object to check
*/
function isJQueryStyleEventEmitter(target: any): target is JQueryStyleEventEmitter<any, any> {
return isFunction(target.on) && isFunction(target.off);
}
/**
* Checks to see if the target implements the required EventTarget methods
* for adding and removing event handlers.
* @param target the object to check
*/
function isEventTarget(target: any): target is HasEventTargetAddRemove<any> {
return isFunction(target.addEventListener) && isFunction(target.removeEventListener);
}

View File

@@ -0,0 +1,152 @@
import { Observable } from '../Observable';
import { isFunction } from '../util/isFunction';
import { NodeEventHandler } from './fromEvent';
import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
/* tslint:disable:max-line-length */
export function fromEventPattern<T>(
addHandler: (handler: NodeEventHandler) => any,
removeHandler?: (handler: NodeEventHandler, signal?: any) => void
): Observable<T>;
export function fromEventPattern<T>(
addHandler: (handler: NodeEventHandler) => any,
removeHandler?: (handler: NodeEventHandler, signal?: any) => void,
resultSelector?: (...args: any[]) => T
): Observable<T>;
/* tslint:enable:max-line-length */
/**
* Creates an Observable from an arbitrary API for registering event handlers.
*
* <span class="informal">When that method for adding event handler was something {@link fromEvent}
* was not prepared for.</span>
*
* ![](fromEventPattern.png)
*
* `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions
* for events. It is similar to {@link fromEvent}, but far
* more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by
* `fromEventPattern` (although in slightly more verbose way).
*
* This operator accepts as a first argument an `addHandler` function, which will be injected with
* handler parameter. That handler is actually an event handler function that you now can pass
* to API expecting it. `addHandler` will be called whenever Observable
* returned by the operator is subscribed, so registering handler in API will not
* necessarily happen when `fromEventPattern` is called.
*
* After registration, every time an event that we listen to happens,
* Observable returned by `fromEventPattern` will emit value that event handler
* function was called with. Note that if event handler was called with more
* than one argument, second and following arguments will not appear in the Observable.
*
* If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`
* another function - `removeHandler` - as a second parameter. It will be injected
* with the same handler function as before, which now you can use to unregister
* it from the API. `removeHandler` will be called when consumer of resulting Observable
* unsubscribes from it.
*
* In some APIs unregistering is actually handled differently. Method registering an event handler
* returns some kind of token, which is later used to identify which function should
* be unregistered or it itself has method that unregisters event handler.
* If that is the case with your API, make sure token returned
* by registering method is returned by `addHandler`. Then it will be passed
* as a second argument to `removeHandler`, where you will be able to use it.
*
* If you need access to all event handler parameters (not only the first one),
* or you need to transform them in any way, you can call `fromEventPattern` with optional
* third parameter - project function which will accept all arguments passed to
* event handler when it is called. Whatever is returned from project function will appear on
* resulting stream instead of usual event handlers first argument. This means
* that default project can be thought of as function that takes its first parameter
* and ignores the rest.
*
* ## Examples
*
* Emits clicks happening on the DOM document
*
* ```ts
* import { fromEventPattern } from 'rxjs';
*
* function addClickHandler(handler) {
* document.addEventListener('click', handler);
* }
*
* function removeClickHandler(handler) {
* document.removeEventListener('click', handler);
* }
*
* const clicks = fromEventPattern(
* addClickHandler,
* removeClickHandler
* );
* clicks.subscribe(x => console.log(x));
*
* // Whenever you click anywhere in the browser, DOM MouseEvent
* // object will be logged.
* ```
*
* Use with API that returns cancellation token
*
* ```ts
* import { fromEventPattern } from 'rxjs';
*
* const token = someAPI.registerEventHandler(function() {});
* someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts
* // not handler itself, but special token.
*
* const someAPIObservable = fromEventPattern(
* function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...
* function(handler, token) { someAPI.unregisterEventHandler(token); } // ...to then use it here.
* );
* ```
*
* Use with project function
*
* ```ts
* import { fromEventPattern } from 'rxjs';
*
* someAPI.registerEventHandler((eventType, eventMessage) => {
* console.log(eventType, eventMessage); // Logs 'EVENT_TYPE' 'EVENT_MESSAGE' to console.
* });
*
* const someAPIObservable = fromEventPattern(
* handler => someAPI.registerEventHandler(handler),
* handler => someAPI.unregisterEventHandler(handler)
* (eventType, eventMessage) => eventType + ' --- ' + eventMessage // without that function only 'EVENT_TYPE'
* ); // would be emitted by the Observable
*
* someAPIObservable.subscribe(value => console.log(value));
*
* // Logs:
* // 'EVENT_TYPE --- EVENT_MESSAGE'
* ```
*
* @see {@link fromEvent}
* @see {@link bindCallback}
* @see {@link bindNodeCallback}
*
* @param addHandler A function that takes a `handler` function as argument and attaches it
* somehow to the actual source of events.
* @param removeHandler A function that takes a `handler` function as an argument and removes
* it from the event source. If `addHandler` returns some kind of token, `removeHandler` function
* will have it as a second parameter.
* @param resultSelector A function to transform results. It takes the arguments from the event
* handler and should return a single value.
* @return Observable which, when an event happens, emits first parameter passed to registered
* event handler. Alternatively it emits whatever project function returns at that moment.
*/
export function fromEventPattern<T>(
addHandler: (handler: NodeEventHandler) => any,
removeHandler?: (handler: NodeEventHandler, signal?: any) => void,
resultSelector?: (...args: any[]) => T
): Observable<T | T[]> {
if (resultSelector) {
return fromEventPattern<T>(addHandler, removeHandler).pipe(mapOneOrManyArgs(resultSelector));
}
return new Observable<T | T[]>((subscriber) => {
const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);
const retValue = addHandler(handler);
return isFunction(removeHandler) ? () => removeHandler(handler, retValue) : undefined;
});
}

View File

@@ -0,0 +1,17 @@
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscribable } from '../types';
/**
* Used to convert a subscribable to an observable.
*
* Currently, this is only used within internals.
*
* TODO: Discuss ObservableInput supporting "Subscribable".
* https://github.com/ReactiveX/rxjs/issues/5909
*
* @param subscribable A subscribable
*/
export function fromSubscribable<T>(subscribable: Subscribable<T>) {
return new Observable((subscriber: Subscriber<T>) => subscribable.subscribe(subscriber));
}

387
node_modules/rxjs/src/internal/observable/generate.ts generated vendored Normal file
View File

@@ -0,0 +1,387 @@
import { Observable } from '../Observable';
import { identity } from '../util/identity';
import { ObservableInput, SchedulerLike } from '../types';
import { isScheduler } from '../util/isScheduler';
import { defer } from './defer';
import { scheduleIterable } from '../scheduled/scheduleIterable';
type ConditionFunc<S> = (state: S) => boolean;
type IterateFunc<S> = (state: S) => S;
type ResultFunc<S, T> = (state: S) => T;
export interface GenerateBaseOptions<S> {
/**
* Initial state.
*/
initialState: S;
/**
* Condition function that accepts state and returns boolean.
* When it returns false, the generator stops.
* If not specified, a generator never stops.
*/
condition?: ConditionFunc<S>;
/**
* Iterate function that accepts state and returns new state.
*/
iterate: IterateFunc<S>;
/**
* SchedulerLike to use for generation process.
* By default, a generator starts immediately.
*/
scheduler?: SchedulerLike;
}
export interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {
/**
* Result selection function that accepts state and returns a value to emit.
*/
resultSelector: ResultFunc<S, T>;
}
/**
* Generates an observable sequence by running a state-driven loop
* producing the sequence's elements, using the specified scheduler
* to send out observer messages.
*
* ![](generate.png)
*
* ## Examples
*
* Produces sequence of numbers
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate(0, x => x < 3, x => x + 1, x => x);
*
* result.subscribe(x => console.log(x));
*
* // Logs:
* // 0
* // 1
* // 2
* ```
*
* Use `asapScheduler`
*
* ```ts
* import { generate, asapScheduler } from 'rxjs';
*
* const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asapScheduler);
*
* result.subscribe(x => console.log(x));
*
* // Logs:
* // 2
* // 3
* // 5
* ```
*
* @see {@link from}
* @see {@link Observable}
*
* @param initialState Initial state.
* @param condition Condition to terminate generation (upon returning false).
* @param iterate Iteration step function.
* @param resultSelector Selector function for results produced in the sequence.
* @param scheduler A {@link SchedulerLike} on which to run the generator loop.
* If not provided, defaults to emit immediately.
* @returns The generated sequence.
* @deprecated Instead of passing separate arguments, use the options argument.
* Signatures taking separate arguments will be removed in v8.
*/
export function generate<T, S>(
initialState: S,
condition: ConditionFunc<S>,
iterate: IterateFunc<S>,
resultSelector: ResultFunc<S, T>,
scheduler?: SchedulerLike
): Observable<T>;
/**
* Generates an Observable by running a state-driven loop
* that emits an element on each iteration.
*
* <span class="informal">Use it instead of nexting values in a for loop.</span>
*
* ![](generate.png)
*
* `generate` allows you to create a stream of values generated with a loop very similar to
* a traditional for loop. The first argument of `generate` is a beginning value. The second argument
* is a function that accepts this value and tests if some condition still holds. If it does,
* then the loop continues, if not, it stops. The third value is a function which takes the
* previously defined value and modifies it in some way on each iteration. Note how these three parameters
* are direct equivalents of three expressions in a traditional for loop: the first expression
* initializes some state (for example, a numeric index), the second tests if the loop can perform the next
* iteration (for example, if the index is lower than 10) and the third states how the defined value
* will be modified on every step (for example, the index will be incremented by one).
*
* Return value of a `generate` operator is an Observable that on each loop iteration
* emits a value. First of all, the condition function is ran. If it returns true, then the Observable
* emits the currently stored value (initial value at the first iteration) and finally updates
* that value with iterate function. If at some point the condition returns false, then the Observable
* completes at that moment.
*
* Optionally you can pass a fourth parameter to `generate` - a result selector function which allows you
* to immediately map the value that would normally be emitted by an Observable.
*
* If you find three anonymous functions in `generate` call hard to read, you can provide
* a single object to the operator instead where the object has the properties: `initialState`,
* `condition`, `iterate` and `resultSelector`, which should have respective values that you
* would normally pass to `generate`. `resultSelector` is still optional, but that form
* of calling `generate` allows you to omit `condition` as well. If you omit it, that means
* condition always holds, or in other words the resulting Observable will never complete.
*
* Both forms of `generate` can optionally accept a scheduler. In case of a multi-parameter call,
* scheduler simply comes as a last argument (no matter if there is a `resultSelector`
* function or not). In case of a single-parameter call, you can provide it as a
* `scheduler` property on the object passed to the operator. In both cases, a scheduler decides when
* the next iteration of the loop will happen and therefore when the next value will be emitted
* by the Observable. For example, to ensure that each value is pushed to the Observer
* on a separate task in the event loop, you could use the `async` scheduler. Note that
* by default (when no scheduler is passed) values are simply emitted synchronously.
*
*
* ## Examples
*
* Use with condition and iterate functions
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate(0, x => x < 3, x => x + 1);
*
* result.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // 0
* // 1
* // 2
* // 'Complete!'
* ```
*
* Use with condition, iterate and resultSelector functions
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate(0, x => x < 3, x => x + 1, x => x * 1000);
*
* result.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // 0
* // 1000
* // 2000
* // 'Complete!'
* ```
*
* Use with options object
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate({
* initialState: 0,
* condition(value) { return value < 3; },
* iterate(value) { return value + 1; },
* resultSelector(value) { return value * 1000; }
* });
*
* result.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // 0
* // 1000
* // 2000
* // 'Complete!'
* ```
*
* Use options object without condition function
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate({
* initialState: 0,
* iterate(value) { return value + 1; },
* resultSelector(value) { return value * 1000; }
* });
*
* result.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!') // This will never run
* });
*
* // Logs:
* // 0
* // 1000
* // 2000
* // 3000
* // ...and never stops.
* ```
*
* @see {@link from}
*
* @param initialState Initial state.
* @param condition Condition to terminate generation (upon returning false).
* @param iterate Iteration step function.
* @param scheduler A {@link Scheduler} on which to run the generator loop. If not
* provided, defaults to emitting immediately.
* @return The generated sequence.
* @deprecated Instead of passing separate arguments, use the options argument.
* Signatures taking separate arguments will be removed in v8.
*/
export function generate<S>(
initialState: S,
condition: ConditionFunc<S>,
iterate: IterateFunc<S>,
scheduler?: SchedulerLike
): Observable<S>;
/**
* Generates an observable sequence by running a state-driven loop
* producing the sequence's elements, using the specified scheduler
* to send out observer messages.
* The overload accepts options object that might contain initial state, iterate,
* condition and scheduler.
*
* ![](generate.png)
*
* ## Examples
*
* Use options object with condition function
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate({
* initialState: 0,
* condition: x => x < 3,
* iterate: x => x + 1
* });
*
* result.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // 0
* // 1
* // 2
* // 'Complete!'
* ```
*
* @see {@link from}
* @see {@link Observable}
*
* @param options Object that must contain initialState, iterate and might contain condition and scheduler.
* @returns The generated sequence.
*/
export function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;
/**
* Generates an observable sequence by running a state-driven loop
* producing the sequence's elements, using the specified scheduler
* to send out observer messages.
* The overload accepts options object that might contain initial state, iterate,
* condition, result selector and scheduler.
*
* ![](generate.png)
*
* ## Examples
*
* Use options object with condition and iterate function
*
* ```ts
* import { generate } from 'rxjs';
*
* const result = generate({
* initialState: 0,
* condition: x => x < 3,
* iterate: x => x + 1,
* resultSelector: x => x
* });
*
* result.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // 0
* // 1
* // 2
* // 'Complete!'
* ```
*
* @see {@link from}
* @see {@link Observable}
*
* @param options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.
* @returns The generated sequence.
*/
export function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;
export function generate<T, S>(
initialStateOrOptions: S | GenerateOptions<T, S>,
condition?: ConditionFunc<S>,
iterate?: IterateFunc<S>,
resultSelectorOrScheduler?: ResultFunc<S, T> | SchedulerLike,
scheduler?: SchedulerLike
): Observable<T> {
let resultSelector: ResultFunc<S, T>;
let initialState: S;
// TODO: Remove this as we move away from deprecated signatures
// and move towards a configuration object argument.
if (arguments.length === 1) {
// If we only have one argument, we can assume it is a configuration object.
// Note that folks not using TypeScript may trip over this.
({
initialState,
condition,
iterate,
resultSelector = identity as ResultFunc<S, T>,
scheduler,
} = initialStateOrOptions as GenerateOptions<T, S>);
} else {
// Deprecated arguments path. Figure out what the user
// passed and set it here.
initialState = initialStateOrOptions as S;
if (!resultSelectorOrScheduler || isScheduler(resultSelectorOrScheduler)) {
resultSelector = identity as ResultFunc<S, T>;
scheduler = resultSelectorOrScheduler as SchedulerLike;
} else {
resultSelector = resultSelectorOrScheduler as ResultFunc<S, T>;
}
}
// The actual generator used to "generate" values.
function* gen() {
for (let state = initialState; !condition || condition(state); state = iterate!(state)) {
yield resultSelector(state);
}
}
// We use `defer` because we want to defer the creation of the iterator from the iterable.
return defer(
(scheduler
? // If a scheduler was provided, use `scheduleIterable` to ensure that iteration/generation
// happens on the scheduler.
() => scheduleIterable(gen(), scheduler!)
: // Otherwise, if there's no scheduler, we can just use the generator function directly in
// `defer` and executing it will return the generator (which is iterable).
gen) as () => ObservableInput<T>
);
}

85
node_modules/rxjs/src/internal/observable/iif.ts generated vendored Normal file
View File

@@ -0,0 +1,85 @@
import { Observable } from '../Observable';
import { defer } from './defer';
import { ObservableInput } from '../types';
/**
* Checks a boolean at subscription time, and chooses between one of two observable sources
*
* `iif` expects a function that returns a boolean (the `condition` function), and two sources,
* the `trueResult` and the `falseResult`, and returns an Observable.
*
* At the moment of subscription, the `condition` function is called. If the result is `true`, the
* subscription will be to the source passed as the `trueResult`, otherwise, the subscription will be
* to the source passed as the `falseResult`.
*
* 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.
*
* ## Examples
*
* Change at runtime which Observable will be subscribed
*
* ```ts
* import { iif, of } from 'rxjs';
*
* let subscribeToFirst;
* const firstOrSecond = iif(
* () => subscribeToFirst,
* of('first'),
* of('second')
* );
*
* subscribeToFirst = true;
* firstOrSecond.subscribe(value => console.log(value));
*
* // Logs:
* // 'first'
*
* subscribeToFirst = false;
* firstOrSecond.subscribe(value => console.log(value));
*
* // Logs:
* // 'second'
* ```
*
* Control access to an Observable
*
* ```ts
* import { iif, of, EMPTY } from 'rxjs';
*
* let accessGranted;
* const observableIfYouHaveAccess = iif(
* () => accessGranted,
* of('It seems you have an access...'),
* EMPTY
* );
*
* accessGranted = true;
* observableIfYouHaveAccess.subscribe({
* next: value => console.log(value),
* complete: () => console.log('The end')
* });
*
* // Logs:
* // 'It seems you have an access...'
* // 'The end'
*
* accessGranted = false;
* observableIfYouHaveAccess.subscribe({
* next: value => console.log(value),
* complete: () => console.log('The end')
* });
*
* // Logs:
* // 'The end'
* ```
*
* @see {@link defer}
*
* @param condition Condition which Observable should be chosen.
* @param trueResult An Observable that will be subscribed if condition is true.
* @param falseResult An Observable that will be subscribed if condition is false.
* @return An observable that proxies to `trueResult` or `falseResult`, depending on the result of the `condition` function.
*/
export function iif<T, F>(condition: () => boolean, trueResult: ObservableInput<T>, falseResult: ObservableInput<F>): Observable<T | F> {
return defer(() => (condition() ? trueResult : falseResult));
}

132
node_modules/rxjs/src/internal/observable/innerFrom.ts generated vendored Normal file
View File

@@ -0,0 +1,132 @@
import { isArrayLike } from '../util/isArrayLike';
import { isPromise } from '../util/isPromise';
import { Observable } from '../Observable';
import { ObservableInput, ObservedValueOf, ReadableStreamLike } from '../types';
import { isInteropObservable } from '../util/isInteropObservable';
import { isAsyncIterable } from '../util/isAsyncIterable';
import { createInvalidObservableTypeError } from '../util/throwUnobservableError';
import { isIterable } from '../util/isIterable';
import { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';
import { Subscriber } from '../Subscriber';
import { isFunction } from '../util/isFunction';
import { reportUnhandledError } from '../util/reportUnhandledError';
import { observable as Symbol_observable } from '../symbol/observable';
export function innerFrom<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;
export function innerFrom<T>(input: ObservableInput<T>): Observable<T> {
if (input instanceof Observable) {
return input;
}
if (input != null) {
if (isInteropObservable(input)) {
return fromInteropObservable(input);
}
if (isArrayLike(input)) {
return fromArrayLike(input);
}
if (isPromise(input)) {
return fromPromise(input);
}
if (isAsyncIterable(input)) {
return fromAsyncIterable(input);
}
if (isIterable(input)) {
return fromIterable(input);
}
if (isReadableStreamLike(input)) {
return fromReadableStreamLike(input);
}
}
throw createInvalidObservableTypeError(input);
}
/**
* Creates an RxJS Observable from an object that implements `Symbol.observable`.
* @param obj An object that properly implements `Symbol.observable`.
*/
export function fromInteropObservable<T>(obj: any) {
return new Observable((subscriber: Subscriber<T>) => {
const obs = obj[Symbol_observable]();
if (isFunction(obs.subscribe)) {
return obs.subscribe(subscriber);
}
// Should be caught by observable subscribe function error handling.
throw new TypeError('Provided object does not correctly implement Symbol.observable');
});
}
/**
* Synchronously emits the values of an array like and completes.
* This is exported because there are creation functions and operators that need to
* make direct use of the same logic, and there's no reason to make them run through
* `from` conditionals because we *know* they're dealing with an array.
* @param array The array to emit values from
*/
export function fromArrayLike<T>(array: ArrayLike<T>) {
return new Observable((subscriber: Subscriber<T>) => {
// Loop over the array and emit each value. Note two things here:
// 1. We're making sure that the subscriber is not closed on each loop.
// This is so we don't continue looping over a very large array after
// something like a `take`, `takeWhile`, or other synchronous unsubscription
// has already unsubscribed.
// 2. In this form, reentrant code can alter that array we're looping over.
// This is a known issue, but considered an edge case. The alternative would
// be to copy the array before executing the loop, but this has
// performance implications.
for (let i = 0; i < array.length && !subscriber.closed; i++) {
subscriber.next(array[i]);
}
subscriber.complete();
});
}
export function fromPromise<T>(promise: PromiseLike<T>) {
return new Observable((subscriber: Subscriber<T>) => {
promise
.then(
(value) => {
if (!subscriber.closed) {
subscriber.next(value);
subscriber.complete();
}
},
(err: any) => subscriber.error(err)
)
.then(null, reportUnhandledError);
});
}
export function fromIterable<T>(iterable: Iterable<T>) {
return new Observable((subscriber: Subscriber<T>) => {
for (const value of iterable) {
subscriber.next(value);
if (subscriber.closed) {
return;
}
}
subscriber.complete();
});
}
export function fromAsyncIterable<T>(asyncIterable: AsyncIterable<T>) {
return new Observable((subscriber: Subscriber<T>) => {
process(asyncIterable, subscriber).catch((err) => subscriber.error(err));
});
}
export function fromReadableStreamLike<T>(readableStream: ReadableStreamLike<T>) {
return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
}
async function process<T>(asyncIterable: AsyncIterable<T>, subscriber: Subscriber<T>) {
for await (const value of asyncIterable) {
subscriber.next(value);
// A side-effect may have closed our subscriber,
// check before the next iteration.
if (subscriber.closed) {
return;
}
}
subscriber.complete();
}

57
node_modules/rxjs/src/internal/observable/interval.ts generated vendored Normal file
View File

@@ -0,0 +1,57 @@
import { Observable } from '../Observable';
import { asyncScheduler } from '../scheduler/async';
import { SchedulerLike } from '../types';
import { timer } from './timer';
/**
* Creates an Observable that emits sequential numbers every specified
* interval of time, on a specified {@link SchedulerLike}.
*
* <span class="informal">Emits incremental numbers periodically in time.</span>
*
* ![](interval.png)
*
* `interval` returns an Observable that emits an infinite sequence of
* ascending integers, with a constant interval of time of your choosing
* between those emissions. The first emission is not sent immediately, but
* only after the first period has passed. By default, this operator uses the
* `async` {@link SchedulerLike} to provide a notion of time, but you may pass any
* {@link SchedulerLike} to it.
*
* ## Example
*
* Emits ascending numbers, one every second (1000ms) up to the number 3
*
* ```ts
* import { interval, take } from 'rxjs';
*
* const numbers = interval(1000);
*
* const takeFourNumbers = numbers.pipe(take(4));
*
* takeFourNumbers.subscribe(x => console.log('Next: ', x));
*
* // Logs:
* // Next: 0
* // Next: 1
* // Next: 2
* // Next: 3
* ```
*
* @see {@link timer}
* @see {@link delay}
*
* @param period The interval size in milliseconds (by default) or the time unit determined
* by the scheduler's clock.
* @param scheduler The {@link SchedulerLike} to use for scheduling the emission of values,
* and providing a notion of "time".
* @return An Observable that emits a sequential number each time interval.
*/
export function interval(period = 0, scheduler: SchedulerLike = asyncScheduler): Observable<number> {
if (period < 0) {
// We cannot schedule an interval in the past.
period = 0;
}
return timer(period, period, scheduler);
}

100
node_modules/rxjs/src/internal/observable/merge.ts generated vendored Normal file
View File

@@ -0,0 +1,100 @@
import { Observable } from '../Observable';
import { ObservableInput, ObservableInputTuple, SchedulerLike } from '../types';
import { mergeAll } from '../operators/mergeAll';
import { innerFrom } from './innerFrom';
import { EMPTY } from './empty';
import { popNumber, popScheduler } from '../util/args';
import { from } from './from';
export function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;
export function merge<A extends readonly unknown[]>(...sourcesAndConcurrency: [...ObservableInputTuple<A>, number?]): Observable<A[number]>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `mergeAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function merge<A extends readonly unknown[]>(
...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike?]
): Observable<A[number]>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `mergeAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function merge<A extends readonly unknown[]>(
...sourcesAndConcurrencyAndScheduler: [...ObservableInputTuple<A>, number?, SchedulerLike?]
): Observable<A[number]>;
/**
* Creates an output Observable which concurrently emits all values from every
* given input Observable.
*
* <span class="informal">Flattens multiple Observables together by blending
* their values into one Observable.</span>
*
* ![](merge.png)
*
* `merge` subscribes to each given input Observable (as arguments), and simply
* forwards (without doing any transformation) all the values from all the input
* Observables to the output Observable. The output Observable only completes
* once all input Observables have completed. Any error delivered by an input
* Observable will be immediately emitted on the output Observable.
*
* ## Examples
*
* Merge together two Observables: 1s interval and clicks
*
* ```ts
* import { merge, fromEvent, interval } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const timer = interval(1000);
* const clicksOrTimer = merge(clicks, timer);
* clicksOrTimer.subscribe(x => console.log(x));
*
* // Results in the following:
* // timer will emit ascending values, one every second(1000ms) to console
* // clicks logs MouseEvents to console every time the "document" is clicked
* // Since the two streams are merged you see these happening
* // as they occur.
* ```
*
* Merge together 3 Observables, but run only 2 concurrently
*
* ```ts
* import { interval, take, merge } from 'rxjs';
*
* const timer1 = interval(1000).pipe(take(10));
* const timer2 = interval(2000).pipe(take(6));
* const timer3 = interval(500).pipe(take(10));
*
* const concurrent = 2; // the argument
* const merged = merge(timer1, timer2, timer3, concurrent);
* merged.subscribe(x => console.log(x));
*
* // Results in the following:
* // - First timer1 and timer2 will run concurrently
* // - timer1 will emit a value every 1000ms for 10 iterations
* // - timer2 will emit a value every 2000ms for 6 iterations
* // - after timer1 hits its max iteration, timer2 will
* // continue, and timer3 will start to run concurrently with timer2
* // - when timer2 hits its max iteration it terminates, and
* // timer3 will continue to emit a value every 500ms until it is complete
* ```
*
* @see {@link mergeAll}
* @see {@link mergeMap}
* @see {@link mergeMapTo}
* @see {@link mergeScan}
*
* @param args `ObservableInput`s to merge together. If the last parameter
* is of type number, `merge` will use it to limit number of concurrently
* subscribed `ObservableInput`s. If the last parameter is {@link SchedulerLike},
* it will be used for scheduling the emission of values.
* @return An Observable that emits items that are the result of every input Observable.
*/
export function merge(...args: (ObservableInput<unknown> | number | SchedulerLike)[]): Observable<unknown> {
const scheduler = popScheduler(args);
const concurrent = popNumber(args, Infinity);
const sources = args as ObservableInput<unknown>[];
return !sources.length
? // No source provided
EMPTY
: sources.length === 1
? // One source? Just return it.
innerFrom(sources[0])
: // Merge all sources
mergeAll(concurrent)(from(sources, scheduler));
}

44
node_modules/rxjs/src/internal/observable/never.ts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { Observable } from '../Observable';
import { noop } from '../util/noop';
/**
* An Observable that emits no items to the Observer and never completes.
*
* ![](never.png)
*
* A simple Observable that emits neither values nor errors nor the completion
* notification. It can be used for testing purposes or for composing with other
* Observables. Please note that by never emitting a complete notification, this
* Observable keeps the subscription from being disposed automatically.
* Subscriptions need to be manually disposed.
*
* ## Example
*
* Emit the number 7, then never emit anything else (not even complete)
*
* ```ts
* import { NEVER, startWith } from 'rxjs';
*
* const info = () => console.log('Will not be called');
*
* const result = NEVER.pipe(startWith(7));
* result.subscribe({
* next: x => console.log(x),
* error: info,
* complete: info
* });
* ```
*
* @see {@link Observable}
* @see {@link EMPTY}
* @see {@link of}
* @see {@link throwError}
*/
export const NEVER = new Observable<never>(noop);
/**
* @deprecated Replaced with the {@link NEVER} constant. Will be removed in v8.
*/
export function never() {
return NEVER;
}

83
node_modules/rxjs/src/internal/observable/of.ts generated vendored Normal file
View File

@@ -0,0 +1,83 @@
import { SchedulerLike, ValueFromArray } from '../types';
import { Observable } from '../Observable';
import { popScheduler } from '../util/args';
import { from } from './from';
// Devs are more likely to pass null or undefined than they are a scheduler
// without accompanying values. To make things easier for (naughty) devs who
// use the `strictNullChecks: false` TypeScript compiler option, these
// overloads with explicit null and undefined values are included.
export function of(value: null): Observable<null>;
export function of(value: undefined): Observable<undefined>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function of(scheduler: SchedulerLike): Observable<never>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function of<A extends readonly unknown[]>(...valuesAndScheduler: [...A, SchedulerLike]): Observable<ValueFromArray<A>>;
export function of(): Observable<never>;
/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */
export function of<T>(): Observable<T>;
export function of<T>(value: T): Observable<T>;
export function of<A extends readonly unknown[]>(...values: A): Observable<ValueFromArray<A>>;
/**
* Converts the arguments to an observable sequence.
*
* <span class="informal">Each argument becomes a `next` notification.</span>
*
* ![](of.png)
*
* Unlike {@link from}, it does not do any flattening and emits each argument in whole
* as a separate `next` notification.
*
* ## Examples
*
* Emit the values `10, 20, 30`
*
* ```ts
* import { of } from 'rxjs';
*
* of(10, 20, 30)
* .subscribe({
* next: value => console.log('next:', value),
* error: err => console.log('error:', err),
* complete: () => console.log('the end'),
* });
*
* // Outputs
* // next: 10
* // next: 20
* // next: 30
* // the end
* ```
*
* Emit the array `[1, 2, 3]`
*
* ```ts
* import { of } from 'rxjs';
*
* of([1, 2, 3])
* .subscribe({
* next: value => console.log('next:', value),
* error: err => console.log('error:', err),
* complete: () => console.log('the end'),
* });
*
* // Outputs
* // next: [1, 2, 3]
* // the end
* ```
*
* @see {@link from}
* @see {@link range}
*
* @param args A comma separated list of arguments you want to be emitted.
* @return An Observable that synchronously emits the arguments described
* above and then immediately completes.
*/
export function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {
const scheduler = popScheduler(args);
return from(args as T[], scheduler);
}

View File

@@ -0,0 +1,98 @@
import { Observable } from '../Observable';
import { ObservableInputTuple } from '../types';
import { argsOrArgArray } from '../util/argsOrArgArray';
import { OperatorSubscriber } from '../operators/OperatorSubscriber';
import { noop } from '../util/noop';
import { innerFrom } from './innerFrom';
export function onErrorResumeNext<A extends readonly unknown[]>(sources: [...ObservableInputTuple<A>]): Observable<A[number]>;
export function onErrorResumeNext<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;
/**
* When any of the provided Observable emits a complete or an error notification, it immediately subscribes to the next one
* that was passed.
*
* <span class="informal">Execute series of Observables no matter what, even if it means swallowing errors.</span>
*
* ![](onErrorResumeNext.png)
*
* `onErrorResumeNext` will subscribe to each observable source it is provided, in order.
* If the source it's subscribed to emits an error or completes, it will move to the next source
* without error.
*
* If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link EMPTY}.
*
* `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its
* sources emits an error.
*
* Note that there is no way to handle any errors thrown by sources via the result of
* `onErrorResumeNext`. If you want to handle errors thrown in any given source, you can
* always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`.
*
* ## Example
*
* Subscribe to the next Observable after map fails
*
* ```ts
* import { onErrorResumeNext, of, map } from 'rxjs';
*
* onErrorResumeNext(
* of(1, 2, 3, 0).pipe(
* map(x => {
* if (x === 0) {
* throw Error();
* }
* return 10 / x;
* })
* ),
* of(1, 2, 3)
* )
* .subscribe({
* next: value => console.log(value),
* error: err => console.log(err), // Will never be called.
* complete: () => console.log('done')
* });
*
* // Logs:
* // 10
* // 5
* // 3.3333333333333335
* // 1
* // 2
* // 3
* // 'done'
* ```
*
* @see {@link concat}
* @see {@link catchError}
*
* @param sources `ObservableInput`s passed either directly or as an array.
* @return An Observable that concatenates all sources, one after the other,
* ignoring all errors, such that any error causes it to move on to the next source.
*/
export function onErrorResumeNext<A extends readonly unknown[]>(
...sources: [[...ObservableInputTuple<A>]] | [...ObservableInputTuple<A>]
): Observable<A[number]> {
const nextSources: ObservableInputTuple<A> = argsOrArgArray(sources) as any;
return new Observable((subscriber) => {
let sourceIndex = 0;
const subscribeNext = () => {
if (sourceIndex < nextSources.length) {
let nextSource: Observable<A[number]>;
try {
nextSource = innerFrom(nextSources[sourceIndex++]);
} catch (err) {
subscribeNext();
return;
}
const innerSubscriber = new OperatorSubscriber(subscriber, undefined, noop, noop);
nextSource.subscribe(innerSubscriber);
innerSubscriber.add(subscribeNext);
} else {
subscriber.complete();
}
};
subscribeNext();
});
}

80
node_modules/rxjs/src/internal/observable/pairs.ts generated vendored Normal file
View File

@@ -0,0 +1,80 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { from } from './from';
/**
* @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.
*/
export function pairs<T>(arr: readonly T[], scheduler?: SchedulerLike): Observable<[string, T]>;
/**
* @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.
*/
export function pairs<O extends Record<string, unknown>>(obj: O, scheduler?: SchedulerLike): Observable<[keyof O, O[keyof O]]>;
/**
* @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.
*/
export function pairs<T>(iterable: Iterable<T>, scheduler?: SchedulerLike): Observable<[string, T]>;
/**
* @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.
*/
export function pairs(
n: number | bigint | boolean | ((...args: any[]) => any) | symbol,
scheduler?: SchedulerLike
): Observable<[never, never]>;
/**
* Convert an object into an Observable of `[key, value]` pairs.
*
* <span class="informal">Turn entries of an object into a stream.</span>
*
* ![](pairs.png)
*
* `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each
* emitted array has exactly two elements - the first is a key from the object
* and the second is a value corresponding to that key. Keys are extracted from
* an object via `Object.keys` function, which means that they will be only
* enumerable keys that are present on an object directly - not ones inherited
* via prototype chain.
*
* By default, these arrays are emitted synchronously. To change that you can
* pass a {@link SchedulerLike} as a second argument to `pairs`.
*
* ## Example
*
* Converts an object to an Observable
*
* ```ts
* import { pairs } from 'rxjs';
*
* const obj = {
* foo: 42,
* bar: 56,
* baz: 78
* };
*
* pairs(obj).subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // ['foo', 42]
* // ['bar', 56]
* // ['baz', 78]
* // 'Complete!'
* ```
*
* ### Object.entries required
*
* In IE, you will need to polyfill `Object.entries` in order to use this.
* [MDN has a polyfill here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
*
* @param obj The object to inspect and turn into an Observable sequence.
* @param scheduler An optional IScheduler to schedule when resulting
* Observable will emit values.
* @returns An observable sequence of [key, value] pairs from the object.
* @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.
*/
export function pairs(obj: any, scheduler?: SchedulerLike) {
return from(Object.entries(obj), scheduler as any);
}

88
node_modules/rxjs/src/internal/observable/partition.ts generated vendored Normal file
View File

@@ -0,0 +1,88 @@
import { not } from '../util/not';
import { filter } from '../operators/filter';
import { ObservableInput } from '../types';
import { Observable } from '../Observable';
import { innerFrom } from './innerFrom';
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function partition<T, U extends T, A>(
source: ObservableInput<T>,
predicate: (this: A, value: T, index: number) => value is U,
thisArg: A
): [Observable<U>, Observable<Exclude<T, U>>];
export function partition<T, U extends T>(
source: ObservableInput<T>,
predicate: (value: T, index: number) => value is U
): [Observable<U>, Observable<Exclude<T, U>>];
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function partition<T, A>(
source: ObservableInput<T>,
predicate: (this: A, value: T, index: number) => boolean,
thisArg: A
): [Observable<T>, Observable<T>];
export function partition<T>(source: ObservableInput<T>, predicate: (value: T, index: number) => boolean): [Observable<T>, Observable<T>];
/**
* Splits the source Observable into two, one with values that satisfy a
* predicate, and another with values that don't satisfy the predicate.
*
* <span class="informal">It's like {@link filter}, but returns two Observables:
* one like the output of {@link filter}, and the other with values that did not
* pass the condition.</span>
*
* ![](partition.png)
*
* `partition` outputs an array with two Observables that partition the values
* from the source Observable through the given `predicate` function. The first
* Observable in that array emits source values for which the predicate argument
* returns true. The second Observable emits source values for which the
* predicate returns false. The first behaves like {@link filter} and the second
* behaves like {@link filter} with the predicate negated.
*
* ## Example
*
* Partition a set of numbers into odds and evens observables
*
* ```ts
* import { of, partition } from 'rxjs';
*
* const observableValues = of(1, 2, 3, 4, 5, 6);
* const [evens$, odds$] = partition(observableValues, value => value % 2 === 0);
*
* odds$.subscribe(x => console.log('odds', x));
* evens$.subscribe(x => console.log('evens', x));
*
* // Logs:
* // odds 1
* // odds 3
* // odds 5
* // evens 2
* // evens 4
* // evens 6
* ```
*
* @see {@link filter}
*
* @param source The source `ObservableInput` that will be split into a tuple of
* two Observable elements.
* @param predicate A function that evaluates each value emitted by the source
* Observable. If it returns `true`, the value is emitted on the first Observable
* in the returned array, if `false` the value is emitted on the second Observable
* in the array. The `index` parameter is the number `i` for the i-th source
* emission that has happened since the subscription, starting from the number `0`.
* @param thisArg An optional argument to determine the value of `this` in the
* `predicate` function.
* @return An array with two Observables: one with values that passed the
* predicate, and another with values that did not pass the predicate.
*/
export function partition<T>(
source: ObservableInput<T>,
predicate: (this: any, value: T, index: number) => boolean,
thisArg?: any
): [Observable<T>, Observable<T>] {
return [filter(predicate, thisArg)(innerFrom(source)), filter(not(predicate, thisArg))(innerFrom(source))] as [
Observable<T>,
Observable<T>
];
}

88
node_modules/rxjs/src/internal/observable/race.ts generated vendored Normal file
View File

@@ -0,0 +1,88 @@
import { Observable } from '../Observable';
import { innerFrom } from './innerFrom';
import { Subscription } from '../Subscription';
import { ObservableInput, ObservableInputTuple } from '../types';
import { argsOrArgArray } from '../util/argsOrArgArray';
import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
import { Subscriber } from '../Subscriber';
export function race<T extends readonly unknown[]>(inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;
export function race<T extends readonly unknown[]>(...inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;
/**
* Returns an observable that mirrors the first source observable to emit an item.
*
* ![](race.png)
*
* `race` returns an observable, that when subscribed to, subscribes to all source observables immediately.
* As soon as one of the source observables emits a value, the result unsubscribes from the other sources.
* The resulting observable will forward all notifications, including error and completion, from the "winning"
* source observable.
*
* If one of the used source observable throws an errors before a first notification
* the race operator will also throw an error, no matter if another source observable
* could potentially win the race.
*
* `race` can be useful for selecting the response from the fastest network connection for
* HTTP or WebSockets. `race` can also be useful for switching observable context based on user
* input.
*
* ## Example
*
* Subscribes to the observable that was the first to start emitting.
*
* ```ts
* import { interval, map, race } from 'rxjs';
*
* const obs1 = interval(7000).pipe(map(() => 'slow one'));
* const obs2 = interval(3000).pipe(map(() => 'fast one'));
* const obs3 = interval(5000).pipe(map(() => 'medium one'));
*
* race(obs1, obs2, obs3)
* .subscribe(winner => console.log(winner));
*
* // Outputs
* // a series of 'fast one'
* ```
*
* @param sources Used to race for which `ObservableInput` emits first.
* @return An Observable that mirrors the output of the first Observable to emit an item.
*/
export function race<T>(...sources: (ObservableInput<T> | ObservableInput<T>[])[]): Observable<any> {
sources = argsOrArgArray(sources);
// If only one source was passed, just return it. Otherwise return the race.
return sources.length === 1 ? innerFrom(sources[0] as ObservableInput<T>) : new Observable<T>(raceInit(sources as ObservableInput<T>[]));
}
/**
* An observable initializer function for both the static version and the
* operator version of race.
* @param sources The sources to race
*/
export function raceInit<T>(sources: ObservableInput<T>[]) {
return (subscriber: Subscriber<T>) => {
let subscriptions: Subscription[] = [];
// Subscribe to all of the sources. Note that we are checking `subscriptions` here
// Is is an array of all actively "racing" subscriptions, and it is `null` after the
// race has been won. So, if we have racer that synchronously "wins", this loop will
// stop before it subscribes to any more.
for (let i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {
subscriptions.push(
innerFrom(sources[i] as ObservableInput<T>).subscribe(
createOperatorSubscriber(subscriber, (value) => {
if (subscriptions) {
// We're still racing, but we won! So unsubscribe
// all other subscriptions that we have, except this one.
for (let s = 0; s < subscriptions.length; s++) {
s !== i && subscriptions[s].unsubscribe();
}
subscriptions = null!;
}
subscriber.next(value);
})
)
);
}
};
}

93
node_modules/rxjs/src/internal/observable/range.ts generated vendored Normal file
View File

@@ -0,0 +1,93 @@
import { SchedulerLike } from '../types';
import { Observable } from '../Observable';
import { EMPTY } from './empty';
export function range(start: number, count?: number): Observable<number>;
/**
* @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
*/
export function range(start: number, count: number | undefined, scheduler: SchedulerLike): Observable<number>;
/**
* Creates an Observable that emits a sequence of numbers within a specified
* range.
*
* <span class="informal">Emits a sequence of numbers in a range.</span>
*
* ![](range.png)
*
* `range` operator emits a range of sequential integers, in order, where you
* select the `start` of the range and its `length`. By default, uses no
* {@link SchedulerLike} and just delivers the notifications synchronously, but may use
* an optional {@link SchedulerLike} to regulate those deliveries.
*
* ## Example
*
* Produce a range of numbers
*
* ```ts
* import { range } from 'rxjs';
*
* const numbers = range(1, 3);
*
* numbers.subscribe({
* next: value => console.log(value),
* complete: () => console.log('Complete!')
* });
*
* // Logs:
* // 1
* // 2
* // 3
* // 'Complete!'
* ```
*
* @see {@link timer}
* @see {@link interval}
*
* @param start The value of the first integer in the sequence.
* @param count The number of sequential integers to generate.
* @param scheduler A {@link SchedulerLike} to use for scheduling the emissions
* of the notifications.
* @return An Observable of numbers that emits a finite range of sequential integers.
*/
export function range(start: number, count?: number, scheduler?: SchedulerLike): Observable<number> {
if (count == null) {
// If one argument was passed, it's the count, not the start.
count = start;
start = 0;
}
if (count <= 0) {
// No count? We're going nowhere. Return EMPTY.
return EMPTY;
}
// Where the range should stop.
const end = count + start;
return new Observable(
scheduler
? // The deprecated scheduled path.
(subscriber) => {
let n = start;
return scheduler.schedule(function () {
if (n < end) {
subscriber.next(n++);
this.schedule();
} else {
subscriber.complete();
}
});
}
: // Standard synchronous range.
(subscriber) => {
let n = start;
while (n < end && !subscriber.closed) {
subscriber.next(n++);
}
subscriber.complete();
}
);
}

125
node_modules/rxjs/src/internal/observable/throwError.ts generated vendored Normal file
View File

@@ -0,0 +1,125 @@
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { SchedulerLike } from '../types';
import { isFunction } from '../util/isFunction';
/**
* Creates an observable that will create an error instance and push it to the consumer as an error
* immediately upon subscription.
*
* <span class="informal">Just errors and does nothing else</span>
*
* ![](throw.png)
*
* This creation function is useful for creating an observable that will create an error and error every
* time it is subscribed to. Generally, inside of most operators when you might want to return an errored
* observable, this is unnecessary. In most cases, such as in the inner return of {@link concatMap},
* {@link mergeMap}, {@link defer}, and many others, you can simply throw the error, and RxJS will pick
* that up and notify the consumer of the error.
*
* ## Example
*
* Create a simple observable that will create a new error with a timestamp and log it
* and the message every time you subscribe to it
*
* ```ts
* import { throwError } from 'rxjs';
*
* let errorCount = 0;
*
* const errorWithTimestamp$ = throwError(() => {
* const error: any = new Error(`This is error number ${ ++errorCount }`);
* error.timestamp = Date.now();
* return error;
* });
*
* errorWithTimestamp$.subscribe({
* error: err => console.log(err.timestamp, err.message)
* });
*
* errorWithTimestamp$.subscribe({
* error: err => console.log(err.timestamp, err.message)
* });
*
* // Logs the timestamp and a new error message for each subscription
* ```
*
* ### Unnecessary usage
*
* Using `throwError` inside of an operator or creation function
* with a callback, is usually not necessary
*
* ```ts
* import { of, concatMap, timer, throwError } from 'rxjs';
*
* const delays$ = of(1000, 2000, Infinity, 3000);
*
* delays$.pipe(
* concatMap(ms => {
* if (ms < 10000) {
* return timer(ms);
* } else {
* // This is probably overkill.
* return throwError(() => new Error(`Invalid time ${ ms }`));
* }
* })
* )
* .subscribe({
* next: console.log,
* error: console.error
* });
* ```
*
* You can just throw the error instead
*
* ```ts
* import { of, concatMap, timer } from 'rxjs';
*
* const delays$ = of(1000, 2000, Infinity, 3000);
*
* delays$.pipe(
* concatMap(ms => {
* if (ms < 10000) {
* return timer(ms);
* } else {
* // Cleaner and easier to read for most folks.
* throw new Error(`Invalid time ${ ms }`);
* }
* })
* )
* .subscribe({
* next: console.log,
* error: console.error
* });
* ```
*
* @param errorFactory A factory function that will create the error instance that is pushed.
*/
export function throwError(errorFactory: () => any): Observable<never>;
/**
* Returns an observable that will error with the specified error immediately upon subscription.
*
* @param error The error instance to emit
* @deprecated Support for passing an error value will be removed in v8. Instead, pass a factory function to `throwError(() => new Error('test'))`. This is
* because it will create the error at the moment it should be created and capture a more appropriate stack trace. If
* for some reason you need to create the error ahead of time, you can still do that: `const err = new Error('test'); throwError(() => err);`.
*/
export function throwError(error: any): Observable<never>;
/**
* Notifies the consumer of an error using a given scheduler by scheduling it at delay `0` upon subscription.
*
* @param errorOrErrorFactory An error instance or error factory
* @param scheduler A scheduler to use to schedule the error notification
* @deprecated The `scheduler` parameter will be removed in v8.
* Use `throwError` in combination with {@link observeOn}: `throwError(() => new Error('test')).pipe(observeOn(scheduler));`.
* Details: https://rxjs.dev/deprecations/scheduler-argument
*/
export function throwError(errorOrErrorFactory: any, scheduler: SchedulerLike): Observable<never>;
export function throwError(errorOrErrorFactory: any, scheduler?: SchedulerLike): Observable<never> {
const errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory;
const init = (subscriber: Subscriber<never>) => subscriber.error(errorFactory());
return new Observable(scheduler ? (subscriber) => scheduler.schedule(init as any, 0, subscriber) : init);
}

186
node_modules/rxjs/src/internal/observable/timer.ts generated vendored Normal file
View File

@@ -0,0 +1,186 @@
import { Observable } from '../Observable';
import { SchedulerLike } from '../types';
import { async as asyncScheduler } from '../scheduler/async';
import { isScheduler } from '../util/isScheduler';
import { isValidDate } from '../util/isDate';
/**
* Creates an observable that will wait for a specified time period, or exact date, before
* emitting the number 0.
*
* <span class="informal">Used to emit a notification after a delay.</span>
*
* This observable is useful for creating delays in code, or racing against other values
* for ad-hoc timeouts.
*
* The `delay` is specified by default in milliseconds, however providing a custom scheduler could
* create a different behavior.
*
* ## Examples
*
* Wait 3 seconds and start another observable
*
* You might want to use `timer` to delay subscription to an
* observable by a set amount of time. Here we use a timer with
* {@link concatMapTo} or {@link concatMap} in order to wait
* a few seconds and start a subscription to a source.
*
* ```ts
* import { of, timer, concatMap } from 'rxjs';
*
* // This could be any observable
* const source = of(1, 2, 3);
*
* timer(3000)
* .pipe(concatMap(() => source))
* .subscribe(console.log);
* ```
*
* Take all values until the start of the next minute
*
* Using a `Date` as the trigger for the first emission, you can
* do things like wait until midnight to fire an event, or in this case,
* wait until a new minute starts (chosen so the example wouldn't take
* too long to run) in order to stop watching a stream. Leveraging
* {@link takeUntil}.
*
* ```ts
* import { interval, takeUntil, timer } from 'rxjs';
*
* // Build a Date object that marks the
* // next minute.
* const currentDate = new Date();
* const startOfNextMinute = new Date(
* currentDate.getFullYear(),
* currentDate.getMonth(),
* currentDate.getDate(),
* currentDate.getHours(),
* currentDate.getMinutes() + 1
* );
*
* // This could be any observable stream
* const source = interval(1000);
*
* const result = source.pipe(
* takeUntil(timer(startOfNextMinute))
* );
*
* result.subscribe(console.log);
* ```
*
* ### Known Limitations
*
* - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.
*
* - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and
* a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission
* should occur will be incorrect. In this case, it would be best to do your own calculations
* ahead of time, and pass a `number` in as the `dueTime`.
*
* @param due If a `number`, the amount of time in milliseconds to wait before emitting.
* If a `Date`, the exact time at which to emit.
* @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.
*/
export function timer(due: number | Date, scheduler?: SchedulerLike): Observable<0>;
/**
* Creates an observable that starts an interval after a specified delay, emitting incrementing numbers -- starting at `0` --
* on each interval after words.
*
* The `delay` and `intervalDuration` are specified by default in milliseconds, however providing a custom scheduler could
* create a different behavior.
*
* ## Example
*
* ### Start an interval that starts right away
*
* Since {@link interval} waits for the passed delay before starting,
* sometimes that's not ideal. You may want to start an interval immediately.
* `timer` works well for this. Here we have both side-by-side so you can
* see them in comparison.
*
* Note that this observable will never complete.
*
* ```ts
* import { timer, interval } from 'rxjs';
*
* timer(0, 1000).subscribe(n => console.log('timer', n));
* interval(1000).subscribe(n => console.log('interval', n));
* ```
*
* ### Known Limitations
*
* - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.
*
* - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and
* a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission
* should occur will be incorrect. In this case, it would be best to do your own calculations
* ahead of time, and pass a `number` in as the `startDue`.
* @param startDue If a `number`, is the time to wait before starting the interval.
* If a `Date`, is the exact time at which to start the interval.
* @param intervalDuration The delay between each value emitted in the interval. Passing a
* negative number here will result in immediate completion after the first value is emitted, as though
* no `intervalDuration` was passed at all.
* @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.
*/
export function timer(startDue: number | Date, intervalDuration: number, scheduler?: SchedulerLike): Observable<number>;
/**
* @deprecated The signature allowing `undefined` to be passed for `intervalDuration` will be removed in v8. Use the `timer(dueTime, scheduler?)` signature instead.
*/
export function timer(dueTime: number | Date, unused: undefined, scheduler?: SchedulerLike): Observable<0>;
export function timer(
dueTime: number | Date = 0,
intervalOrScheduler?: number | SchedulerLike,
scheduler: SchedulerLike = asyncScheduler
): Observable<number> {
// Since negative intervalDuration is treated as though no
// interval was specified at all, we start with a negative number.
let intervalDuration = -1;
if (intervalOrScheduler != null) {
// If we have a second argument, and it's a scheduler,
// override the scheduler we had defaulted. Otherwise,
// it must be an interval.
if (isScheduler(intervalOrScheduler)) {
scheduler = intervalOrScheduler;
} else {
// Note that this *could* be negative, in which case
// it's like not passing an intervalDuration at all.
intervalDuration = intervalOrScheduler;
}
}
return new Observable((subscriber) => {
// If a valid date is passed, calculate how long to wait before
// executing the first value... otherwise, if it's a number just schedule
// that many milliseconds (or scheduler-specified unit size) in the future.
let due = isValidDate(dueTime) ? +dueTime - scheduler!.now() : dueTime;
if (due < 0) {
// Ensure we don't schedule in the future.
due = 0;
}
// The incrementing value we emit.
let n = 0;
// Start the timer.
return scheduler.schedule(function () {
if (!subscriber.closed) {
// Emit the next value and increment.
subscriber.next(n++);
if (0 <= intervalDuration) {
// If we have a interval after the initial timer,
// reschedule with the period.
this.schedule(undefined, intervalDuration);
} else {
// We didn't have an interval. So just complete.
subscriber.complete();
}
}
}, due);
});
}

49
node_modules/rxjs/src/internal/observable/using.ts generated vendored Normal file
View File

@@ -0,0 +1,49 @@
import { Observable } from '../Observable';
import { Unsubscribable, ObservableInput, ObservedValueOf } from '../types';
import { innerFrom } from './innerFrom';
import { EMPTY } from './empty';
/**
* Creates an Observable that uses a resource which will be disposed at the same time as the Observable.
*
* <span class="informal">Use it when you catch yourself cleaning up after an Observable.</span>
*
* `using` is a factory operator, which accepts two functions. First function returns a disposable resource.
* It can be an arbitrary object that implements `unsubscribe` method. Second function will be injected with
* that object and should return an Observable. That Observable can use resource object during its execution.
* Both functions passed to `using` will be called every time someone subscribes - neither an Observable nor
* resource object will be shared in any way between subscriptions.
*
* When Observable returned by `using` is subscribed, Observable returned from the second function will be subscribed
* as well. All its notifications (nexted values, completion and error events) will be emitted unchanged by the output
* Observable. If however someone unsubscribes from the Observable or source Observable completes or errors by itself,
* the `unsubscribe` method on resource object will be called. This can be used to do any necessary clean up, which
* otherwise would have to be handled by hand. Note that complete or error notifications are not emitted when someone
* cancels subscription to an Observable via `unsubscribe`, so `using` can be used as a hook, allowing you to make
* sure that all resources which need to exist during an Observable execution will be disposed at appropriate time.
*
* @see {@link defer}
*
* @param resourceFactory A function which creates any resource object that implements `unsubscribe` method.
* @param observableFactory A function which creates an Observable, that can use injected resource object.
* @return An Observable that behaves the same as Observable returned by `observableFactory`, but
* which - when completed, errored or unsubscribed - will also call `unsubscribe` on created resource object.
*/
export function using<T extends ObservableInput<any>>(
resourceFactory: () => Unsubscribable | void,
observableFactory: (resource: Unsubscribable | void) => T | void
): Observable<ObservedValueOf<T>> {
return new Observable<ObservedValueOf<T>>((subscriber) => {
const resource = resourceFactory();
const result = observableFactory(resource);
const source = result ? innerFrom(result) : EMPTY;
source.subscribe(subscriber);
return () => {
// NOTE: Optional chaining did not work here.
// Related TS Issue: https://github.com/microsoft/TypeScript/issues/40818
if (resource) {
resource.unsubscribe();
}
};
});
}

117
node_modules/rxjs/src/internal/observable/zip.ts generated vendored Normal file
View File

@@ -0,0 +1,117 @@
import { Observable } from '../Observable';
import { ObservableInputTuple } from '../types';
import { innerFrom } from './innerFrom';
import { argsOrArgArray } from '../util/argsOrArgArray';
import { EMPTY } from './empty';
import { createOperatorSubscriber } from '../operators/OperatorSubscriber';
import { popResultSelector } from '../util/args';
export function zip<A extends readonly unknown[]>(sources: [...ObservableInputTuple<A>]): Observable<A>;
export function zip<A extends readonly unknown[], R>(
sources: [...ObservableInputTuple<A>],
resultSelector: (...values: A) => R
): Observable<R>;
export function zip<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;
export function zip<A extends readonly unknown[], R>(
...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]
): Observable<R>;
/**
* Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each
* of its input Observables.
*
* If the last parameter is a function, this function is used to compute the created value from the input values.
* Otherwise, an array of the input values is returned.
*
* ## Example
*
* Combine age and name from different sources
*
* ```ts
* import { of, zip, map } from 'rxjs';
*
* const age$ = of(27, 25, 29);
* const name$ = of('Foo', 'Bar', 'Beer');
* const isDev$ = of(true, true, false);
*
* zip(age$, name$, isDev$).pipe(
* map(([age, name, isDev]) => ({ age, name, isDev }))
* )
* .subscribe(x => console.log(x));
*
* // Outputs
* // { age: 27, name: 'Foo', isDev: true }
* // { age: 25, name: 'Bar', isDev: true }
* // { age: 29, name: 'Beer', isDev: false }
* ```
*
* @param args Any number of `ObservableInput`s provided either as an array or as an object
* to combine with each other.
* @return An Observable of array values of the values emitted at the same index from each
* individual `ObservableInput`.
*/
export function zip(...args: unknown[]): Observable<unknown> {
const resultSelector = popResultSelector(args);
const sources = argsOrArgArray(args) as Observable<unknown>[];
return sources.length
? new Observable<unknown[]>((subscriber) => {
// A collection of buffers of values from each source.
// Keyed by the same index with which the sources were passed in.
let buffers: unknown[][] = sources.map(() => []);
// An array of flags of whether or not the sources have completed.
// This is used to check to see if we should complete the result.
// Keyed by the same index with which the sources were passed in.
let completed = sources.map(() => false);
// When everything is done, release the arrays above.
subscriber.add(() => {
buffers = completed = null!;
});
// Loop over our sources and subscribe to each one. The index `i` is
// especially important here, because we use it in closures below to
// access the related buffers and completion properties
for (let sourceIndex = 0; !subscriber.closed && sourceIndex < sources.length; sourceIndex++) {
innerFrom(sources[sourceIndex]).subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
buffers[sourceIndex].push(value);
// if every buffer has at least one value in it, then we
// can shift out the oldest value from each buffer and emit
// them as an array.
if (buffers.every((buffer) => buffer.length)) {
const result: any = buffers.map((buffer) => buffer.shift()!);
// Emit the array. If theres' a result selector, use that.
subscriber.next(resultSelector ? resultSelector(...result) : result);
// If any one of the sources is both complete and has an empty buffer
// then we complete the result. This is because we cannot possibly have
// any more values to zip together.
if (buffers.some((buffer, i) => !buffer.length && completed[i])) {
subscriber.complete();
}
}
},
() => {
// This source completed. Mark it as complete so we can check it later
// if we have to.
completed[sourceIndex] = true;
// But, if this complete source has nothing in its buffer, then we
// can complete the result, because we can't possibly have any more
// values from this to zip together with the other values.
!buffers[sourceIndex].length && subscriber.complete();
}
)
);
}
// When everything is done, release the arrays above.
return () => {
buffers = completed = null!;
};
})
: EMPTY;
}

View File

@@ -0,0 +1,112 @@
import { Subscriber } from '../Subscriber';
/**
* Creates an instance of an `OperatorSubscriber`.
* @param destination The downstream subscriber.
* @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any
* error that occurs in this function is caught and sent to the `error` method of this subscriber.
* @param onError Handles errors from the subscription, any errors that occur in this handler are caught
* and send to the `destination` error handler.
* @param onComplete Handles completion notification from the subscription. Any errors that occur in
* this handler are sent to the `destination` error handler.
* @param onFinalize Additional teardown logic here. This will only be called on teardown if the
* subscriber itself is not already closed. This is called after all other teardown logic is executed.
*/
export function createOperatorSubscriber<T>(
destination: Subscriber<any>,
onNext?: (value: T) => void,
onComplete?: () => void,
onError?: (err: any) => void,
onFinalize?: () => void
): Subscriber<T> {
return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
/**
* A generic helper for allowing operators to be created with a Subscriber and
* use closures to capture necessary state from the operator function itself.
*/
export class OperatorSubscriber<T> extends Subscriber<T> {
/**
* Creates an instance of an `OperatorSubscriber`.
* @param destination The downstream subscriber.
* @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any
* error that occurs in this function is caught and sent to the `error` method of this subscriber.
* @param onError Handles errors from the subscription, any errors that occur in this handler are caught
* and send to the `destination` error handler.
* @param onComplete Handles completion notification from the subscription. Any errors that occur in
* this handler are sent to the `destination` error handler.
* @param onFinalize Additional finalization logic here. This will only be called on finalization if the
* subscriber itself is not already closed. This is called after all other finalization logic is executed.
* @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.
* NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription
* to the resulting observable does not actually disconnect from the source if there are active subscriptions
* to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)
*/
constructor(
destination: Subscriber<any>,
onNext?: (value: T) => void,
onComplete?: () => void,
onError?: (err: any) => void,
private onFinalize?: () => void,
private shouldUnsubscribe?: () => boolean
) {
// It's important - for performance reasons - that all of this class's
// members are initialized and that they are always initialized in the same
// order. This will ensure that all OperatorSubscriber instances have the
// same hidden class in V8. This, in turn, will help keep the number of
// hidden classes involved in property accesses within the base class as
// low as possible. If the number of hidden classes involved exceeds four,
// the property accesses will become megamorphic and performance penalties
// will be incurred - i.e. inline caches won't be used.
//
// The reasons for ensuring all instances have the same hidden class are
// further discussed in this blog post from Benedikt Meurer:
// https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/
super(destination);
this._next = onNext
? function (this: OperatorSubscriber<T>, value: T) {
try {
onNext(value);
} catch (err) {
destination.error(err);
}
}
: super._next;
this._error = onError
? function (this: OperatorSubscriber<T>, err: any) {
try {
onError(err);
} catch (err) {
// Send any errors that occur down stream.
destination.error(err);
} finally {
// Ensure finalization.
this.unsubscribe();
}
}
: super._error;
this._complete = onComplete
? function (this: OperatorSubscriber<T>) {
try {
onComplete();
} catch (err) {
// Send any errors that occur down stream.
destination.error(err);
} finally {
// Ensure finalization.
this.unsubscribe();
}
}
: super._complete;
}
unsubscribe() {
if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
const { closed } = this;
super.unsubscribe();
// Execute additional teardown if we have any and we didn't already do so.
!closed && this.onFinalize?.();
}
}
}

96
node_modules/rxjs/src/internal/operators/audit.ts generated vendored Normal file
View File

@@ -0,0 +1,96 @@
import { Subscriber } from '../Subscriber';
import { MonoTypeOperatorFunction, ObservableInput } from '../types';
import { operate } from '../util/lift';
import { innerFrom } from '../observable/innerFrom';
import { createOperatorSubscriber } from './OperatorSubscriber';
/**
* Ignores source values for a duration determined by another Observable, then
* emits the most recent value from the source Observable, then repeats this
* process.
*
* <span class="informal">It's like {@link auditTime}, but the silencing
* duration is determined by a second Observable.</span>
*
* ![](audit.svg)
*
* `audit` is similar to `throttle`, but emits the last value from the silenced
* time window, instead of the first value. `audit` emits the most recent value
* from the source Observable on the output Observable as soon as its internal
* timer becomes disabled, and ignores source values while the timer is enabled.
* Initially, the timer is disabled. As soon as the first source value arrives,
* the timer is enabled by calling the `durationSelector` function with the
* source value, which returns the "duration" Observable. When the duration
* Observable emits a value, the timer is disabled, then the most
* recent source value is emitted on the output Observable, and this process
* repeats for the next source value.
*
* ## Example
*
* Emit clicks at a rate of at most one click per second
*
* ```ts
* import { fromEvent, audit, interval } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(audit(ev => interval(1000)));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link auditTime}
* @see {@link debounce}
* @see {@link delayWhen}
* @see {@link sample}
* @see {@link throttle}
*
* @param durationSelector A function
* that receives a value from the source Observable, for computing the silencing
* duration, returned as an Observable or a Promise.
* @return A function that returns an Observable that performs rate-limiting of
* emissions from the source Observable.
*/
export function audit<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {
return operate((source, subscriber) => {
let hasValue = false;
let lastValue: T | null = null;
let durationSubscriber: Subscriber<any> | null = null;
let isComplete = false;
const endDuration = () => {
durationSubscriber?.unsubscribe();
durationSubscriber = null;
if (hasValue) {
hasValue = false;
const value = lastValue!;
lastValue = null;
subscriber.next(value);
}
isComplete && subscriber.complete();
};
const cleanupDuration = () => {
durationSubscriber = null;
isComplete && subscriber.complete();
};
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
hasValue = true;
lastValue = value;
if (!durationSubscriber) {
innerFrom(durationSelector(value)).subscribe(
(durationSubscriber = createOperatorSubscriber(subscriber, endDuration, cleanupDuration))
);
}
},
() => {
isComplete = true;
(!hasValue || !durationSubscriber || durationSubscriber.closed) && subscriber.complete();
}
)
);
});
}

55
node_modules/rxjs/src/internal/operators/auditTime.ts generated vendored Normal file
View File

@@ -0,0 +1,55 @@
import { asyncScheduler } from '../scheduler/async';
import { audit } from './audit';
import { timer } from '../observable/timer';
import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
/**
* Ignores source values for `duration` milliseconds, then emits the most recent
* value from the source Observable, then repeats this process.
*
* <span class="informal">When it sees a source value, it ignores that plus
* the next ones for `duration` milliseconds, and then it emits the most recent
* value from the source.</span>
*
* ![](auditTime.png)
*
* `auditTime` is similar to `throttleTime`, but emits the last value from the
* silenced time window, instead of the first value. `auditTime` emits the most
* recent value from the source Observable on the output Observable as soon as
* its internal timer becomes disabled, and ignores source values while the
* timer is enabled. Initially, the timer is disabled. As soon as the first
* source value arrives, the timer is enabled. After `duration` milliseconds (or
* the time unit determined internally by the optional `scheduler`) has passed,
* the timer is disabled, then the most recent source value is emitted on the
* output Observable, and this process repeats for the next source value.
* Optionally takes a {@link SchedulerLike} for managing timers.
*
* ## Example
*
* Emit clicks at a rate of at most one click per second
*
* ```ts
* import { fromEvent, auditTime } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(auditTime(1000));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link audit}
* @see {@link debounceTime}
* @see {@link delay}
* @see {@link sampleTime}
* @see {@link throttleTime}
*
* @param duration Time to wait before emitting the most recent source value,
* measured in milliseconds or the time unit determined internally by the
* optional `scheduler`.
* @param scheduler The {@link SchedulerLike} to use for managing the timers
* that handle the rate-limiting behavior.
* @return A function that returns an Observable that performs rate-limiting of
* emissions from the source Observable.
*/
export function auditTime<T>(duration: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {
return audit(() => timer(duration, scheduler));
}

81
node_modules/rxjs/src/internal/operators/buffer.ts generated vendored Normal file
View File

@@ -0,0 +1,81 @@
import { OperatorFunction, ObservableInput } from '../types';
import { operate } from '../util/lift';
import { noop } from '../util/noop';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { innerFrom } from '../observable/innerFrom';
/**
* Buffers the source Observable values until `closingNotifier` emits.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when another Observable emits.</span>
*
* ![](buffer.png)
*
* Buffers the incoming Observable values until the given `closingNotifier`
* `ObservableInput` (that internally gets converted to an Observable)
* emits a value, at which point it emits the buffer on the output
* Observable and starts a new buffer internally, awaiting the next time
* `closingNotifier` emits.
*
* ## Example
*
* On every click, emit array of most recent interval events
*
* ```ts
* import { fromEvent, interval, buffer } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const intervalEvents = interval(1000);
* const buffered = intervalEvents.pipe(buffer(clicks));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link window}
*
* @param closingNotifier An `ObservableInput` that signals the
* buffer to be emitted on the output Observable.
* @return A function that returns an Observable of buffers, which are arrays
* of values.
*/
export function buffer<T>(closingNotifier: ObservableInput<any>): OperatorFunction<T, T[]> {
return operate((source, subscriber) => {
// The current buffered values.
let currentBuffer: T[] = [];
// Subscribe to our source.
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => currentBuffer.push(value),
() => {
subscriber.next(currentBuffer);
subscriber.complete();
}
)
);
// Subscribe to the closing notifier.
innerFrom(closingNotifier).subscribe(
createOperatorSubscriber(
subscriber,
() => {
// Start a new buffer and emit the previous one.
const b = currentBuffer;
currentBuffer = [];
subscriber.next(b);
},
noop
)
);
return () => {
// Ensure buffered values are released on finalization.
currentBuffer = null!;
};
});
}

120
node_modules/rxjs/src/internal/operators/bufferCount.ts generated vendored Normal file
View File

@@ -0,0 +1,120 @@
import { OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { arrRemove } from '../util/arrRemove';
/**
* Buffers the source Observable values until the size hits the maximum
* `bufferSize` given.
*
* <span class="informal">Collects values from the past as an array, and emits
* that array only when its size reaches `bufferSize`.</span>
*
* ![](bufferCount.png)
*
* Buffers a number of values from the source Observable by `bufferSize` then
* emits the buffer and clears it, and starts a new buffer each
* `startBufferEvery` values. If `startBufferEvery` is not provided or is
* `null`, then new buffers are started immediately at the start of the source
* and when each buffer closes and is emitted.
*
* ## Examples
*
* Emit the last two click events as an array
*
* ```ts
* import { fromEvent, bufferCount } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferCount(2));
* buffered.subscribe(x => console.log(x));
* ```
*
* On every click, emit the last two click events as an array
*
* ```ts
* import { fromEvent, bufferCount } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferCount(2, 1));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link pairwise}
* @see {@link windowCount}
*
* @param bufferSize The maximum size of the buffer emitted.
* @param startBufferEvery Interval at which to start a new buffer.
* For example if `startBufferEvery` is `2`, then a new buffer will be started
* on every other value from the source. A new buffer is started at the
* beginning of the source by default.
* @return A function that returns an Observable of arrays of buffered values.
*/
export function bufferCount<T>(bufferSize: number, startBufferEvery: number | null = null): OperatorFunction<T, T[]> {
// If no `startBufferEvery` value was supplied, then we're
// opening and closing on the bufferSize itself.
startBufferEvery = startBufferEvery ?? bufferSize;
return operate((source, subscriber) => {
let buffers: T[][] = [];
let count = 0;
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
let toEmit: T[][] | null = null;
// Check to see if we need to start a buffer.
// This will start one at the first value, and then
// a new one every N after that.
if (count++ % startBufferEvery! === 0) {
buffers.push([]);
}
// Push our value into our active buffers.
for (const buffer of buffers) {
buffer.push(value);
// Check to see if we're over the bufferSize
// if we are, record it so we can emit it later.
// If we emitted it now and removed it, it would
// mutate the `buffers` array while we're looping
// over it.
if (bufferSize <= buffer.length) {
toEmit = toEmit ?? [];
toEmit.push(buffer);
}
}
if (toEmit) {
// We have found some buffers that are over the
// `bufferSize`. Emit them, and remove them from our
// buffers list.
for (const buffer of toEmit) {
arrRemove(buffers, buffer);
subscriber.next(buffer);
}
}
},
() => {
// When the source completes, emit all of our
// active buffers.
for (const buffer of buffers) {
subscriber.next(buffer);
}
subscriber.complete();
},
// Pass all errors through to consumer.
undefined,
() => {
// Clean up our memory when we finalize
buffers = null!;
}
)
);
});
}

165
node_modules/rxjs/src/internal/operators/bufferTime.ts generated vendored Normal file
View File

@@ -0,0 +1,165 @@
import { Subscription } from '../Subscription';
import { OperatorFunction, SchedulerLike } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { arrRemove } from '../util/arrRemove';
import { asyncScheduler } from '../scheduler/async';
import { popScheduler } from '../util/args';
import { executeSchedule } from '../util/executeSchedule';
export function bufferTime<T>(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;
export function bufferTime<T>(
bufferTimeSpan: number,
bufferCreationInterval: number | null | undefined,
scheduler?: SchedulerLike
): OperatorFunction<T, T[]>;
export function bufferTime<T>(
bufferTimeSpan: number,
bufferCreationInterval: number | null | undefined,
maxBufferSize: number,
scheduler?: SchedulerLike
): OperatorFunction<T, T[]>;
/**
* Buffers the source Observable values for a specific time period.
*
* <span class="informal">Collects values from the past as an array, and emits
* those arrays periodically in time.</span>
*
* ![](bufferTime.png)
*
* Buffers values from the source for a specific time duration `bufferTimeSpan`.
* Unless the optional argument `bufferCreationInterval` is given, it emits and
* resets the buffer every `bufferTimeSpan` milliseconds. If
* `bufferCreationInterval` is given, this operator opens the buffer every
* `bufferCreationInterval` milliseconds and closes (emits and resets) the
* buffer every `bufferTimeSpan` milliseconds. When the optional argument
* `maxBufferSize` is specified, the buffer will be closed either after
* `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.
*
* ## Examples
*
* Every second, emit an array of the recent click events
*
* ```ts
* import { fromEvent, bufferTime } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferTime(1000));
* buffered.subscribe(x => console.log(x));
* ```
*
* Every 5 seconds, emit the click events from the next 2 seconds
*
* ```ts
* import { fromEvent, bufferTime } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(bufferTime(2000, 5000));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferToggle}
* @see {@link bufferWhen}
* @see {@link windowTime}
*
* @param bufferTimeSpan The amount of time to fill each buffer array.
* @param otherArgs Other configuration arguments such as:
* - `bufferCreationInterval` - the interval at which to start new buffers;
* - `maxBufferSize` - the maximum buffer size;
* - `scheduler` - the scheduler on which to schedule the intervals that determine buffer boundaries.
* @return A function that returns an Observable of arrays of buffered values.
*/
export function bufferTime<T>(bufferTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, T[]> {
const scheduler = popScheduler(otherArgs) ?? asyncScheduler;
const bufferCreationInterval = (otherArgs[0] as number) ?? null;
const maxBufferSize = (otherArgs[1] as number) || Infinity;
return operate((source, subscriber) => {
// The active buffers, their related subscriptions, and removal functions.
let bufferRecords: { buffer: T[]; subs: Subscription }[] | null = [];
// If true, it means that every time we emit a buffer, we want to start a new buffer
// this is only really used for when *just* the buffer time span is passed.
let restartOnEmit = false;
/**
* Does the work of emitting the buffer from the record, ensuring that the
* record is removed before the emission so reentrant code (from some custom scheduling, perhaps)
* does not alter the buffer. Also checks to see if a new buffer needs to be started
* after the emit.
*/
const emit = (record: { buffer: T[]; subs: Subscription }) => {
const { buffer, subs } = record;
subs.unsubscribe();
arrRemove(bufferRecords, record);
subscriber.next(buffer);
restartOnEmit && startBuffer();
};
/**
* Called every time we start a new buffer. This does
* the work of scheduling a job at the requested bufferTimeSpan
* that will emit the buffer (if it's not unsubscribed before then).
*/
const startBuffer = () => {
if (bufferRecords) {
const subs = new Subscription();
subscriber.add(subs);
const buffer: T[] = [];
const record = {
buffer,
subs,
};
bufferRecords.push(record);
executeSchedule(subs, scheduler, () => emit(record), bufferTimeSpan);
}
};
if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {
// The user passed both a bufferTimeSpan (required), and a creation interval
// That means we need to start new buffers on the interval, and those buffers need
// to wait the required time span before emitting.
executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);
} else {
restartOnEmit = true;
}
startBuffer();
const bufferTimeSubscriber = createOperatorSubscriber(
subscriber,
(value: T) => {
// Copy the records, so if we need to remove one we
// don't mutate the array. It's hard, but not impossible to
// set up a buffer time that could mutate the array and
// cause issues here.
const recordsCopy = bufferRecords!.slice();
for (const record of recordsCopy) {
// Loop over all buffers and
const { buffer } = record;
buffer.push(value);
// If the buffer is over the max size, we need to emit it.
maxBufferSize <= buffer.length && emit(record);
}
},
() => {
// The source completed, emit all of the active
// buffers we have before we complete.
while (bufferRecords?.length) {
subscriber.next(bufferRecords.shift()!.buffer);
}
bufferTimeSubscriber?.unsubscribe();
subscriber.complete();
subscriber.unsubscribe();
},
// Pass all errors through to consumer.
undefined,
// Clean up
() => (bufferRecords = null)
);
source.subscribe(bufferTimeSubscriber);
});
}

View File

@@ -0,0 +1,102 @@
import { Subscription } from '../Subscription';
import { OperatorFunction, ObservableInput } from '../types';
import { operate } from '../util/lift';
import { innerFrom } from '../observable/innerFrom';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { noop } from '../util/noop';
import { arrRemove } from '../util/arrRemove';
/**
* Buffers the source Observable values starting from an emission from
* `openings` and ending when the output of `closingSelector` emits.
*
* <span class="informal">Collects values from the past as an array. Starts
* collecting only when `opening` emits, and calls the `closingSelector`
* function to get an Observable that tells when to close the buffer.</span>
*
* ![](bufferToggle.png)
*
* Buffers values from the source by opening the buffer via signals from an
* Observable provided to `openings`, and closing and sending the buffers when
* a Subscribable or Promise returned by the `closingSelector` function emits.
*
* ## Example
*
* Every other second, emit the click events from the next 500ms
*
* ```ts
* import { fromEvent, interval, bufferToggle, EMPTY } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const openings = interval(1000);
* const buffered = clicks.pipe(bufferToggle(openings, i =>
* i % 2 ? interval(500) : EMPTY
* ));
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferWhen}
* @see {@link windowToggle}
*
* @param openings A Subscribable or Promise of notifications to start new
* buffers.
* @param closingSelector A function that takes
* the value emitted by the `openings` observable and returns a Subscribable or Promise,
* which, when it emits, signals that the associated buffer should be emitted
* and cleared.
* @return A function that returns an Observable of arrays of buffered values.
*/
export function bufferToggle<T, O>(
openings: ObservableInput<O>,
closingSelector: (value: O) => ObservableInput<any>
): OperatorFunction<T, T[]> {
return operate((source, subscriber) => {
const buffers: T[][] = [];
// Subscribe to the openings notifier first
innerFrom(openings).subscribe(
createOperatorSubscriber(
subscriber,
(openValue) => {
const buffer: T[] = [];
buffers.push(buffer);
// We use this composite subscription, so that
// when the closing notifier emits, we can tear it down.
const closingSubscription = new Subscription();
const emitBuffer = () => {
arrRemove(buffers, buffer);
subscriber.next(buffer);
closingSubscription.unsubscribe();
};
// The line below will add the subscription to the parent subscriber *and* the closing subscription.
closingSubscription.add(innerFrom(closingSelector(openValue)).subscribe(createOperatorSubscriber(subscriber, emitBuffer, noop)));
},
noop
)
);
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
// Value from our source. Add it to all pending buffers.
for (const buffer of buffers) {
buffer.push(value);
}
},
() => {
// Source complete. Emit all pending buffers.
while (buffers.length > 0) {
subscriber.next(buffers.shift()!);
}
subscriber.complete();
}
)
);
});
}

94
node_modules/rxjs/src/internal/operators/bufferWhen.ts generated vendored Normal file
View File

@@ -0,0 +1,94 @@
import { Subscriber } from '../Subscriber';
import { ObservableInput, OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { noop } from '../util/noop';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { innerFrom } from '../observable/innerFrom';
/**
* Buffers the source Observable values, using a factory function of closing
* Observables to determine when to close, emit, and reset the buffer.
*
* <span class="informal">Collects values from the past as an array. When it
* starts collecting values, it calls a function that returns an Observable that
* tells when to close the buffer and restart collecting.</span>
*
* ![](bufferWhen.svg)
*
* Opens a buffer immediately, then closes the buffer when the observable
* returned by calling `closingSelector` function emits a value. When it closes
* the buffer, it immediately opens a new buffer and repeats the process.
*
* ## Example
*
* Emit an array of the last clicks every [1-5] random seconds
*
* ```ts
* import { fromEvent, bufferWhen, interval } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const buffered = clicks.pipe(
* bufferWhen(() => interval(1000 + Math.random() * 4000))
* );
* buffered.subscribe(x => console.log(x));
* ```
*
* @see {@link buffer}
* @see {@link bufferCount}
* @see {@link bufferTime}
* @see {@link bufferToggle}
* @see {@link windowWhen}
*
* @param closingSelector A function that takes no arguments and returns an
* Observable that signals buffer closure.
* @return A function that returns an Observable of arrays of buffered values.
*/
export function bufferWhen<T>(closingSelector: () => ObservableInput<any>): OperatorFunction<T, T[]> {
return operate((source, subscriber) => {
// The buffer we keep and emit.
let buffer: T[] | null = null;
// A reference to the subscriber used to subscribe to
// the closing notifier. We need to hold this so we can
// end the subscription after the first notification.
let closingSubscriber: Subscriber<T> | null = null;
// Ends the previous closing notifier subscription, so it
// terminates after the first emission, then emits
// the current buffer if there is one, starts a new buffer, and starts a
// new closing notifier.
const openBuffer = () => {
// Make sure to finalize the closing subscription, we only cared
// about one notification.
closingSubscriber?.unsubscribe();
// emit the buffer if we have one, and start a new buffer.
const b = buffer;
buffer = [];
b && subscriber.next(b);
// Get a new closing notifier and subscribe to it.
innerFrom(closingSelector()).subscribe((closingSubscriber = createOperatorSubscriber(subscriber, openBuffer, noop)));
};
// Start the first buffer.
openBuffer();
// Subscribe to our source.
source.subscribe(
createOperatorSubscriber(
subscriber,
// Add every new value to the current buffer.
(value) => buffer?.push(value),
// When we complete, emit the buffer if we have one,
// then complete the result.
() => {
buffer && subscriber.next(buffer);
subscriber.complete();
},
// Pass all errors through to consumer.
undefined,
// Release memory on finalization
() => (buffer = closingSubscriber = null!)
)
);
});
}

139
node_modules/rxjs/src/internal/operators/catchError.ts generated vendored Normal file
View File

@@ -0,0 +1,139 @@
import { Observable } from '../Observable';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
import { Subscription } from '../Subscription';
import { innerFrom } from '../observable/innerFrom';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { operate } from '../util/lift';
export function catchError<T, O extends ObservableInput<any>>(
selector: (err: any, caught: Observable<T>) => O
): OperatorFunction<T, T | ObservedValueOf<O>>;
/**
* Catches errors on the observable to be handled by returning a new observable or throwing an error.
*
* <span class="informal">
* It only listens to the error channel and ignores notifications.
* Handles errors from the source observable, and maps them to a new observable.
* The error may also be rethrown, or a new error can be thrown to emit an error from the result.
* </span>
*
* ![](catch.png)
*
* This operator handles errors, but forwards along all other events to the resulting observable.
* If the source observable terminates with an error, it will map that error to a new observable,
* subscribe to it, and forward all of its events to the resulting observable.
*
* ## Examples
*
* Continue with a different Observable when there's an error
*
* ```ts
* import { of, map, catchError } from 'rxjs';
*
* of(1, 2, 3, 4, 5)
* .pipe(
* map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* }),
* catchError(err => of('I', 'II', 'III', 'IV', 'V'))
* )
* .subscribe(x => console.log(x));
* // 1, 2, 3, I, II, III, IV, V
* ```
*
* Retry the caught source Observable again in case of error, similar to `retry()` operator
*
* ```ts
* import { of, map, catchError, take } from 'rxjs';
*
* of(1, 2, 3, 4, 5)
* .pipe(
* map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* }),
* catchError((err, caught) => caught),
* take(30)
* )
* .subscribe(x => console.log(x));
* // 1, 2, 3, 1, 2, 3, ...
* ```
*
* Throw a new error when the source Observable throws an error
*
* ```ts
* import { of, map, catchError } from 'rxjs';
*
* of(1, 2, 3, 4, 5)
* .pipe(
* map(n => {
* if (n === 4) {
* throw 'four!';
* }
* return n;
* }),
* catchError(err => {
* throw 'error in source. Details: ' + err;
* })
* )
* .subscribe({
* next: x => console.log(x),
* error: err => console.log(err)
* });
* // 1, 2, 3, error in source. Details: four!
* ```
*
* @see {@link onErrorResumeNext}
* @see {@link repeat}
* @see {@link repeatWhen}
* @see {@link retry }
* @see {@link retryWhen}
*
* @param selector A function that takes as arguments `err`, which is the error, and `caught`, which
* is the source observable, in case you'd like to "retry" that observable by returning it again.
* Whatever observable is returned by the `selector` will be used to continue the observable chain.
* @return A function that returns an Observable that originates from either
* the source or the Observable returned by the `selector` function.
*/
export function catchError<T, O extends ObservableInput<any>>(
selector: (err: any, caught: Observable<T>) => O
): OperatorFunction<T, T | ObservedValueOf<O>> {
return operate((source, subscriber) => {
let innerSub: Subscription | null = null;
let syncUnsub = false;
let handledResult: Observable<ObservedValueOf<O>>;
innerSub = source.subscribe(
createOperatorSubscriber(subscriber, undefined, undefined, (err) => {
handledResult = innerFrom(selector(err, catchError(selector)(source)));
if (innerSub) {
innerSub.unsubscribe();
innerSub = null;
handledResult.subscribe(subscriber);
} else {
// We don't have an innerSub yet, that means the error was synchronous
// because the subscribe call hasn't returned yet.
syncUnsub = true;
}
})
);
if (syncUnsub) {
// We have a synchronous error, we need to make sure to
// finalize right away. This ensures that callbacks in the `finalize` operator are called
// at the right time, and that finalization occurs at the expected
// time between the source error and the subscription to the
// next observable.
innerSub.unsubscribe();
innerSub = null;
handledResult!.subscribe(subscriber);
}
});
}

View File

@@ -0,0 +1,6 @@
import { combineLatestAll } from './combineLatestAll';
/**
* @deprecated Renamed to {@link combineLatestAll}. Will be removed in v8.
*/
export const combineAll = combineLatestAll;

View File

@@ -0,0 +1,34 @@
import { combineLatestInit } from '../observable/combineLatest';
import { ObservableInput, ObservableInputTuple, OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { argsOrArgArray } from '../util/argsOrArgArray';
import { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';
import { pipe } from '../util/pipe';
import { popResultSelector } from '../util/args';
/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */
export function combineLatest<T, A extends readonly unknown[], R>(
sources: [...ObservableInputTuple<A>],
project: (...values: [T, ...A]) => R
): OperatorFunction<T, R>;
/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */
export function combineLatest<T, A extends readonly unknown[], R>(sources: [...ObservableInputTuple<A>]): OperatorFunction<T, [T, ...A]>;
/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */
export function combineLatest<T, A extends readonly unknown[], R>(
...sourcesAndProject: [...ObservableInputTuple<A>, (...values: [T, ...A]) => R]
): OperatorFunction<T, R>;
/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */
export function combineLatest<T, A extends readonly unknown[], R>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, [T, ...A]>;
/**
* @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8.
*/
export function combineLatest<T, R>(...args: (ObservableInput<any> | ((...values: any[]) => R))[]): OperatorFunction<T, unknown> {
const resultSelector = popResultSelector(args);
return resultSelector
? pipe(combineLatest(...(args as Array<ObservableInput<any>>)), mapOneOrManyArgs(resultSelector))
: operate((source, subscriber) => {
combineLatestInit([source, ...argsOrArgArray(args)])(subscriber);
});
}

View File

@@ -0,0 +1,50 @@
import { combineLatest } from '../observable/combineLatest';
import { OperatorFunction, ObservableInput } from '../types';
import { joinAllInternals } from './joinAllInternals';
export function combineLatestAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;
export function combineLatestAll<T>(): OperatorFunction<any, T[]>;
export function combineLatestAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;
export function combineLatestAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;
/**
* Flattens an Observable-of-Observables by applying {@link combineLatest} when the Observable-of-Observables completes.
*
* `combineLatestAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes,
* it subscribes to all collected Observables and combines their values using the {@link combineLatest} strategy, such that:
*
* * Every time an inner Observable emits, the output Observable emits
* * When the returned observable emits, it emits all of the latest values by:
* * If a `project` function is provided, it is called with each recent value from each inner Observable in whatever order they
* arrived, and the result of the `project` function is what is emitted by the output Observable.
* * If there is no `project` function, an array of all the most recent values is emitted by the output Observable.
*
* ## Example
*
* Map two click events to a finite interval Observable, then apply `combineLatestAll`
*
* ```ts
* import { fromEvent, map, interval, take, combineLatestAll } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map(() => interval(Math.random() * 2000).pipe(take(3))),
* take(2)
* );
* const result = higherOrder.pipe(combineLatestAll());
*
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link combineLatest}
* @see {@link combineLatestWith}
* @see {@link mergeAll}
*
* @param project optional function to map the most recent values from each inner Observable into a new result.
* Takes each of the most recent values from each collected inner Observable as arguments, in order.
* @return A function that returns an Observable that flattens Observables
* emitted by the source Observable.
*/
export function combineLatestAll<R>(project?: (...values: Array<any>) => R) {
return joinAllInternals(combineLatest, project);
}

View File

@@ -0,0 +1,48 @@
import { ObservableInputTuple, OperatorFunction, Cons } from '../types';
import { combineLatest } from './combineLatest';
/**
* Create an observable that combines the latest values from all passed observables and the source
* into arrays and emits them.
*
* Returns an observable, that when subscribed to, will subscribe to the source observable and all
* sources provided as arguments. Once all sources emit at least one value, all of the latest values
* will be emitted as an array. After that, every time any source emits a value, all of the latest values
* will be emitted as an array.
*
* This is a useful operator for eagerly calculating values based off of changed inputs.
*
* ## Example
*
* Simple concatenation of values from two inputs
*
* ```ts
* import { fromEvent, combineLatestWith, map } from 'rxjs';
*
* // Setup: Add two inputs to the page
* const input1 = document.createElement('input');
* document.body.appendChild(input1);
* const input2 = document.createElement('input');
* document.body.appendChild(input2);
*
* // Get streams of changes
* const input1Changes$ = fromEvent(input1, 'change');
* const input2Changes$ = fromEvent(input2, 'change');
*
* // Combine the changes by adding them together
* input1Changes$.pipe(
* combineLatestWith(input2Changes$),
* map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value)
* )
* .subscribe(x => console.log(x));
* ```
*
* @param otherSources the other sources to subscribe to.
* @return A function that returns an Observable that emits the latest
* emissions from both source and provided Observables.
*/
export function combineLatestWith<T, A extends readonly unknown[]>(
...otherSources: [...ObservableInputTuple<A>]
): OperatorFunction<T, Cons<T, A>> {
return combineLatest(...otherSources);
}

22
node_modules/rxjs/src/internal/operators/concat.ts generated vendored Normal file
View File

@@ -0,0 +1,22 @@
import { ObservableInputTuple, OperatorFunction, SchedulerLike } from '../types';
import { operate } from '../util/lift';
import { concatAll } from './concatAll';
import { popScheduler } from '../util/args';
import { from } from '../observable/from';
/** @deprecated Replaced with {@link concatWith}. Will be removed in v8. */
export function concat<T, A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, T | A[number]>;
/** @deprecated Replaced with {@link concatWith}. Will be removed in v8. */
export function concat<T, A extends readonly unknown[]>(
...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]
): OperatorFunction<T, T | A[number]>;
/**
* @deprecated Replaced with {@link concatWith}. Will be removed in v8.
*/
export function concat<T, R>(...args: any[]): OperatorFunction<T, R> {
const scheduler = popScheduler(args);
return operate((source, subscriber) => {
concatAll()(from([source, ...args], scheduler)).subscribe(subscriber);
});
}

62
node_modules/rxjs/src/internal/operators/concatAll.ts generated vendored Normal file
View File

@@ -0,0 +1,62 @@
import { mergeAll } from './mergeAll';
import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';
/**
* Converts a higher-order Observable into a first-order Observable by
* concatenating the inner Observables in order.
*
* <span class="informal">Flattens an Observable-of-Observables by putting one
* inner Observable after the other.</span>
*
* ![](concatAll.svg)
*
* Joins every Observable emitted by the source (a higher-order Observable), in
* a serial fashion. It subscribes to each inner Observable only after the
* previous inner Observable has completed, and merges all of their values into
* the returned observable.
*
* __Warning:__ If the source Observable emits Observables quickly and
* endlessly, and the inner Observables it emits generally complete slower than
* the source emits, you can run into memory issues as the incoming Observables
* collect in an unbounded buffer.
*
* Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set
* to `1`.
*
* ## Example
*
* For each click event, tick every second from 0 to 3, with no concurrency
*
* ```ts
* import { fromEvent, map, interval, take, concatAll } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map(() => interval(1000).pipe(take(4)))
* );
* const firstOrder = higherOrder.pipe(concatAll());
* firstOrder.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
* ```
*
* @see {@link combineLatestAll}
* @see {@link concat}
* @see {@link concatMap}
* @see {@link concatMapTo}
* @see {@link exhaustAll}
* @see {@link mergeAll}
* @see {@link switchAll}
* @see {@link switchMap}
* @see {@link zipAll}
*
* @return A function that returns an Observable emitting values from all the
* inner Observables concatenated.
*/
export function concatAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {
return mergeAll(1);
}

83
node_modules/rxjs/src/internal/operators/concatMap.ts generated vendored Normal file
View File

@@ -0,0 +1,83 @@
import { mergeMap } from './mergeMap';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
import { isFunction } from '../util/isFunction';
/* tslint:disable:max-line-length */
export function concatMap<T, O extends ObservableInput<any>>(
project: (value: T, index: number) => O
): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
export function concatMap<T, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector: undefined
): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
export function concatMap<T, R, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable, in a serialized fashion waiting for each one to complete before
* merging the next.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link concatAll}.</span>
*
* ![](concatMap.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an (so-called "inner") Observable. Each new inner Observable is
* concatenated with the previous inner Observable.
*
* __Warning:__ if source values arrive endlessly and faster than their
* corresponding inner Observables can complete, it will result in memory issues
* as inner Observables amass in an unbounded buffer waiting for their turn to
* be subscribed to.
*
* Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set
* to `1`.
*
* ## Example
*
* For each click event, tick every second from 0 to 3, with no concurrency
*
* ```ts
* import { fromEvent, concatMap, interval, take } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* concatMap(ev => interval(1000).pipe(take(4)))
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
* ```
*
* @see {@link concat}
* @see {@link concatAll}
* @see {@link concatMapTo}
* @see {@link exhaustMap}
* @see {@link mergeMap}
* @see {@link switchMap}
*
* @param project A function that, when applied to an item emitted by the source
* Observable, returns an Observable.
* @return A function that returns an Observable that emits the result of
* applying the projection function (and the optional deprecated
* `resultSelector`) to each item emitted by the source Observable and taking
* values from each projected inner Observable sequentially.
*/
export function concatMap<T, R, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, ObservedValueOf<O> | R> {
return isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);
}

View File

@@ -0,0 +1,79 @@
import { concatMap } from './concatMap';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
import { isFunction } from '../util/isFunction';
/** @deprecated Will be removed in v9. Use {@link concatMap} instead: `concatMap(() => result)` */
export function concatMapTo<O extends ObservableInput<unknown>>(observable: O): OperatorFunction<unknown, ObservedValueOf<O>>;
/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
export function concatMapTo<O extends ObservableInput<unknown>>(
observable: O,
resultSelector: undefined
): OperatorFunction<unknown, ObservedValueOf<O>>;
/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
export function concatMapTo<T, R, O extends ObservableInput<unknown>>(
observable: O,
resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, R>;
/**
* Projects each source value to the same Observable which is merged multiple
* times in a serialized fashion on the output Observable.
*
* <span class="informal">It's like {@link concatMap}, but maps each value
* always to the same inner Observable.</span>
*
* ![](concatMapTo.png)
*
* Maps each source value to the given Observable `innerObservable` regardless
* of the source value, and then flattens those resulting Observables into one
* single Observable, which is the output Observable. Each new `innerObservable`
* instance emitted on the output Observable is concatenated with the previous
* `innerObservable` instance.
*
* __Warning:__ if source values arrive endlessly and faster than their
* corresponding inner Observables can complete, it will result in memory issues
* as inner Observables amass in an unbounded buffer waiting for their turn to
* be subscribed to.
*
* Note: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter
* set to `1`.
*
* ## Example
*
* For each click event, tick every second from 0 to 3, with no concurrency
*
* ```ts
* import { fromEvent, concatMapTo, interval, take } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* concatMapTo(interval(1000).pipe(take(4)))
* );
* result.subscribe(x => console.log(x));
*
* // Results in the following:
* // (results are not concurrent)
* // For every click on the "document" it will emit values 0 to 3 spaced
* // on a 1000ms interval
* // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3
* ```
*
* @see {@link concat}
* @see {@link concatAll}
* @see {@link concatMap}
* @see {@link mergeMapTo}
* @see {@link switchMapTo}
*
* @param innerObservable An `ObservableInput` to replace each value from the
* source Observable.
* @return A function that returns an Observable of values merged together by
* joining the passed Observable with itself, one after the other, for each
* value emitted from the source.
* @deprecated Will be removed in v9. Use {@link concatMap} instead: `concatMap(() => result)`
*/
export function concatMapTo<T, R, O extends ObservableInput<unknown>>(
innerObservable: O,
resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, ObservedValueOf<O> | R> {
return isFunction(resultSelector) ? concatMap(() => innerObservable, resultSelector) : concatMap(() => innerObservable);
}

48
node_modules/rxjs/src/internal/operators/concatWith.ts generated vendored Normal file
View File

@@ -0,0 +1,48 @@
import { ObservableInputTuple, OperatorFunction } from '../types';
import { concat } from './concat';
/**
* Emits all of the values from the source observable, then, once it completes, subscribes
* to each observable source provided, one at a time, emitting all of their values, and not subscribing
* to the next one until it completes.
*
* `concat(a$, b$, c$)` is the same as `a$.pipe(concatWith(b$, c$))`.
*
* ## Example
*
* Listen for one mouse click, then listen for all mouse moves.
*
* ```ts
* import { fromEvent, map, take, concatWith } from 'rxjs';
*
* const clicks$ = fromEvent(document, 'click');
* const moves$ = fromEvent(document, 'mousemove');
*
* clicks$.pipe(
* map(() => 'click'),
* take(1),
* concatWith(
* moves$.pipe(
* map(() => 'move')
* )
* )
* )
* .subscribe(x => console.log(x));
*
* // 'click'
* // 'move'
* // 'move'
* // 'move'
* // ...
* ```
*
* @param otherSources Other observable sources to subscribe to, in sequence, after the original source is complete.
* @return A function that returns an Observable that concatenates
* subscriptions to the source and provided Observables subscribing to the next
* only once the current subscription completes.
*/
export function concatWith<T, A extends readonly unknown[]>(
...otherSources: [...ObservableInputTuple<A>]
): OperatorFunction<T, T | A[number]> {
return concat(...otherSources);
}

109
node_modules/rxjs/src/internal/operators/connect.ts generated vendored Normal file
View File

@@ -0,0 +1,109 @@
import { OperatorFunction, ObservableInput, ObservedValueOf, SubjectLike } from '../types';
import { Observable } from '../Observable';
import { Subject } from '../Subject';
import { innerFrom } from '../observable/innerFrom';
import { operate } from '../util/lift';
import { fromSubscribable } from '../observable/fromSubscribable';
/**
* An object used to configure {@link connect} operator.
*/
export interface ConnectConfig<T> {
/**
* A factory function used to create the Subject through which the source
* is multicast. By default, this creates a {@link Subject}.
*/
connector: () => SubjectLike<T>;
}
/**
* The default configuration for `connect`.
*/
const DEFAULT_CONFIG: ConnectConfig<unknown> = {
connector: () => new Subject<unknown>(),
};
/**
* Creates an observable by multicasting the source within a function that
* allows the developer to define the usage of the multicast prior to connection.
*
* This is particularly useful if the observable source you wish to multicast could
* be synchronous or asynchronous. This sets it apart from {@link share}, which, in the
* case of totally synchronous sources will fail to share a single subscription with
* multiple consumers, as by the time the subscription to the result of {@link share}
* has returned, if the source is synchronous its internal reference count will jump from
* 0 to 1 back to 0 and reset.
*
* To use `connect`, you provide a `selector` function that will give you
* a multicast observable that is not yet connected. You then use that multicast observable
* to create a resulting observable that, when subscribed, will set up your multicast. This is
* generally, but not always, accomplished with {@link merge}.
*
* Note that using a {@link takeUntil} inside of `connect`'s `selector` _might_ mean you were looking
* to use the {@link takeWhile} operator instead.
*
* When you subscribe to the result of `connect`, the `selector` function will be called. After
* the `selector` function returns, the observable it returns will be subscribed to, _then_ the
* multicast will be connected to the source.
*
* ## Example
*
* Sharing a totally synchronous observable
*
* ```ts
* import { of, tap, connect, merge, map, filter } from 'rxjs';
*
* const source$ = of(1, 2, 3, 4, 5).pipe(
* tap({
* subscribe: () => console.log('subscription started'),
* next: n => console.log(`source emitted ${ n }`)
* })
* );
*
* source$.pipe(
* // Notice in here we're merging 3 subscriptions to `shared$`.
* connect(shared$ => merge(
* shared$.pipe(map(n => `all ${ n }`)),
* shared$.pipe(filter(n => n % 2 === 0), map(n => `even ${ n }`)),
* shared$.pipe(filter(n => n % 2 === 1), map(n => `odd ${ n }`))
* ))
* )
* .subscribe(console.log);
*
* // Expected output: (notice only one subscription)
* 'subscription started'
* 'source emitted 1'
* 'all 1'
* 'odd 1'
* 'source emitted 2'
* 'all 2'
* 'even 2'
* 'source emitted 3'
* 'all 3'
* 'odd 3'
* 'source emitted 4'
* 'all 4'
* 'even 4'
* 'source emitted 5'
* 'all 5'
* 'odd 5'
* ```
*
* @param selector A function used to set up the multicast. Gives you a multicast observable
* that is not yet connected. With that, you're expected to create and return
* and Observable, that when subscribed to, will utilize the multicast observable.
* After this function is executed -- and its return value subscribed to -- the
* operator will subscribe to the source, and the connection will be made.
* @param config The configuration object for `connect`.
*/
export function connect<T, O extends ObservableInput<unknown>>(
selector: (shared: Observable<T>) => O,
config: ConnectConfig<T> = DEFAULT_CONFIG
): OperatorFunction<T, ObservedValueOf<O>> {
const { connector } = config;
return operate((source, subscriber) => {
const subject = connector();
innerFrom(selector(fromSubscribable(subject))).subscribe(subscriber);
subscriber.add(source.subscribe(subject));
});
}

61
node_modules/rxjs/src/internal/operators/count.ts generated vendored Normal file
View File

@@ -0,0 +1,61 @@
import { OperatorFunction } from '../types';
import { reduce } from './reduce';
/**
* Counts the number of emissions on the source and emits that number when the
* source completes.
*
* <span class="informal">Tells how many values were emitted, when the source
* completes.</span>
*
* ![](count.png)
*
* `count` transforms an Observable that emits values into an Observable that
* emits a single value that represents the number of values emitted by the
* source Observable. If the source Observable terminates with an error, `count`
* will pass this error notification along without emitting a value first. If
* the source Observable does not terminate at all, `count` will neither emit
* a value nor terminate. This operator takes an optional `predicate` function
* as argument, in which case the output emission will represent the number of
* source values that matched `true` with the `predicate`.
*
* ## Examples
*
* Counts how many seconds have passed before the first click happened
*
* ```ts
* import { interval, fromEvent, takeUntil, count } from 'rxjs';
*
* const seconds = interval(1000);
* const clicks = fromEvent(document, 'click');
* const secondsBeforeClick = seconds.pipe(takeUntil(clicks));
* const result = secondsBeforeClick.pipe(count());
* result.subscribe(x => console.log(x));
* ```
*
* Counts how many odd numbers are there between 1 and 7
*
* ```ts
* import { range, count } from 'rxjs';
*
* const numbers = range(1, 7);
* const result = numbers.pipe(count(i => i % 2 === 1));
* result.subscribe(x => console.log(x));
* // Results in:
* // 4
* ```
*
* @see {@link max}
* @see {@link min}
* @see {@link reduce}
*
* @param predicate A function that is used to analyze the value and the index and
* determine whether or not to increment the count. Return `true` to increment the count,
* and return `false` to keep the count the same.
* If the predicate is not provided, every value will be counted.
* @return A function that returns an Observable that emits one number that
* represents the count of emissions.
*/
export function count<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, number> {
return reduce((total, value, i) => (!predicate || predicate(value, i) ? total + 1 : total), 0);
}

119
node_modules/rxjs/src/internal/operators/debounce.ts generated vendored Normal file
View File

@@ -0,0 +1,119 @@
import { Subscriber } from '../Subscriber';
import { MonoTypeOperatorFunction, ObservableInput } from '../types';
import { operate } from '../util/lift';
import { noop } from '../util/noop';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { innerFrom } from '../observable/innerFrom';
/**
* Emits a notification from the source Observable only after a particular time span
* determined by another Observable has passed without another source emission.
*
* <span class="informal">It's like {@link debounceTime}, but the time span of
* emission silence is determined by a second Observable.</span>
*
* ![](debounce.svg)
*
* `debounce` delays notifications emitted by the source Observable, but drops previous
* pending delayed emissions if a new notification arrives on the source Observable.
* This operator keeps track of the most recent notification from the source
* Observable, and spawns a duration Observable by calling the
* `durationSelector` function. The notification is emitted only when the duration
* Observable emits a next notification, and if no other notification was emitted on
* the source Observable since the duration Observable was spawned. If a new
* notification appears before the duration Observable emits, the previous notification will
* not be emitted and a new duration is scheduled from `durationSelector` is scheduled.
* If the completing event happens during the scheduled duration the last cached notification
* is emitted before the completion event is forwarded to the output observable.
* If the error event happens during the scheduled duration or after it only the error event is
* forwarded to the output observable. The cache notification is not emitted in this case.
*
* Like {@link debounceTime}, this is a rate-limiting operator, and also a
* delay-like operator since output emissions do not necessarily occur at the
* same time as they did on the source Observable.
*
* ## Example
*
* Emit the most recent click after a burst of clicks
*
* ```ts
* import { fromEvent, scan, debounce, interval } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* scan(i => ++i, 1),
* debounce(i => interval(200 * i))
* );
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link audit}
* @see {@link auditTime}
* @see {@link debounceTime}
* @see {@link delay}
* @see {@link sample}
* @see {@link sampleTime}
* @see {@link throttle}
* @see {@link throttleTime}
*
* @param durationSelector A function
* that receives a value from the source Observable, for computing the timeout
* duration for each source value, returned as an Observable or a Promise.
* @return A function that returns an Observable that delays the emissions of
* the source Observable by the specified duration Observable returned by
* `durationSelector`, and may drop some values if they occur too frequently.
*/
export function debounce<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {
return operate((source, subscriber) => {
let hasValue = false;
let lastValue: T | null = null;
// The subscriber/subscription for the current debounce, if there is one.
let durationSubscriber: Subscriber<any> | null = null;
const emit = () => {
// Unsubscribe any current debounce subscription we have,
// we only cared about the first notification from it, and we
// want to clean that subscription up as soon as possible.
durationSubscriber?.unsubscribe();
durationSubscriber = null;
if (hasValue) {
// We have a value! Free up memory first, then emit the value.
hasValue = false;
const value = lastValue!;
lastValue = null;
subscriber.next(value);
}
};
source.subscribe(
createOperatorSubscriber(
subscriber,
(value: T) => {
// Cancel any pending debounce duration. We don't
// need to null it out here yet tho, because we're just going
// to create another one in a few lines.
durationSubscriber?.unsubscribe();
hasValue = true;
lastValue = value;
// Capture our duration subscriber, so we can unsubscribe it when we're notified
// and we're going to emit the value.
durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);
// Subscribe to the duration.
innerFrom(durationSelector(value)).subscribe(durationSubscriber);
},
() => {
// Source completed.
// Emit any pending debounced values then complete
emit();
subscriber.complete();
},
// Pass all errors through to consumer
undefined,
() => {
// Finalization.
lastValue = durationSubscriber = null;
}
)
);
});
}

View File

@@ -0,0 +1,123 @@
import { asyncScheduler } from '../scheduler/async';
import { Subscription } from '../Subscription';
import { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
/**
* Emits a notification from the source Observable only after a particular time span
* has passed without another source emission.
*
* <span class="informal">It's like {@link delay}, but passes only the most
* recent notification from each burst of emissions.</span>
*
* ![](debounceTime.png)
*
* `debounceTime` delays notifications emitted by the source Observable, but drops
* previous pending delayed emissions if a new notification arrives on the source
* Observable. This operator keeps track of the most recent notification from the
* source Observable, and emits that only when `dueTime` has passed
* without any other notification appearing on the source Observable. If a new value
* appears before `dueTime` silence occurs, the previous notification will be dropped
* and will not be emitted and a new `dueTime` is scheduled.
* If the completing event happens during `dueTime` the last cached notification
* is emitted before the completion event is forwarded to the output observable.
* If the error event happens during `dueTime` or after it only the error event is
* forwarded to the output observable. The cache notification is not emitted in this case.
*
* This is a rate-limiting operator, because it is impossible for more than one
* notification to be emitted in any time window of duration `dueTime`, but it is also
* a delay-like operator since output emissions do not occur at the same time as
* they did on the source Observable. Optionally takes a {@link SchedulerLike} for
* managing timers.
*
* ## Example
*
* Emit the most recent click after a burst of clicks
*
* ```ts
* import { fromEvent, debounceTime } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(debounceTime(1000));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link audit}
* @see {@link auditTime}
* @see {@link debounce}
* @see {@link sample}
* @see {@link sampleTime}
* @see {@link throttle}
* @see {@link throttleTime}
*
* @param dueTime The timeout duration in milliseconds (or the time unit determined
* internally by the optional `scheduler`) for the window of time required to wait
* for emission silence before emitting the most recent source value.
* @param scheduler The {@link SchedulerLike} to use for managing the timers that
* handle the timeout for each value.
* @return A function that returns an Observable that delays the emissions of
* the source Observable by the specified `dueTime`, and may drop some values
* if they occur too frequently.
*/
export function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {
return operate((source, subscriber) => {
let activeTask: Subscription | null = null;
let lastValue: T | null = null;
let lastTime: number | null = null;
const emit = () => {
if (activeTask) {
// We have a value! Free up memory first, then emit the value.
activeTask.unsubscribe();
activeTask = null;
const value = lastValue!;
lastValue = null;
subscriber.next(value);
}
};
function emitWhenIdle(this: SchedulerAction<unknown>) {
// This is called `dueTime` after the first value
// but we might have received new values during this window!
const targetTime = lastTime! + dueTime;
const now = scheduler.now();
if (now < targetTime) {
// On that case, re-schedule to the new target
activeTask = this.schedule(undefined, targetTime - now);
subscriber.add(activeTask);
return;
}
emit();
}
source.subscribe(
createOperatorSubscriber(
subscriber,
(value: T) => {
lastValue = value;
lastTime = scheduler.now();
// Only set up a task if it's not already up
if (!activeTask) {
activeTask = scheduler.schedule(emitWhenIdle, dueTime);
subscriber.add(activeTask);
}
},
() => {
// Source completed.
// Emit any pending debounced values then complete
emit();
subscriber.complete();
},
// Pass all errors through to consumer.
undefined,
() => {
// Finalization.
lastValue = activeTask = null;
}
)
);
});
}

View File

@@ -0,0 +1,59 @@
import { OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
/**
* Emits a given value if the source Observable completes without emitting any
* `next` value, otherwise mirrors the source Observable.
*
* <span class="informal">If the source Observable turns out to be empty, then
* this operator will emit a default value.</span>
*
* ![](defaultIfEmpty.png)
*
* `defaultIfEmpty` emits the values emitted by the source Observable or a
* specified default value if the source Observable is empty (completes without
* having emitted any `next` value).
*
* ## Example
*
* If no clicks happen in 5 seconds, then emit 'no clicks'
*
* ```ts
* import { fromEvent, takeUntil, interval, defaultIfEmpty } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));
* const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link empty}
* @see {@link last}
*
* @param defaultValue The default value used if the source
* Observable is empty.
* @return A function that returns an Observable that emits either the
* specified `defaultValue` if the source Observable emits no items, or the
* values emitted by the source Observable.
*/
export function defaultIfEmpty<T, R>(defaultValue: R): OperatorFunction<T, T | R> {
return operate((source, subscriber) => {
let hasValue = false;
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
hasValue = true;
subscriber.next(value);
},
() => {
if (!hasValue) {
subscriber.next(defaultValue!);
}
subscriber.complete();
}
)
);
});
}

65
node_modules/rxjs/src/internal/operators/delay.ts generated vendored Normal file
View File

@@ -0,0 +1,65 @@
import { asyncScheduler } from '../scheduler/async';
import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
import { delayWhen } from './delayWhen';
import { timer } from '../observable/timer';
/**
* Delays the emission of items from the source Observable by a given timeout or
* until a given Date.
*
* <span class="informal">Time shifts each item by some specified amount of
* milliseconds.</span>
*
* ![](delay.svg)
*
* If the delay argument is a Number, this operator time shifts the source
* Observable by that amount of time expressed in milliseconds. The relative
* time intervals between the values are preserved.
*
* If the delay argument is a Date, this operator time shifts the start of the
* Observable execution until the given date occurs.
*
* ## Examples
*
* Delay each click by one second
*
* ```ts
* import { fromEvent, delay } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second
* delayedClicks.subscribe(x => console.log(x));
* ```
*
* Delay all clicks until a future date happens
*
* ```ts
* import { fromEvent, delay } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const date = new Date('March 15, 2050 12:00:00'); // in the future
* const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date
* delayedClicks.subscribe(x => console.log(x));
* ```
*
* @see {@link delayWhen}
* @see {@link throttle}
* @see {@link throttleTime}
* @see {@link debounce}
* @see {@link debounceTime}
* @see {@link sample}
* @see {@link sampleTime}
* @see {@link audit}
* @see {@link auditTime}
*
* @param due The delay duration in milliseconds (a `number`) or a `Date` until
* which the emission of the source items is delayed.
* @param scheduler The {@link SchedulerLike} to use for managing the timers
* that handle the time-shift for each item.
* @return A function that returns an Observable that delays the emissions of
* the source Observable by the specified timeout or Date.
*/
export function delay<T>(due: number | Date, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {
const duration = timer(due, scheduler);
return delayWhen(() => duration);
}

103
node_modules/rxjs/src/internal/operators/delayWhen.ts generated vendored Normal file
View File

@@ -0,0 +1,103 @@
import { Observable } from '../Observable';
import { MonoTypeOperatorFunction, ObservableInput } from '../types';
import { concat } from '../observable/concat';
import { take } from './take';
import { ignoreElements } from './ignoreElements';
import { mapTo } from './mapTo';
import { mergeMap } from './mergeMap';
import { innerFrom } from '../observable/innerFrom';
/** @deprecated The `subscriptionDelay` parameter will be removed in v8. */
export function delayWhen<T>(
delayDurationSelector: (value: T, index: number) => ObservableInput<any>,
subscriptionDelay: Observable<any>
): MonoTypeOperatorFunction<T>;
export function delayWhen<T>(delayDurationSelector: (value: T, index: number) => ObservableInput<any>): MonoTypeOperatorFunction<T>;
/**
* Delays the emission of items from the source Observable by a given time span
* determined by the emissions of another Observable.
*
* <span class="informal">It's like {@link delay}, but the time span of the
* delay duration is determined by a second Observable.</span>
*
* ![](delayWhen.png)
*
* `delayWhen` operator shifts each emitted value from the source Observable by
* a time span determined by another Observable. When the source emits a value,
* the `delayDurationSelector` function is called with the value emitted from
* the source Observable as the first argument to the `delayDurationSelector`.
* The `delayDurationSelector` function should return an {@link ObservableInput},
* that is internally converted to an Observable that is called the "duration"
* Observable.
*
* The source value is emitted on the output Observable only when the "duration"
* Observable emits ({@link guide/glossary-and-semantics#next next}s) any value.
* Upon that, the "duration" Observable gets unsubscribed.
*
* Before RxJS V7, the {@link guide/glossary-and-semantics#complete completion}
* of the "duration" Observable would have been triggering the emission of the
* source value to the output Observable, but with RxJS V7, this is not the case
* anymore.
*
* Only next notifications (from the "duration" Observable) trigger values from
* the source Observable to be passed to the output Observable. If the "duration"
* Observable only emits the complete notification (without next), the value
* emitted by the source Observable will never get to the output Observable - it
* will be swallowed. If the "duration" Observable errors, the error will be
* propagated to the output Observable.
*
* Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which
* is an Observable. When `subscriptionDelay` emits its first value or
* completes, the source Observable is subscribed to and starts behaving like
* described in the previous paragraph. If `subscriptionDelay` is not provided,
* `delayWhen` will subscribe to the source Observable as soon as the output
* Observable is subscribed.
*
* ## Example
*
* Delay each click by a random amount of time, between 0 and 5 seconds
*
* ```ts
* import { fromEvent, delayWhen, interval } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const delayedClicks = clicks.pipe(
* delayWhen(() => interval(Math.random() * 5000))
* );
* delayedClicks.subscribe(x => console.log(x));
* ```
*
* @see {@link delay}
* @see {@link throttle}
* @see {@link throttleTime}
* @see {@link debounce}
* @see {@link debounceTime}
* @see {@link sample}
* @see {@link sampleTime}
* @see {@link audit}
* @see {@link auditTime}
*
* @param delayDurationSelector A function that returns an `ObservableInput` for
* each `value` emitted by the source Observable, which is then used to delay the
* emission of that `value` on the output Observable until the `ObservableInput`
* returned from this function emits a next value. When called, beside `value`,
* this function receives a zero-based `index` of the emission order.
* @param subscriptionDelay An Observable that triggers the subscription to the
* source Observable once it emits any value.
* @return A function that returns an Observable that delays the emissions of
* the source Observable by an amount of time specified by the Observable
* returned by `delayDurationSelector`.
*/
export function delayWhen<T>(
delayDurationSelector: (value: T, index: number) => ObservableInput<any>,
subscriptionDelay?: Observable<any>
): MonoTypeOperatorFunction<T> {
if (subscriptionDelay) {
// DEPRECATED PATH
return (source: Observable<T>) =>
concat(subscriptionDelay.pipe(take(1), ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));
}
return mergeMap((value, index) => innerFrom(delayDurationSelector(value, index)).pipe(take(1), mapTo(value)));
}

View File

@@ -0,0 +1,58 @@
import { observeNotification } from '../Notification';
import { OperatorFunction, ObservableNotification, ValueFromNotification } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
/**
* Converts an Observable of {@link ObservableNotification} objects into the emissions
* that they represent.
*
* <span class="informal">Unwraps {@link ObservableNotification} objects as actual `next`,
* `error` and `complete` emissions. The opposite of {@link materialize}.</span>
*
* ![](dematerialize.png)
*
* `dematerialize` is assumed to operate an Observable that only emits
* {@link ObservableNotification} objects as `next` emissions, and does not emit any
* `error`. Such Observable is the output of a `materialize` operation. Those
* notifications are then unwrapped using the metadata they contain, and emitted
* as `next`, `error`, and `complete` on the output Observable.
*
* Use this operator in conjunction with {@link materialize}.
*
* ## Example
*
* Convert an Observable of Notifications to an actual Observable
*
* ```ts
* import { NextNotification, ErrorNotification, of, dematerialize } from 'rxjs';
*
* const notifA: NextNotification<string> = { kind: 'N', value: 'A' };
* const notifB: NextNotification<string> = { kind: 'N', value: 'B' };
* const notifE: ErrorNotification = { kind: 'E', error: new TypeError('x.toUpperCase is not a function') };
*
* const materialized = of(notifA, notifB, notifE);
*
* const upperCase = materialized.pipe(dematerialize());
* upperCase.subscribe({
* next: x => console.log(x),
* error: e => console.error(e)
* });
*
* // Results in:
* // A
* // B
* // TypeError: x.toUpperCase is not a function
* ```
*
* @see {@link materialize}
*
* @return A function that returns an Observable that emits items and
* notifications embedded in Notification objects emitted by the source
* Observable.
*/
export function dematerialize<N extends ObservableNotification<any>>(): OperatorFunction<N, ValueFromNotification<N>> {
return operate((source, subscriber) => {
source.subscribe(createOperatorSubscriber(subscriber, (notification) => observeNotification(notification, subscriber)));
});
}

79
node_modules/rxjs/src/internal/operators/distinct.ts generated vendored Normal file
View File

@@ -0,0 +1,79 @@
import { MonoTypeOperatorFunction, ObservableInput } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { noop } from '../util/noop';
import { innerFrom } from '../observable/innerFrom';
/**
* Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.
*
* If a `keySelector` function is provided, then it will project each value from the source observable into a new value that it will
* check for equality with previously projected values. If the `keySelector` function is not provided, it will use each value from the
* source observable directly with an equality check against previous values.
*
* In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.
*
* In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the
* hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`
* use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so
* that the internal `Set` can be "flushed", basically clearing it of values.
*
* ## Examples
*
* A simple example with numbers
*
* ```ts
* import { of, distinct } from 'rxjs';
*
* of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)
* .pipe(distinct())
* .subscribe(x => console.log(x));
*
* // Outputs
* // 1
* // 2
* // 3
* // 4
* ```
*
* An example using the `keySelector` function
*
* ```ts
* import { of, distinct } from 'rxjs';
*
* of(
* { age: 4, name: 'Foo'},
* { age: 7, name: 'Bar'},
* { age: 5, name: 'Foo'}
* )
* .pipe(distinct(({ name }) => name))
* .subscribe(x => console.log(x));
*
* // Outputs
* // { age: 4, name: 'Foo' }
* // { age: 7, name: 'Bar' }
* ```
* @see {@link distinctUntilChanged}
* @see {@link distinctUntilKeyChanged}
*
* @param keySelector Optional `function` to select which value you want to check as distinct.
* @param flushes Optional `ObservableInput` for flushing the internal HashSet of the operator.
* @return A function that returns an Observable that emits items from the
* source Observable with distinct values.
*/
export function distinct<T, K>(keySelector?: (value: T) => K, flushes?: ObservableInput<any>): MonoTypeOperatorFunction<T> {
return operate((source, subscriber) => {
const distinctKeys = new Set();
source.subscribe(
createOperatorSubscriber(subscriber, (value) => {
const key = keySelector ? keySelector(value) : value;
if (!distinctKeys.has(key)) {
distinctKeys.add(key);
subscriber.next(value);
}
})
);
flushes && innerFrom(flushes).subscribe(createOperatorSubscriber(subscriber, () => distinctKeys.clear(), noop));
});
}

View File

@@ -0,0 +1,182 @@
import { MonoTypeOperatorFunction } from '../types';
import { identity } from '../util/identity';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
export function distinctUntilChanged<T>(comparator?: (previous: T, current: T) => boolean): MonoTypeOperatorFunction<T>;
export function distinctUntilChanged<T, K>(
comparator: (previous: K, current: K) => boolean,
keySelector: (value: T) => K
): MonoTypeOperatorFunction<T>;
/**
* Returns a result {@link Observable} that emits all values pushed by the source observable if they
* are distinct in comparison to the last value the result observable emitted.
*
* When provided without parameters or with the first parameter (`{@link distinctUntilChanged#comparator comparator}`),
* it behaves like this:
*
* 1. It will always emit the first value from the source.
* 2. For all subsequent values pushed by the source, they will be compared to the previously emitted values
* using the provided `comparator` or an `===` equality check.
* 3. If the value pushed by the source is determined to be unequal by this check, that value is emitted and
* becomes the new "previously emitted value" internally.
*
* When the second parameter (`{@link distinctUntilChanged#keySelector keySelector}`) is provided, the behavior
* changes:
*
* 1. It will always emit the first value from the source.
* 2. The `keySelector` will be run against all values, including the first value.
* 3. For all values after the first, the selected key will be compared against the key selected from
* the previously emitted value using the `comparator`.
* 4. If the keys are determined to be unequal by this check, the value (not the key), is emitted
* and the selected key from that value is saved for future comparisons against other keys.
*
* ## Examples
*
* A very basic example with no `{@link distinctUntilChanged#comparator comparator}`. Note that `1` is emitted more than once,
* because it's distinct in comparison to the _previously emitted_ value,
* not in comparison to _all other emitted values_.
*
* ```ts
* import { of, distinctUntilChanged } from 'rxjs';
*
* of(1, 1, 1, 2, 2, 2, 1, 1, 3, 3)
* .pipe(distinctUntilChanged())
* .subscribe(console.log);
* // Logs: 1, 2, 1, 3
* ```
*
* With a `{@link distinctUntilChanged#comparator comparator}`, you can do custom comparisons. Let's say
* you only want to emit a value when all of its components have
* changed:
*
* ```ts
* import { of, distinctUntilChanged } from 'rxjs';
*
* const totallyDifferentBuilds$ = of(
* { engineVersion: '1.1.0', transmissionVersion: '1.2.0' },
* { engineVersion: '1.1.0', transmissionVersion: '1.4.0' },
* { engineVersion: '1.3.0', transmissionVersion: '1.4.0' },
* { engineVersion: '1.3.0', transmissionVersion: '1.5.0' },
* { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }
* ).pipe(
* distinctUntilChanged((prev, curr) => {
* return (
* prev.engineVersion === curr.engineVersion ||
* prev.transmissionVersion === curr.transmissionVersion
* );
* })
* );
*
* totallyDifferentBuilds$.subscribe(console.log);
*
* // Logs:
* // { engineVersion: '1.1.0', transmissionVersion: '1.2.0' }
* // { engineVersion: '1.3.0', transmissionVersion: '1.4.0' }
* // { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }
* ```
*
* You can also provide a custom `{@link distinctUntilChanged#comparator comparator}` to check that emitted
* changes are only in one direction. Let's say you only want to get
* the next record temperature:
*
* ```ts
* import { of, distinctUntilChanged } from 'rxjs';
*
* const temps$ = of(30, 31, 20, 34, 33, 29, 35, 20);
*
* const recordHighs$ = temps$.pipe(
* distinctUntilChanged((prevHigh, temp) => {
* // If the current temp is less than
* // or the same as the previous record,
* // the record hasn't changed.
* return temp <= prevHigh;
* })
* );
*
* recordHighs$.subscribe(console.log);
* // Logs: 30, 31, 34, 35
* ```
*
* Selecting update events only when the `updatedBy` field shows
* the account changed hands.
*
* ```ts
* import { of, distinctUntilChanged } from 'rxjs';
*
* // A stream of updates to a given account
* const accountUpdates$ = of(
* { updatedBy: 'blesh', data: [] },
* { updatedBy: 'blesh', data: [] },
* { updatedBy: 'ncjamieson', data: [] },
* { updatedBy: 'ncjamieson', data: [] },
* { updatedBy: 'blesh', data: [] }
* );
*
* // We only want the events where it changed hands
* const changedHands$ = accountUpdates$.pipe(
* distinctUntilChanged(undefined, update => update.updatedBy)
* );
*
* changedHands$.subscribe(console.log);
* // Logs:
* // { updatedBy: 'blesh', data: Array[0] }
* // { updatedBy: 'ncjamieson', data: Array[0] }
* // { updatedBy: 'blesh', data: Array[0] }
* ```
*
* @see {@link distinct}
* @see {@link distinctUntilKeyChanged}
*
* @param comparator A function used to compare the previous and current keys for
* equality. Defaults to a `===` check.
* @param keySelector Used to select a key value to be passed to the `comparator`.
*
* @return A function that returns an Observable that emits items from the
* source Observable with distinct values.
*/
export function distinctUntilChanged<T, K>(
comparator?: (previous: K, current: K) => boolean,
keySelector: (value: T) => K = identity as (value: T) => K
): MonoTypeOperatorFunction<T> {
// We've been allowing `null` do be passed as the `compare`, so we can't do
// a default value for the parameter, because that will only work
// for `undefined`.
comparator = comparator ?? defaultCompare;
return operate((source, subscriber) => {
// The previous key, used to compare against keys selected
// from new arrivals to determine "distinctiveness".
let previousKey: K;
// Whether or not this is the first value we've gotten.
let first = true;
source.subscribe(
createOperatorSubscriber(subscriber, (value) => {
// We always call the key selector.
const currentKey = keySelector(value);
// If it's the first value, we always emit it.
// Otherwise, we compare this key to the previous key, and
// if the comparer returns false, we emit.
if (first || !comparator!(previousKey, currentKey)) {
// Update our state *before* we emit the value
// as emission can be the source of re-entrant code
// in functional libraries like this. We only really
// need to do this if it's the first value, or if the
// key we're tracking in previous needs to change.
first = false;
previousKey = currentKey;
// Emit the value!
subscriber.next(value);
}
})
);
});
}
function defaultCompare(a: any, b: any) {
return a === b;
}

View File

@@ -0,0 +1,75 @@
import { distinctUntilChanged } from './distinctUntilChanged';
import { MonoTypeOperatorFunction } from '../types';
export function distinctUntilKeyChanged<T>(key: keyof T): MonoTypeOperatorFunction<T>;
export function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T>;
/**
* Returns an Observable that emits all items emitted by the source Observable that
* are distinct by comparison from the previous item, using a property accessed by
* using the key provided to check if the two items are distinct.
*
* If a comparator function is provided, then it will be called for each item to
* test for whether that value should be emitted or not.
*
* If a comparator function is not provided, an equality check is used by default.
*
* ## Examples
*
* An example comparing the name of persons
*
* ```ts
* import { of, distinctUntilKeyChanged } from 'rxjs';
*
* of(
* { age: 4, name: 'Foo' },
* { age: 7, name: 'Bar' },
* { age: 5, name: 'Foo' },
* { age: 6, name: 'Foo' }
* ).pipe(
* distinctUntilKeyChanged('name')
* )
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo' }
* // { age: 7, name: 'Bar' }
* // { age: 5, name: 'Foo' }
* ```
*
* An example comparing the first letters of the name
*
* ```ts
* import { of, distinctUntilKeyChanged } from 'rxjs';
*
* of(
* { age: 4, name: 'Foo1' },
* { age: 7, name: 'Bar' },
* { age: 5, name: 'Foo2' },
* { age: 6, name: 'Foo3' }
* ).pipe(
* distinctUntilKeyChanged('name', (x, y) => x.substring(0, 3) === y.substring(0, 3))
* )
* .subscribe(x => console.log(x));
*
* // displays:
* // { age: 4, name: 'Foo1' }
* // { age: 7, name: 'Bar' }
* // { age: 5, name: 'Foo2' }
* ```
*
* @see {@link distinct}
* @see {@link distinctUntilChanged}
*
* @param key String key for object property lookup on each item.
* @param compare Optional comparison function called to test if an item is distinct
* from the previous item in the source.
* @return A function that returns an Observable that emits items from the source
* Observable with distinct values based on the key specified.
*/
export function distinctUntilKeyChanged<T, K extends keyof T>(
key: K,
compare?: (x: T[K], y: T[K]) => boolean
): MonoTypeOperatorFunction<T> {
return distinctUntilChanged((x: T, y: T) => (compare ? compare(x[key], y[key]) : x[key] === y[key]));
}

68
node_modules/rxjs/src/internal/operators/elementAt.ts generated vendored Normal file
View File

@@ -0,0 +1,68 @@
import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';
import { Observable } from '../Observable';
import { OperatorFunction } from '../types';
import { filter } from './filter';
import { throwIfEmpty } from './throwIfEmpty';
import { defaultIfEmpty } from './defaultIfEmpty';
import { take } from './take';
/**
* Emits the single value at the specified `index` in a sequence of emissions
* from the source Observable.
*
* <span class="informal">Emits only the i-th value, then completes.</span>
*
* ![](elementAt.png)
*
* `elementAt` returns an Observable that emits the item at the specified
* `index` in the source Observable, or a default value if that `index` is out
* of range and the `default` argument is provided. If the `default` argument is
* not given and the `index` is out of range, the output Observable will emit an
* `ArgumentOutOfRangeError` error.
*
* ## Example
*
* Emit only the third click event
*
* ```ts
* import { fromEvent, elementAt } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(elementAt(2));
* result.subscribe(x => console.log(x));
*
* // Results in:
* // click 1 = nothing
* // click 2 = nothing
* // click 3 = MouseEvent object logged to console
* ```
*
* @see {@link first}
* @see {@link last}
* @see {@link skip}
* @see {@link single}
* @see {@link take}
*
* @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an
* `ArgumentOutOfRangeError` to the Observer's `error` callback if `i < 0` or the
* Observable has completed before emitting the i-th `next` notification.
*
* @param index Is the number `i` for the i-th source emission that has happened
* since the subscription, starting from the number `0`.
* @param defaultValue The default value returned for missing indices.
* @return A function that returns an Observable that emits a single item, if
* it is found. Otherwise, it will emit the default value if given. If not, it
* emits an error.
*/
export function elementAt<T, D = T>(index: number, defaultValue?: D): OperatorFunction<T, T | D> {
if (index < 0) {
throw new ArgumentOutOfRangeError();
}
const hasDefaultValue = arguments.length >= 2;
return (source: Observable<T>) =>
source.pipe(
filter((v, i) => i === index),
take(1),
hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new ArgumentOutOfRangeError())
);
}

68
node_modules/rxjs/src/internal/operators/endWith.ts generated vendored Normal file
View File

@@ -0,0 +1,68 @@
/** prettier */
import { Observable } from '../Observable';
import { concat } from '../observable/concat';
import { of } from '../observable/of';
import { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction, ValueFromArray } from '../types';
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function endWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;
/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */
export function endWith<T, A extends unknown[] = T[]>(
...valuesAndScheduler: [...A, SchedulerLike]
): OperatorFunction<T, T | ValueFromArray<A>>;
export function endWith<T, A extends unknown[] = T[]>(...values: A): OperatorFunction<T, T | ValueFromArray<A>>;
/**
* Returns an observable that will emit all values from the source, then synchronously emit
* the provided value(s) immediately after the source completes.
*
* NOTE: Passing a last argument of a Scheduler is _deprecated_, and may result in incorrect
* types in TypeScript.
*
* This is useful for knowing when an observable ends. Particularly when paired with an
* operator like {@link takeUntil}
*
* ![](endWith.png)
*
* ## Example
*
* Emit values to know when an interval starts and stops. The interval will
* stop when a user clicks anywhere on the document.
*
* ```ts
* import { interval, map, fromEvent, startWith, takeUntil, endWith } from 'rxjs';
*
* const ticker$ = interval(5000).pipe(
* map(() => 'tick')
* );
*
* const documentClicks$ = fromEvent(document, 'click');
*
* ticker$.pipe(
* startWith('interval started'),
* takeUntil(documentClicks$),
* endWith('interval ended by click')
* )
* .subscribe(x => console.log(x));
*
* // Result (assuming a user clicks after 15 seconds)
* // 'interval started'
* // 'tick'
* // 'tick'
* // 'tick'
* // 'interval ended by click'
* ```
*
* @see {@link startWith}
* @see {@link concat}
* @see {@link takeUntil}
*
* @param values Items you want the modified Observable to emit last.
* @return A function that returns an Observable that emits all values from the
* source, then synchronously emits the provided value(s) immediately after the
* source completes.
*/
export function endWith<T>(...values: Array<T | SchedulerLike>): MonoTypeOperatorFunction<T> {
return (source: Observable<T>) => concat(source, of(...values)) as Observable<T>;
}

66
node_modules/rxjs/src/internal/operators/every.ts generated vendored Normal file
View File

@@ -0,0 +1,66 @@
import { Observable } from '../Observable';
import { Falsy, OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
export function every<T>(predicate: BooleanConstructor): OperatorFunction<T, Exclude<T, Falsy> extends never ? false : boolean>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function every<T>(
predicate: BooleanConstructor,
thisArg: any
): OperatorFunction<T, Exclude<T, Falsy> extends never ? false : boolean>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function every<T, A>(
predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,
thisArg: A
): OperatorFunction<T, boolean>;
export function every<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, boolean>;
/**
* Returns an Observable that emits whether or not every item of the source satisfies the condition specified.
*
* <span class="informal">If all values pass predicate before the source completes, emits true before completion,
* otherwise emit false, then complete.</span>
*
* ![](every.png)
*
* ## Example
*
* A simple example emitting true if all elements are less than 5, false otherwise
*
* ```ts
* import { of, every } from 'rxjs';
*
* of(1, 2, 3, 4, 5, 6)
* .pipe(every(x => x < 5))
* .subscribe(x => console.log(x)); // -> false
* ```
*
* @param predicate A function for determining if an item meets a specified condition.
* @param thisArg Optional object to use for `this` in the callback.
* @return A function that returns an Observable of booleans that determines if
* all items of the source Observable meet the condition specified.
*/
export function every<T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any
): OperatorFunction<T, boolean> {
return operate((source, subscriber) => {
let index = 0;
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
if (!predicate.call(thisArg, value, index++, source)) {
subscriber.next(false);
subscriber.complete();
}
},
() => {
subscriber.next(true);
subscriber.complete();
}
)
);
});
}

6
node_modules/rxjs/src/internal/operators/exhaust.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { exhaustAll } from './exhaustAll';
/**
* @deprecated Renamed to {@link exhaustAll}. Will be removed in v8.
*/
export const exhaust = exhaustAll;

51
node_modules/rxjs/src/internal/operators/exhaustAll.ts generated vendored Normal file
View File

@@ -0,0 +1,51 @@
import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';
import { exhaustMap } from './exhaustMap';
import { identity } from '../util/identity';
/**
* Converts a higher-order Observable into a first-order Observable by dropping
* inner Observables while the previous inner Observable has not yet completed.
*
* <span class="informal">Flattens an Observable-of-Observables by dropping the
* next inner Observables while the current inner is still executing.</span>
*
* ![](exhaustAll.svg)
*
* `exhaustAll` subscribes to an Observable that emits Observables, also known as a
* higher-order Observable. Each time it observes one of these emitted inner
* Observables, the output Observable begins emitting the items emitted by that
* inner Observable. So far, it behaves like {@link mergeAll}. However,
* `exhaustAll` ignores every new inner Observable if the previous Observable has
* not yet completed. Once that one completes, it will accept and flatten the
* next inner Observable and repeat this process.
*
* ## Example
*
* Run a finite timer for each click, only if there is no currently active timer
*
* ```ts
* import { fromEvent, map, interval, take, exhaustAll } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const higherOrder = clicks.pipe(
* map(() => interval(1000).pipe(take(5)))
* );
* const result = higherOrder.pipe(exhaustAll());
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link combineLatestAll}
* @see {@link concatAll}
* @see {@link switchAll}
* @see {@link switchMap}
* @see {@link mergeAll}
* @see {@link exhaustMap}
* @see {@link zipAll}
*
* @return A function that returns an Observable that takes a source of
* Observables and propagates the first Observable exclusively until it
* completes before subscribing to the next.
*/
export function exhaustAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {
return exhaustMap(identity);
}

100
node_modules/rxjs/src/internal/operators/exhaustMap.ts generated vendored Normal file
View File

@@ -0,0 +1,100 @@
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';
import { map } from './map';
import { innerFrom } from '../observable/innerFrom';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
/* tslint:disable:max-line-length */
export function exhaustMap<T, O extends ObservableInput<any>>(
project: (value: T, index: number) => O
): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
export function exhaustMap<T, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector: undefined
): OperatorFunction<T, ObservedValueOf<O>>;
/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */
export function exhaustMap<T, I, R>(
project: (value: T, index: number) => ObservableInput<I>,
resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, R>;
/* tslint:enable:max-line-length */
/**
* Projects each source value to an Observable which is merged in the output
* Observable only if the previous projected Observable has completed.
*
* <span class="informal">Maps each value to an Observable, then flattens all of
* these inner Observables using {@link exhaustAll}.</span>
*
* ![](exhaustMap.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an (so-called "inner") Observable. When it projects a source value to
* an Observable, the output Observable begins emitting the items emitted by
* that projected Observable. However, `exhaustMap` ignores every new projected
* Observable if the previous projected Observable has not yet completed. Once
* that one completes, it will accept and flatten the next projected Observable
* and repeat this process.
*
* ## Example
*
* Run a finite timer for each click, only if there is no currently active timer
*
* ```ts
* import { fromEvent, exhaustMap, interval, take } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(
* exhaustMap(() => interval(1000).pipe(take(5)))
* );
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link concatMap}
* @see {@link exhaust}
* @see {@link mergeMap}
* @see {@link switchMap}
*
* @param project A function that, when applied to an item emitted by the source
* Observable, returns an Observable.
* @return A function that returns an Observable containing projected
* Observables of each item of the source, ignoring projected Observables that
* start before their preceding Observable has completed.
*/
export function exhaustMap<T, R, O extends ObservableInput<any>>(
project: (value: T, index: number) => O,
resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R
): OperatorFunction<T, ObservedValueOf<O> | R> {
if (resultSelector) {
// DEPRECATED PATH
return (source: Observable<T>) =>
source.pipe(exhaustMap((a, i) => innerFrom(project(a, i)).pipe(map((b: any, ii: any) => resultSelector(a, b, i, ii)))));
}
return operate((source, subscriber) => {
let index = 0;
let innerSub: Subscriber<T> | null = null;
let isComplete = false;
source.subscribe(
createOperatorSubscriber(
subscriber,
(outerValue) => {
if (!innerSub) {
innerSub = createOperatorSubscriber(subscriber, undefined, () => {
innerSub = null;
isComplete && subscriber.complete();
});
innerFrom(project(outerValue, index++)).subscribe(innerSub);
}
},
() => {
isComplete = true;
!innerSub && subscriber.complete();
}
)
);
});
}

95
node_modules/rxjs/src/internal/operators/expand.ts generated vendored Normal file
View File

@@ -0,0 +1,95 @@
import { OperatorFunction, ObservableInput, ObservedValueOf, SchedulerLike } from '../types';
import { operate } from '../util/lift';
import { mergeInternals } from './mergeInternals';
/* tslint:disable:max-line-length */
export function expand<T, O extends ObservableInput<unknown>>(
project: (value: T, index: number) => O,
concurrent?: number,
scheduler?: SchedulerLike
): OperatorFunction<T, ObservedValueOf<O>>;
/**
* @deprecated The `scheduler` parameter will be removed in v8. If you need to schedule the inner subscription,
* use `subscribeOn` within the projection function: `expand((value) => fn(value).pipe(subscribeOn(scheduler)))`.
* Details: Details: https://rxjs.dev/deprecations/scheduler-argument
*/
export function expand<T, O extends ObservableInput<unknown>>(
project: (value: T, index: number) => O,
concurrent: number | undefined,
scheduler: SchedulerLike
): OperatorFunction<T, ObservedValueOf<O>>;
/* tslint:enable:max-line-length */
/**
* Recursively projects each source value to an Observable which is merged in
* the output Observable.
*
* <span class="informal">It's similar to {@link mergeMap}, but applies the
* projection function to every source value as well as every output value.
* It's recursive.</span>
*
* ![](expand.png)
*
* Returns an Observable that emits items based on applying a function that you
* supply to each item emitted by the source Observable, where that function
* returns an Observable, and then merging those resulting Observables and
* emitting the results of this merger. *Expand* will re-emit on the output
* Observable every source value. Then, each output value is given to the
* `project` function which returns an inner Observable to be merged on the
* output Observable. Those output values resulting from the projection are also
* given to the `project` function to produce new output values. This is how
* *expand* behaves recursively.
*
* ## Example
*
* Start emitting the powers of two on every click, at most 10 of them
*
* ```ts
* import { fromEvent, map, expand, of, delay, take } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const powersOfTwo = clicks.pipe(
* map(() => 1),
* expand(x => of(2 * x).pipe(delay(1000))),
* take(10)
* );
* powersOfTwo.subscribe(x => console.log(x));
* ```
*
* @see {@link mergeMap}
* @see {@link mergeScan}
*
* @param project A function that, when applied to an item emitted by the source
* or the output Observable, returns an Observable.
* @param concurrent Maximum number of input Observables being subscribed to
* concurrently.
* @param scheduler The {@link SchedulerLike} to use for subscribing to
* each projected inner Observable.
* @return A function that returns an Observable that emits the source values
* and also result of applying the projection function to each value emitted on
* the output Observable and merging the results of the Observables obtained
* from this transformation.
*/
export function expand<T, O extends ObservableInput<unknown>>(
project: (value: T, index: number) => O,
concurrent = Infinity,
scheduler?: SchedulerLike
): OperatorFunction<T, ObservedValueOf<O>> {
concurrent = (concurrent || 0) < 1 ? Infinity : concurrent;
return operate((source, subscriber) =>
mergeInternals(
// General merge params
source,
subscriber,
project,
concurrent,
// onBeforeNext
undefined,
// Expand-specific
true, // Use expand path
scheduler // Inner subscription scheduler
)
);
}

75
node_modules/rxjs/src/internal/operators/filter.ts generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import { OperatorFunction, MonoTypeOperatorFunction, TruthyTypesOf } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function filter<T, S extends T, A>(predicate: (this: A, value: T, index: number) => value is S, thisArg: A): OperatorFunction<T, S>;
export function filter<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;
export function filter<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function filter<T, A>(predicate: (this: A, value: T, index: number) => boolean, thisArg: A): MonoTypeOperatorFunction<T>;
export function filter<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T>;
/**
* Filter items emitted by the source Observable by only emitting those that
* satisfy a specified predicate.
*
* <span class="informal">Like
* [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),
* it only emits a value from the source if it passes a criterion function.</span>
*
* ![](filter.png)
*
* Similar to the well-known `Array.prototype.filter` method, this operator
* takes values from the source Observable, passes them through a `predicate`
* function and only emits those values that yielded `true`.
*
* ## Example
*
* Emit only click events whose target was a DIV element
*
* ```ts
* import { fromEvent, filter } from 'rxjs';
*
* const div = document.createElement('div');
* div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
* document.body.appendChild(div);
*
* const clicks = fromEvent(document, 'click');
* const clicksOnDivs = clicks.pipe(filter(ev => (<HTMLElement>ev.target).tagName === 'DIV'));
* clicksOnDivs.subscribe(x => console.log(x));
* ```
*
* @see {@link distinct}
* @see {@link distinctUntilChanged}
* @see {@link distinctUntilKeyChanged}
* @see {@link ignoreElements}
* @see {@link partition}
* @see {@link skip}
*
* @param predicate A function that
* evaluates each value emitted by the source Observable. If it returns `true`,
* the value is emitted, if `false` the value is not passed to the output
* Observable. The `index` parameter is the number `i` for the i-th source
* emission that has happened since the subscription, starting from the number
* `0`.
* @param thisArg An optional argument to determine the value of `this`
* in the `predicate` function.
* @return A function that returns an Observable that emits items from the
* source Observable that satisfy the specified `predicate`.
*/
export function filter<T>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<T> {
return operate((source, subscriber) => {
// An index passed to our predicate function on each call.
let index = 0;
// Subscribe to the source, all errors and completions are
// forwarded to the consumer.
source.subscribe(
// Call the predicate with the appropriate `this` context,
// if the predicate returns `true`, then send the value
// to the consumer.
createOperatorSubscriber(subscriber, (value) => predicate.call(thisArg, value, index++) && subscriber.next(value))
);
});
}

75
node_modules/rxjs/src/internal/operators/finalize.ts generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import { MonoTypeOperatorFunction } from '../types';
import { operate } from '../util/lift';
/**
* Returns an Observable that mirrors the source Observable, but will call a specified function when
* the source terminates on complete or error.
* The specified function will also be called when the subscriber explicitly unsubscribes.
*
* ## Examples
*
* Execute callback function when the observable completes
*
* ```ts
* import { interval, take, finalize } from 'rxjs';
*
* // emit value in sequence every 1 second
* const source = interval(1000);
* const example = source.pipe(
* take(5), //take only the first 5 values
* finalize(() => console.log('Sequence complete')) // Execute when the observable completes
* );
* const subscribe = example.subscribe(val => console.log(val));
*
* // results:
* // 0
* // 1
* // 2
* // 3
* // 4
* // 'Sequence complete'
* ```
*
* Execute callback function when the subscriber explicitly unsubscribes
*
* ```ts
* import { interval, finalize, tap, noop, timer } from 'rxjs';
*
* const source = interval(100).pipe(
* finalize(() => console.log('[finalize] Called')),
* tap({
* next: () => console.log('[next] Called'),
* error: () => console.log('[error] Not called'),
* complete: () => console.log('[tap complete] Not called')
* })
* );
*
* const sub = source.subscribe({
* next: x => console.log(x),
* error: noop,
* complete: () => console.log('[complete] Not called')
* });
*
* timer(150).subscribe(() => sub.unsubscribe());
*
* // results:
* // '[next] Called'
* // 0
* // '[finalize] Called'
* ```
*
* @param callback Function to be called when source terminates.
* @return A function that returns an Observable that mirrors the source, but
* will call the specified function on termination.
*/
export function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {
return operate((source, subscriber) => {
// TODO: This try/finally was only added for `useDeprecatedSynchronousErrorHandling`.
// REMOVE THIS WHEN THAT HOT GARBAGE IS REMOVED IN V8.
try {
source.subscribe(subscriber);
} finally {
subscriber.add(callback);
}
});
}

96
node_modules/rxjs/src/internal/operators/find.ts generated vendored Normal file
View File

@@ -0,0 +1,96 @@
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { OperatorFunction, TruthyTypesOf } from '../types';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
export function find<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function find<T, S extends T, A>(
predicate: (this: A, value: T, index: number, source: Observable<T>) => value is S,
thisArg: A
): OperatorFunction<T, S | undefined>;
export function find<T, S extends T>(
predicate: (value: T, index: number, source: Observable<T>) => value is S
): OperatorFunction<T, S | undefined>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function find<T, A>(
predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,
thisArg: A
): OperatorFunction<T, T | undefined>;
export function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, T | undefined>;
/**
* Emits only the first value emitted by the source Observable that meets some
* condition.
*
* <span class="informal">Finds the first value that passes some test and emits
* that.</span>
*
* ![](find.png)
*
* `find` searches for the first item in the source Observable that matches the
* specified condition embodied by the `predicate`, and returns the first
* occurrence in the source. Unlike {@link first}, the `predicate` is required
* in `find`, and does not emit an error if a valid value is not found
* (emits `undefined` instead).
*
* ## Example
*
* Find and emit the first click that happens on a DIV element
*
* ```ts
* import { fromEvent, find } from 'rxjs';
*
* const div = document.createElement('div');
* div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
* document.body.appendChild(div);
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(find(ev => (<HTMLElement>ev.target).tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link first}
* @see {@link findIndex}
* @see {@link take}
*
* @param predicate A function called with each item to test for condition matching.
* @param thisArg An optional argument to determine the value of `this` in the
* `predicate` function.
* @return A function that returns an Observable that emits the first item that
* matches the condition.
*/
export function find<T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any
): OperatorFunction<T, T | undefined> {
return operate(createFind(predicate, thisArg, 'value'));
}
export function createFind<T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg: any,
emit: 'value' | 'index'
) {
const findIndex = emit === 'index';
return (source: Observable<T>, subscriber: Subscriber<any>) => {
let index = 0;
source.subscribe(
createOperatorSubscriber(
subscriber,
(value) => {
const i = index++;
if (predicate.call(thisArg, value, i, source)) {
subscriber.next(findIndex ? i : value);
subscriber.complete();
}
},
() => {
subscriber.next(findIndex ? -1 : undefined);
subscriber.complete();
}
)
);
};
}

63
node_modules/rxjs/src/internal/operators/findIndex.ts generated vendored Normal file
View File

@@ -0,0 +1,63 @@
import { Observable } from '../Observable';
import { Falsy, OperatorFunction } from '../types';
import { operate } from '../util/lift';
import { createFind } from './find';
export function findIndex<T>(predicate: BooleanConstructor): OperatorFunction<T, T extends Falsy ? -1 : number>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function findIndex<T>(predicate: BooleanConstructor, thisArg: any): OperatorFunction<T, T extends Falsy ? -1 : number>;
/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */
export function findIndex<T, A>(
predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,
thisArg: A
): OperatorFunction<T, number>;
export function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, number>;
/**
* Emits only the index of the first value emitted by the source Observable that
* meets some condition.
*
* <span class="informal">It's like {@link find}, but emits the index of the
* found value, not the value itself.</span>
*
* ![](findIndex.png)
*
* `findIndex` searches for the first item in the source Observable that matches
* the specified condition embodied by the `predicate`, and returns the
* (zero-based) index of the first occurrence in the source. Unlike
* {@link first}, the `predicate` is required in `findIndex`, and does not emit
* an error if a valid value is not found.
*
* ## Example
*
* Emit the index of first click that happens on a DIV element
*
* ```ts
* import { fromEvent, findIndex } from 'rxjs';
*
* const div = document.createElement('div');
* div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
* document.body.appendChild(div);
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(findIndex(ev => (<HTMLElement>ev.target).tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link find}
* @see {@link first}
* @see {@link take}
*
* @param predicate A function called with each item to test for condition matching.
* @param thisArg An optional argument to determine the value of `this` in the
* `predicate` function.
* @return A function that returns an Observable that emits the index of the
* first item that matches the condition.
*/
export function findIndex<T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
thisArg?: any
): OperatorFunction<T, number> {
return operate(createFind(predicate, thisArg, 'index'));
}

93
node_modules/rxjs/src/internal/operators/first.ts generated vendored Normal file
View File

@@ -0,0 +1,93 @@
import { Observable } from '../Observable';
import { EmptyError } from '../util/EmptyError';
import { OperatorFunction, TruthyTypesOf } from '../types';
import { filter } from './filter';
import { take } from './take';
import { defaultIfEmpty } from './defaultIfEmpty';
import { throwIfEmpty } from './throwIfEmpty';
import { identity } from '../util/identity';
export function first<T, D = T>(predicate?: null, defaultValue?: D): OperatorFunction<T, T | D>;
export function first<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;
export function first<T, D>(predicate: BooleanConstructor, defaultValue: D): OperatorFunction<T, TruthyTypesOf<T> | D>;
export function first<T, S extends T>(
predicate: (value: T, index: number, source: Observable<T>) => value is S,
defaultValue?: S
): OperatorFunction<T, S>;
export function first<T, S extends T, D>(
predicate: (value: T, index: number, source: Observable<T>) => value is S,
defaultValue: D
): OperatorFunction<T, S | D>;
export function first<T, D = T>(
predicate: (value: T, index: number, source: Observable<T>) => boolean,
defaultValue?: D
): OperatorFunction<T, T | D>;
/**
* Emits only the first value (or the first value that meets some condition)
* emitted by the source Observable.
*
* <span class="informal">Emits only the first value. Or emits only the first
* value that passes some test.</span>
*
* ![](first.png)
*
* If called with no arguments, `first` emits the first value of the source
* Observable, then completes. If called with a `predicate` function, `first`
* emits the first value of the source that matches the specified condition. Emits an error
* notification if `defaultValue` was not provided and a matching element is not found.
*
* ## Examples
*
* Emit only the first click that happens on the DOM
*
* ```ts
* import { fromEvent, first } from 'rxjs';
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(first());
* result.subscribe(x => console.log(x));
* ```
*
* Emits the first click that happens on a DIV
*
* ```ts
* import { fromEvent, first } from 'rxjs';
*
* const div = document.createElement('div');
* div.style.cssText = 'width: 200px; height: 200px; background: #09c;';
* document.body.appendChild(div);
*
* const clicks = fromEvent(document, 'click');
* const result = clicks.pipe(first(ev => (<HTMLElement>ev.target).tagName === 'DIV'));
* result.subscribe(x => console.log(x));
* ```
*
* @see {@link filter}
* @see {@link find}
* @see {@link take}
* @see {@link last}
*
* @throws {EmptyError} Delivers an `EmptyError` to the Observer's `error`
* callback if the Observable completes before any `next` notification was sent.
* This is how `first()` is different from `take(1)` which completes instead.
*
* @param predicate An optional function called with each item to test for condition
* matching.
* @param defaultValue The default value emitted in case no valid value was found on
* the source.
* @return A function that returns an Observable that emits the first item that
* matches the condition.
*/
export function first<T, D>(
predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,
defaultValue?: D
): OperatorFunction<T, T | D> {
const hasDefaultValue = arguments.length >= 2;
return (source: Observable<T>) =>
source.pipe(
predicate ? filter((v, i) => predicate(v, i, source)) : identity,
take(1),
hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new EmptyError())
);
}

6
node_modules/rxjs/src/internal/operators/flatMap.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { mergeMap } from './mergeMap';
/**
* @deprecated Renamed to {@link mergeMap}. Will be removed in v8.
*/
export const flatMap = mergeMap;

Some files were not shown because too many files have changed in this diff Show More