@firebase/database
Version:
This is the Firebase Realtime Database component of the Firebase JS SDK.
1,267 lines (1,215 loc) • 120 kB
TypeScript
/**
* Firebase Realtime Database
*
* @packageDocumentation
*/
import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types';
import { AppCheckTokenListener } from '@firebase/app-check-interop-types';
import { AppCheckTokenResult } from '@firebase/app-check-interop-types';
import { EmulatorMockTokenOptions } from '@firebase/util';
import { FirebaseApp } from '@firebase/app';
import { FirebaseApp as FirebaseApp_2 } from '@firebase/app-types';
import { FirebaseAppCheckInternal } from '@firebase/app-check-interop-types';
import { FirebaseAuthInternal } from '@firebase/auth-interop-types';
import { FirebaseAuthInternalName } from '@firebase/auth-interop-types';
import { FirebaseAuthTokenData } from '@firebase/app-types/private';
import { Provider } from '@firebase/component';
/**
* Abstraction around AppCheck's token fetching capabilities.
*/
declare class AppCheckTokenProvider {
private appCheckProvider?;
private appCheck?;
private serverAppAppCheckToken?;
private appName;
constructor(app: FirebaseApp, appCheckProvider?: Provider<AppCheckInternalComponentName>);
getToken(forceRefresh?: boolean): Promise<AppCheckTokenResult>;
addTokenChangeListener(listener: AppCheckTokenListener): void;
notifyForInvalidToken(): void;
}
declare interface AuthTokenProvider {
getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData>;
addTokenChangeListener(listener: (token: string | null) => void): void;
removeTokenChangeListener(listener: (token: string | null) => void): void;
notifyForInvalidToken(): void;
}
/**
* A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully
* initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.
* initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks
* whether a node potentially had children removed due to a filter.
*/
declare class CacheNode {
private node_;
private fullyInitialized_;
private filtered_;
constructor(node_: Node_2, fullyInitialized_: boolean, filtered_: boolean);
/**
* Returns whether this node was fully initialized with either server data or a complete overwrite by the client
*/
isFullyInitialized(): boolean;
/**
* Returns whether this node is potentially missing children due to a filter applied to the node
*/
isFiltered(): boolean;
isCompleteForPath(path: Path): boolean;
isCompleteForChild(key: string): boolean;
getNode(): Node_2;
}
declare class CancelEvent implements Event_2 {
eventRegistration: EventRegistration;
error: Error;
path: Path;
constructor(eventRegistration: EventRegistration, error: Error, path: Path);
getPath(): Path;
getEventType(): string;
getEventRunner(): () => void;
toString(): string;
}
declare interface Change {
/** @param type - The event type */
type: ChangeType;
/** @param snapshotNode - The data */
snapshotNode: Node_2;
/** @param childName - The name for this child, if it's a child even */
childName?: string;
/** @param oldSnap - Used for intermediate processing of child changed events */
oldSnap?: Node_2;
/** * @param prevName - The name for the previous child, if applicable */
prevName?: string | null;
}
declare const enum ChangeType {
/** Event type for a child added */
CHILD_ADDED = "child_added",
/** Event type for a child removed */
CHILD_REMOVED = "child_removed",
/** Event type for a child changed */
CHILD_CHANGED = "child_changed",
/** Event type for a child moved */
CHILD_MOVED = "child_moved",
/** Event type for a value change */
VALUE = "value"
}
/**
* Gets a `Reference` for the location at the specified relative path.
*
* The relative path can either be a simple child name (for example, "ada") or
* a deeper slash-separated path (for example, "ada/name/first").
*
* @param parent - The parent location.
* @param path - A relative path from this location to the desired child
* location.
* @returns The specified child location.
*/
export declare function child(parent: DatabaseReference, path: string): DatabaseReference;
declare class ChildChangeAccumulator {
private readonly changeMap;
trackChildChange(change: Change): void;
getChanges(): Change[];
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Implementation of an immutable SortedMap using a Left-leaning
* Red-Black Tree, adapted from the implementation in Mugs
* (http://mads379.github.com/mugs/) by Mads Hartmann Jensen
* (mads379\@gmail.com).
*
* Original paper on Left-leaning Red-Black Trees:
* http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
*
* Invariant 1: No red node has a red child
* Invariant 2: Every leaf path has the same number of black nodes
* Invariant 3: Only the left child can be red (left leaning)
*/
declare type Comparator<K> = (key1: K, key2: K) => number;
/**
* Since updates to filtered nodes might require nodes to be pulled in from "outside" the node, this interface
* can help to get complete children that can be pulled in.
* A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from
* other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.
*
* @interface
*/
declare interface CompleteChildSource {
getCompleteChild(childKey: string): Node_2 | null;
getChildAfterChild(index: Index, child: NamedNode, reverse: boolean): NamedNode | null;
}
/**
* This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with
* dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write
* modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write
* to reflect the write added.
*/
declare class CompoundWrite {
writeTree_: ImmutableTree<Node_2>;
constructor(writeTree_: ImmutableTree<Node_2>);
static empty(): CompoundWrite;
}
/**
* Modify the provided instance to communicate with the Realtime Database
* emulator.
*
* <p>Note: This method must be called before performing any other operation.
*
* @param db - The instance to modify.
* @param host - The emulator host (ex: localhost)
* @param port - The emulator port (ex: 8080)
* @param options.mockUserToken - the mock auth token to use for unit testing Security Rules
*/
export declare function connectDatabaseEmulator(db: Database, host: string, port: number, options?: {
mockUserToken?: EmulatorMockTokenOptions | string;
}): void;
/**
* Class representing a Firebase Realtime Database.
*/
export declare class Database implements _FirebaseService {
_repoInternal: Repo;
/** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
readonly app: FirebaseApp;
/** Represents a `Database` instance. */
readonly 'type' = "database";
/** Track if the instance has been used (root or repo accessed) */
_instanceStarted: boolean;
/** Backing state for root_ */
private _rootInternal?;
/** @hideconstructor */
constructor(_repoInternal: Repo,
/** The {@link @firebase/app#FirebaseApp} associated with this Realtime Database instance. */
app: FirebaseApp);
get _repo(): Repo;
get _root(): _ReferenceImpl;
_delete(): Promise<void>;
_checkNotDeleted(apiName: string): void;
}
/**
* A `DatabaseReference` represents a specific location in your Database and can be used
* for reading or writing data to that Database location.
*
* You can reference the root or child location in your Database by calling
* `ref()` or `ref("child/path")`.
*
* Writing is done with the `set()` method and reading can be done with the
* `on*()` method. See {@link
* https://firebase.google.com/docs/database/web/read-and-write}
*/
export declare interface DatabaseReference extends Query {
/**
* The last part of the `DatabaseReference`'s path.
*
* For example, `"ada"` is the key for
* `https://<DATABASE_NAME>.firebaseio.com/users/ada`.
*
* The key of a root `DatabaseReference` is `null`.
*/
readonly key: string | null;
/**
* The parent location of a `DatabaseReference`.
*
* The parent of a root `DatabaseReference` is `null`.
*/
readonly parent: DatabaseReference | null;
/** The root `DatabaseReference` of the Database. */
readonly root: DatabaseReference;
}
/**
* A `DataSnapshot` contains data from a Database location.
*
* Any time you read data from the Database, you receive the data as a
* `DataSnapshot`. A `DataSnapshot` is passed to the event callbacks you attach
* with `on()` or `once()`. You can extract the contents of the snapshot as a
* JavaScript object by calling the `val()` method. Alternatively, you can
* traverse into the snapshot by calling `child()` to return child snapshots
* (which you could then call `val()` on).
*
* A `DataSnapshot` is an efficiently generated, immutable copy of the data at
* a Database location. It cannot be modified and will never change (to modify
* data, you always call the `set()` method on a `Reference` directly).
*/
export declare class DataSnapshot {
readonly _node: Node_2;
/**
* The location of this DataSnapshot.
*/
readonly ref: DatabaseReference;
readonly _index: Index;
/**
* @param _node - A SnapshotNode to wrap.
* @param ref - The location this snapshot came from.
* @param _index - The iteration order for this snapshot
* @hideconstructor
*/
constructor(_node: Node_2,
/**
* The location of this DataSnapshot.
*/
ref: DatabaseReference, _index: Index);
/**
* Gets the priority value of the data in this `DataSnapshot`.
*
* Applications need not use priority but can order collections by
* ordinary properties (see
* {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
* ).
*/
get priority(): string | number | null;
/**
* The key (last part of the path) of the location of this `DataSnapshot`.
*
* The last token in a Database location is considered its key. For example,
* "ada" is the key for the /users/ada/ node. Accessing the key on any
* `DataSnapshot` will return the key for the location that generated it.
* However, accessing the key on the root URL of a Database will return
* `null`.
*/
get key(): string | null;
/** Returns the number of child properties of this `DataSnapshot`. */
get size(): number;
/**
* Gets another `DataSnapshot` for the location at the specified relative path.
*
* Passing a relative path to the `child()` method of a DataSnapshot returns
* another `DataSnapshot` for the location at the specified relative path. The
* relative path can either be a simple child name (for example, "ada") or a
* deeper, slash-separated path (for example, "ada/name/first"). If the child
* location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
* whose value is `null`) is returned.
*
* @param path - A relative path to the location of child data.
*/
child(path: string): DataSnapshot;
/**
* Returns true if this `DataSnapshot` contains any data. It is slightly more
* efficient than using `snapshot.val() !== null`.
*/
exists(): boolean;
/**
* Exports the entire contents of the DataSnapshot as a JavaScript object.
*
* The `exportVal()` method is similar to `val()`, except priority information
* is included (if available), making it suitable for backing up your data.
*
* @returns The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
exportVal(): any;
/**
* Enumerates the top-level children in the `IteratedDataSnapshot`.
*
* Because of the way JavaScript objects work, the ordering of data in the
* JavaScript object returned by `val()` is not guaranteed to match the
* ordering on the server nor the ordering of `onChildAdded()` events. That is
* where `forEach()` comes in handy. It guarantees the children of a
* `DataSnapshot` will be iterated in their query order.
*
* If no explicit `orderBy*()` method is used, results are returned
* ordered by key (unless priorities are used, in which case, results are
* returned by priority).
*
* @param action - A function that will be called for each child DataSnapshot.
* The callback can return true to cancel further enumeration.
* @returns true if enumeration was canceled due to your callback returning
* true.
*/
forEach(action: (child: IteratedDataSnapshot) => boolean | void): boolean;
/**
* Returns true if the specified child path has (non-null) data.
*
* @param path - A relative path to the location of a potential child.
* @returns `true` if data exists at the specified child path; else
* `false`.
*/
hasChild(path: string): boolean;
/**
* Returns whether or not the `DataSnapshot` has any non-`null` child
* properties.
*
* You can use `hasChildren()` to determine if a `DataSnapshot` has any
* children. If it does, you can enumerate them using `forEach()`. If it
* doesn't, then either this snapshot contains a primitive value (which can be
* retrieved with `val()`) or it is empty (in which case, `val()` will return
* `null`).
*
* @returns true if this snapshot has any children; else false.
*/
hasChildren(): boolean;
/**
* Returns a JSON-serializable representation of this object.
*/
toJSON(): object | null;
/**
* Extracts a JavaScript value from a `DataSnapshot`.
*
* Depending on the data in a `DataSnapshot`, the `val()` method may return a
* scalar type (string, number, or boolean), an array, or an object. It may
* also return null, indicating that the `DataSnapshot` is empty (contains no
* data).
*
* @returns The DataSnapshot's contents as a JavaScript value (Object,
* Array, string, number, boolean, or `null`).
*/
val(): any;
}
export { EmulatorMockTokenOptions }
/**
* Logs debugging information to the console.
*
* @param enabled - Enables logging if `true`, disables logging if `false`.
* @param persistent - Remembers the logging state between page refreshes if
* `true`.
*/
export declare function enableLogging(enabled: boolean, persistent?: boolean): any;
/**
* Logs debugging information to the console.
*
* @param logger - A custom logger function to control how things get logged.
*/
export declare function enableLogging(logger: (message: string) => unknown): any;
/**
* Creates a `QueryConstraint` with the specified ending point.
*
* Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
* allows you to choose arbitrary starting and ending points for your queries.
*
* The ending point is inclusive, so children with exactly the specified value
* will be included in the query. The optional key argument can be used to
* further limit the range of the query. If it is specified, then children that
* have exactly the specified value must also have a key name less than or equal
* to the specified key.
*
* You can read more about `endAt()` in
* {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
*
* @param value - The value to end at. The argument type depends on which
* `orderBy*()` function was used in this query. Specify a value that matches
* the `orderBy*()` type. When used in combination with `orderByKey()`, the
* value must be a string.
* @param key - The child key to end at, among the children with the previously
* specified priority. This argument is only allowed if ordering by child,
* value, or priority.
*/
export declare function endAt(value: number | string | boolean | null, key?: string): QueryConstraint;
/**
* Creates a `QueryConstraint` with the specified ending point (exclusive).
*
* Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
* allows you to choose arbitrary starting and ending points for your queries.
*
* The ending point is exclusive. If only a value is provided, children
* with a value less than the specified value will be included in the query.
* If a key is specified, then children must have a value less than or equal
* to the specified value and a key name less than the specified key.
*
* @param value - The value to end before. The argument type depends on which
* `orderBy*()` function was used in this query. Specify a value that matches
* the `orderBy*()` type. When used in combination with `orderByKey()`, the
* value must be a string.
* @param key - The child key to end before, among the children with the
* previously specified priority. This argument is only allowed if ordering by
* child, value, or priority.
*/
export declare function endBefore(value: number | string | boolean | null, key?: string): QueryConstraint;
/**
* Creates a `QueryConstraint` that includes children that match the specified
* value.
*
* Using `startAt()`, `startAfter()`, `endBefore()`, `endAt()` and `equalTo()`
* allows you to choose arbitrary starting and ending points for your queries.
*
* The optional key argument can be used to further limit the range of the
* query. If it is specified, then children that have exactly the specified
* value must also have exactly the specified key as their key name. This can be
* used to filter result sets with many matches for the same value.
*
* You can read more about `equalTo()` in
* {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
*
* @param value - The value to match for. The argument type depends on which
* `orderBy*()` function was used in this query. Specify a value that matches
* the `orderBy*()` type. When used in combination with `orderByKey()`, the
* value must be a string.
* @param key - The child key to start at, among the children with the
* previously specified priority. This argument is only allowed if ordering by
* child, value, or priority.
*/
export declare function equalTo(value: number | string | boolean | null, key?: string): QueryConstraint;
/**
* Encapsulates the data needed to raise an event
* @interface
*/
declare interface Event_2 {
getPath(): Path;
getEventType(): string;
getEventRunner(): () => void;
toString(): string;
}
/**
* An EventGenerator is used to convert "raw" changes (Change) as computed by the
* CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()
* for details.
*
*/
declare class EventGenerator {
query_: QueryContext;
index_: Index;
constructor(query_: QueryContext);
}
declare interface EventList {
events: Event_2[];
path: Path;
}
/**
* The event queue serves a few purposes:
* 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more
* events being queued.
* 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,
* raiseQueuedEvents() is called again, the "inner" call will pick up raising events where the "outer" call
* left off, ensuring that the events are still raised synchronously and in order.
* 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued
* events are raised synchronously.
*
* NOTE: This can all go away if/when we move to async events.
*
*/
declare class EventQueue {
eventLists_: EventList[];
/**
* Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.
*/
recursionDepth_: number;
}
/**
* An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback
* to be notified of that type of event.
*
* That said, it can also contain a cancel callback to be notified if the event is canceled. And
* currently, this code is organized around the idea that you would register multiple child_ callbacks
* together, as a single EventRegistration. Though currently we don't do that.
*/
declare interface EventRegistration {
/**
* True if this container has a callback to trigger for this event type
*/
respondsTo(eventType: string): boolean;
createEvent(change: Change, query: QueryContext): Event_2;
/**
* Given event data, return a function to trigger the user's callback
*/
getEventRunner(eventData: Event_2): () => void;
createCancelEvent(error: Error, path: Path): CancelEvent | null;
matches(other: EventRegistration): boolean;
/**
* False basically means this is a "dummy" callback container being used as a sentinel
* to remove all callback containers of a particular type. (e.g. if the user does
* ref.off('value') without specifying a specific callback).
*
* (TODO: Rework this, since it's hacky)
*
*/
hasAnyCallback(): boolean;
}
/**
* One of the following strings: "value", "child_added", "child_changed",
* "child_removed", or "child_moved."
*/
export declare type EventType = 'value' | 'child_added' | 'child_changed' | 'child_moved' | 'child_removed';
/* Excluded from this release type: _FirebaseService */
/**
* Force the use of longPolling instead of websockets. This will be ignored if websocket protocol is used in databaseURL.
*/
export declare function forceLongPolling(): void;
/**
* Force the use of websockets instead of longPolling.
*/
export declare function forceWebSockets(): void;
/**
* Gets the most up-to-date result for this query.
*
* @param query - The query to run.
* @returns A `Promise` which resolves to the resulting DataSnapshot if a value is
* available, or rejects if the client is unable to return a value (e.g., if the
* server is unreachable and there is nothing cached).
*/
export declare function get(query: Query): Promise<DataSnapshot>;
/**
* Returns the instance of the Realtime Database SDK that is associated with the provided
* {@link @firebase/app#FirebaseApp}. Initializes a new instance with default settings if
* no instance exists or if the existing instance uses a custom database URL.
*
* @param app - The {@link @firebase/app#FirebaseApp} instance that the returned Realtime
* Database instance is associated with.
* @param url - The URL of the Realtime Database instance to connect to. If not
* provided, the SDK connects to the default instance of the Firebase App.
* @returns The `Database` instance of the provided app.
*/
export declare function getDatabase(app?: FirebaseApp, url?: string): Database;
/**
* Disconnects from the server (all Database operations will be completed
* offline).
*
* The client automatically maintains a persistent connection to the Database
* server, which will remain active indefinitely and reconnect when
* disconnected. However, the `goOffline()` and `goOnline()` methods may be used
* to control the client connection in cases where a persistent connection is
* undesirable.
*
* While offline, the client will no longer receive data updates from the
* Database. However, all Database operations performed locally will continue to
* immediately fire events, allowing your application to continue behaving
* normally. Additionally, each operation performed locally will automatically
* be queued and retried upon reconnection to the Database server.
*
* To reconnect to the Database and begin receiving remote events, see
* `goOnline()`.
*
* @param db - The instance to disconnect.
*/
export declare function goOffline(db: Database): void;
/**
* Reconnects to the server and synchronizes the offline Database state
* with the server state.
*
* This method should be used after disabling the active connection with
* `goOffline()`. Once reconnected, the client will transmit the proper data
* and fire the appropriate events so that your client "catches up"
* automatically.
*
* @param db - The instance to reconnect.
*/
export declare function goOnline(db: Database): void;
/**
* A tree with immutable elements.
*/
declare class ImmutableTree<T> {
readonly value: T | null;
readonly children: SortedMap<string, ImmutableTree<T>>;
static fromObject<T>(obj: {
[k: string]: T;
}): ImmutableTree<T>;
constructor(value: T | null, children?: SortedMap<string, ImmutableTree<T>>);
/**
* True if the value is empty and there are no children
*/
isEmpty(): boolean;
/**
* Given a path and predicate, return the first node and the path to that node
* where the predicate returns true.
*
* TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
* objects on the way back out, it may be better to pass down a pathSoFar obj.
*
* @param relativePath - The remainder of the path
* @param predicate - The predicate to satisfy to return a node
*/
findRootMostMatchingPathAndValue(relativePath: Path, predicate: (a: T) => boolean): {
path: Path;
value: T;
} | null;
/**
* Find, if it exists, the shortest subpath of the given path that points a defined
* value in the tree
*/
findRootMostValueAndPath(relativePath: Path): {
path: Path;
value: T;
} | null;
/**
* @returns The subtree at the given path
*/
subtree(relativePath: Path): ImmutableTree<T>;
/**
* Sets a value at the specified path.
*
* @param relativePath - Path to set value at.
* @param toSet - Value to set.
* @returns Resulting tree.
*/
set(relativePath: Path, toSet: T | null): ImmutableTree<T>;
/**
* Removes the value at the specified path.
*
* @param relativePath - Path to value to remove.
* @returns Resulting tree.
*/
remove(relativePath: Path): ImmutableTree<T>;
/**
* Gets a value from the tree.
*
* @param relativePath - Path to get value for.
* @returns Value at path, or null.
*/
get(relativePath: Path): T | null;
/**
* Replace the subtree at the specified path with the given new tree.
*
* @param relativePath - Path to replace subtree for.
* @param newTree - New tree.
* @returns Resulting tree.
*/
setTree(relativePath: Path, newTree: ImmutableTree<T>): ImmutableTree<T>;
/**
* Performs a depth first fold on this tree. Transforms a tree into a single
* value, given a function that operates on the path to a node, an optional
* current value, and a map of child names to folded subtrees
*/
fold<V>(fn: (path: Path, value: T, children: {
[k: string]: V;
}) => V): V;
/**
* Recursive helper for public-facing fold() method
*/
private fold_;
/**
* Find the first matching value on the given path. Return the result of applying f to it.
*/
findOnPath<V>(path: Path, f: (path: Path, value: T) => V | null): V | null;
private findOnPath_;
foreachOnPath(path: Path, f: (path: Path, value: T) => void): ImmutableTree<T>;
private foreachOnPath_;
/**
* Calls the given function for each node in the tree that has a value.
*
* @param f - A function to be called with the path from the root of the tree to
* a node, and the value at that node. Called in depth-first order.
*/
foreach(f: (path: Path, value: T) => void): void;
private foreach_;
foreachChild(f: (name: string, value: T) => void): void;
}
/**
* Returns a placeholder value that can be used to atomically increment the
* current database value by the provided delta.
*
* @param delta - the amount to modify the current value atomically.
* @returns A placeholder value for modifying data atomically server-side.
*/
export declare function increment(delta: number): object;
declare abstract class Index {
abstract compare(a: NamedNode, b: NamedNode): number;
abstract isDefinedOn(node: Node_2): boolean;
/**
* @returns A standalone comparison function for
* this index
*/
getCompare(): Comparator<NamedNode>;
/**
* Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
* it's possible that the changes are isolated to parts of the snapshot that are not indexed.
*
*
* @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
*/
indexedValueChanged(oldNode: Node_2, newNode: Node_2): boolean;
/**
* @returns a node wrapper that will sort equal to or less than
* any other node wrapper, using this index
*/
minPost(): NamedNode;
/**
* @returns a node wrapper that will sort greater than or equal to
* any other node wrapper, using this index
*/
abstract maxPost(): NamedNode;
abstract makePost(indexValue: unknown, name: string): NamedNode;
/**
* @returns String representation for inclusion in a query spec
*/
abstract toString(): string;
}
/* Excluded from this release type: _initStandalone */
/**
* Represents a child snapshot of a `Reference` that is being iterated over. The key will never be undefined.
*/
export declare interface IteratedDataSnapshot extends DataSnapshot {
key: string;
}
/**
* Creates a new `QueryConstraint` that if limited to the first specific number
* of children.
*
* The `limitToFirst()` method is used to set a maximum number of children to be
* synced for a given callback. If we set a limit of 100, we will initially only
* receive up to 100 `child_added` events. If we have fewer than 100 messages
* stored in our Database, a `child_added` event will fire for each message.
* However, if we have over 100 messages, we will only receive a `child_added`
* event for the first 100 ordered messages. As items change, we will receive
* `child_removed` events for each item that drops out of the active list so
* that the total number stays at 100.
*
* You can read more about `limitToFirst()` in
* {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
*
* @param limit - The maximum number of nodes to include in this query.
*/
export declare function limitToFirst(limit: number): QueryConstraint;
/**
* Creates a new `QueryConstraint` that is limited to return only the last
* specified number of children.
*
* The `limitToLast()` method is used to set a maximum number of children to be
* synced for a given callback. If we set a limit of 100, we will initially only
* receive up to 100 `child_added` events. If we have fewer than 100 messages
* stored in our Database, a `child_added` event will fire for each message.
* However, if we have over 100 messages, we will only receive a `child_added`
* event for the last 100 ordered messages. As items change, we will receive
* `child_removed` events for each item that drops out of the active list so
* that the total number stays at 100.
*
* You can read more about `limitToLast()` in
* {@link https://firebase.google.com/docs/database/web/lists-of-data#filtering_data | Filtering data}.
*
* @param limit - The maximum number of nodes to include in this query.
*/
export declare function limitToLast(limit: number): QueryConstraint;
/** An options objects that can be used to customize a listener. */
export declare interface ListenOptions {
/** Whether to remove the listener after its first invocation. */
readonly onlyOnce?: boolean;
}
declare interface ListenProvider {
startListening(query: QueryContext, tag: number | null, hashFn: () => string, onComplete: (a: string, b?: unknown) => Event_2[]): Event_2[];
stopListening(a: QueryContext, b: number | null): void;
}
/**
* Represents an empty node (a leaf node in the Red-Black Tree).
*/
declare class LLRBEmptyNode<K, V> {
key: K;
value: V;
left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
color: boolean;
/**
* Returns a copy of the current node.
*
* @returns The node copy.
*/
copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBEmptyNode<K, V>;
/**
* Returns a copy of the tree, with the specified key/value added.
*
* @param key - Key to be added.
* @param value - Value to be added.
* @param comparator - Comparator.
* @returns New tree, with item added.
*/
insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
/**
* Returns a copy of the tree, with the specified key removed.
*
* @param key - The key to remove.
* @param comparator - Comparator.
* @returns New tree, with item removed.
*/
remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V>;
/**
* @returns The total number of nodes in the tree.
*/
count(): number;
/**
* @returns True if the tree is empty.
*/
isEmpty(): boolean;
/**
* Traverses the tree in key order and calls the specified action function
* for each node.
*
* @param action - Callback function to be called for each
* node. If it returns true, traversal is aborted.
* @returns True if traversal was aborted.
*/
inorderTraversal(action: (k: K, v: V) => unknown): boolean;
/**
* Traverses the tree in reverse key order and calls the specified action function
* for each node.
*
* @param action - Callback function to be called for each
* node. If it returns true, traversal is aborted.
* @returns True if traversal was aborted.
*/
reverseTraversal(action: (k: K, v: V) => void): boolean;
minKey(): null;
maxKey(): null;
check_(): number;
/**
* @returns Whether this node is red.
*/
isRed_(): boolean;
}
/**
* Represents a node in a Left-leaning Red-Black tree.
*/
declare class LLRBNode<K, V> {
key: K;
value: V;
color: boolean;
left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
/**
* @param key - Key associated with this node.
* @param value - Value associated with this node.
* @param color - Whether this node is red.
* @param left - Left child.
* @param right - Right child.
*/
constructor(key: K, value: V, color: boolean | null, left?: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right?: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null);
static RED: boolean;
static BLACK: boolean;
/**
* Returns a copy of the current node, optionally replacing pieces of it.
*
* @param key - New key for the node, or null.
* @param value - New value for the node, or null.
* @param color - New color for the node, or null.
* @param left - New left child for the node, or null.
* @param right - New right child for the node, or null.
* @returns The node copy.
*/
copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null, right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null): LLRBNode<K, V>;
/**
* @returns The total number of nodes in the tree.
*/
count(): number;
/**
* @returns True if the tree is empty.
*/
isEmpty(): boolean;
/**
* Traverses the tree in key order and calls the specified action function
* for each node.
*
* @param action - Callback function to be called for each
* node. If it returns true, traversal is aborted.
* @returns The first truthy value returned by action, or the last falsey
* value returned by action
*/
inorderTraversal(action: (k: K, v: V) => unknown): boolean;
/**
* Traverses the tree in reverse key order and calls the specified action function
* for each node.
*
* @param action - Callback function to be called for each
* node. If it returns true, traversal is aborted.
* @returns True if traversal was aborted.
*/
reverseTraversal(action: (k: K, v: V) => void): boolean;
/**
* @returns The minimum node in the tree.
*/
private min_;
/**
* @returns The maximum key in the tree.
*/
minKey(): K;
/**
* @returns The maximum key in the tree.
*/
maxKey(): K;
/**
* @param key - Key to insert.
* @param value - Value to insert.
* @param comparator - Comparator.
* @returns New tree, with the key/value added.
*/
insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V>;
/**
* @returns New tree, with the minimum key removed.
*/
private removeMin_;
/**
* @param key - The key of the item to remove.
* @param comparator - Comparator.
* @returns New tree, with the specified item removed.
*/
remove(key: K, comparator: Comparator<K>): LLRBNode<K, V> | LLRBEmptyNode<K, V>;
/**
* @returns Whether this is a RED node.
*/
isRed_(): boolean;
/**
* @returns New tree after performing any needed rotations.
*/
private fixUp_;
/**
* @returns New tree, after moveRedLeft.
*/
private moveRedLeft_;
/**
* @returns New tree, after moveRedRight.
*/
private moveRedRight_;
/**
* @returns New tree, after rotateLeft.
*/
private rotateLeft_;
/**
* @returns New tree, after rotateRight.
*/
private rotateRight_;
/**
* @returns Newt ree, after colorFlip.
*/
private colorFlip_;
/**
* For testing.
*
* @returns True if all is well.
*/
private checkMaxDepth_;
check_(): number;
}
declare class NamedNode {
name: string;
node: Node_2;
constructor(name: string, node: Node_2);
static Wrap(name: string, node: Node_2): NamedNode;
}
/**
* Node is an interface defining the common functionality for nodes in
* a DataSnapshot.
*
* @interface
*/
declare interface Node_2 {
/**
* Whether this node is a leaf node.
* @returns Whether this is a leaf node.
*/
isLeafNode(): boolean;
/**
* Gets the priority of the node.
* @returns The priority of the node.
*/
getPriority(): Node_2;
/**
* Returns a duplicate node with the new priority.
* @param newPriorityNode - New priority to set for the node.
* @returns Node with new priority.
*/
updatePriority(newPriorityNode: Node_2): Node_2;
/**
* Returns the specified immediate child, or null if it doesn't exist.
* @param childName - The name of the child to retrieve.
* @returns The retrieved child, or an empty node.
*/
getImmediateChild(childName: string): Node_2;
/**
* Returns a child by path, or null if it doesn't exist.
* @param path - The path of the child to retrieve.
* @returns The retrieved child or an empty node.
*/
getChild(path: Path): Node_2;
/**
* Returns the name of the child immediately prior to the specified childNode, or null.
* @param childName - The name of the child to find the predecessor of.
* @param childNode - The node to find the predecessor of.
* @param index - The index to use to determine the predecessor
* @returns The name of the predecessor child, or null if childNode is the first child.
*/
getPredecessorChildName(childName: string, childNode: Node_2, index: Index): string | null;
/**
* Returns a duplicate node, with the specified immediate child updated.
* Any value in the node will be removed.
* @param childName - The name of the child to update.
* @param newChildNode - The new child node
* @returns The updated node.
*/
updateImmediateChild(childName: string, newChildNode: Node_2): Node_2;
/**
* Returns a duplicate node, with the specified child updated. Any value will
* be removed.
* @param path - The path of the child to update.
* @param newChildNode - The new child node, which may be an empty node
* @returns The updated node.
*/
updateChild(path: Path, newChildNode: Node_2): Node_2;
/**
* True if the immediate child specified exists
*/
hasChild(childName: string): boolean;
/**
* @returns True if this node has no value or children.
*/
isEmpty(): boolean;
/**
* @returns The number of children of this node.
*/
numChildren(): number;
/**
* Calls action for each child.
* @param action - Action to be called for
* each child. It's passed the child name and the child node.
* @returns The first truthy value return by action, or the last falsey one
*/
forEachChild(index: Index, action: (a: string, b: Node_2) => void): unknown;
/**
* @param exportFormat - True for export format (also wire protocol format).
* @returns Value of this node as JSON.
*/
val(exportFormat?: boolean): unknown;
/**
* @returns hash representing the node contents.
*/
hash(): string;
/**
* @param other - Another node
* @returns -1 for less than, 0 for equal, 1 for greater than other
*/
compareTo(other: Node_2): number;
/**
* @returns Whether or not this snapshot equals other
*/
equals(other: Node_2): boolean;
/**
* @returns This node, with the specified index now available
*/
withIndex(indexDefinition: Index): Node_2;
isIndexed(indexDefinition: Index): boolean;
}
/**
* NodeFilter is used to update nodes and complete children of nodes while applying queries on the fly and keeping
* track of any child changes. This class does not track value changes as value changes depend on more
* than just the node itself. Different kind of queries require different kind of implementations of this interface.
* @interface
*/
declare interface NodeFilter_2 {
/**
* Update a single complete child in the snap. If the child equals the old child in the snap, this is a no-op.
* The method expects an indexed snap.
*/
updateChild(snap: Node_2, key: string, newChild: Node_2, affectedPath: Path, source: CompleteChildSource, optChangeAccumulator: ChildChangeAccumulator | null): Node_2;
/**
* Update a node in full and output any resulting change from this complete update.
*/
updateFullNode(oldSnap: Node_2, newSnap: Node_2, optChangeAccumulator: ChildChangeAccumulator | null): Node_2;
/**
* Update the priority of the root node
*/
updatePriority(oldSnap: Node_2, newPriority: Node_2): Node_2;
/**
* Returns true if children might be filtered due to query criteria
*/
filtersNodes(): boolean;
/**
* Returns the index filter that this filter uses to get a NodeFilter that doesn't filter any children.
*/
getIndexedFilter(): NodeFilter_2;
/**
* Returns the index that this filter uses
*/
getIndex(): Index;
}
/**
* Detaches a callback previously attached with the corresponding `on*()` (`onValue`, `onChildAdded`) listener.
* Note: This is not the recommended way to remove a listener. Instead, please use the returned callback function from
* the respective `on*` callbacks.
*
* Detach a callback previously attached with `on*()`. Calling `off()` on a parent listener
* will not automatically remove listeners registered on child nodes, `off()`
* must also be called on any child listeners to remove the callback.
*
* If a callback is not specified, all callbacks for the specified eventType
* will be removed. Similarly, if no eventType is specified, all callbacks
* for the `Reference` will be removed.
*
* Individual listeners can also be removed by invoking their unsubscribe
* callbacks.
*
* @param query - The query that the listener was registered with.
* @param eventType - One of the following strings: "value", "child_added",
* "child_changed", "child_removed", or "child_moved." If omitted, all callbacks
* for the `Reference` will be removed.
* @param callback - The callback function that was passed to `on()` or
* `undefined` to remove all callbacks.
*/
export declare function off(query: Query, eventType?: EventType, callback?: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown): void;
/**
* Listens for data changes at a particular location.
*
* This is the primary way to read data from a Database. Your callback
* will be triggered for the initial data and again whenever the data changes.
* Invoke the returned unsubscribe callback to stop receiving updates. See
* {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}
* for more details.
*
* An `onChildAdded` event will be triggered once for each initial child at this
* location, and it will be triggered again every time a new child is added. The
* `DataSnapshot` passed into the callback will reflect the data for the
* relevant child. For ordering purposes, it is passed a second argument which
* is a string containing the key of the previous sibling child by sort order,
* or `null` if it is the first child.
*
* @param query - The query to run.
* @param callback - A callback that fires when the specified event occurs.
* The callback will be passed a DataSnapshot and a string containing the key of
* the previous child, by sort order, or `null` if it is the first child.
* @param cancelCallback - An optional callback that will be notified if your
* event subscription is ever canceled because your client does not have
* permission to read this data (or it had permission but has now lost it).
* This callback will be passed an `Error` object indicating why the failure
* occurred.
* @returns A function that can be invoked to remove the listener.
*/
export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName?: string | null) => unknown, cancelCallback?: (error: Error) => unknown): Unsubscribe;
/**
* Listens for data changes at a particular location.
*
* This is the primary way to read data from a Database. Your callback
* will be triggered for the initial data and again whenever the data changes.
* Invoke the returned unsubscribe callback to stop receiving updates. See
* {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}
* for more details.
*
* An `onChildAdded` event will be triggered once for each initial child at this
* location, and it will be triggered again every time a new child is added. The
* `DataSnapshot` passed into the callback will reflect the data for the
* relevant child. For ordering purposes, it is passed a second argument which
* is a string containing the key of the previous sibling child by sort order,
* or `null` if it is the first child.
*
* @param query - The query to run.
* @param callback - A callback that fires when the specified event occurs.
* The callback will be passed a DataSnapshot and a string containing the key of
* the previous child, by sort order, or `null` if it is the first child.
* @param options - An object that can be used to configure `onlyOnce`, which
* then removes the listener after its first invocation.
* @returns A function that can be invoked to remove the listener.
*/
export declare function onChildAdded(query: Query, callback: (snapshot: DataSnapshot, previousChildName: string | null) => unknown, options: ListenOptions): Unsubscribe;
/**
* Listens for data changes at a particular location.
*
* This is the primary way to read data from a Database. Your callback
* will be triggered for the initial data and again whenever the data changes.
* Invoke the returned unsubscribe callback to stop receiving updates. See
* {@link https://firebase.google.com/docs/database/web/retrieve-data | Retrieve Data on the Web}
* for more details.
*
* An `onChildAdded` event will be triggered once for each initial child at this
* location, and it will be triggered again every time a new child is added. The
* `DataSnapshot` passed into the callback will reflect the data for the
* relevant child. For ordering purposes, it is passed a second argument which
* is a string containing the key of the previous sibling child by sort order,
* or `null` if it is the first child.
*
* @param query - The query to run.
* @param callback - A callback that fires when the specified event occurs.
* The callback will be passed a DataSnapshot and a string containing the key of
* the previous child, by sort order, or `null` if it is the first child.
* @param cancelCallback - An optional callback that will be notified if your
* event subscription is ever canceled because your client does not have
* permission to read this data (or it had pe