import * as bson from 'bson';
import { Timestamp, Long } from 'bson';

declare const flags: {
    /**
     * When enabled, objects can be created by providing an array of values (in the order that they were declared in the object schema) in addition to of an object of property values.
     */
    ALLOW_VALUES_ARRAYS: boolean;
    /**
     * When enabled, accessing the `Realm` without first importing it from the Realm package, will throw.
     * Helps finding places where the app is depending on the now deprecated way of using the package.
     */
    THROW_ON_GLOBAL_REALM: boolean;
    /**
     * Enables calling internal, test-only functions like `Realm.clearTestState`.
     * This is disabled by default, mainly because the data-structures needed to support this, introduce minor memory leaks if clearTestState() is not called regularly and are not intended for production use.
     */
    ALLOW_CLEAR_TEST_STATE: boolean;
};

/**
 * Re-export a subset of the "bson" package, enabling access to the BSON types without requiring an explicit dependency on the "bson" package.
 * @see {@link https://www.npmjs.com/package/bson#documentation|the BSON documentation} for more information.
 */
declare namespace BSON {
    const ObjectId: typeof bson.ObjectID;
    type ObjectId = bson.ObjectId;
    const ObjectID: typeof bson.ObjectID;
    type ObjectID = bson.ObjectID;
    const Decimal128: typeof bson.Decimal128;
    type Decimal128 = bson.Decimal128;
    const UUID: typeof bson.UUID;
    type UUID = bson.UUID;
    const Binary: typeof bson.Binary;
    type Binary = bson.Binary;
    const EJSON: typeof bson.EJSON;
    type EJSON = typeof bson.EJSON;
}

declare class AssertionError extends Error {
}
declare class TypeAssertionError extends AssertionError {
}
declare class SchemaParseError extends Error {
}
declare class ObjectSchemaParseError extends SchemaParseError {
    objectName: string;
}
declare class PropertySchemaParseError extends SchemaParseError {
    objectName: string;
    propertyName: string;
}
/**
 * An class describing a sync error.
 */
declare class SyncError extends Error {
    name: string;
    isOk: boolean;
    /**
     * The error code that represents this error.
     */
    code?: number;
    /**
     * The category of this error.
     * @deprecated
     */
    category: string;
    reason?: string;
    /**
     * The URL to the associated server log, if available. The string will be empty
     * if the sync error is not initiated by the server.
     */
    logUrl: string;
    /**
     * A record of extra user information associated with this error.
     */
    userInfo: Record<string, string>;
    /**
     * @deprecated Check the error message instead.
     */
    isFatal: boolean;
}
/**
 * @deprecated Use the another {@link ClientResetMode} than {@link ClientResetMode.Manual}.
 * @see https://github.com/realm/realm-js/blob/main/CHANGELOG.md#1110-2022-11-01
 * @see https://github.com/realm/realm-js/issues/4135
 */
declare class ClientResetError extends SyncError {
    name: string;
    config: Configuration;
}
/**
 * An error class that indicates that one or more object changes have been reverted by the server.
 * This can happen when the client creates/updates objects that do not match any subscription, or performs writes on
 * an object it didn't have permission to access.
 */
declare class CompensatingWriteError extends SyncError {
    /**
     * The array of information about each object that caused the compensating write.
     */
    writes: CompensatingWriteInfo[];
}
/**
 * The details of a compensating write performed by the server.
 */
type CompensatingWriteInfo = {
    /**
     * The type of the object that caused the compensating write.
     */
    objectName: string;
    /**
     * The reason for the compensating write.
     */
    reason: string;
    /**
     * The primary key of the object that caused the compensating write.
     */
    primaryKey: PrimaryKey;
};

type IndexDecorator = (target: unknown, memberName: string) => void;
/**
 * Specify that the decorated field should be indexed by Realm.
 * See: [documentation](https://www.mongodb.com/docs/realm/sdk/react-native/examples/define-a-realm-object-model/#index-a-property)
 */
declare const index: IndexDecorator;
type MapToDecorator = (propertyName: string) => (target: unknown, memberName: string) => void;
/**
 * Specify that the decorated field should be remapped to a different property name in the Realm database.
 * See: [documentation](https://www.mongodb.com/docs/realm/sdk/react-native/examples/define-a-realm-object-model/#remap-a-property)
 * @param propertyName The name of the property in the Realm database
 */
declare const mapTo: MapToDecorator;

/**
 * The update mode to use when creating an object that already exists.
 */
declare enum UpdateMode {
    /**
     * Objects are only created. If an existing object exists, an exception is thrown.
     */
    Never = "never",
    /**
     * If an existing object exists, only properties where the value has actually
     * changed will be updated. This improves notifications and server side
     * performance but also have implications for how changes across devices are
     * merged. For most use cases, the behavior will match the intuitive behavior
     * of how changes should be merged, but if updating an entire object is
     * considered an atomic operation, this mode should not be used.
     */
    Modified = "modified",
    /**
     * If an existing object is found, all properties provided will be updated,
     * any other properties will remain unchanged.
     */
    All = "all"
}
type AnyRealmObject = RealmObject<any>;
/**
 * Base class for a Realm Object.
 * @example
 * To define a class `Person` with required `name` and `age`
 * properties, define a `static schema`:
 * ```
 * class Person extends Realm.Object<Person> {
 *   _id!: Realm.BSON.ObjectId;
 *   name!: string;
 *   age!: number;
 *   static schema: Realm.ObjectSchema = {
 *     name: "Person",
 *     primaryKey: "_id",
 *     properties: {
 *       _id: "objectId",
 *       name: "string",
 *       age: "int",
 *     },
 *   };
 * }
 * ```
 * @example
 * If using the [@realm/babel-plugin](https://www.npmjs.com/package/@realm/babel-plugin):
 * To define a class `Person` with required `name` and `age` properties, they would
 * need to be specified in the type argument when it is being constructed to allow
 * Typescript-only model definitions:
 * ```
 * class Person extends Realm.Object<Person, "name" | "age"> {
 *   _id = new Realm.Types.ObjectId();
 *   name: Realm.Types.String;
 *   age: Realm.Types.Int;
 *   static primaryKey = "_id";
 * }
 * ```
 * @see {@link ObjectSchema}
 * @typeParam `T` - The type of this class (e.g. if your class is `Person`,
 * `T` should also be `Person` - this duplication is required due to how
 * TypeScript works)
 * @typeParam `RequiredProperties` - The names of any properties of this
 * class which are required when an instance is constructed with `new`. Any
 * properties not specified will be optional, and will default to a sensible
 * null value if no default is specified elsewhere.
 */
declare class RealmObject<T = DefaultObject, RequiredProperties extends keyof OmittedRealmTypes<T> = never> {
    static allowValuesArrays: boolean;
    /**
     * Optionally specify the primary key of the schema when using [@realm/babel-plugin](https://www.npmjs.com/package/@realm/babel-plugin).
     */
    static primaryKey?: string;
    /**
     * Optionally specify that the schema is an embedded schema when using [@realm/babel-plugin](https://www.npmjs.com/package/@realm/babel-plugin).
     */
    static embedded?: boolean;
    /**
     * Optionally specify that the schema should sync unidirectionally if using flexible sync when using [@realm/babel-plugin](https://www.npmjs.com/package/@realm/babel-plugin).
     */
    static asymmetric?: boolean;
    /**
     * Create a `RealmObject` wrapping an `Obj` from the binding.
     * @param realm - The Realm managing the object.
     * @param values - The values of the object's properties at creation.
     */
    constructor(realm: Realm, values: Unmanaged<T, RequiredProperties>);
    /**
     * @returns An array of the names of the object's properties.
     * @deprecated Please use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys | Object.keys()}
     */
    keys(): string[];
    /**
     * @returns An array of key/value pairs of the object's properties.
     * @deprecated Please use {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries | Object.entries()}
     */
    entries(): [string, unknown][];
    /**
     * The plain object representation for JSON serialization.
     * Use circular JSON serialization libraries such as [@ungap/structured-clone](https://www.npmjs.com/package/@ungap/structured-clone)
     * and [flatted](https://www.npmjs.com/package/flatted) to stringify Realm entities that have circular structures.
     * @returns A plain object.
     */
    toJSON(_?: string, cache?: unknown): DefaultObject;
    /**
     * Checks if this object has not been deleted and is part of a valid Realm.
     * @returns `true` if the object can be safely accessed, `false` if not.
     */
    isValid(): boolean;
    /**
     * The schema for the type this object belongs to.
     * @returns The {@link CanonicalObjectSchema} that describes this object.
     */
    objectSchema(): CanonicalObjectSchema<T>;
    /**
     * Returns all the objects that link to this object in the specified relationship.
     * @param objectType - The type of the objects that link to this object's type.
     * @param propertyName - The name of the property that references objects of this object's type.
     * @throws An {@link AssertionError} if the relationship is not valid.
     * @returns The {@link Results} that link to this object.
     */
    linkingObjects<T = DefaultObject>(objectType: string, propertyName: string): Results<RealmObject<T> & T>;
    linkingObjects<T extends AnyRealmObject>(objectType: Constructor<T>, propertyName: string): Results<T>;
    /**
     * Returns the total count of incoming links to this object
     * @returns The number of links to this object.
     */
    linkingObjectsCount(): number;
    /**
     * @deprecated
     * TODO: Remove completely once the type tests are abandoned.
     */
    _objectId(): string;
    /**
     * A string uniquely identifying the object across all objects of the same type.
     */
    _objectKey(): string;
    /**
     * Add a listener `callback` which will be called when a **live** object instance changes.
     * @param callback - A function to be called when changes occur.
     * @param callback.obj - The object that changed.
     * @param callback.changes - A dictionary with information about the changes.
     * @param callback.changes.deleted - Is `true` if the object has been deleted.
     * @param callback.changes.changedProperties  - An array of properties that have changed their value.
     * @throws A {@link TypeAssertionError} if `callback` is not a function.
     * @example
     * wine.addListener((obj, changes) => {
     *  // obj === wine
     *  console.log(`object is deleted: ${changes.deleted}`);
     *  console.log(`${changes.changedProperties.length} properties have been changed:`);
     *  changes.changedProperties.forEach(prop => {
     *      console.log(` ${prop}`);
     *   });
     * })
     * @note Adding the listener is an asynchronous operation, so the callback is invoked the first time to notify the caller when the listener has been added.
     * Thus, when the callback is invoked the first time it will contain empty array for `changes.changedProperties`.
     */
    addListener(callback: ObjectChangeCallback<T>): void;
    /**
     * Remove the listener `callback` from this object.
     * @throws A {@link TypeAssertionError} if `callback` is not a function.
     * @param callback A function previously added as listener
     */
    removeListener(callback: ObjectChangeCallback<T>): void;
    /**
     * Remove all listeners from this object.
     */
    removeAllListeners(): void;
    /**
     * Get underlying type of a property value.
     * @param propertyName - The name of the property to retrieve the type of.
     * @throws An {@link Error} if property does not exist.
     * @returns Underlying type of the property value.
     */
    getPropertyType(propertyName: string): string;
}

type ObjectChangeSet<T> = {
    deleted: boolean;
    changedProperties: (keyof T)[];
};
type ObjectChangeCallback<T> = (object: RealmObject<T> & T, changes: ObjectChangeSet<T>) => void;

/**
 * Abstract base class containing methods shared by Realm {@link List}, {@link Dictionary} and {@link Results}.
 *
 * A {@link Collection} always reflect the current state of the Realm. The one exception to this is
 * when using `for...in` or `for...of` enumeration, which will always enumerate over the
 * objects which matched the query when the enumeration is begun, even if some of them are
 * deleted or modified to be excluded by the filter during the enumeration.
 * @since 0.11.0
 */
declare abstract class Collection<KeyType = unknown, ValueType = unknown, EntryType = [KeyType, ValueType], T = ValueType, ChangeCallbackType = unknown> implements Iterable<T> {
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys}
     * @returns An iterator with all keys in the collection.
     * @since 0.11.0
     */
    abstract keys(): Iterable<KeyType>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys}
     * @returns An iterator with all values in the collection.
     * @since 0.11.0
     */
    abstract values(): Iterable<ValueType>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries Array.prototype.keys}
     * @returns An iterator with all key/value pairs in the collection.
     * @since 0.11.0
     */
    abstract entries(): Iterable<EntryType>;
    /**
     * This is the same method as the {@link Collection.values} method.
     * Its presence makes collections _iterable_, thus able to be used with ES6
     * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of `for-of`}
     * loops,
     * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator `...`}
     * spread operators, and more.
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator Symbol.iterator}
     *   and the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable iterable protocol}
     * @returns An iterable of each value in the collection.
     * @example
     * for (let object of collection) {
     *   // do something with each object
     * }
     * @since 0.11.0
     */
    abstract [Symbol.iterator](): Iterator<T>;
    /**
     * Checks if this collection has not been deleted and is part of a valid Realm.
     * @returns `true` if the collection can be safely accessed.
     * @since 0.14.0
     */
    abstract isValid(): boolean;
    /**
     * Add a listener `callback` which will be called when a **live** collection instance changes.
     * @param callback - A function to be called when changes occur.
     * @param callback.collection - The collection instance that changed,
     * @param callback.changes - An object with information about the changes.
     * @param callback.changes.insertions - The indices in the collection where objects were inserted.
     * @param callback.changes.newModifications - The indices in the collection where objects were modified.
     * @param callback.changes.oldModifications - The indices in the collection where objects were modified.
     * @param callback.changes.deletions - The indices in the collection where objects were deleted.
     * @note `deletions and `oldModifications` report the indices in the collection before the change happened,
     * while `insertions` and `newModifications` report the indices into the new version of the collection.
     * @throws A {@link TypeAssertionError} if `callback` is not a function.
     * @example
     * wines.addListener((collection, changes) => {
     *  // collection === wines
     *  console.log(`${changes.insertions.length} insertions`);
     *  console.log(`${changes.oldModifications.length} oldModifications`);
     *  console.log(`${changes.newModifications.length} newModifications`);
     *  console.log(`${changes.deletions.length} deletions`);
     *  console.log(`new size of collection: ${collection.length}`);
     * });
     * @note Adding the listener is an asynchronous operation, so the callback is invoked the first time to notify the caller when the listener has been added.
     * Thus, when the callback is invoked the first time it will contain empty arrays for each property in the `changes` object.
     */
    addListener(callback: ChangeCallbackType): void;
    /**
     * Remove the listener `callback` from the collection instance.
     * @param callback - Callback function that was previously
     *   added as a listener through the {@link Collection.addListener} method.
     * @throws a {@link TypeAssertionError} If `callback` is not a function.
     */
    removeListener(callback: ChangeCallbackType): void;
    /**
     * Remove all `callback` listeners from the collection instance.
     */
    removeAllListeners(): void;
}

type PropertyType = string;
/**
 * A sort descriptor is either a string containing one or more property names
 * separate by dots or an array with two items: `[propertyName, reverse]`.
 */
type SortDescriptor = string | [string, boolean];
type CollectionChangeSet = {
    insertions: number[];
    deletions: number[];
    newModifications: number[];
    oldModifications: number[];
};
type CollectionChangeCallback<T = unknown, EntryType extends [unknown, unknown] = [unknown, unknown]> = (collection: OrderedCollection<T, EntryType>, changes: CollectionChangeSet) => void;
/**
 * An {@link OrderedCollection} is a homogenous sequence of values of any of the types
 * that can be stored as properties of Realm objects. It can be
 * accessed in any of the ways that a normal JavaScript Array can, including
 * subscripting, enumerating with `for-of` and so on.
 * @see {@link https://mdn.io/Array | Array}
 */
declare abstract class OrderedCollection<T = unknown, EntryType extends [unknown, unknown] = [number, T]> extends Collection<number, T, EntryType, T, CollectionChangeCallback<T, EntryType>> implements Omit<ReadonlyArray<T>, "entries"> {
    private mixedToBinding;
    /**
     * The plain object representation for JSON serialization.
     * Use circular JSON serialization libraries such as [@ungap/structured-clone](https://www.npmjs.com/package/@ungap/structured-clone)
     * and [flatted](https://www.npmjs.com/package/flatted) to stringify Realm entities that have circular structures.
     * @returns An array of plain objects.
     */
    toJSON(): Array<DefaultObject>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys | Array.prototype.keys()}
     * @returns An iterator with all keys in the collection.
     */
    keys(): Generator<number>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values} | Array.prototype.values()}
     * @returns An iterator with all values in the collection.
     */
    values(): Generator<T>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries | Array.prototype.entries()}
     * @returns An iterator with all key/value pairs in the collection.
     */
    entries(): Generator<EntryType>;
    [n: number]: T;
    /**
     * @returns The number of values.
     */
    get length(): number;
    /**
     * @throws An {@link Error} as the length property cannot be assigned.
     */
    set length(value: number);
    /**
     * Name of the type of items.
     * @returns The name of the type of values.
     */
    get type(): PropertyType;
    /**
     * Whether `null` is a valid value for the collection.
     * @returns Whether `null` is a valid value for the collection.
     * @readonly
     */
    get optional(): boolean;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString | Array.prototype.toString()}
     * @returns A string representation of the collection.
     */
    toString(): string;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toLocaleString | Array.prototype.toLocaleString()}
     * @returns A localized string representation of the collection.
     */
    toLocaleString(): string;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat | Array.prototype.concat()}
     * @param items - Arrays and/or values to concatenate into a new array.
     * @returns A new array with the results of calling a provided function on every element in this array.
     */
    concat(...items: ConcatArray<T>[]): T[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat | Array.prototype.concat()}
     * @param items - Arrays and/or values to concatenate into a new array.
     * @returns A new array with the results of calling a provided function on every element in this array.
     */
    concat(...items: (T | ConcatArray<T>)[]): T[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join | Array.prototype.join()}
     * @params separator - A string used to separate one element of the collection from the next in the resulting String.
     * @returns A string representing the elements of the collection.
     */
    join(separator?: string): string;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.slice()}
     * @params start - Zero-based index at which to begin extraction.
     * @params end - Zero-based index at which to end extraction. It extracts up to but not including `end`.
     * @returns A new array containing the elements between the start and end indices.
     */
    slice(start?: number, end?: number): T[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf | Array.prototype.indexOf()}
     * @params searchElement - Element to locate in the collection.
     * @params fromIndex - The collection index at which to begin the search. If omitted, the search starts at index 0.
     * @note `fromIndex` is currently not supported. So all searches start at index 0.
     * @returns The first index at which a given element can be found in the collection, or -1 if it is not present.
     */
    indexOf(searchElement: T, fromIndex?: number): number;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf | Array.prototype.lastIndexOf()}
     * @params searchElement - Element to locate in the collection.
     * @params fromIndex - The collection index at which to begin the search. If omitted, the search starts at the last index.
     * @returns The last index at which a given element can be found in the collection, or -1 if it is not present. The collection is searched backwards, starting at `fromIndex`.
     */
    lastIndexOf(searchElement: T, fromIndex?: number): number;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.prototype.every()}
     * @params predicate - A function to test for each element.
     * @params predicate.value - The current element being processed in the collection.
     * @params predicate.index - The index of the current element being processed in the collection.
     * @params predicate.array - The collection `every` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the predicate function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns `true` if the callback function returns a truthy value for every collection element; otherwise, `false`.
     */
    every<S extends T>(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): this is readonly S[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.prototype.every()}
     * @params predicate - A function to test for each element.
     * @params predicate.value - The current element being processed in the collection.
     * @params predicate.index - The index of the current element being processed in the collection.
     * @params predicate.array - The collection `every` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the predicate function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns `true` if the callback function returns a truthy value for every collection element; otherwise, `false`.
     */
    every(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.prototype.some()}
     * @params predicate - A function to test for each element.
     * @params predicate.value - The current element being processed in the collection.
     * @params predicate.index - The index of the current element being processed in the collection.
     * @params predicate.array - The collection `every` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the predicate function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns `true` if the callback function returns a truthy value for any collection element; otherwise, `false`.
     */
    some(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): boolean;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach | Array.prototype.forEach()}
     * @params callbackfn - A function that accepts up to three arguments. `forEach` calls the callbackfn function one time for each element in the collection.
     * @params callbackfn.value - The current element being processed in the collection.
     * @params callbackfn.index - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `forEach` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the `callbackfn` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     */
    forEach(callbackfn: (value: T, index: number, array: readonly T[]) => void, thisArg?: any): void;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.prototype.map()}
     * @params callbackfn - A function that accepts up to three arguments. The `map` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.value - The current element being processed in the collection.
     * @params callbackfn.index - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `map` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the `callbackfn` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns A new array containing the results of calling the `callbackfn` function on each element in the collection.
     */
    map<U>(callbackfn: (value: T, index: number, array: readonly T[]) => U, thisArg?: any): U[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.prototype.filter()}
     * @params predicate - A function that accepts up to three arguments. The `filter` method calls the `predicate` function one time for each element in the collection.
     * @params predicate.value - The current element being processed in the collection.
     * @params predicate.index - The index of the current element being processed in the collection.
     * @params predicate.array - The collection `filter` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns A new array containing the elements of the collection for which the `predicate` function returned `true`.
     */
    filter<S extends T>(predicate: (value: T, index: number, array: readonly T[]) => value is S, thisArg?: any): S[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.prototype.filter()}
     * @params predicate - A function that accepts up to three arguments. The `filter` method calls the `predicate` function one time for each element in the collection.
     * @params predicate.value - The current element being processed in the collection.
     * @params predicate.index - The index of the current element being processed in the collection.
     * @params predicate.array - The collection `filter` was called upon.
     * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns A new array containing the elements of the collection for which the `predicate` function returned `true`.
     */
    filter(predicate: (value: T, index: number, array: readonly T[]) => unknown, thisArg?: any): T[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.prototype.reduce()}
     * @params callbackfn - A function that accepts up to four arguments. The `reduce` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.)
     * @params callbackfn.currentValue - The current element being processed in the collection.
     * @params callbackfn.currentIndex - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `reduce` was called upon.
     * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value.
     * @returns The value that results from the reduction.
     */
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.prototype.reduce()}
     * @params callbackfn - A function that accepts up to four arguments. The `reduce` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.)
     * @params callbackfn.currentValue - The current element being processed in the collection.
     * @params callbackfn.currentIndex - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `reduce` was called upon.
     * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value.
     * @returns The value that results from the reduction.
     */
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.prototype.reduce()}
     * @params callbackfn - A function that accepts up to four arguments. The `reduce` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.)
     * @params callbackfn.currentValue - The current element being processed in the collection.
     * @params callbackfn.currentIndex - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `reduce` was called upon.
     * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value.
     * @returns The value that results from the reduction.
     */
    reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array.prototype.reduceRight()}
     * @params callbackfn - A function that accepts up to four arguments. The `reduceRight` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.)
     * @params callbackfn.currentValue - The current element being processed in the collection.
     * @params callbackfn.currentIndex - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `reduceRight` was called upon.
     * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value.
     * @returns The value that results from the reduction.
     */
    reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T): T;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array.prototype.reduceRight()}
     * @params callbackfn - A function that accepts up to four arguments. The `reduceRight` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.)
     * @params callbackfn.currentValue - The current element being processed in the collection.
     * @params callbackfn.currentIndex - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `reduceRight` was called upon.
     * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value.
     * @returns The value that results from the reduction.
     */
    reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: readonly T[]) => T, initialValue: T): T;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduceRight | Array.prototype.reduceRight()}
     * @params callbackfn - A function that accepts up to four arguments. The `reduceRight` method calls the `callbackfn` function one time for each element in the collection.
     * @params callbackfn.previousValue - The value previously returned in the last invocation of the `callbackfn` function, or `initialValue`, if supplied. (See below.)
     * @params callbackfn.currentValue - The current element being processed in the collection.
     * @params callbackfn.currentIndex - The index of the current element being processed in the collection.
     * @params callbackfn.array - The collection `reduceRight` was called upon.
     * @params initialValue - If `initialValue` is specified, it is used as the initial value to start the accumulation. The first call to the `callbackfn` function provides this value as an argument instead of an element value.
     * @returns The value that results from the reduction.
     */
    reduceRight<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: readonly T[]) => U, initialValue: U): U;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.prototype.find()}
     * @params predicate - A function that accepts up to three arguments. The `find` method calls the `predicate` function one time for each element in the collection.
     * @params predicate.value - The value of the element.
     * @params predicate.index - The index of the element.
     * @params predicate.obj - The object being traversed.
     * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns The value of the first element in the array that satisfies the provided testing function. Otherwise, `undefined` is returned.
     */
    find<S extends T>(predicate: (this: void, value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.prototype.find()}
     * @params predicate - A function that accepts up to three arguments. The `find` method calls the `predicate` function one time for each element in the collection.
     * @params predicate.value - The value of the element.
     * @params predicate.index - The index of the element.
     * @params predicate.obj - The object being traversed.
     * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns The value of the first element in the array that satisfies the provided testing function. Otherwise, `undefined` is returned.
     */
    find<T>(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.prototype.findIndex()}
     * @params predicate - A function that accepts up to three arguments. The `findIndex` method calls the `predicate` function one time for each element in the collection.
     * @params predicate.value - The value of the element.
     * @params predicate.index - The index of the element.
     * @params predicate.obj - The object being traversed.
     * @params thisArg - An object to which the `this` keyword can refer in the `predicate` function. If `thisArg` is omitted, `undefined` is used as the `this` value.
     * @returns The index of the first element in the array that satisfies the provided testing function. Otherwise, -1 is returned.
     */
    findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes | Array.prototype.includes()}
     * @params searchElement - The element to search for.
     * @params fromIndex - The position in this array at which to begin searching for `searchElement`. A negative value searches from the index of array.length + fromIndex by asc.
     * @note `fromIndex` is currently not supported. So all searches start at index 0.
     * @returns `true` if the `searchElement` is found in the array; otherwise, `false`.
     */
    includes(searchElement: T, fromIndex?: number): boolean;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.prototype.flatMap()}
     * @params callback - Function that produces an element of the new Array, taking three arguments:
     * @params callback.currentValue - The current element being processed in the array.
     * @params callback.index - The index of the current element being processed in the array.
     * @params callback.array - The array `flatMap` was called upon.
     * @params thisArg - Value to use as this when executing callback.
     * @returns A new array with each element being the result of the callback function and flattened to a depth of 1.
     */
    flatMap<U, This = undefined>(callback: (this: This, value: T, index: number, array: T[]) => U | readonly U[], thisArg?: This): U[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat | Array.prototype.flat()}
     * @params depth - The depth level specifying how deep a nested array structure should be flattened. Defaults to 1.
     * @returns A new array with the sub-array elements concatenated into it.
     */
    flat<A, D extends number = 1>(this: A, depth?: D): FlatArray<A, D>[];
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.prototype.at()}
     * @params index - The index of the element to return from the array. If the index is a negative number, the element at `array.length + index` is returned.
     * @returns The element at the given index in the array; `undefined` if there is no element at the given index.
     */
    at(index: number): T | undefined;
    /**
     * @returns An iterator that iterates over all the values in the collection.
     */
    [Symbol.iterator](): IterableIterator<T>;
    /**
     * @returns A string describing the filters applied to this collection.
     */
    description(): string;
    /**
     * Checks if this collection is empty.
     * @returns `true` if the collection is empty, `false` if not.
     */
    isEmpty(): boolean;
    /**
     * Returns the minimum value of the values in the collection or of the
     * given property among all the objects in the collection, or `undefined`
     * if the collection is empty.
     *
     * Only supported for int, float, double and date properties. `null` values
     * are ignored entirely by this method and will not be returned.
     * @param property - For a collection of objects, the property to take the minimum of.
     * @throws A {@link TypeAssertionError} if no property with the name exists or if property is not numeric/date.
     * @returns The minimum value.
     */
    min(property?: string): number | Date | undefined;
    /**
     * Returns the maximum value of the values in the collection or of the
     * given property among all the objects in the collection, or `undefined`
     * if the collection is empty.
     *
     * Only supported for int, float, double and date properties. `null` values
     * are ignored entirely by this method and will not be returned.
     * @param property - For a collection of objects, the property to take the maximum of.
     * @throws An {@link Error} if no property with the name exists or if property is not numeric/date.
     * @returns The maximum value.
     */
    max(property?: string): number | Date | undefined;
    /**
     * Computes the sum of the values in the collection or of the given
     * property among all the objects in the collection, or 0 if the collection
     * is empty.
     *
     * Only supported for int, float and double properties. `null` values are
     * ignored entirely by this method.
     * @param property - For a collection of objects, the property to take the sum of.
     * @throws An {@link Error} if no property with the name exists or if property is not numeric.
     * @returns The sum.
     */
    sum(property?: string): number;
    /**
     * Computes the average of the values in the collection or of the given
     * property among all the objects in the collection, or `undefined` if the collection
     * is empty.
     *
     * Only supported for int, float and double properties. `null` values are
     * ignored entirely by this method and will not be factored into the average.
     * @param property - For a collection of objects, the property to take the average of.
     * @throws An {@link Error} if no property with the name exists or if property is not numeric.
     * @returns The sum.
     */
    avg(property?: string): number | undefined;
    /**
     * Returns new {@link Results} that represent this collection being filtered by the provided query.
     * @param queryString - Query used to filter objects from the collection.
     * @param args - Each subsequent argument is used by the placeholders
     * (e.g. `$0`, `$1`, `$2`, …) in the query.
     * @throws An {@link Error} if the query or any other argument passed into this method is invalid.
     * @returns Results filtered according to the provided query.
     * @note This is currently only supported for collections of Realm Objects.
     * @example
     * let merlots = wines.filtered('variety == "Merlot" && vintage <= $0', maxYear);
     */
    filtered(queryString: string, ...args: unknown[]): Results<T>;
    /**
     * Returns new _Results_ that represent a sorted view of this collection.
     *
     * A collection of Realm Objects can be sorted on one or more properties of
     * those objects, or of properties of objects linked to by those objects.
     * To sort by a single property, simply pass the name of that property to
     * `sorted()`, optionally followed by a boolean indicating if the sort should be reversed.
     * For more than one property, you must pass an array of
     * **sort descriptors** which list
     * which properties to sort on.
     *
     * Collections of other types sort on the values themselves rather than
     * properties of the values, and so no property name or sort descriptors
     * should be supplied.
     * @param reverse - Sort in descending order rather than ascended.
     * It may not be applied if `descriptor` is an array of sort descriptors.
     * @throws An {@link Error} if a specified property does not exist.
     * @returns Results sorted according to the arguments passed in.
     */
    sorted(reverse?: boolean): Results<T>;
    /**
     * Returns new _Results_ that represent a sorted view of this collection.
     *
     * A collection of Realm Objects can be sorted on one or more properties of
     * those objects, or of properties of objects linked to by those objects.
     * To sort by a single property, simply pass the name of that property to
     * `sorted()`, optionally followed by a boolean indicating if the sort should be reversed.
     * For more than one property, you must pass an array of
     * **sort descriptors** which list
     * which properties to sort on.
     *
     * Collections of other types sort on the values themselves rather than
     * properties of the values, and so no property name or sort descriptors
     * should be supplied.
     * @param descriptor - The property name(s) to sort the collection on.
     * @throws An {@link Error} if a specified property does not exist.
     * @returns Results sorted according to the arguments passed in.
     */
    sorted(descriptor: SortDescriptor[]): Results<T>;
    /**
     * Returns new _Results_ that represent a sorted view of this collection.
     *
     * A collection of Realm Objects can be sorted on one or more properties of
     * those objects, or of properties of objects linked to by those objects.
     * To sort by a single property, simply pass the name of that property to
     * `sorted()`, optionally followed by a boolean indicating if the sort should be reversed.
     * For more than one property, you must pass an array of
     * **sort descriptors** which list
     * which properties to sort on.
     *
     * Collections of other types sort on the values themselves rather than
     * properties of the values, and so no property name or sort descriptors
     * should be supplied.
     * @param descriptor - The property name(s) to sort the collection on.
     * @throws An {@link Error} if a specified property does not exist.
     * @returns Results sorted according to the arguments passed in.
     */
    sorted(descriptor: string, reverse?: boolean): Results<T>;
    /**
     * Create a frozen snapshot of the collection.
     *
     * Values added to and removed from the original collection will not be
     * reflected in the _Results_ returned by this method, including if the
     * values of properties are changed to make them match or not match any
     * filters applied.
     *
     * This is **not** a _deep_ snapshot. Realm objects contained in this
     * snapshot will continue to update as changes are made to them, and if
     * they are deleted from the Realm they will be replaced by `null` at the
     * respective indices.
     * @returns Results which will **not** live update.
     */
    snapshot(): Results<T>;
    private getPropertyColumnKey;
}

/**
 * Instances of this class are typically **live** collections returned by
 * objects() that will update as new objects are either
 * added to or deleted from the Realm that match the underlying query. Results returned by
 * snapshot()}, however, will **not** live update
 * (and listener callbacks added through addListener()
 * will thus never be called).
 * @see https://www.mongodb.com/docs/realm/sdk/react-native/model-data/data-types/collections/
 */
declare class Results<T = unknown> extends OrderedCollection<T> {
    get length(): number;
    set length(value: number);
    description(): string;
    /**
     * Bulk update objects in the collection.
     * @param propertyName - The name of the property.
     * @param value - The updated property value.
     * @throws An {@link Error} if no property with the name exists.
     * @since 2.0.0
     */
    update(propertyName: keyof Unmanaged<T>, value: Unmanaged<T>[typeof propertyName]): void;
    /**
     * Add this query result to the set of active subscriptions. The query will be joined
     * via an `OR` operator with any existing queries for the same type.
     * @param options - Options to use when adding this subscription (e.g. a name or wait behavior).
     * @returns A promise that resolves to this {@link Results} instance.
     * @experimental This API is experimental and may change or be removed.
     */
    subscribe(options?: SubscriptionOptions): Promise<this>;
    /**
     * Unsubscribe from this query result. It returns immediately without waiting
     * for synchronization.
     *
     * If the subscription is unnamed, the subscription matching the query will
     * be removed.
     * @experimental This API is experimental and may change or be removed.
     */
    unsubscribe(): void;
    /**
     * Checks if this results collection has not been deleted and is part of a valid Realm.
     * @returns `true` if the collection can be safely accessed.
     */
    isValid(): boolean;
    /**
     * Checks if this collection result is empty.
     * @returns `true` if the collection result is empty, `false` if not.
     */
    isEmpty(): boolean;
}
type AnyResults = Results<any>;

type PartiallyWriteableArray<T> = Pick<Array<T>, "pop" | "push" | "shift" | "unshift" | "splice">;
/**
 * Instances of this class will be returned when accessing object properties whose type is `"list"`.
 *
 * Lists mostly behave like normal Javascript Arrays, except for that they can
 * only store values of a single type (indicated by the `type` and `optional`
 * properties of the List), and can only be modified inside a {@link Realm.write | write} transaction.
 */
declare class List<T = unknown> extends OrderedCollection<T> implements PartiallyWriteableArray<T> {
    /**
     * Checks if this collection has not been deleted and is part of a valid Realm.
     * @returns `true` if the collection can be safely accessed.
     */
    isValid(): boolean;
    /**
     * @returns The number of values in the list.
     */
    get length(): number;
    /**
     * @throws An {@link Error} as the length property cannot be assigned.
     */
    set length(value: number);
    /**
     * Remove the **last** value from the list and return it.
     * @throws an {@link AssertionError} If not inside a write transaction.
     * @returns The last value or undefined if the list is empty.
     */
    pop(): T | undefined;
    /**
     * Add one or more values to the _end_ of the list.
     * @param items - Values to add to the list.
     * @throws A {TypeError} if a value is not of a type which can be stored in
     * the list, or if an object being added to the list does not match the {@link ObjectSchema} for the list.
     * @throws An {@link AssertionError} if not inside a write transaction.
     * @returns The new length of the list after adding the values.
     */
    push(...items: T[]): number;
    /**
     * Remove the **first** value from the list and return it.
     * @throws An {@link AssertionError} if not inside a write transaction.
     * @returns The first value or `undefined` if the list is empty.
     */
    shift(): T | undefined;
    /**
     * Add one or more values to the _beginning_ of the list.
     * @param items - Values to add to the list.
     * @throws A {TypeError} if a value is not of a type which can be stored in
     * the list, or if an object being added to the list does not match the {@link ObjectSchema} for the list.
     * @throws An {@link AssertionError} if not inside a write transaction.
     * @returns The new length of the list after adding the values.
     */
    unshift(...items: T[]): number;
    /**
     * Changes the contents of the list by removing value and/or inserting new value.
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Array.prototype.splice}
     * @param start - The start index. If greater than the length of the list,
     * the start index will be set to the length instead. If negative, then the start index
     * will be counted from the end of the list (e.g. `list.length - index`).
     * @param deleteCount - The number of values to remove from the list.
     * If not provided, then all values from the start index through the end of
     * the list will be removed.
     * @returns An array containing the value that were removed from the list. The
     * array is empty if no value were removed.
     */
    splice(start: number, deleteCount?: number): T[];
    /**
     * Changes the contents of the list by removing value and/or inserting new value.
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice Array.prototype.splice}
     * @param start - The start index. If greater than the length of the list,
     * the start index will be set to the length instead. If negative, then the start index
     * will be counted from the end of the list (e.g. `list.length - index`).
     * @param deleteCount - The number of values to remove from the list.
     * If not provided, then all values from the start index through the end of
     * the list will be removed.
     * @param items - Values to insert into the list starting at `index`.
     * @returns An array containing the value that were removed from the list. The
     * array is empty if no value were removed.
     */
    splice(start: number, deleteCount: number, ...items: T[]): T[];
    /**
     * Removes the element of the list at the specified index.
     * @param index - The index of the element to remove.
     * @throws An {@link AssertionError} if not inside a write transaction or the input index is less than 0
     * or greater than or equal to the size of the list.
     */
    remove(index: number): void;
    /**
     * Moves one element of the list from one index to another.
     * @param from - The index of the element to move.
     * @param to - The destination index of the element.
     * @throws An {@link AssertionError} if not inside a write transaction or if any of the input indexes
     * is less than 0 or greater than or equal to the size of the list.
     */
    move(from: number, to: number): void;
    /**
     * Swaps the positions of the elements of the list at two indexes.
     * @param index1 - The index of the first element.
     * @param index2 - The index of the second element.
     * @throws An {@link AssertionError} if not inside a write transaction or if any of the input indexes
     * is less than 0 or greater than or equal to the size of the list.
     */
    swap(index1: number, index2: number): void;
}

/**
 * Instances of this class will be returned when accessing object properties whose type is `"Set"`
 *
 * Sets mostly behave like normal JavaScript Sets, with a few exceptions:
 * They can only store values of a single type (indicated by the `type`
 * and `optional` properties of the Set).
 * They can only be modified inside a **write** transaction.
 * Unlike JavaScript's Set, Realm~Set does NOT make any guarantees about the
 * traversal order of `values()`, `entries()`, `keys()`, or `forEach` iterations.
 * If values in a Set are required to have some order, it must be implemented
 * by the developer by, for example, wrapping values in an object that holds
 * a user-supplied insertion order.
 * @see https://www.mongodb.com/docs/realm/sdk/react-native/model-data/data-types/sets/
 */
declare class RealmSet<T = unknown> extends OrderedCollection<T, [T, T]> {
    /**
     * @returns The number of values in the Set.
     */
    get size(): number;
    /**
     * Checks if this Set has not been deleted and is part of a valid Realm.
     * @returns `true` if the set can be safely accessed, `false` if not.
     */
    isValid(): boolean;
    /**
     * Delete a value from the Set.
     * @param value - Value to delete from the Set.
     * @throws An {@link Error} if not inside a write transaction.
     * @returns `true` if the value existed in the Set prior to deletion, `false` if not.
     */
    delete(value: T): boolean;
    /**
     * Add a new value to the Set.
     * @param value - Value to add to the Set.
     * @throws A {@link TypeError} if a `value` is not of a type which can be stored in
     * the Set, or if an object being added to the Set does not match the for the Set.
     * @throws An {@link Error} if not inside a write transaction.
     * @returns The Set itself, after adding the new value.
     */
    add(value: T): this;
    /**
     * Remove all values from the Set.
     * @throws An {@link Error} if not inside a write transaction.
     */
    clear(): void;
    /**
     * Check for existence of a value in the Set.
     * @param value - Value to search for in the Set
     * @throws A {@link TypeError} if a `value` is not of a type which can be stored in
     * the Set, or if an object being added to the Set does not match the
     * **object schema** for the Set.
     * @returns `true` if the value exists in the Set, `false` if not.
     */
    has(value: T): boolean;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries | Set.prototype.entries()}
     * @returns An iterator over the entries of the Set. Each entry is a two-element array
     * containing the value from the Set, followed by a copy of the same value (`[value, value]`).
     */
    entries(): Generator<[T, T]>;
}

type DictionaryChangeSet = {
    deletions: string[];
    modifications: string[];
    insertions: string[];
};
type DictionaryChangeCallback = (dictionary: Dictionary, changes: DictionaryChangeSet) => void;
/**
 * Instances of this class are returned when accessing object properties whose type is `"Dictionary"`
 *
 * Dictionaries behave mostly like a JavaScript object i.e., as a key/value pair
 * where the key is a string.
 */
declare class Dictionary<T = unknown> extends Collection<string, T, [string, T], [string, T], DictionaryChangeCallback> {
    /** @ts-expect-error We're exposing methods in the end-users namespace of keys */
    [key: string]: T;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries Array.prototype.entries}
     * @returns An iterator with all entries in the dictionary.
     */
    [Symbol.iterator](): Generator<[string, T]>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/keys Array.prototype.keys}
     * @returns An iterator with all values in the dictionary.
     * @since 10.5.0
     * @ts-expect-error We're exposing methods in the end-users namespace of keys */
    keys(): Generator<string>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values Array.prototype.values}
     * @returns An iterator with all values in the dictionary.
     * @since 10.5.0
     * @ts-expect-error We're exposing methods in the end-users namespace of values */
    values(): Generator<T>;
    /**
     * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries Array.prototype.entries}
     * @returns An iterator with all key/value pairs in the dictionary.
     * @since 10.5.0
     * @ts-expect-error We're exposing methods in the end-users namespace of entries */
    entries(): Generator<[string, T]>;
    /**
     * Checks if this dictionary has not been deleted and is part of a valid Realm.
     * @returns `true` if the dictionary can be safely accessed.
     * @since 0.14.0
     * @ts-expect-error We're exposing methods in the end-users namespace of keys */
    isValid(): boolean;
    /**
     * Adds one or more elements with specified key and value to the dictionary or updates value if key exists.
     * @param elements The object of element(s) to add.
     * @throws an {@link AssertionError} If not inside a write transaction, input object contains symbol keys or if any value violates types constraints.
     * @returns The dictionary.
     * @since 10.6.0
     * @ts-expect-error We're exposing methods in the end-users namespace of keys */
    set(elements: {
        [key: string]: T;
    }): this;
    /**
     * Adds an element with the specified key and value to the dictionary or updates value if key exists.
     * @param key The key of the element to add.
     * @param value The value of the element to add.
     * @throws an {@link AssertionError} If not inside a write transaction, key is a symbol or if value violates type constraints.
     * @returns The dictionary.
     * @since 12.0.0
     */
    set(key: string, value: T): this;
    /**
     * Removes elements from the dictionary, with the keys provided.
     * This does not throw if the keys are already missing from the dictionary.
     * @param key - The key to be removed.
     * @throws An {@link AssertionError} if not inside a write transaction.
     * @returns The dictionary
     * @since 10.6.0
     * @ts-expect-error We're exposing methods in the end-users namespace of keys */
    remove(key: string | string[]): this;
    /**
     * The plain object representation for JSON serialization.
     * Use circular JSON serialization libraries such as [@ungap/structured-clone](https://www.npmjs.com/package/@ungap/structured-clone)
     * and [flatted](https://www.npmjs.com/package/flatted) to stringify Realm entities that have circular structures.
     * @returns A plain object.
     * @ts-expect-error We're exposing methods in the end-users namespace of keys */
    toJSON(_?: string, cache?: unknown): DefaultObject;
}

declare const RealmDictionary: typeof Dictionary;
type RealmDictionary<T> = Dictionary<T>;
declare const RealmList: typeof List;
type RealmList<T> = List<T>;
declare const RealmResults: typeof Results;
type RealmResults<T> = Results<T>;
declare const GlobalDate$1: DateConstructor;
declare namespace Types {
    type Bool = boolean;
    type String = string;
    type Int = number;
    type Float = number;
    type Double = number;
    type Decimal128 = BSON.Decimal128;
    const Decimal128: typeof bson.Decimal128;
    type ObjectId = BSON.ObjectId;
    const ObjectId: typeof bson.ObjectID;
    type UUID = BSON.UUID;
    const UUID: typeof bson.UUID;
    type Date = typeof GlobalDate$1;
    const Date: DateConstructor;
    type Data = ArrayBuffer;
    const Data: ArrayBufferConstructor;
    type List<T> = RealmList<T>;
    const List: typeof RealmList;
    type Set<T> = RealmSet<T>;
    const Set: typeof RealmSet;
    type Dictionary<T> = RealmDictionary<T>;
    const Dictionary: typeof RealmDictionary;
    type Mixed = unknown;
    type LinkingObjects<ObjectTypeT, LinkingPropertyName> = RealmResults<ObjectTypeT>;
    const LinkingObjects: typeof RealmResults;
}

/**
 * Represents the coordinates of a point. The first two required elements of the array are longitude (index 0) and latitude (index 1).
 * The third and optional element is altitude (index 2), but is currently ignored in the geospatial queries calculations.
 */
type GeoPosition = [number, number] | [number, number, number];
/**
 * Interface that satisfies the GeoJSON specification for a polygon.
 * This can be used as one of the possible forms of {@link GeoPolygon}.
 */
interface CanonicalGeoPolygon {
    coordinates: GeoPosition[][];
    type: "Polygon";
}
/**
 * Interface that satisfies the GeoJSON specification for a point.
 * Any embedded object that adhere to this interface can be queried in geospatial queries.
 * Additionally, this can be used as one of the possible forms of {@link GeoPoint}.
 */
interface CanonicalGeoPoint {
    coordinates: GeoPosition;
    type: "Point";
}
/**
 * Represents a point in spherical geometry.
 * This type cannot be used on its own, only as a building block for the other geospatial types.
 * ({@link GeoCircle}, {@link GeoBox}, {@link GeoPolygon}).
 */
type GeoPoint = 
/**
 * This is compatible with {@link https://developer.mozilla.org/en-US/docs/Web/API/GeolocationCoordinates|GeoLocationCoordinates}
 */
{
    latitude: number;
    longitude: number;
    altitude?: number;
} | CanonicalGeoPoint | GeoPosition;
/**
 * Represents a circle in spherical geometry that can be used as an argument for geospatial queries.
 * @example
 * let circle: GeoCircle = {
 *   center: [20, 40],
 *   distance: 0.05,
 * };
 * realm.objects(Restaurant).filtered("location geoWithin $0", circle)
 */
type GeoCircle = {
    /** The center of the circle. */
    center: GeoPoint;
    /**
     * The radius of the circle in radians. You can use {@link kmToRadians} and {@link miToRadians}
     * to respectively convert kilometers and miles to radians.
     */
    distance: number;
};
/**
 * Represents a polygon in spherical geometry that can be used as an argument for geospatial queries.
 * The polygon is comprised of at least one outer ring and optionally multiple internal rings representing holes with the following restrictions:
 * - Each ring must contains at least 3 distinct points, where the first and the last point must be the same to indicate a closed ring (this means that each ring
 * must have at least 4 points).
 * - The interior rings must be entirely inside the outer ring.
 * - Rings can share vertices but not edges.
 * - No ring may be empty.
 * @example
 * let polygon: GeoPolygon = {
 *  outerRing: [
 *   [-2, -2],
 *   [3.45, -4.23],
 *   [2.56, 4.62],
 *   [-3.23, 2.5],
 *   [-2, -2],
 *  ],
 * };
 * realm.objects(Restaurant).filtered("location geoWithin $0", polygon)
 */
type GeoPolygon = {
    outerRing: GeoPoint[];
    holes?: GeoPoint[][];
} | CanonicalGeoPolygon;
/**
 * Represents a box in spherical geometry that can be used as an argument for geospatial queries.
 * This is a short-hand for the equivalent {@link GeoPolygon}.
 * @example
 * let box: GeoBox = {
 *   bottomLeft: [-1, -1],
 *   topRight: [1, 1],
 * };
 * realm.objects(Restaurant).filtered("location geoWithin $0", box)
 */
type GeoBox = {
    /** The bottom left point of the box. */
    bottomLeft: GeoPoint;
    /** The top right point of the box. */
    topRight: GeoPoint;
};
/**
 * Converts the input kilometer value in radians.
 * @param km - The kilometers to convert.
 * @returns The corresponding number of radians.
 */
declare function kmToRadians(km: number): number;
/**
 * Converts the input miles value in radians.
 * @param mi - The miles to convert.
 * @returns The corresponding number of radians.
 */
declare function miToRadians(mi: number): number;

type LogLevel = "all" | "trace" | "debug" | "detail" | "info" | "warn" | "error" | "fatal" | "off";
declare enum NumericLogLevel {
    All = 0,
    Trace = 1,
    Debug = 2,
    Detail = 3,
    Info = 4,
    Warn = 5,
    Error = 6,
    Fatal = 7,
    Off = 8
}
/**
 * A callback passed to `Realm.App.Sync.setLogger` when instrumenting the Atlas Device Sync client with a custom logger.
 * @param level - The level of the log entry between 0 and 8 inclusively.
 * Use this as an index into `['all', 'trace', 'debug', 'detail', 'info', 'warn', 'error', 'fatal', 'off']` to get the name of the level.
 * @param message - The message of the log entry.
 */
type Logger = (level: NumericLogLevel, message: string) => void;
type LoggerCallback = (level: LogLevel, message: string) => void;

type PartitionValue = string | number | BSON.ObjectId | BSON.UUID | null;
declare enum OpenRealmBehaviorType {
    DownloadBeforeOpen = "downloadBeforeOpen",
    OpenImmediately = "openImmediately"
}
declare enum OpenRealmTimeOutBehavior {
    OpenLocalRealm = "openLocalRealm",
    ThrowException = "throwException"
}
type OpenRealmBehaviorConfiguration = {
    type: OpenRealmBehaviorType;
    timeOut?: number;
    timeOutBehavior?: OpenRealmTimeOutBehavior;
};
type ErrorCallback = (session: SyncSession, error: SyncError | ClientResetError) => void;
type ClientResetFallbackCallback = (session: SyncSession, path: string) => void;
type ClientResetBeforeCallback = (localRealm: Realm) => void;
type ClientResetAfterCallback = (localRealm: Realm, remoteRealm: Realm) => void;
declare enum SessionStopPolicy {
    AfterUpload = "after-upload",
    Immediately = "immediately",
    Never = "never"
}
/**
 */
declare enum ClientResetMode {
    /** @deprecated See {@link Realm.App.Sync.initiateClientReset} */
    Manual = "manual",
    /**
     * Download a fresh copy from the server.
     */
    DiscardUnsyncedChanges = "discardUnsyncedChanges",
    /**
     * Merged remote and local, unsynced changes.
     */
    RecoverUnsyncedChanges = "recoverUnsyncedChanges",
    /**
     * Download a fresh copy from the server if recovery of unsynced changes is not possible.
     */
    RecoverOrDiscardUnsyncedChanges = "recoverOrDiscardUnsyncedChanges"
}
type ClientResetManualConfiguration = {
    mode: ClientResetMode.Manual;
    onManual?: ClientResetFallbackCallback;
};
type ClientResetDiscardUnsyncedChangesConfiguration = {
    mode: ClientResetMode.DiscardUnsyncedChanges;
    onAfter?: ClientResetAfterCallback;
    /**
     * Called before sync initiates a client reset.
     */
    onBefore?: ClientResetBeforeCallback;
};
type ClientResetRecoverUnsyncedChangesConfiguration = {
    mode: ClientResetMode.RecoverUnsyncedChanges;
    onAfter?: ClientResetAfterCallback;
    /**
     * Called before sync initiates a client reset.
     */
    onBefore?: ClientResetBeforeCallback;
    /**
     * Called if recovery or discard fail.
     */
    onFallback?: ClientResetFallbackCallback;
};
type ClientResetRecoverOrDiscardUnsyncedChangesConfiguration = {
    mode: ClientResetMode.RecoverOrDiscardUnsyncedChanges;
    onAfter?: ClientResetAfterCallback;
    /**
     * Called before sync initiates a client reset.
     */
    onBefore?: ClientResetBeforeCallback;
    /**
     * Called if recovery or discard fail.
     */
    onFallback?: ClientResetFallbackCallback;
};
type ClientResetConfig = ClientResetManualConfiguration | ClientResetDiscardUnsyncedChangesConfiguration | ClientResetRecoverUnsyncedChangesConfiguration | ClientResetRecoverOrDiscardUnsyncedChangesConfiguration;
type SSLConfiguration = {
    /**
     * Whether the SSL certificates must be validated. This should generally
     * be `true` in production.
     *
     * Default is `true`.
     */
    validate?: boolean;
    /**
     * The path where to find trusted SSL certificates used to validate the
     * server certificate. If `undefined`, validation will be delegated to
     * the provided `validateCertificates` callback.
     */
    certificatePath?: string;
    /**
     * A callback function used to validate the server's SSL certificate. It
     * is invoked for every certificate in the certificate chain starting from
     * the root downward. An SSL connection will be established if all certificates
     * are accepted. The certificate will be accepted if the callback returns `true`,
     * or rejected if returning `false`. This callback is only invoked if
     * `certificatePath` is `undefined`.
     */
    validateCertificates?: SSLVerifyCallback;
};
type SSLVerifyCallback = (sslVerifyObject: SSLVerifyObject) => boolean;
type SSLVerifyObject = {
    /**
     * The address that the SSL connection is being established to.
     */
    serverAddress: string;
    /**
     * The port that the SSL connection is being established to.
     */
    serverPort: number;
    /**
     * The certificate using the PEM format.
     */
    pemCertificate: string;
    /**
     * The result of OpenSSL's pre-verification of the certificate. If `true`,
     * the certificate has been accepted and will generally be safe to trust.
     * If `false`, it has been rejected and the user should do an independent
     * validation step.
     */
    acceptedByOpenSSL: boolean;
    /**
     * The position of the certificate in the certificate chain. The actual
     * server certificate has `depth` 0 (lowest) and also contains the host
     * name, while all other certificates up the chain have higher depths in
     * increments of 1.
     */
    depth: number;
};
declare enum ProxyType {
    HTTP = "http",
    HTTPS = "https"
}
type SyncProxyConfig = {
    address: string;
    port: number;
    type: ProxyType;
};
/**
 * This describes the different options used to create a {@link Realm} instance with Atlas App Services synchronization.
 */
type BaseSyncConfiguration = {
    /**
     * A {@link Realm.User} object obtained by calling `Realm.App.logIn`.
     */
    user: AnyUser;
    /**
     * Whether to create a new file and sync in background or wait for the file to be synced.
     * @default
     * {
     *   type: OpenRealmBehaviorType.DownloadBeforeOpen,
     *   timeOut: 30 * 1000,
     *   timeOutBehavior: OpenRealmTimeOutBehavior.ThrowException,
     * }
     */
    newRealmFileBehavior?: OpenRealmBehaviorConfiguration;
    /**
     * Whether to open existing file and sync in background or wait for the sync of the file to complete and then open.
     * If not set, the Realm will be downloaded before opened.
     * @default
     * {
     *   type: OpenRealmBehaviorType.DownloadBeforeOpen,
     *   timeOut: 30 * 1000,
     *   timeOutBehavior: OpenRealmTimeOutBehavior.ThrowException,
     * }
     */
    existingRealmFileBehavior?: OpenRealmBehaviorConfiguration;
    /**
     * A callback function which is called in error situations.
     * The callback is passed two arguments: `session` and `syncError`.
     * If `syncError.name == "ClientReset"`, `syncError.path` and `syncError.config` are set and `syncError.readOnly` is true (deprecated, see `Realm.App.Sync~ClientResetConfiguration`).
     * Otherwise, `syncError` can have up to five properties: `name`, `message`, `isFatal`, `category`, and `code`.
     */
    onError?: ErrorCallback;
    /**
     * Custom HTTP headers, which are included when making requests to the server.
     */
    customHttpHeaders?: Record<string, string>;
    /**
     * SSL configuration.
     */
    ssl?: SSLConfiguration;
    /**
     * Configuration of Client Reset
     */
    clientReset?: ClientResetConfig;
    /**
     * Set to true, all async operations (such as opening the Realm with `Realm.open`) will fail when a non-fatal error, such as a timeout, occurs.
     */
    cancelWaitsOnNonFatalError?: boolean;
    /**
     * HTTP proxy configuration (node.js/Electron only)
     */
    proxyConfig?: SyncProxyConfig;
};
type InitialSubscriptions = {
    /**
     * A callback to make changes to a SubscriptionSet.
     * @see {@link SubscriptionSet.update} for more information.
     */
    update: (mutableSubscriptions: MutableSubscriptionSet, realm: Realm) => void;
    /**
     * If `true`, the {@link InitialSubscriptions.update} callback will be rerun every time the Realm is
     * opened (e.g. every time a user opens your app), otherwise (by default) it
     * will only be run if the Realm does not yet exist.
     */
    rerunOnOpen?: boolean;
};
type FlexibleSyncConfiguration = BaseSyncConfiguration & {
    flexible: true;
    partitionValue?: never;
    /**
     * Optional object to configure the setup of an initial set of flexible
     * sync subscriptions to be used when opening the Realm. If this is specified,
     * {@link Realm.open} will not resolve until this set of subscriptions has been
     * fully synchronized with the server.
     * @example
     * const config: Realm.Configuration = {
     *   sync: {
     *     user,
     *     flexible: true,
     *     initialSubscriptions: {
     *       update: (subs, realm) => {
     *         subs.add(realm.objects('Task'));
     *       },
     *       rerunOnOpen: true,
     *     },
     *   },
     *   // ... rest of config ...
     * };
     * const realm = await Realm.open(config);
     *
     * // At this point, the Realm will be open with the data for the initial set
     * // subscriptions fully synchronised.
     */
    initialSubscriptions?: InitialSubscriptions;
};
type PartitionSyncConfiguration = BaseSyncConfiguration & {
    flexible?: never;
    partitionValue: PartitionValue;
    initialSubscriptions?: never;
};
type SyncConfiguration = FlexibleSyncConfiguration | PartitionSyncConfiguration;

/**
 * Types of an authentication provider.
 */
declare enum ProviderType {
    AnonUser = "anon-user",
    ApiKey = "api-key",
    LocalUserPass = "local-userpass",
    CustomFunction = "custom-function",
    CustomToken = "custom-token",
    OAuth2Google = "oauth2-google",
    OAuth2Facebook = "oauth2-facebook",
    OAuth2Apple = "oauth2-apple"
}
declare class Credentials {
    /**
     * Creates credentials for an anonymous user. These can only be used once - using them a second
     * time will result in a different user being logged in. If you need to get a user that has already logged
     * in with the Anonymous credentials, use {@link App.currentUser} or {@link App.allUsers}.
     * @param reuse - Reuse any existing anonymous user already logged in.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://docs.mongodb.com/realm/authentication/anonymous/
     */
    static anonymous(reuse?: boolean): Credentials;
    /**
     * Creates credentials based on a login with an email address and a password.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/email-password/
     */
    static emailPassword(credentials: {
        email: string;
        password: string;
    }): Credentials;
    static emailPassword(email: string, password: string): Credentials;
    /**
     * Creates credentials from an API key.
     * @param key - A string identifying the API key.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/api-key/
     */
    static apiKey(key: string): Credentials;
    /**
     * Creates credentials based on an Apple login.
     * @param token - An Apple authentication token, obtained by logging into Apple.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/apple/
     */
    static apple(token: string): Credentials;
    /**
     * Creates credentials based on a Facebook login.
     * @param token - A Facebook authentication token, obtained by logging into Facebook.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/facebook/
     */
    static facebook(token: string): Credentials;
    /**
     * Creates credentials based on a Google login.
     * @param authObject - An object with either an `authCode` or `idToken` property.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/google/
     */
    static google(authObject: {
        authCode: string;
    } | {
        idToken: string;
    }): Credentials;
    /**
     * Creates credentials with a JSON Web Token (JWT) provider and user identifier.
     * @param token - A string identifying the user. Usually an identity token or a username.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/custom-jwt/
     */
    static jwt(token: string): Credentials;
    /**
     * Creates credentials with an Atlas App Services function and user identifier.
     * @param payload - An object identifying the user. Usually an identity token or a username.
     * @returns An instance of `Credentials` that can be used in {@link App.logIn}.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/custom-function/
     */
    static function(payload: object): Credentials;
}

type UserChangeCallback = () => void;
/**
 * The state of a user.
 */
declare enum UserState {
    /**
     * Authenticated and available to communicate with services.
     * @deprecated Will be removed in v13. Please use {@link UserState.LoggedIn}
     */
    Active = "active",
    /** Authenticated and available to communicate with services. */
    LoggedIn = "LoggedIn",
    /** Logged out, but ready to be logged in. */
    LoggedOut = "LoggedOut",
    /** Removed from the app entirely. */
    Removed = "Removed"
}
/**
 * A user's identity with a particular authentication provider.
 */
interface UserIdentity {
    /**
     * The ID of the identity.
     */
    id: string;
    /**
     * The type of the provider associated with the identity.
     */
    providerType: ProviderType;
}
type AnyUser = User<any, any, any>;
/**
 * Representation of an authenticated user of an {@link App}.
 */
declare class User<UserFunctionsFactoryType extends DefaultFunctionsFactory = DefaultFunctionsFactory, UserCustomDataType extends DefaultObject = DefaultObject, UserProfileDataType extends DefaultUserProfileData = DefaultUserProfileData> {
    private cachedProfile;
    private listeners;
    /**
     * The automatically-generated internal ID of the user.
     * @returns The user ID as a string.
     */
    get id(): string;
    /**
     * The provider type used when authenticating the user.
     * @returns The provider type as an enumerated string.
     */
    get providerType(): ProviderType;
    /**
     * The ID of the device.
     * @returns The device ID as a string or `null`.
     */
    get deviceId(): string | null;
    /**
     * The state of the user.
     * @returns The state as an enumerated string.
     */
    get state(): UserState;
    /**
     * The logged in state of the user.
     * @returns `true` if the user is logged in, `false` otherwise.
     */
    get isLoggedIn(): boolean;
    /**
     * The identities of the user at any of the app's authentication providers.
     * @returns An array of {@link UserIdentity} objects.
     */
    get identities(): UserIdentity[];
    /**
     * The access token used when requesting a new access token.
     * @returns The access token as a string or `null`.
     */
    get accessToken(): string | null;
    /**
     * The refresh token used when requesting a new access token.
     * @returns The refresh token as a string or `null`.
     */
    get refreshToken(): string | null;
    /**
     * You can store arbitrary data about your application users in a MongoDB collection and configure
     * Atlas App Services to automatically expose each user’s data in a field of their user object.
     * For example, you might store a user’s preferred language, date of birth, or their local timezone.
     *
     * If this value has not been configured, it will be empty.
     * @returns The custom data as an object.
     */
    get customData(): UserCustomDataType;
    /**
     * A profile containing additional information about the user.
     * @returns The user profile data as an object.
     */
    get profile(): UserProfileDataType;
    /**
     * Use this to call functions defined by the Atlas App Services application, as this user.
     * @returns A {@link FunctionsFactory} that can be used to call the app's functions.
     */
    get functions(): UserFunctionsFactoryType;
    /**
     * Perform operations related to the API-key auth provider.
     * @returns An {@link ApiKeyAuth} object that can be used to manage API keys.
     */
    get apiKeys(): ApiKeyAuth;
    /**
     * Log out the user.
     * @returns A promise that resolves once the user has been logged out of the app.
     */
    logOut(): Promise<void>;
    /**
     * Link the user with an identity represented by another set of credentials.
     * @param credentials - The credentials to use when linking.
     * @returns A promise that resolves once the user has been linked with the credentials.
     */
    linkCredentials(credentials: Credentials): Promise<void>;
    /**
     * Call a remote Atlas App Services Function by its name.
     * @note Consider using `functions[name]()` instead of calling this method.
     * @param name - Name of the App Services Function.
     * @param args - Arguments passed to the Function.
     * @returns A promise that resolves to the value returned by the Function.
     * @example
     * // These are all equivalent:
     * await user.callFunction("doThing", a1, a2, a3);
     * await user.functions.doThing(a1, a2, a3);
     * await user.functions["doThing"](a1, a2, a3);
     * @example
     * // The methods returned from the functions object are bound, which is why it's okay to store the function in a variable before calling it:
     * const doThing = user.functions.doThing;
     * await doThing(a1);
     * await doThing(a2);
     */
    callFunction(name: string, ...args: unknown[]): Promise<unknown>;
    /**
     * Refresh the access token and derive custom data from it.
     * @returns A promise that resolves to the refreshed custom data.
     */
    refreshCustomData(): Promise<UserCustomDataType>;
    /**
     * Use the Push service to enable sending push messages to this user via Firebase Cloud Messaging (FCM).
     * @deprecated https://www.mongodb.com/docs/atlas/app-services/reference/push-notifications/
     * @returns A {@link PushClient} with methods to register and deregister the device on the user.
     */
    push(serviceName: string): PushClient;
    /**
     * @param serviceName - The name of the MongoDB service to connect to.
     * @returns A client enabling access to a {@link MongoDB} service.
     * @example
     * let blueWidgets = user.mongoClient("myService")
     *                       .db("myDb")
     *                       .collection<Widget>("widgets")
     *                       .find({ color: "blue" });
     */
    mongoClient(serviceName: string): MongoDB;
    /**
     * Adds a listener that will be fired on various user related events.
     * This includes auth token refresh, refresh token refresh, refresh custom user data, and logout.
     * @param callback - The callback to be fired when the event occurs.
     */
    addListener(callback: UserChangeCallback): void;
    /**
     * Removes an event listener previously added via {@link User.addListener}.
     * @param callback - The callback to be removed.
     */
    removeListener(callback: UserChangeCallback): void;
    /**
     * Removes all event listeners previously added via {@link User.addListener}.
     */
    removeAllListeners(): void;
}

declare enum ProgressDirection {
    /**
     * Data going from the server to the client.
     */
    Download = "download",
    /**
     * Data going from the client to the server.
     */
    Upload = "upload"
}
declare enum ProgressMode {
    ReportIndefinitely = "reportIndefinitely",
    ForCurrentlyOutstandingWork = "forCurrentlyOutstandingWork"
}
type ProgressNotificationCallback = 
/**
 * @param transferred - The current number of bytes already transferred
 * @param transferable - The total number of transferable bytes (i.e. the number of bytes already transferred plus the number of bytes pending transfer)
 */
(transferred: number, transferable: number) => void;
declare enum ConnectionState {
    Disconnected = "disconnected",
    Connecting = "connecting",
    Connected = "connected"
}
type ConnectionNotificationCallback = (newState: ConnectionState, oldState: ConnectionState) => void;
declare enum SessionState {
    /**
     * The sync session encountered a non-recoverable error and is permanently invalid. Create a new Session to continue syncing.
     */
    Invalid = "invalid",
    /**
     * The sync session is actively communicating or attempting to communicate with Atlas App Services. A session may be considered active even if it is not currently connected. To find out if a session is online, check its connection state.
     */
    Active = "active",
    /**
     * The sync session is not attempting to communicate with Atlas App Services due to the user logging out or synchronization being paused.
     */
    Inactive = "inactive"
}
declare class SyncSession {
    /**
     * Gets the Sync-part of the configuration that the corresponding Realm was constructed with.
     */
    get config(): SyncConfiguration;
    /**
     * Gets the current state of the session.
     */
    get state(): SessionState;
    /**
     * Gets the URL of the Realm Object Server that this session is connected to.
     */
    get url(): string;
    /**
     * Gets the User that this session was created with.
     */
    get user(): User<Realm.DefaultFunctionsFactory, DefaultObject, Realm.DefaultUserProfileData>;
    /**
     * Gets the current state of the connection to the server. Multiple sessions might share the same underlying
     * connection. In that case, any connection change is sent to all sessions.
     *
     * Data will only be synchronized with the server if this method returns `Connected` and `state()` returns `Active` or `Dying`.
     */
    get connectionState(): ConnectionState;
    /**
     * Returns `true` if the session is currently active and connected to the server, `false` if not.
     */
    isConnected(): boolean;
    /**
     * Pause a sync session.
     *
     * This method is asynchronous so in order to know when the session has started you will need
     * to add a connection notification with {@link addConnectionNotification}.
     *
     * This method is idempotent so it will be a no-op if the session is already paused or if multiplexing
     * is enabled.
     * @since 2.16.0-rc.2
     */
    pause(): void;
    /**
     * Resumes a sync session that has been paused.
     *
     * This method is asynchronous so in order to know when the session has started you will need
     * to add a connection notification with {@link addConnectionNotification}.
     *
     * This method is idempotent so it will be a no-op if the session is already started or if multiplexing
     * is enabled.
     * @since 2.16.0-rc.2
     */
    resume(): void;
    /**
     * Reconnects to Altas Device Sync.
     *
     * This method is asynchronous so in order to know when the session has started you will need
     * to add a connection notification with {@link addConnectionNotification}.
     *
     * This method is idempotent so it will be a no-op if the session is already started.
     * @since 12.2.0
     */
    reconnect(): void;
    /**
     * Register a progress notification callback on a session object
     * @param direction - The progress direction to register for.
     * @param mode - The progress notification mode to use for the registration.
     * Can be either:
     *  - `reportIndefinitely` - the registration will stay active until the callback is unregistered
     *  - `forCurrentlyOutstandingWork` - the registration will be active until only the currently transferable bytes are synced
     * @param callback - Called with the following arguments:
     * 1. `transferred`: The current number of bytes already transferred
     * 2. `transferable`: The total number of transferable bytes (the number of bytes already transferred plus the number of bytes pending transfer)
     * @since 1.12.0
     */
    addProgressNotification(direction: ProgressDirection, mode: ProgressMode, callback: ProgressNotificationCallback): void;
    /**
     * Unregister a progress notification callback that was previously registered with {@link addProgressNotification}.
     * Calling the function multiple times with the same callback is ignored.
     * @param callback - A previously registered progress callback.
     * @since 1.12.0
     */
    removeProgressNotification(callback: ProgressNotificationCallback): void;
    /**
     * Registers a connection notification on the session object. This will be notified about changes to the
     * underlying connection to the Realm Object Server.
     * @param callback - Called with the following arguments:
     * 1. `newState`: The new state of the connection
     * 2. `oldState`: The state the connection transitioned from.
     * @since 2.15.0
     */
    addConnectionNotification(callback: ConnectionNotificationCallback): void;
    /**
     * Unregister a state notification callback that was previously registered with addStateNotification.
     * Calling the function multiple times with the same callback is ignored.
     * @param callback - A previously registered state callback.
     * @since 2.15.0
     */
    removeConnectionNotification(callback: ConnectionNotificationCallback): void;
    /**
     * This method returns a promise that does not resolve successfully until all known remote changes have been
     * downloaded and applied to the Realm or the specified timeout is hit in which case it will be rejected. If the method
     * times out, the download will still continue in the background.
     *
     * This method cannot be called before the Realm has been opened.
     * @param timeoutMs - maximum amount of time to wait in milliseconds before the promise will be rejected. If no timeout
     * is specified the method will wait forever.
     */
    downloadAllServerChanges(timeoutMs?: number): Promise<void>;
    /**
     * This method returns a promise that does not resolve successfully until all known local changes have been uploaded
     * to the server or the specified timeout is hit in which case it will be rejected. If the method times out, the upload
     * will still continue in the background.
     *
     * This method cannot be called before the Realm has been opened.
     * @param timeoutMs - Maximum amount of time to wait in milliseconds before the promise is rejected. If no timeout is specified the method will wait forever.
     */
    uploadAllLocalChanges(timeoutMs?: number): Promise<void>;
}

/**
 * The representation of an API-key stored in the service.
 */
type ApiKey = {
    /**
     * The internal identifier of the key.
     */
    _id: string;
    /**
     * A name for the key.
     */
    name: string;
    /**
     * When disabled, the key cannot authenticate.
     */
    disabled: boolean;
};
/**
 * The representation of an API-key when returned from the server, just after creation.
 */
type SecretApiKey = ApiKey & {
    /**
     * The secret part of the key.
     */
    key: string;
};
/**
 * Authentication provider where users identify using an API-key.
 */
declare class ApiKeyAuth {
    /**
     * Creates an API key that can be used to authenticate as the current user.
     * @param keyName the name of the API key to be created.
     */
    create(keyName: string): Promise<SecretApiKey>;
    /**
     * Fetches an API key associated with the current user.
     * @param keyId the id of the API key to fetch.
     */
    fetch(keyId: string): Promise<ApiKey>;
    /**
     * Fetches the API keys associated with the current user.
     */
    fetchAll(): Promise<ApiKey[]>;
    /**
     * Deletes an API key associated with the current user.
     * @param keyId the ID of the API key to delete
     */
    delete(keyId: string): Promise<void>;
    /**
     * Enables an API key associated with the current user.
     * @param keyId the ID of the API key to enable
     */
    enable(keyId: string): Promise<void>;
    /**
     * Disable an API key associated with the current user.
     * @param keyId the ID of the API key to disable
     */
    disable(keyId: string): Promise<void>;
}

/**
 * Authentication provider where users identify using email and password.
 * @see https://www.mongodb.com/docs/atlas/app-services/authentication/email-password/
 */
declare class EmailPasswordAuth {
    /**
     * Registers a new email identity with the email/password provider,
     * and sends a confirmation email to the provided address.
     * @param details - The new user's email and password details.
     * @param details.email - The email address of the user to register.
     * @param details.password - The password that the user created for the new username/password identity.
     * @since v10.10.0
     */
    registerUser(details: {
        email: string;
        password: string;
    }): Promise<void>;
    /**
     * Confirms an email identity with the email/password provider.
     * @param details - The received token and ID details
     * @param details.token - The confirmation token that was emailed to the user.
     * @param details.tokenId - The confirmation token id that was emailed to the user.
     * @since v10.10.0
     */
    confirmUser(details: {
        token: string;
        tokenId: string;
    }): Promise<void>;
    /**
     * Re-sends a confirmation email to a user that has registered but
     * not yet confirmed their email address.
     * @param details - The associated email details.
     * @param details.email - The email address of the user to re-send a confirmation for.
     * @since v10.10.0
     */
    resendConfirmationEmail(details: {
        email: string;
    }): Promise<void>;
    /**
     * Re-run the custom confirmation function for user that has registered but
     * not yet confirmed their email address.
     * @param details - The associated email details.
     * @param details.email - The email address of the user to re-run the confirmation for.
     * @since v10.10.0
     */
    retryCustomConfirmation(details: {
        email: string;
    }): Promise<void>;
    /**
     * Resets the password of an email identity using the password reset token emailed to a user.
     * @param details - The token and password details for the reset.
     * @param details.password - The desired new password.
     * @param details.token - The password reset token that was emailed to the user.
     * @param details.tokenId - The password reset token id that was emailed to the user.
     * @since v10.10.0
     */
    resetPassword(details: {
        password: string;
        token: string;
        tokenId: string;
    }): Promise<void>;
    /**
     * Sends an email to the user for resetting the password.
     * @param details - The email details to send the reset to.
     * @param details.email - The email address of the user to re-send a confirmation for.
     * @since v10.10.0
     */
    sendResetPasswordEmail(details: {
        email: string;
    }): Promise<void>;
    /**
     * Call the custom function to reset the password.
     * @param details - The new user's email and password details.
     * @param details.email - The email address of the user to register.
     * @param details.password - The password that the user created for the new username/password identity.
     * @param args One or more arguments to pass to the function.
     * @since v10.10.0
     */
    callResetPasswordFunction(details: {
        email: string;
        password: string;
    }, ...args: unknown[]): Promise<void>;
}

/**
 * Authentication provider where users identify using an API-key.
 */
declare class PushClient {
    /**
     * Register this device with the user.
     * @param token - A Firebase Cloud Messaging (FCM) token, retrieved via the firebase SDK.
     * @returns A promise that resolves once the device has been registered.
     */
    register(token: string): Promise<void>;
    /**
     * Deregister this device with the user, to disable sending messages to this device.
     * @returns A promise that resolves once the device has been deregistered.
     */
    deregister(): Promise<void>;
}

/**
 * A remote MongoDB service enabling access to an Atlas cluster.
 */
type MongoDB = {
    /**
     * The name of the MongoDB service.
     */
    serviceName: string;
    /**
     * @returns The remote MongoDB database.
     */
    db(databaseName: string): MongoDBDatabase;
};
/**
 * A remote MongoDB database enabling access to collections of objects.
 */
type MongoDBDatabase = {
    /**
     * The name of the MongoDB database.
     */
    name: string;
    /**
     * @returns The remote MongoDB collection.
     */
    collection<T extends Document>(collectionName: string): MongoDBCollection<T>;
};
/**
 * Options passed when finding a single document
 */
type FindOneOptions = {
    /**
     * Limits the fields to return for all matching documents.
     * See [Tutorial: Project Fields to Return from Query](https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/).
     */
    readonly projection?: Record<string, unknown>;
    /**
     * The order in which to return matching documents.
     */
    readonly sort?: Record<string, unknown>;
};
/**
 * Options passed when finding a multiple documents
 */
type FindOptions = FindOneOptions & {
    /**
     * The maximum number of documents to return.
     */
    readonly limit?: number;
};
/**
 * Options passed when finding and modifying a single document
 */
type FindOneAndModifyOptions = FindOneOptions & {
    /**
     * Optional. Default: false.
     * A boolean that, if true, indicates that MongoDB should insert a new document that matches the
     * query filter when the query does not match any existing documents in the collection.
     */
    readonly upsert?: boolean;
    /**
     * Optional. Default: false.
     * A boolean that, if true, indicates that the action should return
     * the document in its updated form instead of its original, pre-update form.
     */
    readonly returnNewDocument?: boolean;
};
/**
 * Options passed when counting documents
 */
type CountOptions = {
    /**
     * The maximum number of documents to count.
     */
    readonly limit?: number;
};
/**
 * Options passed when updating documents
 */
type UpdateOptions = {
    /**
     * When true, creates a new document if no document matches the query.
     */
    readonly upsert?: boolean;
    /**
     * Array Filters
     */
    readonly arrayFilters?: Filter[];
};
/**
 * A document from a MongoDB collection
 */
type Document<IdType = unknown> = {
    /**
     * The ID of the document.
     */
    _id: IdType;
};
/**
 * A new document with an optional _id defined.
 */
type NewDocument<T extends Document> = Omit<T, "_id"> & Partial<Pick<T, "_id">>;
/**
 * Result of inserting one document
 */
type InsertOneResult<IdType> = {
    /**
     * The ID of the inserted document
     */
    readonly insertedId: IdType;
};
/**
 * Result of inserting many documents
 */
type InsertManyResult<IdType> = {
    /**
     * The IDs of the inserted documents
     */
    readonly insertedIds: IdType[];
};
/**
 * Result of deleting documents
 */
type DeleteResult = {
    /**
     * The number of documents that were deleted.
     */
    readonly deletedCount: number;
};
/**
 * Result of updating documents
 */
type UpdateResult<IdType> = {
    /**
     * The number of documents that matched the filter.
     */
    readonly matchedCount: number;
    /**
     * The number of documents matched by the query.
     */
    readonly modifiedCount: number;
    /**
     * The identifier of the inserted document if an upsert took place.
     *
     * See [[RemoteUpdateOptions.upsert]].
     */
    readonly upsertedId?: IdType;
};
/**
 * A filter applied to limit the documents being queried for.
 */
type Filter = Record<string, unknown>;
/**
 * An object specifying the update operations to perform when updating a document.
 */
type Update = Record<string, unknown>;
/**
 * A stage of an aggregation pipeline.
 */
type AggregatePipelineStage = Record<string, unknown>;
/**
 * An operation performed on a document.
 */
type OperationType = 
/**
 * A document got inserted into the collection.
 */
"insert"
/**
 * A document got deleted from the collection.
 */
 | "delete"
/**
 * A document got replaced in the collection.
 */
 | "replace"
/**
 * A document got updated in the collection.
 */
 | "update"
/**
 * A collection got dropped from a database.
 */
 | "drop"
/**
 * A collection got renamed.
 */
 | "rename"
/**
 * A database got dropped.
 */
 | "dropDatabase"
/**
 * Invalidate events close the change stream cursor.
 */
 | "invalidate";
/**
 * The namespace of a document.
 */
type DocumentNamespace = {
    /** The name of the database. */
    db: string;
    /** The name of the collection. */
    coll: string;
};
/**
 * A detailed description of an update performed on a document.
 */
type UpdateDescription = {
    /** Names of fields that got updated. */
    updatedFields: Record<string, unknown>;
    /** Names of fields that got removed. */
    removedFields: string[];
};
/**
 * Acts as the `resumeToken` for the `resumeAfter` parameter when resuming a change stream.
 */
type ChangeEventId = unknown;
/**
 * A document that contains the _id of the document created or modified by the insert, replace,
 * delete, update operations (i.e. CRUD operations). For sharded collections, also displays the full
 * shard key for the document. The _id field is not repeated if it is already a part of the shard key.
 */
type DocumentKey<IdType> = {
    /** The ID of the document. */
    _id: IdType;
} & Record<string, unknown>;
/**
 * A base change event containing the properties which apply across operation types.
 */
type BaseChangeEvent<T extends OperationType> = {
    /** The ID of the change event. */
    _id: ChangeEventId;
    /** The type of operation which was performed on the document. */
    operationType: T;
    /** The timestamp from the oplog entry associated with the event. */
    clusterTime: Timestamp;
    /**
     * The transaction number.
     * Only present if the operation is part of a multi-document transaction.
     */
    txnNumber?: Long;
    /**
     * The identifier for the session associated with the transaction.
     * Only present if the operation is part of a multi-document transaction.
     */
    lsid?: Record<string, unknown>;
};
/**
 * A document got inserted into the collection.
 */
type InsertEvent<T extends Document> = {
    /** The namespace (database and collection) of the document got inserted into. */
    ns: DocumentNamespace;
    /** A document that contains the _id of the inserted document. */
    documentKey: DocumentKey<T["_id"]>;
    /** The new document created by the operation */
    fullDocument: T;
} & BaseChangeEvent<"insert">;
/**
 * A document got updated in the collection.
 */
type UpdateEvent<T extends Document> = {
    /** The namespace (database and collection) of the updated document. */
    ns: DocumentNamespace;
    /** A document that contains the _id of the updated document. */
    documentKey: DocumentKey<T["_id"]>;
    /** A document describing the fields that were updated or removed. */
    updateDescription: UpdateDescription;
    /**
     * For change streams opened with the `fullDocument: updateLookup` option, this will represent
     * the most current majority-committed version of the document modified by the update operation.
     */
    fullDocument?: T;
} & BaseChangeEvent<"update">;
/**
 * A document got replaced in the collection.
 */
type ReplaceEvent<T extends Document> = {
    /** The namespace (database and collection) of the document got replaced within. */
    ns: DocumentNamespace;
    /** A document that contains the _id of the replaced document. */
    documentKey: DocumentKey<T["_id"]>;
    /** The document after the insert of the replacement document. */
    fullDocument: T;
} & BaseChangeEvent<"replace">;
/**
 * A document got deleted from the collection.
 */
type DeleteEvent<T extends Document> = {
    /** The namespace (database and collection) which the document got deleted from. */
    ns: DocumentNamespace;
    /** A document that contains the _id of the deleted document. */
    documentKey: DocumentKey<T["_id"]>;
} & BaseChangeEvent<"delete">;
/**
 * Occurs when a collection is dropped from a database.
 */
type DropEvent = {
    /** The namespace (database and collection) of the collection that got dropped. */
    ns: DocumentNamespace;
} & BaseChangeEvent<"drop">;
/**
 * Occurs when a collection is renamed.
 */
type RenameEvent = {
    /** The original namespace (database and collection) that got renamed. */
    ns: DocumentNamespace;
    /** The namespace (database and collection) going forward. */
    to: DocumentNamespace;
} & BaseChangeEvent<"rename">;
/**
 * Occurs when a database is dropped.
 */
type DropDatabaseEvent = {
    /** The namespace (specifying only the database name) of the database that got dropped. */
    ns: Omit<DocumentNamespace, "coll">;
} & BaseChangeEvent<"dropDatabase">;
/**
 * Invalidate events close the change stream cursor.
 */
type InvalidateEvent = BaseChangeEvent<"invalidate">;
/**
 * A change event communicated via a MongoDB change stream.
 * @see https://docs.mongodb.com/manual/reference/change-events/
 */
type ChangeEvent<T extends Document> = InsertEvent<T> | UpdateEvent<T> | ReplaceEvent<T> | DeleteEvent<T> | DropEvent | RenameEvent | DropDatabaseEvent | InvalidateEvent;
/**
 * A remote collection of documents in a MongoDB database.
 */
declare class MongoDBCollection<T extends Document> {
    readonly serviceName: string;
    readonly databaseName: string;
    private readonly collectionName;
    private functions;
    /**
     * The name of the collection.
     */
    get name(): string;
    /**
     * Finds the documents which match the provided query.
     * @param filter - An optional filter applied to narrow down the results.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to the found documents.
     */
    find(filter?: Filter, options?: FindOptions): Promise<T[]>;
    /**
     * Finds a document which matches the provided filter.
     * @param filter - A filter applied to narrow down the result.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to the found document.
     */
    findOne(filter?: Filter, options?: FindOneOptions): Promise<T | null>;
    /**
     * Finds a document which matches the provided query and performs the desired update to individual fields.
     * @param filter - A filter applied to narrow down the result.
     * @param update - The new values for the document.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to the found document before applying the update.
     */
    findOneAndUpdate(filter: Filter, update: Update, options?: FindOneAndModifyOptions): Promise<T | null>;
    /**
     * Finds a document which matches the provided filter and replaces it with a new document.
     * @param filter - A filter applied to narrow down the result.
     * @param replacement - The new replacing document.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to the found document found before replacement.
     */
    findOneAndReplace(filter: Filter, replacement: unknown, options?: FindOneAndModifyOptions): Promise<T | null>;
    /**
     * Finds a document which matches the provided filter and deletes it
     * @param filter - A filter applied to narrow down the result.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to the found document before deletion.
     */
    findOneAndDelete(filter?: Filter, options?: FindOneOptions): Promise<T | null>;
    /**
     * Runs an aggregation framework pipeline against this collection.
     * @param pipeline - An array of aggregation pipeline stages.
     * @returns A promise that resolves to the aggregation result.
     */
    aggregate(pipeline: AggregatePipelineStage[]): Promise<unknown>;
    /**
     * Counts the number of documents in this collection matching the provided filter.
     *
     * Note: When calling this without a filter, you may receive inaccurate document counts
     * as it returns results based on the collection's metadata, which may result in an
     * approximate count. In particular:
     *  - On a sharded cluster, the resulting count will not correctly filter out
     *    {@link https://www.mongodb.com/docs/manual/reference/glossary/#std-term-orphaned-document orphaned documents}.
     *  - After an unclean shutdown or file copy based initial sync, the count may be incorrect.
     * @param filter - An optional filter applied to narrow down the results.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to the number of documents matching the filter.
     */
    count(filter?: Filter, options?: CountOptions): Promise<number>;
    /**
     * Inserts a single document into the collection.
     * Note: If the document is missing an _id, one will be generated for it by the server.
     * @param document - The document to insert.
     * @returns A promise that resolves an object containing the inserted object ID (`insertedId`).
     */
    insertOne(document: NewDocument<T>): Promise<InsertOneResult<T["_id"]>>;
    /**
     * Inserts an array of documents into the collection.
     * If any values are missing identifiers, they will be generated by the server.
     * @param documents - The array of documents to insert.
     * @returns A promise that resolves to an object containing an array of IDs inserted (`insertedIds`).
     */
    insertMany(documents: NewDocument<T>[]): Promise<InsertManyResult<T["_id"]>>;
    /**
     * Deletes a single matching document from the collection.
     * @param filter - A filter applied to narrow down the result.
     * @returns A promise that resolves to an object containing the number of deleted documents (`deletedCount`).
     */
    deleteOne(filter?: Filter): Promise<DeleteResult>;
    /**
     * Deletes multiple documents.
     * @param filter - A filter applied to narrow down the result. If omitted, it defaults
     *  to `{}` which deletes all documents in the collection.
     * @returns A promise that resolves to an object containing the number of deleted documents (`deletedCount`).
     */
    deleteMany(filter?: Filter): Promise<DeleteResult>;
    /**
     * Updates a single document matching the provided filter in this collection.
     * @param filter - A filter applied to narrow down the result.
     * @param update - The new values for the document.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to an object containing:
     * ```
     * {
     *  matchedCount: number;
     *  modifiedCount: number;
     *  upsertedId: IdType | undefined;
     * }
     * ```
     */
    updateOne(filter: Filter, update: Update, options?: UpdateOptions): Promise<UpdateResult<T["_id"]>>;
    /**
     * Updates multiple documents matching the provided filter in this collection.
     * @param filter - A filter applied to narrow down the result.
     * @param update - The new values for the documents.
     * @param options - Additional options to apply.
     * @returns A promise that resolves to an object containing:
     * ```
     * {
     *  matchedCount: number;
     *  modifiedCount: number;
     *  upsertedId: IdType | undefined;
     * }
     * ```
     */
    updateMany(filter: Filter, update: Update, options?: UpdateOptions): Promise<UpdateResult<T["_id"]>>;
    /**
     * Creates an asynchronous change stream to monitor this collection for changes.
     *
     * By default, yields all change events for this collection. You may specify at most one of
     * the `filter` or `ids` options.
     *
     * Important Note: To use this on React Native, you must install:
     *
     * 1. Polyfills for `fetch` and `ReadableStream`: https://www.npmjs.com/package/react-native-polyfill-globals
     * 2. Babel plugin enabling async generator syntax: https://npmjs.com/package/@babel/plugin-proposal-async-generator-functions
     * @param options.filter - A filter for which change events you want to watch.
     * @param options.ids - A list of document IDs for which change events you want to watch.
     * @returns An async generator of change events.
     * @see https://docs.mongodb.com/manual/reference/change-events/
     */
    watch(): AsyncGenerator<ChangeEvent<T>>;
    watch(options: {
        ids: T["_id"][];
        filter?: never;
    }): AsyncGenerator<ChangeEvent<T>>;
    watch(options: {
        ids?: never;
        filter: Filter;
    }): AsyncGenerator<ChangeEvent<T>>;
}

/**
 * A function which executes on the Atlas App Services server.
 */
type AppServicesFunction<R, A extends unknown[]> = (...args: A) => Promise<R>;
/**
 * The default functions factory, providing types for easily calling functions.
 */
type DefaultFunctionsFactory = {
    /**
     * All the functions are accessible as members on this instance.
     */
    [name: string]: AppServicesFunction<unknown, unknown[]>;
};

type DefaultUserProfileData = {
    /**
     * The commonly displayed name of the user.
     */
    name?: string;
    /**
     * The users email address.
     */
    email?: string;
    /**
     * A URL referencing a picture associated with the user.
     */
    pictureUrl?: string;
    /**
     * The users first name.
     */
    firstName?: string;
    /**
     * The users last name.
     */
    lastName?: string;
    /**
     * The users gender.
     */
    gender?: string;
    /**
     * The users birthday.
     */
    birthday?: string;
    /**
     * The minimal age of the user.
     */
    minAge?: string;
    /**
     * The maximal age of the user.
     */
    maxAge?: string;
} & {
    /**
     * Authentication providers might store additional data here.
     */
    [key: string]: unknown;
};

/**
 * Enum representing the state of a {@link SubscriptionSet}.
 */
declare enum SubscriptionSetState {
    /**
     * The subscription update has been persisted locally, but the server hasn't
     * yet returned all the data that matched the updated subscription queries.
     */
    Pending = "pending",
    /**
     * The server has acknowledged the subscription and sent all the data that
     * matched the subscription queries at the time the SubscriptionSet was
     * updated. The server is now in steady-state synchronization mode where it
     * will stream updates as they come.
     */
    Complete = "complete",
    /**
     * The server has returned an error and synchronization is paused for this
     * Realm. To view the actual error, use `Subscriptions.error`.
     *
     * You can still use {@link SubscriptionSet.update} to update the subscriptions,
     * and if the new update doesn't trigger an error, synchronization will be restarted.
     */
    Error = "error",
    /**
     * The SubscriptionSet has been superseded by an updated one. This typically means
     * that someone has called {@link SubscriptionSet.update} on a different instance
     * of the {@link SubscriptionSet}. You should not use a superseded SubscriptionSet,
     * and instead obtain a new instance from {@link Realm.subscriptions}.
     */
    Superseded = "superseded"
}
/**
 * @deprecated Will be removed in v13.0.0. Please use {@link SubscriptionSetState}.
 */
declare enum SubscriptionsState {
    /**
     * The subscription update has been persisted locally, but the server hasn't
     * yet returned all the data that matched the updated subscription queries.
     */
    Pending = "pending",
    /**
     * The server has acknowledged the subscription and sent all the data that
     * matched the subscription queries at the time the SubscriptionSet was
     * updated. The server is now in steady-state synchronization mode where it
     * will stream updates as they come.
     */
    Complete = "complete",
    /**
     * The server has returned an error and synchronization is paused for this
     * Realm. To view the actual error, use `Subscriptions.error`.
     *
     * You can still use {@link SubscriptionSet.update} to update the subscriptions,
     * and if the new update doesn't trigger an error, synchronization will be restarted.
     */
    Error = "error",
    /**
     * The SubscriptionSet has been superseded by an updated one. This typically means
     * that someone has called {@link SubscriptionSet.update} on a different instance
     * of the {@link SubscriptionSet}. You should not use a superseded SubscriptionSet,
     * and instead obtain a new instance from {@link Realm.subscriptions}.
     */
    Superseded = "superseded"
}
/**
 * Class representing the common functionality for the {@link SubscriptionSet} and
 * {@link MutableSubscriptionSet} classes.
 *
 * SubscriptionSets can only be modified inside a {@link SubscriptionSet.update} callback.
 *
 * The SubscriptionSet is an iterable; thus, the contained {@link Subscription}s can be
 * accessed in `for-of` loops or spread into an `Array` for access to the ECMAScript
 * Array API, e.g. `[...realm.subscriptions][0]`.
 */
declare abstract class BaseSubscriptionSet {
    /**
     * Whether there are no subscriptions in the set.
     * @returns `true` if there are no subscriptions in the set, `false` otherwise.
     */
    get isEmpty(): boolean;
    /**
     * The version of the SubscriptionSet. This is incremented every time a
     * {@link SubscriptionSet.update} is applied.
     * @returns The version of the {@link SubscriptionSet}.
     */
    get version(): number;
    /**
     * @returns The state of the SubscriptionSet.
     */
    get state(): SubscriptionSetState;
    /**
     * If `state` is {@link SubscriptionSetState.Error}, this will be a string representing
     * why the {@link SubscriptionSet} is in an error state. It will be `null` if there is no error.
     * @returns A string representing the error, or `null` if there is no error.
     */
    get error(): string | null;
    /**
     * @returns The number of subscriptions in the set.
     */
    get length(): number;
    /**
     * Find a subscription by name.
     * @param name - The name to search for.
     * @returns The named subscription, or `null` if the subscription is not found.
     */
    findByName(name: string): Subscription | null;
    /**
     * Find a subscription by query. Will match both named and unnamed subscriptions.
     * @param query - The query to search for, represented as a {@link Results} instance,
     *  e.g. `Realm.objects("Cat").filtered("age > 10")`.
     * @returns The subscription with the specified query, or `null` if the subscription is not found.
     */
    findByQuery<Subscription>(query: Results<Subscription & RealmObject<Subscription>>): Subscription | null;
    /**
     * Makes the subscription set iterable.
     * @returns Iterable of each value in the set.
     * @example
     * for (const subscription of subscriptions) {
     *   // ...
     * }
     */
    [Symbol.iterator](): IterableIterator<Subscription>;
}

/**
 * Behavior when waiting for subscribed objects to be synchronized/downloaded.
 */
declare enum WaitForSync {
    /**
     * Waits until the objects have been downloaded from the server
     * the first time the subscription is created. If the subscription
     * already exists, the `Results` is returned immediately.
     */
    FirstTime = "first-time",
    /**
     * Always waits until the objects have been downloaded from the server.
     */
    Always = "always",
    /**
     * Never waits for the download to complete, but keeps downloading the
     * objects in the background.
     */
    Never = "never"
}
/**
 * Options for {@link MutableSubscriptionSet.add}.
 */
type SubscriptionOptions = {
    /**
     * Sets the name of the subscription being added. This allows you to later refer
     * to the subscription by name, e.g. when calling {@link MutableSubscriptionSet.removeByName}.
     */
    name?: string;
    /**
     * By default, adding a subscription with the same name as an existing one
     * but a different query will update the existing subscription with the new
     * query. If `throwOnUpdate` is set to true, adding a subscription with the
     * same name but a different query will instead throw an exception.
     * Adding a subscription with the same name and query is always a no-op.
     */
    throwOnUpdate?: boolean;
    /**
     * Specifies how to wait or not wait for subscribed objects to be downloaded.
     * @default WaitForSync.FirstTime
     */
    behavior?: WaitForSync;
    /**
     * The maximum time (in milliseconds) to wait for objects to be downloaded.
     * If the time exceeds this limit, the `Results` is returned and the download
     * continues in the background.
     */
    timeout?: number;
};
/**
 * The mutable version of a given SubscriptionSet. The {@link MutableSubscriptionSet}
 * instance can only be used from inside the {@link SubscriptionSet.update} callback.
 */
declare class MutableSubscriptionSet extends BaseSubscriptionSet {
    /**
     * Add a query to the set of active subscriptions. The query will be joined via
     * an `OR` operator with any existing queries for the same type.
     *
     * A query is represented by a {@link Results} instance returned from {@link Realm.objects},
     * for example: `mutableSubs.add(realm.objects("Cat").filtered("age > 10"));`.
     * @param query - A {@link Results} instance representing the query to subscribe to.
     * @param options - An optional {@link SubscriptionOptions} object containing options to
     * use when adding this subscription (e.g. to give the subscription a name).
     * @returns A `Subscription` instance for the new subscription.
     */
    add(query: AnyResults, options?: SubscriptionOptions): Subscription;
    /**
     * Remove a subscription with the given query from the SubscriptionSet.
     * @param query - A {@link Results} instance representing the query to remove a subscription to.
     * @returns `true` if the subscription was removed, `false` if it was not found.
     */
    remove(query: AnyResults): boolean;
    /**
     * Remove a subscription with the given name from the SubscriptionSet.
     * @param name - The name of the subscription to remove.
     * @returns `true` if the subscription was removed, `false` if it was not found.
     */
    removeByName(name: string): boolean;
    /**
     * Remove the specified subscription from the SubscriptionSet.
     * @param subscription - The {@link Subscription} instance to remove.
     * @returns `true` if the subscription was removed, `false` if it was not found.
     */
    removeSubscription(subscription: Subscription): boolean;
    /**
     * Remove all subscriptions for the specified object type from the SubscriptionSet.
     * @param objectType - The string name of the object type to remove all subscriptions for.
     * @returns The number of subscriptions removed.
     */
    removeByObjectType(objectType: string): number;
    /**
     * Remove all subscriptions from the SubscriptionSet.
     * @returns The number of subscriptions removed.
     */
    removeAll(): number;
    /**
     * Remove all unnamed/anonymous subscriptions from the SubscriptionSet.
     * @returns The number of subscriptions removed.
     */
    removeUnnamed(): number;
}

/**
 * Represents the set of all active flexible sync subscriptions for a Realm instance.
 *
 * The server will continuously evaluate the queries that the instance is subscribed to
 * and will send data that matches them, as well as remove data that no longer does.
 *
 * The set of subscriptions can only be modified inside a {@link SubscriptionSet.update} callback,
 * by calling methods on the corresponding {@link MutableSubscriptionSet} instance.
 */
declare class SubscriptionSet extends BaseSubscriptionSet {
    /**
     * Wait for the server to acknowledge this set of subscriptions and return the
     * matching objects.
     *
     * If `state` is {@link SubscriptionSetState.Complete}, the promise will be resolved immediately.
     *
     * If `state` is {@link SubscriptionSetState.Error}, the promise will be rejected immediately.
     * @returns A promise which is resolved when synchronization is complete, or is
     *  rejected if there is an error during synchronization.
     */
    waitForSynchronization(): Promise<void>;
    /**
     * Call this to make changes to this SubscriptionSet from inside the callback,
     * such as adding or removing subscriptions from the set.
     *
     * The MutableSubscriptionSet argument can only be used from the callback and must
     * not be used after it returns.
     *
     * All changes done by the callback will be batched and sent to the server. You can either
     * `await` the call to `update`, or call {@link SubscriptionSet.waitForSynchronization}
     * to wait for the new data to be available.
     * @param callback A callback function which receives a {@link MutableSubscriptionSet}
     *  instance as the first argument, which can be used to add or remove subscriptions
     *  from the set, and the {@link Realm} associated with the SubscriptionSet as the
     *  second argument (mainly useful when working with `initialSubscriptions` in
     *  {@link FlexibleSyncConfiguration}).
     * @returns A promise which resolves when the SubscriptionSet is synchronized, or is rejected
     *  if there was an error during synchronization (see {@link SubscriptionSet.waitForSynchronization})
     * @example
     * await realm.subscriptions.update(mutableSubscriptions => {
     *   mutableSubscriptions.add(realm.objects("Cat").filtered("age > 10"));
     *   mutableSubscriptions.add(realm.objects("Dog").filtered("age > 20"), { name: "oldDogs" });
     *   mutableSubscriptions.removeByName("youngDogs");
     * });
     * // `realm` will now return the expected results based on the updated subscriptions
     */
    update(callback: (mutableSubscriptions: MutableSubscriptionSet, realm: Realm) => void): Promise<void>;
}

/**
 * Class representing a single query subscription in a set of flexible sync
 * {@link SubscriptionSet}. This class contains readonly information about the
 * subscription – any changes to the set of subscriptions must be carried out
 * in a {@link SubscriptionSet.update} callback.
 */
declare class Subscription {
    /**
     * The ObjectId of the subscription.
     * @returns The ObjectId of the subscription.
     */
    get id(): BSON.ObjectId;
    /**
     * The date when this subscription was created.
     * @returns The date when this subscription was created.
     */
    get createdAt(): Date;
    /**
     * The date when this subscription was last updated.
     * @returns The date when this subscription was last updated.
     */
    get updatedAt(): Date;
    /**
     * The name given to this subscription when it was created.
     * If no name was set, this will be `null`.
     * @returns The name of the subscription or `null` if unnamed.
     */
    get name(): string | null;
    /**
     * The type of objects the subscription refers to.
     * @returns The type of objects the subscription refers to.
     */
    get objectType(): string;
    /**
     * The string representation of the query the subscription was created with.
     * If no filter or sort was specified, this will be `"TRUEPREDICATE"`.
     * @returns The string representation of the query the subscription was created with.
     */
    get queryString(): string;
}

declare class Sync {
    static Session: typeof SyncSession;
    static ConnectionState: typeof ConnectionState;
    static Subscription: typeof Subscription;
    static SubscriptionSet: typeof SubscriptionSet;
    static MutableSubscriptionSet: typeof MutableSubscriptionSet;
    static SubscriptionSetState: typeof SubscriptionSetState;
    /** @deprecated Please use {@link SubscriptionSetState} as a named import */
    static SubscriptionsState: typeof SubscriptionSetState;
    static NumericLogLevel: typeof NumericLogLevel;
    /** @deprecated Will be removed in v13.0.0. Please use {@link Realm.setLogLevel}. */
    static setLogLevel(app: App, level: LogLevel): void;
    /** @deprecated Will be removed in v13.0.0. Please use {@link Realm.setLogger}. */
    static setLogger(app: App, logger: Logger): void;
    /**
     * Get all sync sessions for a particular user.
     * @since 10.0.0
     */
    static getAllSyncSessions(user: User): SyncSession[];
    /**
     * Get the session associated with a particular user and partition value.
     * @since 10.0.0
     */
    static getSyncSession(user: User, partitionValue: PartitionValue): SyncSession | null;
    /**
     * Set the application part of the User-Agent string that will be sent to the Realm Object Server when a session
     * is created.
     *
     * This method can only be called up to the point where the first Realm is opened. After that, the User-Agent
     * can no longer be changed.
     */
    static setUserAgent(app: App, userAgent: string): void;
    /**
     * Enable multiplexing multiple sync sessions over a single connection for a Realm app.
     * When having a lot of synchronized realms open the system might run out of file
     * descriptors because of all the open sockets to the server. Session multiplexing
     * is designed to alleviate that, but it might not work with a server configured with
     * fail-over. Only use if you're seeing errors about reaching the file descriptor limit
     * and you know you are using many sync sessions.
     */
    static enableSessionMultiplexing(app: App): void;
    /**
     * Initiate a client reset. The Realm must be closed prior to the reset.
     *
     * A synced Realm may need to be reset if the communications with the Atlas Device Sync Server
     * indicate an unrecoverable error that prevents continuing with normal synchronization. The
     * most common reason for this is if a client has been disconnected for too long.
     *
     * The local copy of the Realm is moved into a recovery directory
     * for safekeeping.
     *
     * Local writes that were not successfully synchronized to Atlas
     * will be present in the local recovery copy of the Realm file. The re-downloaded Realm will
     * initially contain only the data present at the time the Realm was synchronized up on the server.
     * @deprecated
     * @throws An {@link Error} if reset is not possible.
     * @example
     * {
     *   // Once you have opened your Realm, you will have to keep a reference to it.
     *   // In the error handler, this reference is called `realm`
     *   const config = {
     *     // schema, etc.
     *     sync: {
     *       user,
     *       partitionValue,
     *       error: (session, error) => {
     *         if (error.name === 'ClientReset') {
     *           let path = realm.path; // realm.path will no be accessible after realm.close()
     *           realm.close();
     *           Realm.App.Sync.initiateClientReset(app, path);
     *           // - open Realm at `error.config.path` (oldRealm)
     *           // - open Realm with `config` (newRealm)
     *           // - copy required objects from oldRealm to newRealm
     *           // - close both Realms
     *         }
     *       }
     *     }
     *   };
     * }
     */
    static initiateClientReset(app: App, path: string): void;
    /**
     * @deprecated
     */
    static reconnect(app: App): void;
    /**
     * The default behavior settings if you want to open a synchronized Realm immediately and start working on it.
     * If this is the first time you open the Realm, it will be empty while the server data is being downloaded in the background.
     * @deprecated since v12
     */
    static openLocalRealmBehavior: Readonly<OpenRealmBehaviorConfiguration>;
    /**
     * The default behavior settings if you want to wait for downloading a synchronized Realm to complete before opening it.
     * @deprecated since v12
     */
    static downloadBeforeOpenBehavior: Readonly<OpenRealmBehaviorConfiguration>;
}

/**
 * Persistence modes for metadata.
 */
declare enum MetadataMode {
    /**
     * Persist {@link User} objects, but do not encrypt them.
     */
    NoEncryption = "noEncryption",
    /**
     * Persist {@link User} objects in an encrypted store.
     */
    Encryption = "encryption",
    /**
     * Do not persist {@link User} objects.
     */
    NoMetadata = "noMetadata"
}
/**
 * Configuration for how to handle the `App`'s metadata.
 */
type Metadata = {
    /**
     * The different modes for storing meta data in Realm Apps.
     * @since 12.2.0
     */
    mode: MetadataMode;
    /**
     * The 512-bit (64-byte) encryption key used to encrypt and decrypt meta data in Realm Apps.
     * This will not change the encryption key for individual Realms. This should still be set in
     * {@link Configuration.encryptionKey} when opening the Realm.
     * @since 12.2.0
     */
    encryptionKey?: ArrayBuffer;
};
/**
 * This describes the options used to create a Realm App instance.
 */
type AppConfiguration = {
    /**
     * The Realm App ID
     * @since v10.0.0
     */
    id: string;
    /**
     * An optional URL to use as a prefix when sending requests to the Atlas App Services server.
     * @since v10.0.0
     */
    baseUrl?: string;
    /**
     * This describes the local app, sent to the server when a user authenticates.
     * Specifying this will enable the server to respond differently to specific versions of specific apps.
     * @since v10.0.0
     */
    app?: LocalAppConfiguration;
    /**
     * The timeout for requests (in milliseconds)
     * @since v10.0.0
     */
    timeout?: number;
    /**
     * Use the same underlying connection towards the server across multiple sync sessions.
     * This uses less resources on the server and provides a small increase in speed when opening subsequent synced Realms.
     * @default true
     */
    multiplexSessions?: boolean;
    /**
     * Specify where synced Realms and metadata is stored. If not specified, the current work directory is used.
     * @since v11.7.0
     */
    baseFilePath?: string;
    /**
     * Specify how meta data should be stored.
     * @since 12.2.0
     */
    metadata?: Metadata;
};
/**
 * This describes the local app, sent to the server when a user authenticates.
 */
type LocalAppConfiguration = {
    /**
     * The name / ID of the local app.
     * Note: This should be the name or a bundle ID of your app, not the Atlas App Services application.
     */
    name?: string;
    /**
     * The version of the local app.
     */
    version?: string;
};
type AppChangeCallback = () => void;
/**
 * The class represents an Atlas App Services Application.
 *
 * ```js
 * const app = new App({ id: "my-app-qwert" });
 * ```
 */
declare class App<FunctionsFactoryType extends DefaultFunctionsFactory = DefaultFunctionsFactory, CustomDataType extends DefaultObject = DefaultObject> {
    private static appById;
    private static appByUserId;
    /**
     * Get or create a singleton Realm App from an ID.
     * Calling this function multiple times with the same ID will return the same instance.
     * @deprecated Use {@link App.get}.
     * @param id - The Realm App ID visible from the Atlas App Services UI or a configuration.
     * @returns The Realm App instance.
     */
    static getApp(id: string): App;
    /**
     * Get or create a singleton Realm App from an ID.
     * Calling this function multiple times with the same ID will return the same instance.
     * @param id - The Realm App ID visible from the Atlas App Services UI or a configuration.
     * @returns The Realm App instance.
     */
    static get(id: string): App;
    static Sync: typeof Sync;
    /**
     * All credentials available for authentication.
     * @see https://www.mongodb.com/docs/atlas/app-services/authentication/
     */
    static Credentials: typeof Credentials;
    private listeners;
    /**
     * Constructs a new {@link App} instance, used to connect to an Atlas App Services App.
     * @param id - A string app ID.
     * @throws an {@link Error} If no {@link id} is provided.
     */
    constructor(id: string);
    /**
     * Constructs a new {@link App} instance, used to connect to an Atlas App Services App.
     * @param config - The configuration of the app.
     * @throws an {@link Error} If no {@link AppConfiguration.id | app id} is provided.
     */
    constructor(config: AppConfiguration);
    /**
     * @returns The app ID.
     */
    get id(): string;
    /**
     * Log in a user.
     * @param credentials - A credentials object describing the type of authentication provider and its parameters.
     * @returns A promise that resolves to the logged in {@link User}.
     * @throws An {@link Error} if the login failed.
     */
    logIn(credentials: Credentials): Promise<User<FunctionsFactoryType, CustomDataType>>;
    /**
     * Perform operations related to the email/password auth provider.
     * @returns An instance of the email password authentication provider.
     */
    get emailPasswordAuth(): EmailPasswordAuth;
    /**
     * The last user to log in or being switched to.
     * @returns A {@link User} object representing the currently logged in user. If no user is logged in, `null` is returned.
     */
    get currentUser(): User<FunctionsFactoryType, CustomDataType> | null;
    /**
     * All users that have logged into the device and have not been removed.
     * @returns A mapping from user ID to user.
     */
    get allUsers(): Readonly<Record<string, User<FunctionsFactoryType, CustomDataType>>>;
    /**
     * Switches the current user to the one specified in {@link user}.
     * @throws an {@link Error} if the new user is logged out or removed.
     * @param user - The user to switch to.
     */
    switchUser(user: AnyUser): void;
    /**
     * Logs out and removes a user from the client.
     * @returns A promise that resolves once the user has been logged out and removed from the app.
     */
    removeUser(user: AnyUser): Promise<void>;
    /**
     * Delete the user.
     * NOTE: This irrecoverably deletes the user from the device as well as the server!
     * @returns A promise that resolves once the user has been deleted.
     */
    deleteUser(user: AnyUser): Promise<void>;
    /**
     * Adds a listener that will be fired on various user events.
     * This includes login, logout, switching users, linking users and refreshing custom data.
     * @param callback - A callback function that will be called when the event occurs.
     */
    addListener(callback: AppChangeCallback): void;
    /**
     * Removes an event listener previously added via {@link App.addListener}.
     * @param callback - The callback to remove.
     */
    removeListener(callback: AppChangeCallback): void;
    /**
     * Removes all event listeners previously added via {@link App.addListener}.
     */
    removeAllListeners(): void;
}

type RealmEventName = "change" | "schema" | "beforenotify";
type AppType<FunctionsFactoryType extends DefaultFunctionsFactory = DefaultFunctionsFactory, CustomDataType extends DefaultObject = DefaultObject> = App<FunctionsFactoryType, CustomDataType>;
type BSONType = typeof BSON;
type ClientResetModeType = ClientResetMode;
type CollectionType<KeyType = unknown, ValueType = unknown, EntryType = [KeyType, ValueType], T = ValueType, ChangeCallbackType = unknown> = Collection<KeyType, ValueType, EntryType, T, ChangeCallbackType>;
type CompensatingWriteErrorType = CompensatingWriteError;
type ConnectionStateType = ConnectionState;
type CredentialsType = Credentials;
type DictionaryType<T> = Dictionary<T>;
type IndexDecoratorType = IndexDecorator;
type ListType<T = unknown> = List<T>;
type MapToDecoratorType = MapToDecorator;
type MetadataModeType = MetadataMode;
type MetadataType = Metadata;
type Mixed$1 = unknown;
type ObjectType$1 = string | RealmObjectConstructor;
type OpenRealmBehaviorTypeType = OpenRealmBehaviorType;
type OpenRealmTimeOutBehaviorType = OpenRealmTimeOutBehavior;
type ProgressDirectionType = ProgressDirection;
type ProgressModeType = ProgressMode;
type PropertySchemaParseErrorType = PropertySchemaParseError;
type ProviderTypeType = ProviderType;
type ProxyTypeType = ProxyType;
type ResultsType<T = unknown> = Results<T>;
type SchemaParseErrorType = SchemaParseError;
type SessionStateType = SessionState;
type SessionStopPolicyType = SessionStopPolicy;
type SetType<T = unknown> = RealmSet<T>;
type SSLConfigurationType = SSLConfiguration;
type SSLVerifyCallbackType = SSLVerifyCallback;
type SSLVerifyObjectType = SSLVerifyObject;
type SyncErrorType = SyncError;
type SyncSessionType = SyncSession;
type TypesType = typeof Types;
type UpdateModeType = UpdateMode;
type UserStateType = UserState;
type UserType<UserFunctionsType extends DefaultFunctionsFactory = DefaultFunctionsFactory, UserCustomDataType extends DefaultObject = DefaultObject, UserProfileDataType extends DefaultUserProfileData = DefaultUserProfileData> = User<UserFunctionsType, UserCustomDataType, UserProfileDataType>;
type BaseSubscriptionSetType = BaseSubscriptionSet;
type LogLevelType = LogLevel;
type NumericLogLevelType = NumericLogLevel;
type MutableSubscriptionSetType = MutableSubscriptionSet;
type PartitionValueType = PartitionValue;
type SubscriptionOptionsType = SubscriptionOptions;
type SubscriptionSetType = SubscriptionSet;
type SubscriptionSetStateType = SubscriptionSetState;
type SubscriptionType = Subscription;
type ObjectIdType = BSON.ObjectId;
type Decimal128Type = BSON.Decimal128;
type UUIDType = BSON.UUID;
type ApiKeyType = ApiKey;
type EmailPasswordAuthType = EmailPasswordAuth;
type ApiKeyAuthType = ApiKeyAuth;
type AggregatePipelineStageType = AggregatePipelineStage;
type BaseChangeEventType<T extends OperationType> = BaseChangeEvent<T>;
type ChangeEventType<T extends Document> = ChangeEvent<T>;
type ChangeEventIdType = ChangeEventId;
type CountOptionsType = CountOptions;
type DeleteEventType<T extends Document> = DeleteEvent<T>;
type DeleteResultType = DeleteResult;
type DocumentType<IdType> = Document<IdType>;
type DocumentKeyType<IdType> = DocumentKey<IdType>;
type DocumentNamespaceType = DocumentNamespace;
type DropDatabaseEventType = DropDatabaseEvent;
type DropEventType = DropEvent;
type FilterType = Filter;
type FindOneAndModifyOptionsType = FindOneAndModifyOptions;
type FindOneOptionsType = FindOneOptions;
type FindOptionsType = FindOptions;
type InsertEventType<T extends Document> = InsertEvent<T>;
type InsertManyResultType<IdType> = InsertManyResult<IdType>;
type InsertOneResultType<IdType> = InsertOneResult<IdType>;
type InvalidateEventType = InvalidateEvent;
type MongoDBType = MongoDB;
type MongoDBCollectionType<T extends Document> = MongoDBCollection<T>;
type MongoDBDatabaseType = MongoDBDatabase;
type NewDocumentType<T extends Document> = NewDocument<T>;
type OperationTypeType = OperationType;
type OrderedCollectionType<T = unknown> = OrderedCollection<T>;
type RenameEventType = RenameEvent;
type ReplaceEventType<T extends Document> = ReplaceEvent<T>;
type UpdateType = Update;
type UpdateDescriptionType = UpdateDescription;
type UpdateEventType<T extends Document> = UpdateEvent<T>;
type UpdateOptionsType = UpdateOptions;
type UpdateResultType<IdType> = UpdateResult<IdType>;
type WaitForSyncType = WaitForSync;
type GlobalDate = Date;
/**
 * The Realm database.
 */
declare class Realm {
    static App: typeof App;
    static Auth: {
        EmailPasswordAuth: typeof EmailPasswordAuth;
        ApiKeyAuth: typeof ApiKeyAuth;
    };
    static BSON: typeof BSON;
    static ClientResetMode: typeof ClientResetMode;
    static Collection: typeof Collection;
    static CompensatingWriteError: typeof CompensatingWriteError;
    static ConnectionState: typeof ConnectionState;
    static Credentials: typeof Credentials;
    static Dictionary: typeof Dictionary;
    static flags: {
        ALLOW_VALUES_ARRAYS: boolean;
        THROW_ON_GLOBAL_REALM: boolean;
        ALLOW_CLEAR_TEST_STATE: boolean;
    };
    static index: IndexDecorator;
    static List: typeof List;
    static mapTo: MapToDecorator;
    static MetadataMode: typeof MetadataMode;
    static NumericLogLevel: typeof NumericLogLevel;
    static Object: typeof RealmObject;
    static OpenRealmBehaviorType: typeof OpenRealmBehaviorType;
    static OpenRealmTimeOutBehavior: typeof OpenRealmTimeOutBehavior;
    static OrderedCollection: typeof OrderedCollection;
    static ProgressDirection: typeof ProgressDirection;
    static ProgressMode: typeof ProgressMode;
    static PropertySchemaParseError: typeof PropertySchemaParseError;
    static ProviderType: typeof ProviderType;
    static ProxyType: typeof ProxyType;
    static Results: typeof Results;
    static SchemaParseError: typeof SchemaParseError;
    static SessionState: typeof SessionState;
    static SessionStopPolicy: typeof SessionStopPolicy;
    static Set: typeof RealmSet;
    static SubscriptionSetState: typeof SubscriptionSetState;
    static SyncError: typeof SyncError;
    static Types: typeof Types;
    static UpdateMode: typeof UpdateMode;
    static User: typeof User;
    static UserState: typeof UserState;
    static WaitForSync: typeof WaitForSync;
    static kmToRadians: typeof kmToRadians;
    static miToRadians: typeof miToRadians;
    static defaultPath: string;
    private static internals;
    /**
     * Sets the log level.
     * @param level - The log level to be used by the logger. The default value is `info`.
     * @note The log level can be changed during the lifetime of the application.
     * @since 12.0.0
     */
    static setLogLevel(level: LogLevel): void;
    /**
     * Sets the logger callback.
     * @param loggerCallback - The callback invoked by the logger. The default callback uses `console.log`, `console.warn` and `console.error`, depending on the level of the message.
     * @note The logger callback needs to be setup before opening the first realm.
     * @since 12.0.0
     */
    static setLogger(loggerCallback: LoggerCallback): void;
    /**
     * Clears the state by closing and deleting any Realm in the default directory and logout all users.
     * NOTE: Not a part of the public API and it's primarily used from the library's tests.
     * @private
     */
    static clearTestState(): void;
    /**
     * Delete the Realm file for the given configuration.
     * @param config - The configuration for the Realm being deleted.
     * @throws An {@link Error} if anything in the provided {@link config} is invalid.
     */
    static deleteFile(config: Configuration): void;
    /**
     * Checks if the Realm already exists on disk.
     * @param arg - The configuration for the Realm or the path to it.
     * @throws An {@link Error} if anything in the provided {@link config} is invalid.
     * @returns `true` if the Realm exists on the device, `false` if not.
     */
    static exists(arg?: Configuration | string): boolean;
    /**
     * Open a Realm asynchronously with a promise. If the Realm is synced, it will be fully
     * synchronized before it is available.
     * In the case of query-based sync, {@link Configuration.scheme | config.schema} is required. An exception will be
     * thrown if {@link Configuration.scheme | config.schema} is not defined.
     * @param arg - The configuration for the Realm or the path to it.
     * @returns A promise that will be resolved with the Realm instance when it's available.
     * @throws An {@link Error} if anything in the provided {@link arg} is invalid.
     */
    static open(arg?: Configuration | string): ProgressRealmPromise;
    /**
     * Get the current schema version of the Realm at the given path.
     * @param path - The path to the file where the Realm database is stored.
     * @param encryptionKey - Required only when accessing encrypted Realms.
     * @throws An {@link Error} if passing an invalid or non-matching encryption key.
     * @returns Version of the schema as an integer, or `-1` if no Realm exists at {@link path}.
     * @since 0.11.0
     */
    static schemaVersion(path: string, encryptionKey?: ArrayBuffer | ArrayBufferView): number;
    /**
     * Creates a template object for a Realm model class where all optional fields are undefined
     * and all required fields have the default value for the given data type, either the value
     * set by the default property in the schema or the default value for the datatype if the schema
     * doesn't specify one, i.e. 0, false and "".
     * @param objectSchema - Schema describing the object that should be created.
     */
    static createTemplateObject<T extends Record<string, unknown>>(objectSchema: ObjectSchema): T;
    /**
     * Copy any Realm files  (i.e. `*.realm`) bundled with the application from the application
     * directory into the application's documents directory, so that they can be opened and used
     * by Realm. If the file already exists in the documents directory, it will not be
     * overwritten, so this can safely be called multiple times.
     *
     * This should be called before opening the Realm, in order to move the bundled Realm
     * files into a place where they can be written to.
     * @example
     * ```
     * // Given a bundled file, example.realm, this will copy example.realm (and any other .realm files)
     * // from the app bundle into the app's documents directory. If the file already exists, it will
     * // not be overwritten, so it is safe to call this every time the app starts.
     * Realm.copyBundledRealmFiles();
     *
     * const realm = await Realm.open({
     * // This will open example.realm from the documents directory, with the bundled data in.
     * path: "example.realm"
     * });
     * ```
     *
     * This is only implemented for React Native.
     * @throws an {@link Error} If an I/O error occurred or method is not implemented.
     */
    static copyBundledRealmFiles(): void;
    /**
     * TODO: Consider breaking this by ensuring a ".realm" suffix (coordinating with other SDK teams in the process)
     */
    private static normalizePath;
    /**
     * @note When the path is relative and the config contains a sync object, Core will replace any existing file extension
     * or add the ".realm" suffix.
     */
    private static determinePath;
    private static determineEncryptionKey;
    private static extractSchemaExtras;
    private static determineSchemaMode;
    private static wrapMigration;
    /**
     * The sync session if this is a synced Realm
     */
    readonly syncSession: SyncSession | null;
    private schemaExtras;
    private classes;
    private changeListeners;
    private beforeNotifyListeners;
    private schemaListeners;
    /**
     * Create a new {@link Realm} instance, at the default path.
     * @throws An {@link Error} when an incompatible synced Realm is opened.
     */
    constructor();
    /**
     * Create a new {@link Realm} instance at the provided {@link path}.
     * @param path - Required when first creating the Realm.
     * @throws An {@link Error} if the Realm cannot be opened at the provided {@link path}.
     * @throws An {@link Error} when an incompatible synced Realm is opened.
     */
    constructor(path: string);
    /**
     * Create a new {@link Realm} instance using the provided {@link config}. If a Realm does not yet exist
     * at {@link Configuration.path | config.path} (or {@link Realm.defaultPath} if not provided), then this constructor
     * will create it with the provided {@link Configuration.schema | config.schema} (which is _required_ in this case).
     * Otherwise, the instance will access the existing Realm from the file at that path.
     * In this case, {@link Configuration.schema | config.schema} is _optional_ or not have changed, unless
     * {@link Configuration.schemaVersion | config.schemaVersion} is incremented, in which case the Realm will be automatically
     * migrated to use the new schema.
     * In the case of query-based sync, {@link Configuration.schema | config.schema} is required. An exception will be
     * thrown if {@link Configuration.schema | config.schema} is not defined.
     * @param config - Required when first creating the Realm.
     * @throws An {@link Error} if anything in the provided {@link config} is invalid.
     * @throws An {@link Error} when an incompatible synced Realm is opened.
     */
    constructor(config: Configuration);
    /**
     * Indicates if this Realm contains any objects.
     * @returns `true` if empty, `false` otherwise.
     * @readonly
     * @since 1.10.0
     */
    get isEmpty(): boolean;
    /**
     * The path to the file where this Realm is stored.
     * @returns A string containing the path to the file where this Realm is stored.
     * @readonly
     * @since 0.12.0
     */
    get path(): string;
    /**
     * Indicates if this Realm was opened as read-only.
     * @returns `true` if this Realm is read-only, `false` otherwise.
     * @readonly
     * @since 0.12.0
     */
    get isReadOnly(): boolean;
    /**
     * Indicates if this Realm was opened in-memory.
     * @returns `true` if this Realm is in-memory, `false` otherwise.
     * @readonly
     */
    get isInMemory(): boolean;
    /**
     * A normalized representation of the schema provided in the {@link Configuration} when this Realm was constructed.
     * @returns An array of {@link CanonicalObjectSchema} describing all objects in this Realm.
     * @readonly
     * @since 0.12.0
     */
    get schema(): CanonicalObjectSchema[];
    /**
     * The current schema version of the Realm.
     * @returns The schema version of this Realm, as a `number`.
     * @readonly
     * @since 0.12.0
     */
    get schemaVersion(): number;
    /**
     * Indicates if this Realm is in a write transaction.
     * @returns `true` if in a write transaction, `false` otherwise.
     * @readonly
     * @since 1.10.3
     */
    get isInTransaction(): boolean;
    /**
     * Indicates if this Realm has been closed.
     * @returns `true` if closed, `false` otherwise.
     * @readonly
     * @since 2.1.0
     */
    get isClosed(): boolean;
    /**
     * The latest set of flexible sync subscriptions.
     * @returns A {@link SubscriptionSet} object.
     * @throws An {@link Error} if flexible sync is not enabled for this app.
     */
    get subscriptions(): SubscriptionSet;
    /**
     * Closes this Realm so it may be re-opened with a newer schema version.
     * All objects and collections from this Realm are no longer valid after calling this method.
     * The method is idempotent.
     */
    close(): void;
    /**
     * Create a new {@link RealmObject} of the given type and with the specified properties. For objects marked asymmetric,
     * `undefined` is returned. The API for asymmetric objects is subject to changes in the future.
     * @param type - The type of Realm object to create.
     * @param values - Property values for all required properties without a
     * default value.
     * @param mode Optional update mode. The default is `UpdateMode.Never`.
     * @returns A {@link RealmObject} or `undefined` if the object is asymmetric.
     */
    create<T = DefaultObject>(type: string, values: Partial<T> | Partial<Unmanaged<T>>, mode?: UpdateMode.Never | UpdateMode.All | UpdateMode.Modified | boolean): RealmObject<T> & T;
    create<T extends AnyRealmObject>(type: Constructor<T>, values: Partial<T> | Partial<Unmanaged<T>>, mode?: UpdateMode.Never | UpdateMode.All | UpdateMode.Modified | boolean): T;
    /**
     * Deletes the provided Realm object, or each one inside the provided collection.
     * @param subject - The Realm object to delete, or a collection containing multiple Realm objects to delete.
     */
    delete(subject: AnyRealmObject | AnyRealmObject[] | AnyList | AnyResults | any): void;
    /**
     * Deletes a Realm model, including all of its objects.
     * If called outside a migration function, {@link schema} and {@link schemaVersion} are updated.
     * @param name - The model name.
     */
    deleteModel(name: string): void;
    /**
     * **WARNING:** This will delete **all** objects in the Realm!
     */
    deleteAll(): void;
    /**
     * Searches for a Realm object by its primary key.
     * @param type - The type of Realm object to search for.
     * @param primaryKey - The primary key value of the object to search for.
     * @throws An {@link Error} if type passed into this method is invalid, or if the object type did
     * not have a {@link primaryKey} specified in the schema, or if it was marked asymmetric.
     * @returns A {@link RealmObject} or `null` if no object is found.
     * @since 0.14.0
     */
    objectForPrimaryKey<T = DefaultObject>(type: string, primaryKey: T[keyof T]): (RealmObject<T> & T) | null;
    objectForPrimaryKey<T extends AnyRealmObject>(type: Constructor<T>, primaryKey: T[keyof T]): T | null;
    _objectForObjectKey<T extends RealmObject>(type: Constructor<T>, objectKey: string): T | undefined;
    /**
     * Returns all objects of the given {@link type} in the Realm.
     * @param type - The type of Realm objects to retrieve.
     * @throws An {@link Error} if type passed into this method is invalid or if the type is marked embedded or asymmetric.
     * @returns Results that will live-update as objects are created, modified, and destroyed.
     */
    objects<T = DefaultObject>(type: string): Results<RealmObject<T> & T>;
    objects<T extends AnyRealmObject = RealmObject & DefaultObject>(type: Constructor<T>): Results<T>;
    /**
     * Add a listener {@link callback} for the specified {@link eventName}.
     * @param eventName - The name of event that should cause the callback to be called.
     * @param callback - Function to be called when a change event occurs.
     * Each callback will only be called once per event, regardless of the number of times
     * it was added.
     * @param callback.realm - The Realm in which the change event occurred.
     * @param callback.name - The name of the event that occurred.
     * @param callback.schema - The schema of the Realm file when the event occurred.
     * @throws An {@link Error} if an invalid event {@link eventName} is supplied, if Realm is closed or if {@link callback} is not a function.
     */
    addListener(eventName: RealmEventName, callback: RealmListenerCallback): void;
    /**
     * Remove the listener {@link callback} for the specified event {@link eventName}.
     * @param eventName - The event name.
     * @param callback - Function that was previously added as a listener for this event through the {@link addListener} method.
     * @throws an {@link Error} If an invalid event {@link eventName} is supplied, if Realm is closed or if {@link callback} is not a function.
     */
    removeListener(eventName: RealmEventName, callback: RealmListenerCallback): void;
    /**
     * Remove all event listeners (restricted to the event {@link eventName}, if provided).
     * @param eventName - The name of the event whose listeners should be removed.
     * @throws An {@link Error} when invalid event {@link eventName} is supplied.
     */
    removeAllListeners(eventName?: RealmEventName): void;
    /**
     * Synchronously call the provided {@link callback} inside a write transaction. If an exception happens inside a transaction,
     * you’ll lose the changes in that transaction, but the Realm itself won’t be affected (or corrupted).
     * More precisely, {@link beginTransaction} and {@link commitTransaction} will be called
     * automatically. If any exception is thrown during the transaction {@link cancelTransaction} will
     * be called instead of {@link commitTransaction} and the exception will be re-thrown to the caller of {@link write}.
     *
     * Nested transactions (calling {@link write} within {@link write}) is not possible.
     * @param callback - Function to be called inside a write transaction.
     * @returns Returned value from the callback.
     */
    write<T>(callback: () => T): T;
    /**
     * Initiate a write transaction.
     *
     * When doing a transaction, it is highly recommended to do error handling.
     * If you don't handle errors, your data might become inconsistent. Error handling
     * will often involve canceling the transaction.
     * @throws An {@link Error} if already in write transaction
     * @see {@link cancelTransaction}
     * @see {@link commitTransaction}
     * @example
     * realm.beginTransaction();
     * try {
     *   realm.create('Person', { name: 'Arthur Dent',  origin: 'Earth' });
     *   realm.create('Person', { name: 'Ford Prefect', origin: 'Betelgeuse Five' });
     *   realm.commitTransaction();
     * } catch (e) {
     *   realm.cancelTransaction();
     *   throw e;
     * }
     */
    beginTransaction(): void;
    /**
     * Commit a write transaction.
     * @see {@link beginTransaction}
     */
    commitTransaction(): void;
    /**
     * Cancel a write transaction.
     * @see {@link beginTransaction}
     */
    cancelTransaction(): void;
    /**
     * Replaces all string columns in this Realm with a string enumeration column and compacts the
     * database file.
     *
     * Cannot be called from a write transaction.
     *
     * Compaction will not occur if other {@link Realm} instances exist.
     *
     * While compaction is in progress, attempts by other threads or processes to open the database will
     * wait.
     *
     * Be warned that resource requirements for compaction is proportional to the amount of live data in
     * the database. Compaction works by writing the database contents to a temporary database file and
     * then replacing the database with the temporary one.
     * @returns `true` if compaction succeeds, `false` if not.
     */
    compact(): boolean;
    /**
     * Writes a compacted copy of the Realm with the given configuration.
     *
     * The destination file cannot already exist.
     * All conversions between synced and non-synced Realms are supported, and will be
     * performed according to the {@link config} parameter, which describes the desired output.
     *
     * Note that if this method is called from within a write transaction, the current data is written,
     * not the data from the point when the previous write transaction was committed.
     * @param config - Realm configuration that describes the output realm.
     */
    writeCopyTo(config: Configuration): void;
    /**
     * Update subscriptions with the initial subscriptions if needed.
     * @param initialSubscriptions The initial subscriptions.
     * @param realmExists Whether the realm already exists.
     */
    private handleInitialSubscriptions;
}
declare namespace Realm {
    export type Object<T = DefaultObject> = RealmObject<T>;
    export { AppType as App, AppChangeCallback, AppConfiguration, AppServicesFunction, 
    /** @deprecated Will be removed in v13.0.0. Please use {@link AppServicesFunction} */
    AppServicesFunction as RealmFunction, BaseConfiguration, BaseObjectSchema, BaseSyncConfiguration, BSONType as BSON, CanonicalObjectSchema, 
    /** @deprecated Will be removed in v13.0.0. Please use {@link CanonicalPropertySchema} */
    CanonicalObjectSchemaProperty, CanonicalPropertySchema, CanonicalPropertiesTypes, ClientResetModeType as ClientResetMode, ClientResetFallbackCallback, ClientResetBeforeCallback, ClientResetAfterCallback, ClientResetManualConfiguration, ClientResetDiscardUnsyncedChangesConfiguration, ClientResetRecoverUnsyncedChangesConfiguration, 
    /** @deprecated Will be removed in v13.0.0. Please use {@link ClientResetRecoverUnsyncedChangesConfiguration} */
    ClientResetRecoverUnsyncedChangesConfiguration as ClientResetRecoveryConfiguration, ClientResetRecoverOrDiscardUnsyncedChangesConfiguration, ClientResetConfig, CollectionChangeCallback, CollectionChangeSet, CollectionPropertyTypeName, CollectionType as Collection, CompensatingWriteErrorType as CompensatingWriteError, CompensatingWriteInfo, ConfigurationWithoutSync, ConfigurationWithSync, Configuration, ConnectionNotificationCallback, ConnectionStateType as ConnectionState, CredentialsType as Credentials, DefaultFunctionsFactory, DefaultUserProfileData, DictionaryType as Dictionary, DictionaryChangeCallback, DictionaryChangeSet, ErrorCallback, FlexibleSyncConfiguration, IndexDecoratorType as IndexDecorator, ListType as List, LocalAppConfiguration, MapToDecoratorType as MapToDecorator, MetadataModeType as MetadataMode, MetadataType as Metadata, MigrationCallback, Mixed$1 as Mixed, NumericLogLevelType as NumericLogLevel, ObjectChangeCallback, ObjectChangeSet, ObjectSchema, 
    /** @deprecated Will be removed in v13.0.0. Please use {@link PropertySchema} */
    ObjectSchemaProperty, ObjectType$1 as ObjectType, OpenRealmBehaviorConfiguration, OpenRealmBehaviorTypeType as OpenRealmBehaviorType, OpenRealmTimeOutBehaviorType as OpenRealmTimeOutBehavior, OrderedCollectionType as OrderedCollection, PartitionSyncConfiguration, PrimaryKey, PrimitivePropertyTypeName, ProgressDirectionType as ProgressDirection, ProgressModeType as ProgressMode, ProgressNotificationCallback, PropertiesTypes, PropertySchema, PropertySchemaParseErrorType as PropertySchemaParseError, PropertySchemaShorthand, PropertySchemaStrict, PropertyTypeName, ProviderTypeType as ProviderType, ProxyTypeType as ProxyType, RealmObjectConstructor, 
    /** @deprecated Will be removed in v13.0.0. Please use {@link RealmObjectConstructor} */
    RealmObjectConstructor as ObjectClass, RelationshipPropertyTypeName, ResultsType as Results, SchemaParseErrorType as SchemaParseError, SessionStateType as SessionState, SessionStopPolicyType as SessionStopPolicy, SetType as Set, SortDescriptor, SSLConfigurationType as SSLConfiguration, SSLVerifyCallbackType as SSLVerifyCallback, SSLVerifyObjectType as SSLVerifyObject, SubscriptionSetStateType as SubscriptionSetState, SyncConfiguration, SyncErrorType as SyncError, TypesType as Types, UpdateModeType as UpdateMode, UserChangeCallback, UserStateType as UserState, UserType as User, WaitForSyncType as WaitForSync, GeoBox, GeoCircle, GeoPoint, GeoPolygon, CanonicalGeoPolygon, CanonicalGeoPoint, GeoPosition, };
    export namespace App {
        type Credentials = CredentialsType;
        namespace Sync {
            type BaseSubscriptionSet = BaseSubscriptionSetType;
            type LogLevel = LogLevelType;
            type NumericLogLevel = NumericLogLevelType;
            type MutableSubscriptionSet = MutableSubscriptionSetType;
            type PartitionValue = PartitionValueType;
            type SubscriptionOptions = SubscriptionOptionsType;
            type SubscriptionSet = SubscriptionSetType;
            type SubscriptionSetState = SubscriptionSetStateType;
            /** @deprecated Please use {@link SubscriptionSetState} */
            type SubscriptionsState = SubscriptionSetStateType;
            type Subscription = SubscriptionType;
            type SyncSession = SyncSessionType;
            /**
             * @deprecated Got renamed to {@SyncSession} and please use named imports
             */
            type Session = SyncSessionType;
        }
    }
    /**
     * Re-export of a subset of the "bson" package, enabling access to the BSON types without requiring an explicit dependency on the "bson" package.
     * @see {@link https://www.npmjs.com/package/bson#documentation|the BSON documentation} for more information.
     */
    export namespace BSON {
        type ObjectId = ObjectIdType;
        type Decimal128 = Decimal128Type;
        type UUID = UUIDType;
    }
    export namespace Auth {
        type EmailPasswordAuth = EmailPasswordAuthType;
        type ApiKey = ApiKeyType;
        type ApiKeyAuth = ApiKeyAuthType;
    }
    export namespace Services {
        type MongoDB = MongoDBType;
        type MongoDBDatabase = MongoDBDatabaseType;
        /** @deprecated Please read {@link https://www.mongodb.com/docs/atlas/app-services/reference/push-notifications/} */
        type Push = PushClient;
        namespace MongoDB {
            type AggregatePipelineStage = AggregatePipelineStageType;
            type BaseChangeEvent<T extends OperationType> = BaseChangeEventType<T>;
            type ChangeEvent<T extends Document> = ChangeEventType<T>;
            type ChangeEventId = ChangeEventIdType;
            type CountOptions = CountOptionsType;
            type DeleteEvent<T extends Document> = DeleteEventType<T>;
            type DeleteResult = DeleteResultType;
            type Document<IdType = any> = DocumentType<IdType>;
            type DocumentKey<IdType> = DocumentKeyType<IdType>;
            type DocumentNamespace = DocumentNamespaceType;
            type DropDatabaseEvent = DropDatabaseEventType;
            type DropEvent = DropEventType;
            type Filter = FilterType;
            type FindOneAndModifyOptions = FindOneAndModifyOptionsType;
            type FindOneOptions = FindOneOptionsType;
            type FindOptions = FindOptionsType;
            type InsertEvent<T extends Document> = InsertEventType<T>;
            type InsertManyResult<IdType> = InsertManyResultType<IdType>;
            type InsertOneResult<IdType> = InsertOneResultType<IdType>;
            type InvalidateEvent = InvalidateEventType;
            type MongoDBCollection<T extends Document> = MongoDBCollectionType<T>;
            type NewDocument<T extends Document> = NewDocumentType<T>;
            type OperationType = OperationTypeType;
            type RenameEvent = RenameEventType;
            type ReplaceEvent<T extends Document> = ReplaceEventType<T>;
            type Update = UpdateType;
            type UpdateDescription = UpdateDescriptionType;
            type UpdateEvent<T extends Document> = UpdateEventType<T>;
            type UpdateOptions = UpdateOptionsType;
            type UpdateResult<IdType> = UpdateResultType<IdType>;
        }
    }
    export namespace Types {
        type Bool = boolean;
        type String = string;
        type Int = number;
        type Float = number;
        type Double = number;
        type Decimal128 = Realm.BSON.Decimal128;
        type ObjectId = Realm.BSON.ObjectId;
        type UUID = Realm.BSON.UUID;
        type Date = GlobalDate;
        type Data = ArrayBuffer;
        type List<T> = Realm.List<T>;
        type Set<T> = Realm.Set<T>;
        type Dictionary<T> = Realm.Dictionary<T>;
        type Mixed = unknown;
        type LinkingObjects<ObjectTypeT, LinkingPropertyName> = Realm.Results<ObjectTypeT>;
    }
}
declare const RealmConstructor: typeof Realm;
declare global {
    /** @deprecated Will be removed in v13.0.0. Please use an import statement. */
    export class Realm extends RealmConstructor {
    }
    export namespace Realm {
        export type Object<T = DefaultObject> = RealmObject<T>;
        export { AppType as App, AppChangeCallback, AppConfiguration, AppServicesFunction, 
        /** @deprecated Will be removed in v13.0.0. Please use {@link AppServicesFunction} */
        AppServicesFunction as RealmFunction, BaseConfiguration, BaseObjectSchema, BaseSyncConfiguration, BSONType as BSON, CanonicalObjectSchema, 
        /** @deprecated Will be removed in v13.0.0. Please use {@link CanonicalPropertySchema} */
        CanonicalObjectSchemaProperty, CanonicalPropertySchema, CanonicalPropertiesTypes, ClientResetModeType as ClientResetMode, ClientResetFallbackCallback, ClientResetBeforeCallback, ClientResetAfterCallback, ClientResetManualConfiguration, ClientResetDiscardUnsyncedChangesConfiguration, ClientResetRecoverUnsyncedChangesConfiguration, 
        /** @deprecated Will be removed in v13.0.0. Please use {@link ClientResetRecoverUnsyncedChangesConfiguration} */
        ClientResetRecoverUnsyncedChangesConfiguration as ClientResetRecoveryConfiguration, ClientResetRecoverOrDiscardUnsyncedChangesConfiguration, ClientResetConfig, CollectionChangeCallback, CollectionChangeSet, CollectionPropertyTypeName, CollectionType as Collection, CompensatingWriteErrorType as CompensatingWriteError, CompensatingWriteInfo, ConfigurationWithoutSync, ConfigurationWithSync, Configuration, ConnectionNotificationCallback, ConnectionStateType as ConnectionState, CredentialsType as Credentials, DefaultFunctionsFactory, DefaultUserProfileData, DictionaryType as Dictionary, DictionaryChangeCallback, DictionaryChangeSet, ErrorCallback, FlexibleSyncConfiguration, IndexDecoratorType as IndexDecorator, ListType as List, LocalAppConfiguration, MapToDecoratorType as MapToDecorator, MetadataModeType as MetadataMode, Metadata, MigrationCallback, Mixed$1, NumericLogLevelType as NumericLogLevel, ObjectChangeCallback, ObjectChangeSet, ObjectSchema, 
        /** @deprecated Will be removed in v13.0.0. Please use {@link PropertySchema} */
        ObjectSchemaProperty, ObjectType$1, OpenRealmBehaviorConfiguration, OpenRealmBehaviorTypeType as OpenRealmBehaviorType, OpenRealmTimeOutBehaviorType as OpenRealmTimeOutBehavior, PartitionSyncConfiguration, PrimaryKey, PrimitivePropertyTypeName, ProgressDirectionType as ProgressDirection, ProgressModeType as ProgressMode, ProgressNotificationCallback, PropertiesTypes, PropertySchema, PropertySchemaParseErrorType as PropertySchemaParseError, PropertySchemaShorthand, PropertySchemaStrict, PropertyTypeName, ProviderTypeType as ProviderType, RealmObjectConstructor, 
        /** @deprecated Will be removed in v13.0.0. Please use {@link RealmObjectConstructor} */
        RealmObjectConstructor as ObjectClass, RelationshipPropertyTypeName, ResultsType as Results, SchemaParseErrorType as SchemaParseError, SessionStateType as SessionState, SessionStopPolicyType as SessionStopPolicy, SetType as Set, SortDescriptor, SSLConfigurationType as SSLConfiguration, SSLVerifyCallbackType as SSLVerifyCallback, SSLVerifyObjectType as SSLVerifyObject, SubscriptionSetStateType as SubscriptionSetState, SyncConfiguration, SyncErrorType as SyncError, TypesType as Types, UpdateModeType as UpdateMode, UserChangeCallback, UserStateType as UserState, GeoBox, GeoCircle, GeoPoint, GeoPolygon, CanonicalGeoPolygon, CanonicalGeoPoint, GeoPosition, UserType as User, WaitForSyncType as WaitForSync, };
        export namespace App {
            type Credentials = CredentialsType;
            namespace Sync {
                type BaseSubscriptionSet = BaseSubscriptionSetType;
                type LogLevel = LogLevelType;
                type NumericLogLevel = NumericLogLevelType;
                type MutableSubscriptionSet = MutableSubscriptionSetType;
                type PartitionValue = PartitionValueType;
                type SubscriptionOptions = SubscriptionOptionsType;
                type SubscriptionSet = SubscriptionSetType;
                type SubscriptionSetState = SubscriptionSetStateType;
                /** @deprecated Please use {@link SubscriptionSetState} */
                type SubscriptionsState = SubscriptionSetStateType;
                type Subscription = SubscriptionType;
                type SyncSession = SyncSessionType;
                /**
                 * @deprecated Got renamed to {@SyncSession} and please use named imports
                 */
                type Session = SyncSessionType;
            }
        }
        export namespace BSON {
            type ObjectId = ObjectIdType;
            type Decimal128 = Decimal128Type;
            type UUID = UUIDType;
        }
        export namespace Auth {
            type EmailPasswordAuth = EmailPasswordAuthType;
            type ApiKey = ApiKeyType;
            type ApiKeyAuth = ApiKeyAuthType;
        }
        export namespace Services {
            type MongoDB = MongoDBType;
            type MongoDBDatabase = MongoDBDatabaseType;
            /** @deprecated Please read {@link https://www.mongodb.com/docs/atlas/app-services/reference/push-notifications/} */
            type Push = PushClient;
            namespace MongoDB {
                type AggregatePipelineStage = AggregatePipelineStageType;
                type BaseChangeEvent<T extends OperationType> = BaseChangeEventType<T>;
                type ChangeEvent<T extends Document> = ChangeEventType<T>;
                type ChangeEventId = ChangeEventIdType;
                type CountOptions = CountOptionsType;
                type DeleteEvent<T extends Document> = DeleteEventType<T>;
                type DeleteResult = DeleteResultType;
                type Document<IdType = any> = DocumentType<IdType>;
                type DocumentKey<IdType> = DocumentKeyType<IdType>;
                type DocumentNamespace = DocumentNamespaceType;
                type DropDatabaseEvent = DropDatabaseEventType;
                type DropEvent = DropEventType;
                type Filter = FilterType;
                type FindOneAndModifyOptions = FindOneAndModifyOptionsType;
                type FindOneOptions = FindOneOptionsType;
                type FindOptions = FindOptionsType;
                type InsertEvent<T extends Document> = InsertEventType<T>;
                type InsertManyResult<IdType> = InsertManyResultType<IdType>;
                type InsertOneResult<IdType> = InsertOneResultType<IdType>;
                type InvalidateEvent = InvalidateEventType;
                type MongoDBCollection<T extends Document> = MongoDBCollectionType<T>;
                type NewDocument<T extends Document> = NewDocumentType<T>;
                type OperationType = OperationTypeType;
                type RenameEvent = RenameEventType;
                type ReplaceEvent<T extends Document> = ReplaceEventType<T>;
                type Update = UpdateType;
                type UpdateDescription = UpdateDescriptionType;
                type UpdateEvent<T extends Document> = UpdateEventType<T>;
                type UpdateOptions = UpdateOptionsType;
                type UpdateResult<IdType> = UpdateResultType<IdType>;
            }
        }
        export namespace Types {
            type Bool = boolean;
            type String = string;
            type Int = number;
            type Float = number;
            type Double = number;
            type Decimal128 = Realm.BSON.Decimal128;
            type ObjectId = Realm.BSON.ObjectId;
            type UUID = Realm.BSON.UUID;
            type Date = GlobalDate;
            type Data = ArrayBuffer;
            type List<T> = Realm.List<T>;
            type Set<T> = Realm.Set<T>;
            type Dictionary<T> = Realm.Dictionary<T>;
            type Mixed = unknown;
            type LinkingObjects<ObjectTypeT, LinkingPropertyName> = Realm.Results<ObjectTypeT>;
        }
    }
}

declare enum RealmEvent {
    Change = "change",
    Schema = "schema",
    BeforeNotify = "beforenotify"
}
type RealmListenerCallback = (realm: Realm, name: RealmEvent, schema?: CanonicalObjectSchema[]) => void;

/**
 * A function which can be called to migrate a Realm from one version of the schema to another.
 */
type MigrationCallback = (oldRealm: Realm, newRealm: Realm) => void;
/**
 * This describes options used during schema migration.
 */
type MigrationOptions = {
    /**
     * A flag to indicate whether Realm should resolve
     * embedded object constraints after migration. If this is `true` then all embedded objects
     * without a parent will be deleted and every embedded object with every embedded object with
     * one or more references to it will be duplicated so that every referencing object will hold
     * its own copy of the embedded object.
     * @default false
     * @since 12.1.0
     */
    resolveEmbeddedConstraints?: boolean;
};
/**
 * The options used to create a {@link Realm} instance.
 */
type BaseConfiguration = {
    /**
     * The path to the file where the Realm database should be stored. For synced Realms, a relative path
     * is used together with the {@link AppConfiguration.id | app ID} and {@link User.id | user ID} in order
     * to avoid collisions with other apps or users.
     * An absolute path is left untouched and on some platforms (iOS and Android) the app might not have
     * permissions to create or open the file - permissions are not validated.
     * If a relative path is specified, it is relative to {@link AppConfiguration.baseFilePath}.
     * @since 0.10.0
     */
    path?: string;
    /**
     * Specifies all the object types in this Realm. **Required** when first creating a Realm at this `path`.
     * If omitted, the schema will be read from the existing Realm file.
     * @since 0.10.0
     */
    schema?: (RealmObjectConstructor<AnyRealmObject> | ObjectSchema)[];
    /**
     * If changing the `schema`, this field is **required** and must be incremented. This only
     * applies to local Realms.
     * @since 0.11.0
     */
    schemaVersion?: number;
    /**
     * Specifies if this Realm should be opened in-memory. This
     * still requires a path (can be the default path) to identify the Realm so other processes can
     * open the same Realm. The file will also be used as swap space if the Realm becomes bigger than
     * what fits in memory, but it is not persistent and will be removed when the last instance
     * is closed. This option is incompatible with option `sync`.
     * @default false
     * @since 0.10.0
     */
    inMemory?: boolean;
    /**
     * Specifies if this Realm should be opened as read-only.
     * @default false
     * @since 0.10.0
     */
    readOnly?: boolean;
    /**
     * Opening a Realm creates a number of FIFO special files in order to
     * coordinate access to the Realm across threads and processes. If the Realm file is stored in a location
     * that does not allow the creation of FIFO special files (e.g. FAT32 file systems), then the Realm cannot be opened.
     * In that case Realm needs a different location to store these files and this property defines that location.
     * The FIFO special files are very lightweight and the main Realm file will still be stored in the location defined
     * by the `path` property. This property is ignored if the directory defined by `path` allow FIFO special files.
     * @since 2.23.0
     */
    fifoFilesFallbackPath?: string;
    sync?: SyncConfiguration;
    /**
     * The function called when opening a Realm for the first time during the life of
     * a process to determine if it should be compacted before being returned to the user.
     *
     * It returns `true` to indicate that an attempt to compact the file should be made. The compaction
     * will be skipped if another process is accessing it.
     * @param totalBytes - The total file size (data + free space).
     * @param usedBytes - The total bytes used by data in the file.
     * @returns `true` if Realm file should be compacted before opening.
     * @since 2.9.0
     * @example
     * // compact large files (>100 MB) with more than half is free space
     * shouldCompact: (totalBytes, usedBytes) => {
     *   const oneHundredMB = 100 * 1024 * 1024; // 100 MB
     *   return totalBytes > oneHundredMB && usedBytes / totalBytes < 0.5;
     * }
     */
    shouldCompact?: (totalBytes: number, usedBytes: number) => boolean;
    /**
     * Specifies if this Realm should be deleted if a migration is needed.
     * The option is incompatible with option `sync`.
     * @default: false
     * @since 1.13.0
     */
    deleteRealmIfMigrationNeeded?: boolean;
    /**
     * Specifies if this Realm's file format should
     * be automatically upgraded if it was created with an older version of the Realm library.
     * If set to `true` and a file format upgrade is required, an error will be thrown instead.
     * @default false
     * @since 2.1.0
     */
    disableFormatUpgrade?: boolean;
    /**
     * The 512-bit (64-byte) encryption key used to encrypt and decrypt all data in the Realm.
     * @since 0.11.1
     */
    encryptionKey?: ArrayBuffer | ArrayBufferView | Int8Array;
    /**
     * The function to run if a migration is needed.
     *
     * This function should provide all the logic for converting data models from previous schemas
     * to the new schema. This option is incompatible with option `sync`.
     *
     * The function takes two arguments:
     *   - `oldRealm` - The Realm before migration is performed.
     *   - `newRealm` - The Realm that uses the latest `schema`, which should be modified as necessary.
     * @since 0.12.0
     */
    onMigration?: MigrationCallback;
    /**
     * The function called when opening a Realm for the first time. The function can populate the Realm
     * prior to opening it. When calling the callback, the Realm will be in a write transaction.
     * @param realm - The newly created Realm.
     * @since 10.14.0
     */
    onFirstOpen?: (realm: Realm) => void;
    migrationOptions?: MigrationOptions;
};
type ConfigurationWithSync = BaseConfiguration & {
    sync: SyncConfiguration;
};
type ConfigurationWithoutSync = BaseConfiguration & {
    sync?: never;
};
type Configuration = ConfigurationWithSync | ConfigurationWithoutSync;

declare class ProgressRealmPromise implements Promise<Realm> {
    /**
     * Cancels the download of the Realm
     * If multiple `ProgressRealmPromise` instances are in progress for the same Realm, then canceling one of them
     * will cancel all of them.
     */
    cancel(): void;
    /**
     * Register to receive progress notifications while the download is in progress.
     * @param callback Called multiple times as the client receives data, with two arguments:
     * 1. `transferred` The current number of bytes already transferred
     * 2. `transferable` The total number of transferable bytes (i.e. the number of bytes already transferred plus the number of bytes pending transfer)
     */
    progress(callback: ProgressNotificationCallback): this;
    then: <TResult1 = Realm, TResult2 = never>(onfulfilled?: ((value: Realm) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined) => Promise<TResult1 | TResult2>;
    catch: <TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | null | undefined) => Promise<Realm | TResult>;
    finally: (onfinally?: (() => void) | null | undefined) => Promise<Realm>;
    private emitProgress;
    private createTimeoutPromise;
    private cancelAndResetTask;
    private rejectAsCanceled;
    get [Symbol.toStringTag](): string;
}

type AnyCollection = Collection<any, any, any, any, any>;
type AnyDictionary = Dictionary<any>;
type AnyList = List<any>;
type ExtractPropertyNamesOfType<T, PropType> = {
    [K in keyof T]: T[K] extends PropType ? K : never;
}[keyof T];
/**
 * Exchanges properties defined as {@link List} with an optional {@link Array}.
 */
type RealmListsRemappedModelPart<T> = {
    [K in ExtractPropertyNamesOfType<T, AnyList>]?: T[K] extends List<infer GT> ? Array<GT | Unmanaged<GT>> : never;
};
/**
 * Exchanges properties defined as {@link Dictionary} with an optional key to mixed value object.
 */
type RealmDictionaryRemappedModelPart<T> = {
    [K in ExtractPropertyNamesOfType<T, AnyDictionary>]?: T[K] extends Dictionary<infer ValueType> ? {
        [key: string]: ValueType;
    } : never;
};
/** Omits all properties of a model which are not defined by the schema */
type OmittedRealmTypes<T> = Omit<T, keyof AnyRealmObject | ExtractPropertyNamesOfType<T, Function> | ExtractPropertyNamesOfType<T, AnyCollection> | ExtractPropertyNamesOfType<T, AnyDictionary>>;
/** Make all fields optional except those specified in K */
type OptionalExcept<T, K extends keyof T> = Partial<T> & Pick<T, K>;
/**
 * Omits all properties of a model which are not defined by the schema,
 * making all properties optional except those specified in RequiredProperties.
 */
type OmittedRealmTypesWithRequired<T, RequiredProperties extends keyof OmittedRealmTypes<T>> = OptionalExcept<OmittedRealmTypes<T>, RequiredProperties>;
/** Remaps realm types to "simpler" types (arrays and objects) */
type RemappedRealmTypes<T> = RealmListsRemappedModelPart<T> & RealmDictionaryRemappedModelPart<T>;
/**
 * Joins `T` stripped of all keys which value extends {@link Collection} and all inherited from {@link Realm.Object},
 * with only the keys which value extends {@link List}, remapped as {@link Array}. All properties are optional
 * except those specified in `RequiredProperties`.
 */
type Unmanaged<T, RequiredProperties extends keyof OmittedRealmTypes<T> = never> = OmittedRealmTypesWithRequired<T, RequiredProperties> & RemappedRealmTypes<T>;

type DefaultObject = Record<string, unknown>;
type Constructor<T = unknown> = {
    new (...args: any): T;
};
type RealmObjectConstructor<T extends RealmObject = RealmObject> = {
    new (...args: any): T;
    schema?: ObjectSchema;
};
/**
 * The names of the supported Realm property types.
 */
type PropertyTypeName = PrimitivePropertyTypeName | CollectionPropertyTypeName | RelationshipPropertyTypeName;
/**
 * Valid types for an object primary key.
 */
type PrimaryKey = null | number | string | BSON.ObjectId | BSON.UUID;
/**
 * The names of the supported Realm primitive property types.
 */
type PrimitivePropertyTypeName = "bool" | "int" | "float" | "double" | "decimal128" | "objectId" | "string" | "data" | "date" | "mixed" | "uuid";
/**
 * The names of the supported Realm collection property types.
 */
type CollectionPropertyTypeName = "list" | "dictionary" | "set";
/**
 * The names of the supported Realm relationship property types.
 */
type RelationshipPropertyTypeName = "object" | "linkingObjects";
/**
 * The name of a user-defined Realm object type. It must contain at least 1 character
 * and cannot be a {@link PropertyTypeName}. (Unicode is supported.)
 */
type UserTypeName = string;
/**
 * @deprecated Will be removed in v13.0.0. Please use {@link CanonicalPropertySchema}.
 */
type CanonicalObjectSchemaProperty = CanonicalPropertySchema;
/**
 * The type of index on a property:
 * - `true` enables a regular index
 * - `"full-text"` enables a full-text search index and can only be applied to string properties.
 */
type IndexedType = boolean | "full-text";
/**
 * The canonical representation of the schema of a specific property.
 */
type CanonicalPropertySchema = {
    name: string;
    type: PropertyTypeName;
    optional: boolean;
    indexed: IndexedType;
    mapTo: string;
    objectType?: string;
    property?: string;
    default?: unknown;
};
/**
 * The schema for specifying the type of Realm object.
 */
type BaseObjectSchema = {
    /**
     * The name of the Realm object type. The name must be unique across all objects
     * within the same Realm.
     */
    name: string;
    /**
     * The name of the property in `properties` that is used as the primary key. The
     * value of that property must be unique across all objects of this type within
     * the same Realm.
     */
    primaryKey?: string;
    /**
     * Whether the object is embedded. An embedded object always belongs to exactly
     * one parent object and is deleted if its parent is deleted.
     *
     * Default value: `false`.
     */
    embedded?: boolean;
    /**
     * Whether the object is used in asymmetric sync. An object that is asymmetrically
     * synced is not stored locally and cannot be accessed locally. Querying such
     * objects will throw an error. This is useful for write-heavy applications that
     * only need to get data from devices to the cloud fast.
     *
     * Default value: `false`.
     */
    asymmetric?: boolean;
    /**
     * The properties and their types belonging to this object.
     */
    properties: unknown;
};
/**
 * The schema of a specific type of object.
 */
type ObjectSchema = BaseObjectSchema & {
    properties: PropertiesTypes;
};
/**
 * The canonical representation of the schema of a specific type of object.
 */
type CanonicalObjectSchema<T = DefaultObject> = BaseObjectSchema & {
    properties: CanonicalPropertiesTypes<keyof T>;
    ctor?: RealmObjectConstructor;
};
/**
 * The properties of a Realm object defined in {@link ObjectSchema.properties} where
 * each key is the name of a property and the value is its type in the form of a
 * {@link PropertySchemaShorthand} or {@link PropertySchema}.
 */
type PropertiesTypes = {
    [key: string]: PropertySchema | PropertySchemaShorthand;
};
type CanonicalPropertiesTypes<K extends symbol | number | string = string> = Record<K, CanonicalPropertySchema>;
/**
 * The shorthand string representation of a schema for specifying the type of a
 * Realm object property.
 *
 * Required string structure:
 * - ({@link PrimitivePropertyTypeName} | {@link UserTypeName})(`"?"` | `""`)(`"[]"` | `"{}"` | `"<>"` | `""`)
 *   - `"?"`
 *     - The marker to declare an optional type or an optional element in a collection
 *       if the type itself is a collection. Can only be used when declaring property
 *       types using this shorthand string notation.
 *   - `"[]"` (list)
 *   - `"{}"` (dictionary)
 *   - `"<>"` (set)
 *     - The markers to declare a collection type. Can only be used when declaring
 *       property types using this shorthand string notation.
 * @example
 * "int"
 * "int?"
 * "int[]"
 * "int?[]"
 * @see {@link PropertySchema} for using the object representation of a property schema.
 */
type PropertySchemaShorthand = string;
/**
 * @deprecated Will be removed in v13.0.0. Please use {@link PropertySchema}.
 */
type ObjectSchemaProperty = PropertySchema;
/**
 * The schema for specifying the type of a specific Realm object property.
 *
 * Requirements:
 * - `"mixed"` types are always optional because `null` is a valid value within `"mixed"`
 *   itself. Therefore, they cannot be made non-optional.
 * - User-defined object types are always optional except in lists and sets due to the
 *   object being deleted whenever it is removed from lists and sets and are therefore
 *   never set to `null` or `undefined`. Whereas in in dictionaries, deleted values are
 *   set to `null` and cannot be made non-optional.
 * - Properties declared as the primary key in {@link ObjectSchema.primaryKey} are always
 *   indexed. In such cases, they cannot be made non-indexed.
 * @see {@link PropertySchemaShorthand} for a shorthand representation of a property
 * schema.
 * @see {@link PropertySchemaStrict} for a precise type definition of the requirements
 * with the allowed combinations. This type is less strict in order to provide a more
 * user-friendly option due to misleading TypeScript error messages when working with
 * the strict type. This type is currently recommended for that reason, but the strict
 * type is provided as guidance. (Exact errors will always be shown when creating a
 * {@link Realm} instance if the schema is invalid.)
 */
type PropertySchema = {
    /**
     * The type of the property.
     */
    type: PropertyTypeName;
    /**
     * The type of the elements in the collection if `type` is a {@link CollectionPropertyTypeName},
     * or the specific Realm object type if `type` is a {@link RelationshipPropertyTypeName}.
     */
    objectType?: PrimitivePropertyTypeName | UserTypeName;
    /**
     * The name of the property of the object specified in `objectType` that creates this
     * link. (Can only be set for linking objects.)
     */
    property?: string;
    /**
     * Whether to allow `null` or `undefined` to be assigned to the property; or in the
     * case of a collection, to be assigned to its elements. (Realm object types in lists
     * and sets cannot be optional.)
     *
     * Default value: `false` except in cases listed in the documentation for this type.
     */
    optional?: boolean;
    /**
     * The type of index applied to the property.
     *
     * Default value: `false` if the property is not a primary key, otherwise `true`.
     */
    indexed?: IndexedType;
    /**
     * The name to be persisted in the Realm file if it differs from the already-defined
     * JavaScript/TypeScript (JS/TS) property name. This is useful for allowing different
     * naming conventions than what is persisted in the Realm file. Reading and writing
     * properties must be done using the JS/TS name, but queries can use either the JS/TS
     * name or the persisted name.
     */
    mapTo?: string;
    /**
     * The default value that the property will be set to when created.
     */
    default?: unknown;
};
/**
 * Keys used in the property schema that are common among all variations of {@link PropertySchemaStrict}.
 */
type PropertySchemaCommon = {
    indexed?: IndexedType;
    mapTo?: string;
    default?: unknown;
};
/**
 * The strict schema for specifying the type of a specific Realm object property.
 *
 * Unlike the less strict {@link PropertySchema}, this type precisely defines the type
 * requirements and their allowed combinations; however, TypeScript error messages tend
 * to be more misleading. {@link PropertySchema} is recommended for that reason, but the
 * strict type is provided as guidance.
 * @see {@link PropertySchema} for a textual explanation of the requirements defined here,
 *   as well as documentation for each property.
 */
type PropertySchemaStrict = PropertySchemaCommon & ({
    type: Exclude<PrimitivePropertyTypeName, "mixed">;
    optional?: boolean;
} | {
    type: "mixed";
    optional?: true;
} | {
    type: CollectionPropertyTypeName;
    objectType: Exclude<PrimitivePropertyTypeName, "mixed">;
    optional?: boolean;
} | {
    type: CollectionPropertyTypeName;
    objectType: "mixed";
    optional?: true;
} | {
    type: "list" | "set";
    objectType: UserTypeName;
    optional?: false;
} | {
    type: "dictionary";
    objectType: UserTypeName;
    optional?: true;
} | {
    type: "object";
    objectType: UserTypeName;
    optional?: true;
} | {
    type: "linkingObjects";
    objectType: UserTypeName;
    property: string;
    optional?: false;
});

type Mixed = unknown;
type ObjectType = string | RealmObjectConstructor;

export { AggregatePipelineStage, ApiKey, ApiKeyAuth, App, AppChangeCallback, AppConfiguration, AppServicesFunction, AssertionError, BSON, BaseChangeEvent, BaseConfiguration, BaseObjectSchema, BaseSubscriptionSet, BaseSyncConfiguration, CanonicalGeoPoint, CanonicalGeoPolygon, CanonicalObjectSchema, CanonicalObjectSchemaProperty, CanonicalPropertiesTypes, CanonicalPropertySchema, ChangeEvent, ChangeEventId, ClientResetAfterCallback, ClientResetBeforeCallback, ClientResetConfig, ClientResetDiscardUnsyncedChangesConfiguration, ClientResetFallbackCallback, ClientResetManualConfiguration, ClientResetMode, ClientResetRecoverOrDiscardUnsyncedChangesConfiguration, ClientResetRecoverUnsyncedChangesConfiguration, ClientResetRecoverUnsyncedChangesConfiguration as ClientResetRecoveryConfiguration, Collection, CollectionChangeCallback, CollectionChangeSet, CollectionPropertyTypeName, CompensatingWriteError, CompensatingWriteInfo, Configuration, ConfigurationWithSync, ConfigurationWithoutSync, ConnectionNotificationCallback, ConnectionState, CountOptions, Credentials, DefaultFunctionsFactory, DefaultUserProfileData, DeleteEvent, DeleteResult, Dictionary, DictionaryChangeCallback, DictionaryChangeSet, Document, DocumentKey, DocumentNamespace, DropDatabaseEvent, DropEvent, EmailPasswordAuth, ErrorCallback, Filter, FindOneAndModifyOptions, FindOneOptions, FindOptions, FlexibleSyncConfiguration, GeoBox, GeoCircle, GeoPoint, GeoPolygon, GeoPosition, IndexDecorator, InsertEvent, InsertManyResult, InsertOneResult, InvalidateEvent, List, LocalAppConfiguration, LogLevel, LoggerCallback, MapToDecorator, Metadata, MetadataMode, MigrationCallback, Mixed, MongoDB, MongoDBCollection, MongoDBDatabase, MutableSubscriptionSet, NewDocument, NumericLogLevel, RealmObject as Object, ObjectChangeCallback, ObjectChangeSet, RealmObjectConstructor as ObjectClass, ObjectSchema, ObjectSchemaParseError, ObjectSchemaProperty, ObjectType, OpenRealmBehaviorConfiguration, OpenRealmBehaviorType, OpenRealmTimeOutBehavior, OperationType, OrderedCollection, PartitionSyncConfiguration, PartitionValue, PrimaryKey, PrimitivePropertyTypeName, ProgressDirection, ProgressMode, ProgressNotificationCallback, ProgressRealmPromise, PropertiesTypes, PropertySchema, PropertySchemaCommon, PropertySchemaParseError, PropertySchemaShorthand, PropertySchemaStrict, PropertyTypeName, ProviderType, ProxyType, Realm, AppServicesFunction as RealmFunction, RealmObjectConstructor, RelationshipPropertyTypeName, RenameEvent, ReplaceEvent, Results, SSLConfiguration, SSLVerifyCallback, SSLVerifyObject, SchemaParseError, SyncSession as Session, SessionState, SessionStopPolicy, RealmSet as Set, SortDescriptor, Subscription, SubscriptionOptions, SubscriptionSet, SubscriptionSetState, SubscriptionsState, Sync, SyncConfiguration, SyncError, SyncSession, TypeAssertionError, Types, Update, UpdateDescription, UpdateEvent, UpdateMode, UpdateOptions, UpdateResult, User, UserChangeCallback, UserState, UserTypeName, WaitForSync, Realm as default, flags, index, kmToRadians, mapTo, miToRadians };
